Merge pull request #2600 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 a5c48ff, 78fa4ca · Browse files · 74 files·+2911 added−695 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
74 files+2911 added−695 removed
- tests:+1374 added−90 removed
- other:+1537 added−605 removed
Provenance
- Commit
1564cde- Tree
343eaf4- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent 1
a5c48ff- Parent 2
78fa4ca
74 files changed+2911 added−695 removed
modified:deno_dist/adapter/deno/serve-static.ts+1 added-1 removed
16 unmodified lines171819202121222324257 unmodified lines16 unmodified lines file = await open(path) } catch (e) { console.warn(`${e}`) } return file ? file.readable : undefined return file ? file.readable : null } const pathResolve = (path: string) => { return `./${path}` }7 unmodified linesmodified:deno_dist/client/client.ts+1 added
121 unmodified lines122 return (opt?.fetch || fetch)(url, {123 body: setBody ? this.rBody : undefined,124 method: methodUpperCase,125 headers: headers,126+ ...opt?.init,127 })128 }129 }130 60 unmodified linesmodified:deno_dist/client/types.ts+66 added-22 removed
1132345678891011121314151617181920211322232417182526272128293024253132333435362 unmodified lines39404142364344453946474849505 unmodified lines5657585960616263646566675368697071727374757677785657798081828384856364868788899091929394952 unmodified lines989910010175102103771041051067980107828310810911011111211311411511611711811912012112212312412512612712812913013113213346 unmodified linesimport type { UpgradedWebSocketResponseInputJSONType } from '../helper/websocket/index.ts'import type { Hono } from '../hono.ts'import type { Schema } from '../types.ts'import type { Endpoint, ResponseFormat, Schema } from '../types.ts'import type { StatusCode, SuccessStatusCode } from '../utils/http-status.ts'import type { HasRequiredKeys } from '../utils/types.ts'
type HonoRequest = (typeof Hono.prototype)['request']
export type ClientRequestOptions<T = unknown> = keyof T extends neverexport type ClientRequestOptions<T = unknown> = { fetch?: typeof fetch | HonoRequest /** * Standard `RequestInit`, caution that this take highest priority * and could be used to overwrite things that Hono sets for you, like `body | method | headers`. * * If you want to add some headers, use in `headers` instead of `init` */ init?: RequestInit} & (keyof T extends never ? { headers?: | Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>) fetch?: typeof fetch | HonoRequest } : { headers: T | (() => T | Promise<T>) fetch?: typeof fetch | HonoRequest } })
export type ClientRequest<S extends Schema> = { [M in keyof S]: S[M] extends { input: infer R; output: infer O } [M in keyof S]: S[M] extends Endpoint & { input: infer R } ? R extends object ? HasRequiredKeys<R> extends true ? (args: R, options?: ClientRequestOptions) => Promise<ClientResponse<O>> : (args?: R, options?: ClientRequestOptions) => Promise<ClientResponse<O>> ? (args: R, options?: ClientRequestOptions) => Promise<ClientResponseOfEndpoint<S[M]>> : (args?: R, options?: ClientRequestOptions) => Promise<ClientResponseOfEndpoint<S[M]>> : never : never} & { $url: (2 unmodified lines ? { param: P } : {} : {} ) => URL} & (S['$get'] extends { input: { json: UpgradedWebSocketResponseInputJSONType } }} & (S['$get'] extends { outputFormat: 'ws' } ? S['$get'] extends { input: infer I } ? { $ws: (args?: Omit<I, 'json'>) => WebSocket $ws: (args?: I) => WebSocket } : {} : {})
5 unmodified lines ? never : T : never
type ClientResponseOfEndpoint<T extends Endpoint = Endpoint> = T extends { output: infer O outputFormat: infer F status: infer S} ? ClientResponse<O, S extends number ? S : never, F extends ResponseFormat ? F : never> : never
export interface ClientResponse<T> {export interface ClientResponse< T, U extends number = StatusCode, F extends ResponseFormat = ResponseFormat> extends globalThis.Response { readonly body: ReadableStream | null readonly bodyUsed: boolean ok: U extends SuccessStatusCode ? true : U extends Exclude<StatusCode, SuccessStatusCode> ? false ok: boolean status: number : boolean status: U statusText: string headers: Headers url: string redirect(url: string, status: number): Response clone(): Response json(): Promise<BlankRecordToNever<T>> text(): Promise<string> json(): F extends 'text' ? Promise<never> : F extends 'json' ? Promise<BlankRecordToNever<T>> : Promise<unknown> text(): F extends 'text' ? (T extends string ? Promise<T> : Promise<never>) : Promise<string> blob(): Promise<Blob> formData(): Promise<FormData> arrayBuffer(): Promise<ArrayBuffer>}2 unmodified lines
export type Fetch<T> = ( args?: InferRequestType<T>, opt?: ClientRequestOptions) => Promise<ClientResponse<InferResponseType<T>>>) => Promise<ClientResponseOfEndpoint<InferEndpointType<T>>>
export type InferResponseType<T> = T extends (type InferEndpointType<T> = T extends ( args: infer R, // eslint-disable-next-line @typescript-eslint/no-explicit-any args: any | undefined, // eslint-disable-next-line @typescript-eslint/no-explicit-any options: any | undefined) => Promise<ClientResponse<infer O>> ? O) => Promise<infer U> ? U extends ClientResponse<infer O, infer S, infer F> ? { input: NonNullable<R>; output: O; outputFormat: F; status: S } extends Endpoint ? { input: NonNullable<R>; output: O; outputFormat: F; status: S } : never : never : never
export type InferResponseType<T, U extends StatusCode = StatusCode> = InferResponseTypeFromEndpoint< InferEndpointType<T>, U>
type InferResponseTypeFromEndpoint<T extends Endpoint, U extends StatusCode> = T extends { output: infer O status: infer S} ? S extends U ? O : never : never
export type InferRequestType<T> = T extends ( args: infer R, // eslint-disable-next-line @typescript-eslint/no-explicit-any options: any | undefined46 unmodified linesmodified:deno_dist/helper/cookie/index.ts+3 added-1 removed
116 unmodified lines117 }118 c.header('set-cookie', cookie, { append: true })119 }120 121-export const deleteCookie = (c: Context, name: string, opt?: CookieOptions): void => {121+export const deleteCookie = (c: Context, name: string, opt?: CookieOptions) => {122+ const deletedCookie = getCookie(c, name)123 setCookie(c, name, '', { ...opt, maxAge: 0 })124+ return deletedCookie125 }modified:deno_dist/helper/factory/index.ts+24 added-1 removed
1 /* eslint-disable @typescript-eslint/no-explicit-any */2+import { Hono } from '../../hono.ts'3 import type { Env, H, HandlerResponse, Input, MiddlewareHandler } from '../../types.ts'4 5+type InitApp<E extends Env = Env> = (app: Hono<E>) => void6+7 export class Factory<E extends Env = any, P extends string = any> {8+ private initApp?: InitApp<E>9+10+ constructor(init?: { initApp?: InitApp<E> }) {11+ this.initApp = init?.initApp12+ }13+14+ /**15+ * @experimental16+ * `createApp` is an experimental feature.17+ */18+ createApp = () => {19+ const app = new Hono<E>()20+ if (this.initApp) {21+ this.initApp(app)22+ }23+ return app24+ }25+26 createMiddleware = <I extends Input = {}>(middleware: MiddlewareHandler<E, P, I>) => middleware27 28 createHandlers<I extends Input = {}, R extends HandlerResponse<any> = any>(29 handler1: H<E, P, I, R>199 unmodified lines229 return handlers.filter((handler) => handler !== undefined)230 }231 }232 212-export const createFactory = <E extends Env = any, P extends string = any>() => new Factory<E, P>()233+export const createFactory = <E extends Env = any, P extends string = any>(init?: {234+ initApp?: InitApp<E>235+}) => new Factory<E, P>(init)236 237 export const createMiddleware = <E extends Env = any, P extends string = any, I extends Input = {}>(238 middleware: MiddlewareHandler<E, P, I>239 ) => createFactory<E, P>().createMiddleware<I>(middleware)modified:deno_dist/helper/websocket/index.ts+1 added-5 removed
10 unmodified lines11 onClose?: (evt: CloseEvent, ws: WSContext) => void12 onError?: (evt: Event, ws: WSContext) => void13 }14 15-export type UpgradedWebSocketResponseInputJSONType = '__websocket'16-15 /**16 * Upgrade WebSocket Type17 */18 export type UpgradeWebSocket = (1 unmodified line20 ) => MiddlewareHandler<21 any,22 string,23 {26- in: {27- json: UpgradedWebSocketResponseInputJSONType28- }24+ outputFormat: 'ws'25 }26 >27 28 export type WSReadyState = 0 | 1 | 2 | 323 unmodified linesmodified:deno_dist/jsx/dom/context.ts+25 added-13 removed
1 unmodified line2 import { DOM_ERROR_HANDLER } from '../constants.ts'3 import type { Context } from '../context.ts'4 import { globalContexts } from '../context.ts'5 import { Fragment } from './jsx-runtime.ts'6+import { setInternalTagFlag } from './utils.ts'7 7-export const createContextProviderFunction =8- <T>(values: T[]) =>9- ({ value, children }: { value: T; children: Child[] }) => {10- const res = Fragment({8+export const createContextProviderFunction = <T>(values: T[]) =>9+ setInternalTagFlag(({ value, children }: { value: T; children: Child[] }) => {10+ if (!children) {11+ return undefined12+ }13+14+ // eslint-disable-next-line @typescript-eslint/no-explicit-any15+ const props: { children: any } = {16 children: [17 {13- tag: () => {18+ tag: setInternalTagFlag(() => {19 values.push(value)15- },20+ }),21+ props: {},22 },17- ...(children as Child[]),18- {19- tag: () => {20- values.pop()21- },22- },23 ],24+ }25+ if (Array.isArray(children)) {26+ props.children.push(...children.flat())27+ } else {28+ props.children.push(children)29+ }30+ props.children.push({31+ tag: setInternalTagFlag(() => {32+ values.pop()33+ }),34+ props: {},35 })36+ const res = Fragment(props)37 // eslint-disable-next-line @typescript-eslint/no-explicit-any38 ;(res as any)[DOM_ERROR_HANDLER] = (err: unknown) => {39 values.pop()40 throw err41 }42 return res31- }43+ })44 45 export const createContext = <T>(defaultValue: T): Context<T> => {46 const values = [defaultValue]47 const context = {7 unmodified linesmodified:deno_dist/jsx/dom/css.ts+8 added-4 removed
108 unmodified lines109 // eslint-disable-next-line @typescript-eslint/no-explicit-any110 const Style: FC<PropsWithChildren<void>> = ({ children }) =>111 ({112 tag: 'style',113+ props: {114+ id,115+ children:116+ children &&113- children: (Array.isArray(children) ? children : [children]).map(114- (c) => (c as unknown as CssClassName)[STYLE_STRING]115- ),116- props: { id },117+ (Array.isArray(children) ? children : [children]).map(118+ (c) => (c as unknown as CssClassName)[STYLE_STRING]119+ ),120+ },121 // eslint-disable-next-line @typescript-eslint/no-explicit-any122 } as any)123 124 return [cssObject, Style] as const86 unmodified linesmodified:deno_dist/jsx/dom/index.ts+36 added-5 removed
1-import type { Props, Child, JSXNode } from '../base.ts'1+import type { Props, Child, DOMAttributes, JSXNode } from '../base.ts'2 import { memo, isValidElement } from '../base.ts'3+import { Children } from '../children.ts'4 import { useContext } from '../context.ts'5 import {6 useState,7 useEffect,9 unmodified lines17 useLayoutEffect,18 useReducer,19 useId,20 useDebugValue,21+ createRef,22+ forwardRef,23+ useImperativeHandle,24+ useSyncExternalStore,25 } from '../hooks/index.ts'26 import { Suspense, ErrorBoundary } from './components.ts'27 import { createContext } from './context.ts'23-import { jsx } from './jsx-runtime.ts'28+import { jsx, Fragment } from './jsx-runtime.ts'29+import { flushSync, createPortal } from './render.ts'30 31 export { render } from './render.ts'32 33 const createElement = (34 tag: string | ((props: Props) => JSXNode),29- props: Props,35+ props: Props | null,36 ...children: Child[]37 ): JSXNode => {32- const jsxProps: Props = { ...props, children }38+ const jsxProps: Props = props ? { ...props } : {}39+ if (children.length) {40+ jsxProps.children = children.length === 1 ? children[0] : children41+ }42+43 let key = undefined44 if ('key' in jsxProps) {45 key = jsxProps.key46 delete jsxProps.key11 unmodified lines58 (element as JSXNode).tag,59 {60 ...(element as JSXNode).props,61 ...props,52- children: children.length ? children : (element as JSXNode).children,62+ children: children.length ? children : (element as JSXNode).props.children,63 },64 (element as JSXNode).key65 ) as T66 }14 unmodified lines81 useLayoutEffect,82 useReducer,83 useId,84 useDebugValue,85+ createRef,86+ forwardRef,87+ useImperativeHandle,88+ useSyncExternalStore,89 Suspense,90 ErrorBoundary,91 createContext,92 useContext,93 memo,94 isValidElement,95 createElement,96 cloneElement,97+ Children,98+ Fragment,99+ DOMAttributes,100+ flushSync,101+ createPortal,102 }103 104 export default {105 useState,10 unmodified lines116 useLayoutEffect,117 useReducer,118 useId,119 useDebugValue,120+ createRef,121+ forwardRef,122+ useImperativeHandle,123+ useSyncExternalStore,124 Suspense,125 ErrorBoundary,126 createContext,127 useContext,128 memo,129 isValidElement,130 createElement,131 cloneElement,132+ Children,133+ Fragment,134+ flushSync,135+ createPortal,136 }137 138 export type { Context } from '../context.ts'139+140+// TODO: change to `export type *` after denoify bug is fixed141+// https://github.com/garronej/denoify/issues/124142+export * from '../types.ts'modified:deno_dist/jsx/dom/jsx-dev-runtime.ts+23 added-15 removed
1-import type { Props } from '../base.ts'1+import type { Props, JSXNode } from '../base.ts'2 import { normalizeIntrinsicElementProps } from '../utils.ts'3 4+const JSXNodeCompatPrototype = {5+ type: {6+ get(this: { tag: string | Function }): string | Function {7+ return this.tag8+ },9+ },10+ ref: {11+ get(this: { props?: { ref: unknown } }): unknown {12+ return this.props?.ref13+ },14+ },15+}16+4-export const jsxDEV = (tag: string | Function, props: Props, key?: string) => {17+export const jsxDEV = (tag: string | Function, props: Props, key?: string): JSXNode => {18 if (typeof tag === 'string') {19 normalizeIntrinsicElementProps(props)20 }8- let children9- if (props && 'children' in props) {10- children = props.children11- delete props['children']12- } else {13- children = []14- }15- return {16- tag,17- props,18- key,19- children: Array.isArray(children) ? children : [children],20- }21+ return Object.defineProperties(22+ {23+ tag,24+ props,25+ key,26+ },27+ JSXNodeCompatPrototype28+ ) as JSXNode29 }30 31 export const Fragment = (props: Record<string, unknown>) => jsxDEV('', props, undefined)modified:deno_dist/jsx/dom/render.ts+130 added-51 removed
1 import type { JSXNode } from '../base.ts'2 import type { FC, Child, Props } from '../base.ts'3+import { toArray } from '../children.ts'3-import { DOM_RENDERER, DOM_ERROR_HANDLER, DOM_STASH } from '../constants.ts'4+import { DOM_RENDERER, DOM_ERROR_HANDLER, DOM_STASH, DOM_INTERNAL_TAG } from '../constants.ts'5 import type { Context as JSXContext } from '../context.ts'6 import { globalContexts as globalJSXContexts, useContext } from '../context.ts'7 import type { EffectData } from '../hooks/index.ts'8 import { STASH_EFFECT } from '../hooks/index.ts'9+import { styleObjectForEach } from '../utils.ts'10 import { createContext } from './context.ts' // import dom-specific versions11 12+const HONO_PORTAL_ELEMENT = '_hp'13+14 const eventAliasMap: Record<string, string> = {15 Change: 'Input',16 DoubleClick: 'DblClick',17 } as const2 unmodified lines20 svg: 'http://www.w3.org/2000/svg',21 math: 'http://www.w3.org/1998/Math/MathML',22 } as const23 24+const skipProps = new Set(['children'])25+26 // eslint-disable-next-line @typescript-eslint/no-explicit-any27 export type HasRenderToDom = FC<any> & { [DOM_RENDERER]: FC<any> }28 // eslint-disable-next-line @typescript-eslint/no-explicit-any29 export type ErrorHandler = (error: any, retry: () => void) => Child | undefined23 unmodified lines53 // eslint-disable-next-line @typescript-eslint/no-explicit-any54 any[][]55 ]56 } & JSXNode51-type NodeString = [52- string, // text content53- boolean // is dirty54-] & {57+type NodeString = {58+ t: string // text content59+ d: boolean // is dirty60+} & {61 e?: Text62 // like a NodeObject63 vC: undefined64 nN: undefined27 unmodified lines92 export const buildDataStack: [Context, Node][] = []93 94 let nameSpaceContext: JSXContext<string> | undefined = undefined95 90-const isNodeString = (node: Node): node is NodeString => Array.isArray(node)96+const isNodeString = (node: Node): node is NodeString => 't' in (node as NodeString)97 98 const getEventSpec = (key: string): [string, boolean] | undefined => {99 const match = key.match(/^on([A-Z][a-zA-Z]+?(?:PointerCapture)?)(Capture)?$/)100 if (match) {5 unmodified lines106 107 const applyProps = (container: SupportedElement, attributes: Props, oldAttributes?: Props) => {108 attributes ||= {}109 for (const [key, value] of Object.entries(attributes)) {104- if (!oldAttributes || oldAttributes[key] !== value) {110+ if (!skipProps.has(key) && (!oldAttributes || oldAttributes[key] !== value)) {111 const eventSpec = getEventSpec(key)112 if (eventSpec) {107- if (typeof value !== 'function') {108- throw new Error(`Event handler for "${key}" is not a function`)109- }110-113 if (oldAttributes) {114 container.removeEventListener(eventSpec[0], oldAttributes[key], eventSpec[1])115 }116+ if (value != null) {117+ if (typeof value !== 'function') {118+ throw new Error(`Event handler for "${key}" is not a function`)119+ }114- container.addEventListener(eventSpec[0], value, eventSpec[1])120+ container.addEventListener(eventSpec[0], value, eventSpec[1])121+ }122 } else if (key === 'dangerouslySetInnerHTML' && value) {123 container.innerHTML = value.__html124 } else if (key === 'ref') {125 if (typeof value === 'function') {126 value(container)120- } else if ('current' in value) {127+ } else if (value && 'current' in value) {128 value.current = container129 }130 } else if (key === 'style') {131+ const style = container.style132 if (typeof value === 'string') {125- container.style.cssText = value133+ style.cssText = value134 } else {127- container.style.cssText = ''128- Object.assign(container.style, value)135+ style.cssText = ''136+ if (value != null) {137+ styleObjectForEach(value, style.setProperty.bind(style))138+ }139 }140 } else {141 const nodeName = container.nodeName142 if (key === 'value') {32 unmodified lines175 }176 }177 if (oldAttributes) {178 for (const [key, value] of Object.entries(oldAttributes)) {169- if (!(key in attributes)) {179+ if (!skipProps.has(key) && !(key in attributes)) {180 const eventSpec = getEventSpec(key)181 if (eventSpec) {182 container.removeEventListener(eventSpec[0], value, eventSpec[1])183 } else if (key === 'ref') {22 unmodified lines206 const func = (node.tag as HasRenderToDom)[DOM_RENDERER] || node.tag207 try {208 return [209 func.call(null, {210+ // eslint-disable-next-line @typescript-eslint/no-explicit-any211+ ...((func as any).defaultProps || {}),212 ...node.props,201- children: node.children,213 }),214 ]215 } finally {216 buildDataStack.pop()47 unmodified lines264 265 const removeNode = (node: Node) => {266 if (!isNodeString(node)) {267 node[DOM_STASH]?.[1][STASH_EFFECT]?.forEach((data: EffectData) => data[2]?.())268+269+ if (node.e && node.props?.ref) {270+ if (typeof node.props.ref === 'function') {271+ node.props.ref(null)272+ } else {273+ node.props.ref.current = null274+ }275+ }276 node.vC?.forEach(removeNode)277 }259- node.e?.remove()260- node.tag = undefined278+ if (node.tag !== HONO_PORTAL_ELEMENT) {279+ node.e?.remove()280+ }281+ if (typeof node.tag === 'function') {282+ updateMap.delete(node)283+ fallbackUpdateFnArrayMap.delete(node)284+ }285 }286 287 const apply = (node: NodeObject, container: Container) => {264- if (node.tag === undefined) {265- return266- }267-288 node.c = container289 applyNodeObject(node, container)290 }291 292 const applyNode = (node: Node, container: Container) => {293 if (isNodeString(node)) {274- container.textContent = node[0]294+ container.textContent = node.t295 } else {296 applyNodeObject(node, container)297 }298 }31 unmodified lines330 const child = next[i]331 332 let el: SupportedElement | Text333 if (isNodeString(child)) {314- if (child.e && child[1]) {315- child.e.textContent = child[0]334+ if (child.e && child.d) {335+ child.e.textContent = child.t336 }317- child[1] = false318- el = child.e ||= document.createTextNode(child[0])337+ child.d = false338+ el = child.e ||= document.createTextNode(child.t)339 } else {340 el = child.e ||= child.n341 ? (document.createElementNS(child.n, child.tag as string) as SVGElement | MathMLElement)342 : document.createElement(child.tag as string)343 applyProps(el as HTMLElement, child.props, child.pP)344 applyNode(child, el as HTMLElement)345 }326- if (childNodes[offset] !== el && childNodes[offset - 1] !== child.e) {346+ if (347+ childNodes[offset] !== el &&348+ childNodes[offset - 1] !== child.e &&349+ child.tag !== HONO_PORTAL_ELEMENT350+ ) {351 container.insertBefore(el, childNodes[offset] || null)352 }353 }354 remove.forEach(removeNode)2 unmodified lines357 callbacks.forEach(([, , , cb]) => cb?.())358 })359 }360 361+const fallbackUpdateFnArrayMap = new WeakMap<362+ NodeObject,363+ Array<() => Promise<NodeObject | undefined>>364+>()365 export const build = (366 context: Context,367 node: NodeObject,368 topLevelErrorHandlerNode: NodeObject | undefined,369 children?: Child[]370 ): void => {343- if (node.tag === undefined) {344- return345- }346-371 let errorHandler: ErrorHandler | undefined348- children ||= typeof node.tag == 'function' ? invokeTag(context, node) : node.children372+ children ||=373+ typeof node.tag == 'function' ? invokeTag(context, node) : toArray(node.props.children)374 if ((children[0] as JSXNode)?.tag === '') {375 // eslint-disable-next-line @typescript-eslint/no-explicit-any376 errorHandler = (children[0] as any)[DOM_ERROR_HANDLER] as ErrorHandler377 topLevelErrorHandlerNode ||= node10 unmodified lines388 prevNode.nN = child389 }390 prevNode = child391 367- if (typeof child.tag === 'function' && globalJSXContexts.length > 0) {392+ if (393+ typeof child.tag === 'function' &&394+ // eslint-disable-next-line @typescript-eslint/no-explicit-any395+ !(child.tag as any)[DOM_INTERNAL_TAG] &&396+ globalJSXContexts.length > 0397+ ) {398 child[DOM_STASH][2] = globalJSXContexts.map((c) => [c, c.values.at(-1)])399 }400 401 let oldChild: Node | undefined7 unmodified lines409 if (isNodeString(child)) {410 if (!isNodeString(oldChild)) {411 vChildrenToRemove.push(oldChild)412 } else {383- if (oldChild[0] !== child[0]) {384- oldChild[0] = child[0] // update text content385- oldChild[1] = true413+ if (oldChild.t !== child.t) {414+ oldChild.t = child.t // update text content415+ oldChild.d = true416 }417 child = oldChild418 }419 } else if (oldChild.tag !== child.tag) {420 vChildrenToRemove.push(oldChild)421 } else {422 oldChild.pP = oldChild.props423 oldChild.props = child.props394- oldChild.children = child.children424+ if (typeof child.tag === 'function') {425+ oldChild[DOM_STASH][2] = child[DOM_STASH][2] || []426+ }427 child = oldChild428 }429 } else if (!isNodeString(child) && nameSpaceContext) {430 const ns = useContext(nameSpaceContext)12 unmodified lines443 vChildrenToRemove.push(...oldVChildren)444 node.vR = vChildrenToRemove445 } catch (e) {446 if (errorHandler) {415- const fallback = errorHandler(e, () =>447+ const fallbackUpdateFn = () =>448 update([0, false, context[2] as UpdateHook], topLevelErrorHandlerNode as NodeObject)417- )449+ const fallbackUpdateFnArray =450+ fallbackUpdateFnArrayMap.get(topLevelErrorHandlerNode as NodeObject) || []451+ fallbackUpdateFnArray.push(fallbackUpdateFn)452+ fallbackUpdateFnArrayMap.set(topLevelErrorHandlerNode as NodeObject, fallbackUpdateFnArray)453+ const fallback = errorHandler(e, () => {454+ const fnArray = fallbackUpdateFnArrayMap.get(topLevelErrorHandlerNode as NodeObject)455+ if (fnArray) {456+ const i = fnArray.indexOf(fallbackUpdateFn)457+ if (i !== -1) {458+ fnArray.splice(i, 1)459+ return fallbackUpdateFn()460+ }461+ }462+ })463 if (fallback) {464 if (context[0] === 1) {465 context[1] = true466 } else {9 unmodified lines476 const buildNode = (node: Child): Node | undefined => {477 if (node === undefined || node === null || typeof node === 'boolean') {478 return undefined479 } else if (typeof node === 'string' || typeof node === 'number') {435- return [node.toString(), true] as NodeString480+ return { t: node.toString(), d: true } as NodeString481 } else {482 if (typeof (node as JSXNode).tag === 'function') {483+ if ((node as NodeObject)[DOM_STASH]) {484+ node = { ...node } as NodeObject485+ }486 ;(node as NodeObject)[DOM_STASH] = [0, []]487 } else {488 const ns = nameSpaceMap[(node as JSXNode).tag as string]489 if (ns) {490 ;(node as NodeObject).n = ns491 nameSpaceContext ||= createContext('')444- ;(node as JSXNode).children = [492+ ;(node as JSXNode).props.children = [493 {494 tag: nameSpaceContext.Provider,495 props: {496 value: ns,497+ children: (node as JSXNode).props.children,498 },450- children: (node as JSXNode).children,499 },500 // eslint-disable-next-line @typescript-eslint/no-explicit-any501 ] as any502 }23 unmodified lines526 }527 528 type UpdateMapResolve = (node: NodeObject | undefined) => void529 const updateMap = new WeakMap<NodeObject, [UpdateMapResolve, Function]>()530+const currentUpdateSets: Set<NodeObject>[] = []531 export const update = async (532 context: Context,533 node: NodeObject534 ): Promise<NodeObject | undefined> => {18 unmodified lines553 }554 },555 ])556 557+ if (currentUpdateSets.length) {558+ ;(currentUpdateSets.at(-1) as Set<NodeObject>).add(node)559+ } else {508- await Promise.resolve()560+ await Promise.resolve()561 510- const latest = updateMap.get(node)511- if (latest) {512- updateMap.delete(node)513- latest[1]()562+ const latest = updateMap.get(node)563+ if (latest) {564+ updateMap.delete(node)565+ latest[1]()566+ }567 }568 569 return promise570 }571 572 export const render = (jsxNode: unknown, container: Container) => {573+ // eslint-disable-next-line @typescript-eslint/no-explicit-any520- const node = buildNode({ tag: '', children: [jsxNode] } as JSXNode) as NodeObject574+ const node = buildNode({ tag: '', props: { children: jsxNode } } as any) as NodeObject575 build([], node, undefined)576 577 const fragment = document.createDocumentFragment()578 apply(node, fragment)579 replaceContainer(node, fragment, container)580 container.replaceChildren(fragment)581 }582+583+export const flushSync = (callback: () => void) => {584+ const set = new Set<NodeObject>()585+ currentUpdateSets.push(set)586+ callback()587+ set.forEach((node) => {588+ const latest = updateMap.get(node)589+ if (latest) {590+ updateMap.delete(node)591+ latest[1]()592+ }593+ })594+ currentUpdateSets.pop()595+}596+597+export const createPortal = (children: Child, container: HTMLElement, key?: string): Child =>598+ ({599+ tag: HONO_PORTAL_ELEMENT,600+ props: {601+ children,602+ },603+ key,604+ e: container,605+ // eslint-disable-next-line @typescript-eslint/no-explicit-any606+ } as any)added:deno_dist/jsx/dom/utils.ts+7 added
1+import { DOM_INTERNAL_TAG } from '../constants.ts'2+3+export const setInternalTagFlag = (fn: Function) => {4+ // eslint-disable-next-line @typescript-eslint/no-explicit-any5+ ;(fn as any)[DOM_INTERNAL_TAG] = true6+ return fn7+}modified:deno_dist/jsx/hooks/index.ts+50 added-1 removed
164 unmodified lines165 if (typeof newState === 'function') {166 newState = (newState as (currentState: T) => T)(stateData[0])167 }168 169- if (newState !== stateData[0]) {169+ if (!Object.is(newState, stateData[0])) {170 stateData[0] = newState171 if (pendingStack.length) {172 const pendingType = pendingStack.at(-1) as PendingType173 update([pendingType, false, localUpdateHook as UpdateHook], node).then((node) => {186 unmodified lines360 361 // Define to avoid errors. This hook currently does nothing.362 // eslint-disable-next-line @typescript-eslint/no-unused-vars363 export const useDebugValue = (_value: unknown, _formatter?: (value: unknown) => string): void => {}364+365+export const createRef = <T>(): RefObject<T> => {366+ return { current: null }367+}368+369+export const forwardRef = <T, P = {}>(370+ Component: (props: P, ref: RefObject<T>) => JSX.Element371+): ((props: P & { ref: RefObject<T> }) => JSX.Element) => {372+ return (props) => {373+ const { ref, ...rest } = props374+ return Component(rest as P, ref)375+ }376+}377+378+export const useImperativeHandle = <T>(379+ ref: RefObject<T>,380+ createHandle: () => T,381+ deps: readonly unknown[]382+): void => {383+ useEffect(() => {384+ ref.current = createHandle()385+ return () => {386+ ref.current = null387+ }388+ }, deps)389+}390+391+let useSyncExternalStoreGetServerSnapshotNotified = false392+export const useSyncExternalStore = <T>(393+ subscribe: (callback: (value: T) => void) => () => void,394+ getSnapshot: () => T,395+ getServerSnapshot?: () => T396+): T => {397+ const [state, setState] = useState(getSnapshot())398+ useEffect(399+ () =>400+ subscribe(() => {401+ setState(getSnapshot())402+ }),403+ []404+ )405+406+ if (getServerSnapshot && !useSyncExternalStoreGetServerSnapshotNotified) {407+ useSyncExternalStoreGetServerSnapshotNotified = true408+ console.info('`getServerSnapshot` is not supported yet.')409+ }410+411+ return state412+}modified:deno_dist/jsx/base.ts+44 added-29 removed
2 unmodified lines3 import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../utils/html.ts'4 import type { Context } from './context.ts'5 import { globalContexts } from './context.ts'6 import type { IntrinsicElements as IntrinsicElementsDefined } from './intrinsic-elements.ts'7-import { normalizeIntrinsicElementProps } from './utils.ts'7+import { normalizeIntrinsicElementProps, styleObjectForEach } from './utils.ts'8 9 // eslint-disable-next-line @typescript-eslint/no-explicit-any10 export type Props = Record<string, any>11-export type FC<T = Props> = (props: T) => HtmlEscapedString | Promise<HtmlEscapedString>11+export type FC<P = Props> = {12+ (props: P): HtmlEscapedString | Promise<HtmlEscapedString>13+ defaultProps?: Partial<P> | undefined14+ displayName?: string | undefined15+}16+export type DOMAttributes = Hono.HTMLAttributes17 18 declare global {19 // eslint-disable-next-line @typescript-eslint/no-namespace20 namespace JSX {97 unmodified lines118 this.props = props119 this.children = children120 }121 122+ get type(): string | Function {123+ return this.tag as string124+ }125+126+ // Added for compatibility with libraries that rely on React's internal structure127+ // eslint-disable-next-line @typescript-eslint/no-explicit-any128+ get ref(): any {129+ return this.props.ref || null130+ }131+132 toString(): string | Promise<string> {133 const buffer: StringBuffer = ['']134 this.localContexts?.forEach(([context, value]) => {135 context.values.push(value)19 unmodified lines155 156 for (let i = 0, len = propsKeys.length; i < len; i++) {157 const key = propsKeys[i]158 const v = props[key]144- // object to style strings145- if (key === 'style' && typeof v === 'object') {146- const styles = Object.keys(v)147- .map((k) => {148- const property = k.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`)149- return `${property}:${v[k]}`150- })151- .join(';')159+ if (key === 'children') {160+ // skip children161+ } else if (key === 'style' && typeof v === 'object') {162+ // object to style strings163+ let styleStr = ''164+ styleObjectForEach(v, (property, value) => {165+ if (value != null) {166+ styleStr += `${styleStr ? ';' : ''}${property}:${value}`167+ }168+ })169 buffer[0] += ' style="'153- escapeToBuffer(styles, buffer)170+ escapeToBuffer(styleStr, buffer)171 buffer[0] += '"'172 } else if (typeof v === 'string') {173 buffer[0] += ` ${key}="`174 escapeToBuffer(v, buffer)82 unmodified lines257 }258 259 export const jsx = (260 tag: string | Function,244- props: Props,245- ...children: (string | HtmlEscapedString)[]261+ props: Props | null,262+ ...children: (string | number | HtmlEscapedString)[]263 ): JSXNode => {247- let key248- if (props) {249- key = props?.key250- delete props['key']264+ props ??= {}265+ if (children.length) {266+ props.children = children.length === 1 ? children[0] : children267 }268+269+ const key = props.key270+ delete props['key']271+272 const node = jsxFn(tag, props, children)273 node.key = key274 return node275 }276 277 export const jsxFn = (278 tag: string | Function,279 props: Props,260- children: (string | HtmlEscapedString)[]280+ children: (string | number | HtmlEscapedString)[]281 ): JSXNode => {282 if (typeof tag === 'function') {283 return new JSXFunctionNode(tag, props, children)284 } else {51 unmodified lines336 children?: Child | HtmlEscapedString337 }): HtmlEscapedString => {338 return new JSXFragmentNode(339 '',320- {},340+ {341+ children,342+ },343 Array.isArray(children) ? children : children ? [children] : []344 ) as never345 }346 347 export const isValidElement = (element: unknown): element is JSXNode => {326- return !!(327- element &&328- typeof element === 'object' &&329- 'tag' in element &&330- 'props' in element &&331- 'children' in element332- )348+ return !!(element && typeof element === 'object' && 'tag' in element && 'props' in element)349 }350 351 export const cloneElement = <T extends JSXNode | JSX.Element>(352 element: T,353 props: Partial<Props>,354 ...children: Child[]355 ): T => {340- return jsxFn(356+ return jsx(357 (element as JSXNode).tag,358 { ...(element as JSXNode).props, ...props },343- // eslint-disable-next-line @typescript-eslint/no-explicit-any344- children.length ? children : ((element as JSXNode).children as any) || []359+ ...(children as (string | number | HtmlEscapedString)[])360 ) as T361 }added:deno_dist/jsx/children.ts+20 added
1+import type { Child } from './base.ts'2+3+export const toArray = (children: Child): Child[] =>4+ Array.isArray(children) ? children : [children]5+export const Children = {6+ map: (children: Child[], fn: (child: Child, index: number) => Child): Child[] =>7+ toArray(children).map(fn),8+ forEach: (children: Child[], fn: (child: Child, index: number) => void): void => {9+ toArray(children).forEach(fn)10+ },11+ count: (children: Child[]): number => toArray(children).length,12+ only: (_children: Child[]): Child => {13+ const children = toArray(_children)14+ if (children.length !== 1) {15+ throw new Error('Children.only() expects only one child')16+ }17+ return children[0]18+ },19+ toArray,20+}modified:deno_dist/jsx/constants.ts+1 added
1 export const DOM_RENDERER = Symbol('RENDERER')2 export const DOM_ERROR_HANDLER = Symbol('ERROR_HANDLER')3 export const DOM_STASH = Symbol('STASH')4+export const DOM_INTERNAL_TAG = Symbol('INTERNAL')modified:deno_dist/jsx/index.ts+17 added
1 import { jsx, memo, Fragment, isValidElement, cloneElement } from './base.ts'2+import type { DOMAttributes } from './base.ts'3+import { Children } from './children.ts'4 import { ErrorBoundary } from './components.ts'5 import { createContext, useContext } from './context.ts'6 import {7 useState,10 unmodified lines18 useLayoutEffect,19 useReducer,20 useId,21 useDebugValue,22+ createRef,23+ forwardRef,24+ useImperativeHandle,25+ useSyncExternalStore,26 } from './hooks/index.ts'27 import { Suspense } from './streaming.ts'28 29 export {20 unmodified lines50 startViewTransition,51 useViewTransition,52 useMemo,53 useLayoutEffect,54+ createRef,55+ forwardRef,56+ useImperativeHandle,57+ useSyncExternalStore,58 Suspense,59+ Children,60+ DOMAttributes,61 }62 63 export default {64 memo,18 unmodified lines83 startViewTransition,84 useViewTransition,85 useMemo,86 useLayoutEffect,87+ createRef,88+ forwardRef,89+ useImperativeHandle,90+ useSyncExternalStore,91 Suspense,92+ Children,93 }94 95 // TODO: change to `export type *` after denoify bug is fixed96 // https://github.com/garronej/denoify/issues/1241 unmodified linemodified:deno_dist/jsx/jsx-dev-runtime.ts-1 removed
11 unmodified lines12 if (!props || !('children' in props)) {13 node = jsxFn(tag, props, [])14 } else {15 const children = props.children as string | HtmlEscapedString16- delete props['children']16 node = Array.isArray(children) ? jsxFn(tag, props, children) : jsxFn(tag, props, [children])17 }18 node.key = key19 return node1 unmodified linemodified:deno_dist/jsx/types.ts+30 added-1 removed
1 /**2 * All types exported from "hono/jsx" are in this file.3 */4-import type { Child } from './base.ts'4+import type { Child, JSXNode } from './base.ts'5 6 export type { Child, JSXNode, FC } from './base.ts'7 export type { RefObject } from './hooks/index.ts'8 export type { Context } from './context.ts'9 10 export type PropsWithChildren<P = unknown> = P & { children?: Child | undefined }11 export type CSSProperties = Hono.CSSProperties12+13+/**14+ * React types15+ */16+17+// eslint-disable-next-line @typescript-eslint/no-explicit-any18+type ReactElement<P = any, T = string | Function> = JSXNode & {19+ type: T20+ props: P21+ key: string | null22+}23+type ReactNode = ReactElement | string | number | boolean | null | undefined24+// eslint-disable-next-line @typescript-eslint/no-unused-vars25+type ComponentClass<P = {}, S = {}> = unknown26+27+export type { ReactElement, ReactNode, ComponentClass }28+29+export type Event = globalThis.Event30+export type MouseEvent = globalThis.MouseEvent31+export type KeyboardEvent = globalThis.KeyboardEvent32+export type FocusEvent = globalThis.FocusEvent33+export type ClipboardEvent = globalThis.ClipboardEvent34+export type InputEvent = globalThis.InputEvent35+export type PointerEvent = globalThis.PointerEvent36+export type TouchEvent = globalThis.TouchEvent37+export type WheelEvent = globalThis.WheelEvent38+export type AnimationEvent = globalThis.AnimationEvent39+export type TransitionEvent = globalThis.TransitionEvent40+export type DragEvent = globalThis.DragEventmodified:deno_dist/jsx/utils.ts+14 added
2 unmodified lines3 props['class'] = props['className']4 delete props['className']5 }6 }7+8+export const styleObjectForEach = (9+ style: Record<string, string>,10+ fn: (key: string, value: string | null) => void11+): void => {12+ for (const [k, v] of Object.entries(style)) {13+ fn(14+ k[0] === '-'15+ ? k // CSS variable16+ : k.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`), // style property. convert to kebab-case17+ v == null ? null : typeof v === 'number' ? v + 'px' : (v as string)18+ )19+ }20+}modified:deno_dist/middleware/bearer-auth/index.ts+4 added-1 removed
3 unmodified lines4 import { timingSafeEqual } from '../../utils/buffer.ts'5 6 const TOKEN_STRINGS = '[A-Za-z0-9._~+/-]+=*'7 const PREFIX = 'Bearer'8+const HEADER = 'Authorization'9 10 type BearerAuthOptions =11 | {12 token: string | string[]13 realm?: string14 prefix?: string15+ headerName?: string16 hashFunction?: Function17 }18 | {19 realm?: string20 prefix?: string21+ headerName?: string22 verifyToken: (token: string, c: Context) => boolean | Promise<boolean>23 hashFunction?: Function24 }25 10 unmodified lines36 37 const realm = options.realm?.replace(/"/g, '\\"')38 39 return async function bearerAuth(c, next) {37- const headerToken = c.req.header('Authorization')40+ const headerToken = c.req.header(options.headerName || HEADER)41 42 if (!headerToken) {43 // No Authorization header44 const res = new Response('Unauthorized', {47 unmodified linesmodified:deno_dist/middleware/secure-headers/index.ts+108 added-32 removed
1+import { Buffer } from "node:buffer";2 import type { Context } from '../../context.ts'3 import type { MiddlewareHandler } from '../../types.ts'4 5+declare module '../../context.ts' {6+ interface ContextVariableMap {7+ secureHeadersNonce?: string8+ }9+}10+11+export type ContentSecurityPolicyOptionHandler = (ctx: Context, directive: string) => string12+type ContentSecurityPolicyOptionValue = (string | ContentSecurityPolicyOptionHandler)[]13+14 interface ContentSecurityPolicyOptions {5- defaultSrc?: string[]6- baseUri?: string[]7- childSrc?: string[]8- connectSrc?: string[]9- fontSrc?: string[]10- formAction?: string[]11- frameAncestors?: string[]12- frameSrc?: string[]13- imgSrc?: string[]14- manifestSrc?: string[]15- mediaSrc?: string[]16- objectSrc?: string[]15+ defaultSrc?: ContentSecurityPolicyOptionValue16+ baseUri?: ContentSecurityPolicyOptionValue17+ childSrc?: ContentSecurityPolicyOptionValue18+ connectSrc?: ContentSecurityPolicyOptionValue19+ fontSrc?: ContentSecurityPolicyOptionValue20+ formAction?: ContentSecurityPolicyOptionValue21+ frameAncestors?: ContentSecurityPolicyOptionValue22+ frameSrc?: ContentSecurityPolicyOptionValue23+ imgSrc?: ContentSecurityPolicyOptionValue24+ manifestSrc?: ContentSecurityPolicyOptionValue25+ mediaSrc?: ContentSecurityPolicyOptionValue26+ objectSrc?: ContentSecurityPolicyOptionValue27 reportTo?: string18- sandbox?: string[]19- scriptSrc?: string[]20- scriptSrcAttr?: string[]21- scriptSrcElem?: string[]22- styleSrc?: string[]23- styleSrcAttr?: string[]24- styleSrcElem?: string[]25- upgradeInsecureRequests?: string[]26- workerSrc?: string[]28+ sandbox?: ContentSecurityPolicyOptionValue29+ scriptSrc?: ContentSecurityPolicyOptionValue30+ scriptSrcAttr?: ContentSecurityPolicyOptionValue31+ scriptSrcElem?: ContentSecurityPolicyOptionValue32+ styleSrc?: ContentSecurityPolicyOptionValue33+ styleSrcAttr?: ContentSecurityPolicyOptionValue34+ styleSrcElem?: ContentSecurityPolicyOptionValue35+ upgradeInsecureRequests?: ContentSecurityPolicyOptionValue36+ workerSrc?: ContentSecurityPolicyOptionValue37 }38 39 interface ReportToOptions {40 group: string63 unmodified lines104 xPermittedCrossDomainPolicies: true,105 xXssProtection: true,106 }107 108+type SecureHeadersCallback = (109+ ctx: Context,110+ headersToSet: [string, string | string[]][]111+) => [string, string][]112+113+const generateNonce = () => {114+ const buffer = new Uint8Array(16)115+ crypto.getRandomValues(buffer)116+ return Buffer.from(buffer).toString('base64')117+}118+export const NONCE: ContentSecurityPolicyOptionHandler = (ctx) => {119+ const nonce =120+ ctx.get('secureHeadersNonce') ||121+ (() => {122+ const newNonce = generateNonce()123+ ctx.set('secureHeadersNonce', newNonce)124+ return newNonce125+ })()126+ return `'nonce-${nonce}'`127+}128+129 export const secureHeaders = (customOptions?: Partial<SecureHeadersOptions>): MiddlewareHandler => {130 const options = { ...DEFAULT_OPTIONS, ...customOptions }131 const headersToSet = getFilteredHeaders(options)132+ const callbacks: SecureHeadersCallback[] = []133 134 if (options.contentSecurityPolicy) {103- headersToSet.push(['Content-Security-Policy', getCSPDirectives(options.contentSecurityPolicy)])135+ const [callback, value] = getCSPDirectives(options.contentSecurityPolicy)136+ if (callback) {137+ callbacks.push(callback)138+ }139+ headersToSet.push(['Content-Security-Policy', value as string])140 }141 142 if (options.reportingEndpoints) {143 headersToSet.push(['Reporting-Endpoints', getReportingEndpoints(options.reportingEndpoints)])3 unmodified lines147 headersToSet.push(['Report-To', getReportToOptions(options.reportTo)])148 }149 150 return async function secureHeaders(ctx, next) {151+ // should evaluate callbacks before next()152+ // some callback calls ctx.set() for embedding nonce to the page153+ const headersToSetForReq =154+ callbacks.length === 0155+ ? headersToSet156+ : callbacks.reduce((acc, cb) => cb(ctx, acc), headersToSet)157 await next()116- setHeaders(ctx, headersToSet)158+ setHeaders(ctx, headersToSetForReq)159 ctx.res.headers.delete('X-Powered-By')160 }161 }162 6 unmodified lines169 })170 }171 172 function getCSPDirectives(131- contentSecurityPolicy: SecureHeadersOptions['contentSecurityPolicy']132-): string {133- return Object.entries(contentSecurityPolicy || [])134- .map(([directive, value]) => {135- const kebabCaseDirective = directive.replace(/[A-Z]+(?![a-z])|[A-Z]/g, (match, offset) =>136- offset ? '-' + match.toLowerCase() : match.toLowerCase()137- )138- return `${kebabCaseDirective} ${Array.isArray(value) ? value.join(' ') : value}`173+ contentSecurityPolicy: ContentSecurityPolicyOptions174+): [SecureHeadersCallback | undefined, string | string[]] {175+ const callbacks: ((ctx: Context, values: string[]) => void)[] = []176+ const resultValues: string[] = []177+178+ for (const [directive, value] of Object.entries(contentSecurityPolicy)) {179+ const valueArray = Array.isArray(value) ? value : [value]180+181+ valueArray.forEach((value, i) => {182+ if (typeof value === 'function') {183+ const index = i * 2 + 2 + resultValues.length184+ callbacks.push((ctx, values) => {185+ values[index] = value(ctx, directive)186+ })187+ }188 })140- .join('; ')189+190+ resultValues.push(191+ directive.replace(/[A-Z]+(?![a-z])|[A-Z]/g, (match, offset) =>192+ offset ? '-' + match.toLowerCase() : match.toLowerCase()193+ ),194+ ...valueArray.flatMap((value) => [' ', value]),195+ '; '196+ )197+ }198+ resultValues.pop()199+200+ return callbacks.length === 0201+ ? [undefined, resultValues.join('')]202+ : [203+ (ctx, headersToSet) =>204+ headersToSet.map((values) => {205+ if (values[0] === 'Content-Security-Policy') {206+ const clone = values[1].slice() as unknown as string[]207+ callbacks.forEach((cb) => {208+ cb(ctx, clone)209+ })210+ return [values[0], clone.join('')]211+ } else {212+ return values as [string, string]213+ }214+ }),215+ resultValues,216+ ]217 }218 219 function getReportingEndpoints(220 reportingEndpoints: SecureHeadersOptions['reportingEndpoints'] = []13 unmodified linesmodified:deno_dist/middleware/serve-static/index.ts+8 added-5 removed
1-import type { Context } from '../../context.ts'1+import type { Context, Data } from '../../context.ts'2 import type { Env, MiddlewareHandler } from '../../types.ts'3 import { getFilePath, getFilePathWithoutDefaultDocument } from '../../utils/filepath.ts'4 import { getMimeType } from '../../utils/mime.ts'5 12 unmodified lines18 * This middleware is not directly used by the user. Create a wrapper specifying `getContent()` by the environment such as Deno or Bun.19 */20 export const serveStatic = <E extends Env = Env>(21 options: ServeStaticOptions<E> & {22- // eslint-disable-next-line @typescript-eslint/no-explicit-any23- getContent: (path: string) => any22+ getContent: (path: string, c: Context<E>) => Promise<Data | Response | null>23 pathResolve?: (path: string) => string24 }25 ): MiddlewareHandler => {26 return async (c, next) => {20 unmodified lines47 const getContent = options.getContent48 const pathResolve = options.pathResolve ?? defaultPathResolve49 50 path = pathResolve(path)52- let content = await getContent(path)51+ let content = await getContent(path, c)52 53 if (!content) {54 let pathWithOutDefaultDocument = getFilePathWithoutDefaultDocument({55 filename,2 unmodified lines58 if (!pathWithOutDefaultDocument) {59 return await next()60 }61 pathWithOutDefaultDocument = pathResolve(pathWithOutDefaultDocument)63- content = await getContent(pathWithOutDefaultDocument)62+ content = await getContent(pathWithOutDefaultDocument, c)63 if (content) {64 path = pathWithOutDefaultDocument65 }66 }67 68+ if (content instanceof Response) {69+ return c.newResponse(content.body, content)70+ }71+72 if (content) {73 let mimeType: string | undefined74 if (options.mimes) {75 mimeType = getMimeType(path, options.mimes) ?? getMimeType(path)14 unmodified linesmodified:deno_dist/middleware/timing/index.ts+7 added-3 removed
19 unmodified lines20 total: boolean21 enabled: boolean | ((c: Context) => boolean)22 totalDescription: string23 autoEnd: boolean24- crossOrigin: boolean | string24+ crossOrigin: boolean | string | ((c: Context) => boolean | string)25 }26 27 const getTime = () => {28 try {34 unmodified lines63 const enabled = typeof options.enabled === 'function' ? options.enabled(c) : options.enabled64 65 if (enabled) {66 c.res.headers.append('Server-Timing', headers.join(','))67+68+ const crossOrigin =69+ typeof options.crossOrigin === 'function' ? options.crossOrigin(c) : options.crossOrigin70+67- if (options.crossOrigin) {71+ if (crossOrigin) {72 c.res.headers.append(73 'Timing-Allow-Origin',70- typeof options.crossOrigin === 'string' ? options.crossOrigin : '*'74+ typeof crossOrigin === 'string' ? crossOrigin : '*'75 )76 }77 }78 }61 unmodified linesmodified:deno_dist/utils/mime.ts+1 added
17 unmodified lines18 }19 }20 }21 22+export { baseMimes as mimes }23 const baseMimes: Record<string, string> = {24 aac: 'audio/aac',25 avi: 'video/x-msvideo',26 avif: 'image/avif',53 unmodified linesmodified:deno_dist/utils/types.ts+3 added
34 unmodified lines35 : T extends object36 ? { [K in keyof T]: JSONParsed<T[K]> }37 : never38 39+// from sindresorhus/type-fest40+export type Simplify<T> = { [KeyType in keyof T]: T[KeyType] } & {}41+42 export type InterfaceToType<T> = T extends Function ? T : { [K in keyof T]: InterfaceToType<T[K]> }43 44 export type RequiredKeysOf<BaseType extends object> = Exclude<45 {14 unmodified linesmodified:deno_dist/context.ts+30 added-26 removed
1 import type { HonoRequest } from './request.ts'2 import type { Env, FetchEventLike, NotFoundHandler, Input, TypedResponse } from './types.ts'3 import { resolveCallback, HtmlEscapedCallbackPhase } from './utils/html.ts'4 import type { RedirectStatusCode, StatusCode } from './utils/http-status.ts'5-import type { JSONValue, InterfaceToType, JSONParsed, IsAny } from './utils/types.ts'5+import type { JSONValue, JSONParsed, IsAny, Simplify } from './utils/types.ts'6 7 type HeaderRecord = Record<string, string | string[]>8-type Data = string | ArrayBuffer | ReadableStream8+export type Data = string | ArrayBuffer | ReadableStream9 10 export interface ExecutionContext {11 waitUntil(promise: Promise<unknown>): void12 passThroughOnException(): void31 unmodified lines44 45 interface BodyRespond extends NewResponse {}46 47 interface TextRespond {48- (text: string, status?: StatusCode, headers?: HeaderRecord): Response49- (text: string, init?: ResponseInit): Response48+ <T extends string, U extends StatusCode>(text: T, status?: U, headers?: HeaderRecord): Response &49+ TypedResponse<T, U, 'text'>50+ <T extends string, U extends StatusCode>(text: T, init?: ResponseInit): Response &51+ TypedResponse<T, U, 'text'>52 }53 54 interface JSONRespond {53- <T>(54- object: InterfaceToType<T> extends JSONValue ? T : JSONValue,55- status?: StatusCode,55+ <T extends JSONValue | Simplify<any>, U extends StatusCode>(56+ object: T,57+ status?: U,58 headers?: HeaderRecord59 ): Response &60 TypedResponse<59- InterfaceToType<T> extends JSONValue60- ? JSONValue extends InterfaceToType<T>61+ Simplify<T> extends JSONValue62+ ? JSONValue extends Simplify<T>63 ? never64 : JSONParsed<T>63- : never65+ : never,66+ U,67+ 'json'68 >65- <T>(object: InterfaceToType<T> extends JSONValue ? T : JSONValue, init?: ResponseInit): Response &69+ <T extends JSONValue | Simplify<any>, U extends StatusCode>(70+ object: Simplify<T> extends JSONValue ? T : Simplify<T>,71+ init?: ResponseInit72+ ): Response &73 TypedResponse<67- InterfaceToType<T> extends JSONValue68- ? JSONValue extends InterfaceToType<T>74+ Simplify<T> extends JSONValue75+ ? JSONValue extends Simplify<T>76 ? never77 : JSONParsed<T>71- : never78+ : never,79+ U,80+ 'json'81 >82 }83 84 interface HTMLRespond {375 unmodified lines460 text: TextRespond = (461 text: string,462 arg?: StatusCode | ResponseInit,463 headers?: HeaderRecord455- ): Response => {464+ ): ReturnType<TextRespond> => {465 // If the header is empty, return Response immediately.466 // Content-Type will be added automatically as `text/plain`.467 if (!this.#preparedHeaders) {468 if (this.#isFresh && !headers && !arg) {469+ // @ts-expect-error `Response` due to missing some types-only keys470 return new Response(text)471 }472 this.#preparedHeaders = {}473 }474 this.#preparedHeaders['content-type'] = TEXT_PLAIN475+ // @ts-expect-error `Response` due to missing some types-only keys476 return typeof arg === 'number'477 ? this.newResponse(text, arg, headers)478 : this.newResponse(text, arg)479 }7 unmodified lines487 * })488 * ```489 * @see https://hono.dev/api/context#json490 */480- json: JSONRespond = <T>(481- object: InterfaceToType<T> extends JSONValue ? T : JSONValue,482- arg?: StatusCode | ResponseInit,491+ json: JSONRespond = <T extends JSONValue | Simplify<any>, U extends StatusCode>(492+ object: T,493+ arg?: U | ResponseInit,494 headers?: HeaderRecord484- ): Response &485- TypedResponse<486- InterfaceToType<T> extends JSONValue487- ? JSONValue extends InterfaceToType<T>488- ? never489- : JSONParsed<T>490- : never491- > => {495+ ): ReturnType<JSONRespond> => {496 const body = JSON.stringify(object)497 this.#preparedHeaders ??= {}498 this.#preparedHeaders['content-type'] = 'application/json; charset=UTF-8'499 /* eslint-disable @typescript-eslint/no-explicit-any */66 unmodified linesmodified:deno_dist/types.ts+100 added-85 removed
1 unmodified line2 /* eslint-disable @typescript-eslint/no-explicit-any */3 /* eslint-disable @typescript-eslint/ban-types */4 import type { Context } from './context.ts'5 import type { Hono } from './hono.ts'6+import type { StatusCode } from './utils/http-status.ts'7 import type {8 IfAnyThenEmptyObject,9+ JSONValue,10 Prettify,11 RemoveBlankRecord,12 UnionToIntersection,13 } from './utils/types.ts'16 unmodified lines30 31 export type Input = {32 in?: {}33 out?: {}34+ outputFormat?: ResponseFormat35 }36 37 export type BlankSchema = {}38 export type BlankInput = {}63 unmodified lines102 R extends HandlerResponse<any> = any,103 E2 extends Env = E104 >(105 handler: H<E2, P, I, R>103- ): Hono<104- IntersectNonAnyTypes<[E, E2]>,105- S & ToSchema<M, P, I['in'], MergeTypedResponseData<R>>,106- BasePath107- >106+ ): Hono<IntersectNonAnyTypes<[E, E2]>, S & ToSchema<M, P, I, MergeTypedResponse<R>>, BasePath>107 108 // app.get(path, handler)109 <110 P extends string,5 unmodified lines116 path: P,117 handler: H<E2, MergedPath, I, R>118 ): Hono<119 IntersectNonAnyTypes<[E, E2]>,121- S & ToSchema<M, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>,120+ S & ToSchema<M, MergePath<BasePath, P>, I, MergeTypedResponse<R>>,121 BasePath122 >123 124 // app.get(handler x2)7 unmodified lines132 >(133 ...handlers: [H<E2, P, I>, H<E3, P, I2, R>]134 ): Hono<135 IntersectNonAnyTypes<[E, E2, E3]>,137- S & ToSchema<M, P, I2['in'], MergeTypedResponseData<R>>,136+ S & ToSchema<M, P, I2, MergeTypedResponse<R>>,137 BasePath138 >139 140 // app.get(path, handler x2)9 unmodified lines150 path: P,151 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2, R>]152 ): Hono<153 IntersectNonAnyTypes<[E, E2, E3]>,155- S & ToSchema<M, MergePath<BasePath, P>, I2['in'], MergeTypedResponseData<R>>,154+ S & ToSchema<M, MergePath<BasePath, P>, I2, MergeTypedResponse<R>>,155 BasePath156 >157 158 // app.get(handler x 3)9 unmodified lines168 >(169 ...handlers: [H<E2, P, I>, H<E3, P, I2>, H<E4, P, I3, R>]170 ): Hono<171 IntersectNonAnyTypes<[E, E2, E3, E4]>,173- S & ToSchema<M, P, I3['in'], MergeTypedResponseData<R>>,172+ S & ToSchema<M, P, I3, MergeTypedResponse<R>>,173 BasePath174 >175 176 // app.get(path, handler x3)11 unmodified lines188 path: P,189 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2>, H<E4, MergedPath, I3, R>]190 ): Hono<191 IntersectNonAnyTypes<[E, E2, E3, E4]>,193- S & ToSchema<M, MergePath<BasePath, P>, I3['in'], MergeTypedResponseData<R>>,192+ S & ToSchema<M, MergePath<BasePath, P>, I3, MergeTypedResponse<R>>,193 BasePath194 >195 196 // app.get(handler x 4)11 unmodified lines208 >(209 ...handlers: [H<E2, P, I>, H<E3, P, I2>, H<E4, P, I3>, H<E5, P, I4, R>]210 ): Hono<211 IntersectNonAnyTypes<[E, E2, E3, E4, E5]>,213- S & ToSchema<M, P, I4['in'], MergeTypedResponseData<R>>,212+ S & ToSchema<M, P, I4, MergeTypedResponse<R>>,213 BasePath214 >215 216 // app.get(path, handler x4)18 unmodified lines235 H<E5, MergedPath, I4, R>236 ]237 ): Hono<238 IntersectNonAnyTypes<[E, E2, E3, E4, E5]>,240- S & ToSchema<M, MergePath<BasePath, P>, I4['in'], MergeTypedResponseData<R>>,239+ S & ToSchema<M, MergePath<BasePath, P>, I4, MergeTypedResponse<R>>,240 BasePath241 >242 243 // app.get(handler x 5)13 unmodified lines257 >(258 ...handlers: [H<E2, P, I>, H<E3, P, I2>, H<E4, P, I3>, H<E5, P, I4>, H<E6, P, I5, R>]259 ): Hono<260 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>,262- S & ToSchema<M, P, I5['in'], MergeTypedResponseData<R>>,261+ S & ToSchema<M, P, I5, MergeTypedResponse<R>>,262 BasePath263 >264 265 // app.get(path, handler x5)21 unmodified lines287 H<E6, MergedPath, I5, R>288 ]289 ): Hono<290 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>,292- S & ToSchema<M, MergePath<BasePath, P>, I5['in'], MergeTypedResponseData<R>>,291+ S & ToSchema<M, MergePath<BasePath, P>, I5, MergeTypedResponse<R>>,292 BasePath293 >294 295 // app.get(handler x 6)22 unmodified lines318 H<E7, P, I6, R>319 ]320 ): Hono<321 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>,323- S & ToSchema<M, P, I6['in'], MergeTypedResponseData<R>>,322+ S & ToSchema<M, P, I6, MergeTypedResponse<R>>,323 BasePath324 >325 326 // app.get(path, handler x6)24 unmodified lines351 H<E7, MergedPath, I6, R>352 ]353 ): Hono<354 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>,356- S & ToSchema<M, MergePath<BasePath, P>, I6['in'], MergeTypedResponseData<R>>,355+ S & ToSchema<M, MergePath<BasePath, P>, I6, MergeTypedResponse<R>>,356 BasePath357 >358 359 // app.get(handler x 7)25 unmodified lines385 H<E8, P, I7, R>386 ]387 ): Hono<388 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>,390- S & ToSchema<M, P, I7['in'], MergeTypedResponseData<R>>,389+ S & ToSchema<M, P, I7, MergeTypedResponse<R>>,390 BasePath391 >392 393 // app.get(path, handler x7)27 unmodified lines421 H<E8, MergedPath, I7, R>422 ]423 ): Hono<424 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>,426- S & ToSchema<M, MergePath<BasePath, P>, I7['in'], MergeTypedResponseData<R>>,425+ S & ToSchema<M, MergePath<BasePath, P>, I7, MergeTypedResponse<R>>,426 BasePath427 >428 429 // app.get(handler x 8)28 unmodified lines458 H<E9, P, I8, R>459 ]460 ): Hono<461 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>,463- S & ToSchema<M, P, I8['in'], MergeTypedResponseData<R>>,462+ S & ToSchema<M, P, I8, MergeTypedResponse<R>>,463 BasePath464 >465 466 // app.get(path, handler x8)30 unmodified lines497 H<E9, MergedPath, I8, R>498 ]499 ): Hono<500 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>,502- S & ToSchema<M, MergePath<BasePath, P>, I8['in'], MergeTypedResponseData<R>>,501+ S & ToSchema<M, MergePath<BasePath, P>, I8, MergeTypedResponse<R>>,502 BasePath503 >504 505 // app.get(handler x 9)31 unmodified lines537 H<E10, P, I9, R>538 ]539 ): Hono<540 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>,542- S & ToSchema<M, P, I9['in'], MergeTypedResponseData<R>>,541+ S & ToSchema<M, P, I9, MergeTypedResponse<R>>,542 BasePath543 >544 545 // app.get(path, handler x9)33 unmodified lines579 H<E10, MergedPath, I9, R>580 ]581 ): Hono<582 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>,584- S & ToSchema<M, MergePath<BasePath, P>, I9['in'], MergeTypedResponseData<R>>,583+ S & ToSchema<M, MergePath<BasePath, P>, I9, MergeTypedResponse<R>>,584 BasePath585 >586 587 // app.get(handler x 10)34 unmodified lines622 H<E11, P, I10, R>623 ]624 ): Hono<625 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11]>,627- S & ToSchema<M, P, I10['in'], MergeTypedResponseData<R>>,626+ S & ToSchema<M, P, I10, MergeTypedResponse<R>>,627 BasePath628 >629 630 // app.get(path, handler x10)36 unmodified lines667 H<E11, MergedPath, I10, R>668 ]669 ): Hono<670 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11]>,672- S & ToSchema<M, MergePath<BasePath, P>, I10['in'], MergeTypedResponseData<R>>,671+ S & ToSchema<M, MergePath<BasePath, P>, I10, MergeTypedResponse<R>>,672 BasePath673 >674 675 // app.get(...handlers[])2 unmodified lines678 I extends Input = BlankInput,679 R extends HandlerResponse<any> = any680 >(681 ...handlers: H<E, P, I, R>[]683- ): Hono<E, S & ToSchema<M, P, I['in'], MergeTypedResponseData<R>>, BasePath>682+ ): Hono<E, S & ToSchema<M, P, I, MergeTypedResponse<R>>, BasePath>683 684 // app.get(path, ...handlers[])685 <P extends string, I extends Input = BlankInput, R extends HandlerResponse<any> = any>(686 path: P,687 ...handlers: H<E, MergePath<BasePath, P>, I, R>[]689- ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>, BasePath>688+ ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I, MergeTypedResponse<R>>, BasePath>689 690 // app.get(path)691 <P extends string, R extends HandlerResponse<any> = any, I extends Input = {}>(path: P): Hono<692 E,694- S & ToSchema<M, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>,693+ S & ToSchema<M, MergePath<BasePath, P>, I, MergeTypedResponse<R>>,694 BasePath695 >696 }697 224 unmodified lines922 path: P,923 handler: H<E2, MergedPath, I, R>924 ): Hono<925 IntersectNonAnyTypes<[E, E2]>,927- S & ToSchema<M, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>,926+ S & ToSchema<M, MergePath<BasePath, P>, I, MergeTypedResponse<R>>,927 BasePath928 >929 930 // app.on(method, path, handler x2)11 unmodified lines942 path: P,943 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2, R>]944 ): Hono<945 IntersectNonAnyTypes<[E, E2, E3]>,947- S & ToSchema<M, MergePath<BasePath, P>, I2['in'], MergeTypedResponseData<R>>,946+ S & ToSchema<M, MergePath<BasePath, P>, I2, MergeTypedResponse<R>>,947 BasePath948 >949 950 // app.on(method, path, handler x3)13 unmodified lines964 path: P,965 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2>, H<E4, MergedPath, I3, R>]966 ): Hono<967 IntersectNonAnyTypes<[E, E2, E3, E4]>,969- S & ToSchema<M, MergePath<BasePath, P>, I3['in'], MergeTypedResponseData<R>>,968+ S & ToSchema<M, MergePath<BasePath, P>, I3, MergeTypedResponse<R>>,969 BasePath970 >971 972 // app.on(method, path, handler x4)20 unmodified lines993 H<E5, MergedPath, I4, R>994 ]995 ): Hono<996 IntersectNonAnyTypes<[E, E2, E3, E4, E5]>,998- S & ToSchema<M, MergePath<BasePath, P>, I4['in'], MergeTypedResponseData<R>>,997+ S & ToSchema<M, MergePath<BasePath, P>, I4, MergeTypedResponse<R>>,998 BasePath999 >1000 1001 // app.on(method, path, handler x5)23 unmodified lines1025 H<E6, MergedPath, I5, R>1026 ]1027 ): Hono<1028 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>,1030- S & ToSchema<M, MergePath<BasePath, P>, I5['in'], MergeTypedResponseData<R>>,1029+ S & ToSchema<M, MergePath<BasePath, P>, I5, MergeTypedResponse<R>>,1030 BasePath1031 >1032 1033 // app.on(method, path, handler x6)26 unmodified lines1060 H<E7, MergedPath, I6, R>1061 ]1062 ): Hono<1063 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>,1065- S & ToSchema<M, MergePath<BasePath, P>, I6['in'], MergeTypedResponseData<R>>,1064+ S & ToSchema<M, MergePath<BasePath, P>, I6, MergeTypedResponse<R>>,1065 BasePath1066 >1067 1068 // app.on(method, path, handler x7)29 unmodified lines1098 H<E8, MergedPath, I7, R>1099 ]1100 ): Hono<1101 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>,1103- S & ToSchema<M, MergePath<BasePath, P>, I7['in'], MergeTypedResponseData<R>>,1102+ S & ToSchema<M, MergePath<BasePath, P>, I7, MergeTypedResponse<R>>,1103 BasePath1104 >1105 1106 // app.on(method, path, handler x8)32 unmodified lines1139 H<E9, MergedPath, I8, R>1140 ]1141 ): Hono<1142 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>,1144- S & ToSchema<M, MergePath<BasePath, P>, I8['in'], MergeTypedResponseData<R>>,1143+ S & ToSchema<M, MergePath<BasePath, P>, I8, MergeTypedResponse<R>>,1144 BasePath1145 >1146 1147 // app.on(method, path, handler x9)35 unmodified lines1183 H<E10, MergedPath, I9, R>1184 ]1185 ): Hono<1186 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>,1188- S & ToSchema<M, MergePath<BasePath, P>, I9['in'], MergeTypedResponseData<R>>,1187+ S & ToSchema<M, MergePath<BasePath, P>, I9, MergeTypedResponse<R>>,1188 BasePath1189 >1190 1191 // app.on(method, path, handler x10)37 unmodified lines1229 H<E11, MergedPath, I10>1230 ]1231 ): Hono<1232 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11]>,1234- S &1235- ToSchema<M, MergePath<BasePath, P>, I10['in'], MergeTypedResponseData<HandlerResponse<any>>>,1233+ S & ToSchema<M, MergePath<BasePath, P>, I10, MergeTypedResponse<HandlerResponse<any>>>,1234 BasePath1235 >1236 1237 // app.get(method, path, ...handler)1238 <M extends string, P extends string, R extends HandlerResponse<any> = any, I extends Input = {}>(1239 method: M,1240 path: P,1241 ...handlers: H<E, MergePath<BasePath, P>, I, R>[]1244- ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>, BasePath>1242+ ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I, MergeTypedResponse<R>>, BasePath>1243 1244 // app.get(method[], path, handler)1245 <1246 Ms extends string[],7 unmodified lines1254 path: P,1255 handler: H<E2, MergedPath, I, R>1256 ): Hono<1257 IntersectNonAnyTypes<[E, E2]>,1260- S & ToSchema<Ms[number], MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>,1258+ S & ToSchema<Ms[number], MergePath<BasePath, P>, I, MergeTypedResponse<R>>,1259 BasePath1260 >1261 1262 // app.get(method[], path, handler x2)11 unmodified lines1274 path: P,1275 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2, R>]1276 ): Hono<1277 IntersectNonAnyTypes<[E, E2, E3]>,1280- S & ToSchema<Ms[number], MergePath<BasePath, P>, I2['in'], MergeTypedResponseData<R>>,1278+ S & ToSchema<Ms[number], MergePath<BasePath, P>, I2, MergeTypedResponse<R>>,1279 BasePath1280 >1281 1282 // app.get(method[], path, handler x3)13 unmodified lines1296 path: P,1297 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2>, H<E4, MergedPath, I3, R>]1298 ): Hono<1299 IntersectNonAnyTypes<[E, E2, E3, E4]>,1302- S & ToSchema<Ms[number], MergePath<BasePath, P>, I3['in'], MergeTypedResponseData<R>>,1300+ S & ToSchema<Ms[number], MergePath<BasePath, P>, I3, MergeTypedResponse<R>>,1301 BasePath1302 >1303 1304 // app.get(method[], path, handler x4)20 unmodified lines1325 H<E5, MergedPath, I4, R>1326 ]1327 ): Hono<1328 IntersectNonAnyTypes<[E, E2, E3, E4, E5]>,1331- S & ToSchema<Ms[number], MergePath<BasePath, P>, I4['in'], MergeTypedResponseData<R>>,1329+ S & ToSchema<Ms[number], MergePath<BasePath, P>, I4, MergeTypedResponse<R>>,1330 BasePath1331 >1332 1333 // app.get(method[], path, handler x5)23 unmodified lines1357 H<E6, MergedPath, I5, R>1358 ]1359 ): Hono<1360 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>,1363- S & ToSchema<Ms[number], MergePath<BasePath, P>, I5['in'], MergeTypedResponseData<R>>,1361+ S & ToSchema<Ms[number], MergePath<BasePath, P>, I5, MergeTypedResponse<R>>,1362 BasePath1363 >1364 1365 // app.get(method[], path, handler x6)26 unmodified lines1392 H<E7, MergedPath, I6, R>1393 ]1394 ): Hono<1395 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>,1398- S & ToSchema<Ms[number], MergePath<BasePath, P>, I6['in'], MergeTypedResponseData<R>>,1396+ S & ToSchema<Ms[number], MergePath<BasePath, P>, I6, MergeTypedResponse<R>>,1397 BasePath1398 >1399 1400 // app.get(method[], path, handler x7)29 unmodified lines1430 H<E8, MergedPath, I7, R>1431 ]1432 ): Hono<1433 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>,1436- S & ToSchema<Ms[number], MergePath<BasePath, P>, I7['in'], MergeTypedResponseData<R>>,1434+ S & ToSchema<Ms[number], MergePath<BasePath, P>, I7, MergeTypedResponse<R>>,1435 BasePath1436 >1437 1438 // app.get(method[], path, handler x8)32 unmodified lines1471 H<E9, MergedPath, I8, R>1472 ]1473 ): Hono<1474 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>,1477- S & ToSchema<Ms[number], MergePath<BasePath, P>, I8['in'], MergeTypedResponseData<R>>,1475+ S & ToSchema<Ms[number], MergePath<BasePath, P>, I8, MergeTypedResponse<R>>,1476 BasePath1477 >1478 1479 // app.get(method[], path, handler x9)34 unmodified lines1514 H<E10, MergedPath, I9>1515 ]1516 ): Hono<1517 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>,1520- S &1521- ToSchema<1522- Ms[number],1523- MergePath<BasePath, P>,1524- I9['in'],1525- MergeTypedResponseData<HandlerResponse<any>>1526- >,1518+ S & ToSchema<Ms[number], MergePath<BasePath, P>, I9, MergeTypedResponse<HandlerResponse<any>>>,1519 BasePath1520 >1521 1522 // app.get(method[], path, handler x10)37 unmodified lines1560 H<E11, MergedPath, I10>1561 ]1562 ): Hono<1563 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11]>,1572- S &1573- ToSchema<1574- Ms[number],1575- MergePath<BasePath, P>,1576- I10['in'],1577- MergeTypedResponseData<HandlerResponse<any>>1578- >,1564+ S & ToSchema<Ms[number], MergePath<BasePath, P>, I10, MergeTypedResponse<HandlerResponse<any>>>,1565 BasePath1566 >1567 1568 // app.on(method[], path, ...handler)1569 <P extends string, R extends HandlerResponse<any> = any, I extends Input = {}>(1570 methods: string[],1571 path: P,1572 ...handlers: H<E, MergePath<BasePath, P>, I, R>[]1587- ): Hono<1588- E,1589- S & ToSchema<string, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>,1590- BasePath1591- >1573+ ): Hono<E, S & ToSchema<string, MergePath<BasePath, P>, I, MergeTypedResponse<R>>, BasePath>1574 1575 // app.on(method | method[], path[], ...handlers[])1576 <I extends Input = BlankInput, R extends HandlerResponse<any> = any>(1577 methods: string | string[],1578 paths: string[],1579 ...handlers: H<E, any, I, R>[]1598- ): Hono<E, S & ToSchema<string, string, I['in'], MergeTypedResponseData<R>>, BasePath>1580+ ): Hono<E, S & ToSchema<string, string, I, MergeTypedResponse<R>>, BasePath>1581 }1582 1583 type ExtractKey<S> = S extends Record<infer Key, unknown>1584 ? Key extends string6 unmodified lines1591 ////// ToSchema //////1592 ////// //////1593 ////////////////////////////////////////1594 1613-export type ToSchema<M extends string, P extends string, I extends Input['in'], O> = Prettify<{1595+export type ToSchema<1596+ M extends string,1597+ P extends string,1598+ I extends Input,1599+ R extends TypedResponse1600+> = Prettify<{1601 [K in P]: {1615- [K2 in M as AddDollar<K2>]: {1616- input: unknown extends I ? AddParam<{}, P> : AddParam<I, P>1617- output: unknown extends O ? {} : O1618- }1602+ [K2 in M as AddDollar<K2>]: R extends TypedResponse<infer T, infer U, infer F>1603+ ? {1604+ input: unknown extends I['in'] ? AddParam<{}, P> : AddParam<I['in'], P>1605+ output: unknown extends T ? {} : T1606+ outputFormat: I extends { outputFormat: string }1607+ ? I['outputFormat']1608+ : unknown extends F1609+ ? never1610+ : F1611+ status: U1612+ }1613+ : never1614 }1615 }>1616 1617 export type Schema = {1618 [Path: string]: {1624- [Method: `$${Lowercase<string>}`]: {1625- input: Partial<ValidationTargets>1626- output: any1627- }1619+ [Method: `$${Lowercase<string>}`]: Endpoint1620 }1621 }1622 1623+export type Endpoint = {1624+ input: Partial<ValidationTargets>1625+ output: any1626+ outputFormat: ResponseFormat1627+ status: StatusCode1628+}1629+1630 type ExtractParams<Path extends string> = string extends Path1631 ? Record<string, string>1632 : Path extends `${infer _Start}:${infer Param}/${infer Rest}`1633 ? { [K in Param | keyof ExtractParams<`/${Rest}`>]: string }7 unmodified lines1641 [P in keyof OrigSchema as MergePath<SubPath, P & string>]: {1642 [M in keyof OrigSchema[P]]: OrigSchema[P][M] extends {1643 input: infer Input1644 output: infer Output1645+ outputFormat: infer OutputFormat1646+ status: infer Status1647 }1648 ? {1649 input: Input extends { param: infer _ }1650 ? ExtractParams<SubPath> extends never18 unmodified lines1669 : K]: string1670 }1671 }1672 output: Output1673+ outputFormat: OutputFormat1674+ status: Status1675 }1676 : never1677 }1678 }>27 unmodified lines1706 ////// TypedResponse //////1707 ////// //////1708 ////////////////////////////////////////1709 1707-export type TypedResponse<T = unknown> = {1710+export type KnownResponseFormat = 'json' | 'text'1711+export type ResponseFormat = KnownResponseFormat | string1712+1713+export type TypedResponse<1714+ T = unknown,1715+ U extends StatusCode = StatusCode,1716+ F extends ResponseFormat = T extends string1717+ ? 'text'1718+ : T extends JSONValue1719+ ? 'json'1720+ : ResponseFormat1721+> = {1722 data: T1709- format: 'json' // Currently, support only `json` with `c.json()`1723+ status: U1724+ format: F1725 }1726 1712-type MergeTypedResponseData<T> = T extends Promise<infer T2>1713- ? T2 extends TypedResponse<infer U>1714- ? U1715- : {}1716- : T extends TypedResponse<infer U>1717- ? U1718- : {}1727+type MergeTypedResponse<T> = T extends Promise<infer T2>1728+ ? T2 extends TypedResponse1729+ ? T21730+ : TypedResponse1731+ : T extends TypedResponse1732+ ? T1733+ : TypedResponse1734 1735 ////////////////////////////////////////1736 ////// /////1737 ////// ValidationTargets /////80 unmodified linesmodified:src/adapter/cloudflare-workers/serve-static.ts+6 added-1 removed
8 unmodified lines9 namespace?: KVNamespace10 manifest: object | string11 }12 13-// This middleware is available only on Cloudflare Workers.13+/**14+ * @deprecated15+ * `serveStatic` in the Cloudflare Workers adapter is deprecated.16+ * If you want to create an application serving static assets, please consider using Cloudflare Pages.17+ * You can start to create the Cloudflare Pages application with the `npm create hono@latest` command.18+ */19 export const serveStatic = <E extends Env = Env>(20 options: ServeStaticOptions<E>21 ): MiddlewareHandler => {22 return async function serveStatic(c, next) {18 unmodified linesmodified:src/adapter/deno/serve-static.ts+1 added-1 removed
16 unmodified lines17 file = await open(path)18 } catch (e) {19 console.warn(`${e}`)20 }21- return file ? file.readable : undefined21+ return file ? file.readable : null22 }23 const pathResolve = (path: string) => {24 return `./${path}`25 }7 unmodified linesmodified:src/client/client.test.ts+275 added
72 unmodified lines73 return res(ctx.status(404))74 }),75 rest.get('http://localhost/null', (_req, res, ctx) => {76 return res(ctx.status(200), ctx.json(null))77+ }),78+ rest.get('http://localhost/api/string', async (req, res, ctx) => {79+ return res(ctx.json('a-string'))80+ }),81+ rest.get('http://localhost/api/number', async (req, res, ctx) => {82+ return res(ctx.json(37))83+ }),84+ rest.get('http://localhost/api/boolean', async (req, res, ctx) => {85+ return res(ctx.json(true))86+ }),87+ rest.get('http://localhost/api/generic', async (req, res, ctx) => {88+ return res(ctx.json(Math.random() > 0.5 ? Boolean(Math.random()) : Math.random()))89 })90 )91 92 beforeAll(() => server.listen())42 unmodified lines135 const data = await res.json()136 expectTypeOf(data).toMatchTypeOf<null>()137 expect(data).toBe(null)138 })139+140+ it('Should have correct types - primitives', async () => {141+ const app = new Hono()142+ const route = app143+ .get('/api/string', (c) => c.json('a-string'))144+ .get('/api/number', (c) => c.json(37))145+ .get('/api/boolean', (c) => c.json(true))146+ .get('/api/generic', (c) =>147+ c.json(Math.random() > 0.5 ? Boolean(Math.random()) : Math.random())148+ )149+ type AppType = typeof route150+ const client = hc<AppType>('http://localhost')151+ const stringFetch = await client.api.string.$get()152+ const stringRes = await stringFetch.json()153+ const numberFetch = await client.api.number.$get()154+ const numberRes = await numberFetch.json()155+ const booleanFetch = await client.api.boolean.$get()156+ const booleanRes = await booleanFetch.json()157+ const genericFetch = await client.api.generic.$get()158+ const genericRes = await genericFetch.json()159+ type stringVerify = Expect<Equal<'a-string', typeof stringRes>>160+ expect(stringRes).toBe('a-string')161+ type numberVerify = Expect<Equal<37, typeof numberRes>>162+ expect(numberRes).toBe(37)163+ type booleanVerify = Expect<Equal<true, typeof booleanRes>>164+ expect(booleanRes).toBe(true)165+ type genericVerify = Expect<Equal<number | boolean, typeof genericRes>>166+ expect(typeof genericRes === 'number' || typeof genericRes === 'boolean').toBe(true)167+168+ // using .text() on json endpoint should return string169+ type textTest = Expect<Equal<Promise<string>, ReturnType<typeof genericFetch.text>>>170+ })171 })172 173 describe('Basic - query, queries, form, path params, header and cookie', () => {174 const app = new Hono()335 unmodified lines510 511 it('Should have correct types - with interface', async () => {512 interface Result {513 ok: boolean514+ okUndefined?: boolean515 }516 const result: Result = { ok: true }517 const base = new Hono<Env>().basePath('/api')518 const app = base.get('/search', (c) => c.json(result))131 unmodified lines650 expectTypeOf(json).toEqualTypeOf<{ data: string } | { message: string }>()651 })652 })653 654+describe('Response with different status codes', () => {655+ const condition = () => true656+ const app = new Hono().get('/', async (c) => {657+ const ok = condition()658+ if (ok) {659+ return c.json({ data: 'foo' }, 200)660+ }661+ if (!ok) {662+ return c.json({ message: 'error' }, 400)663+ }664+ return c.json(null)665+ })666+667+ const client = hc<typeof app>('', { fetch: app.request })668+669+ it('all', async () => {670+ const res = await client.index.$get()671+ const json = await res.json()672+ expectTypeOf(json).toEqualTypeOf<{ data: string } | { message: string } | null>()673+ })674+675+ it('status 200', async () => {676+ const res = await client.index.$get()677+ if (res.status === 200) {678+ const json = await res.json()679+ expectTypeOf(json).toEqualTypeOf<{ data: string } | null>()680+ }681+ })682+683+ it('status 400', async () => {684+ const res = await client.index.$get()685+ if (res.status === 400) {686+ const json = await res.json()687+ expectTypeOf(json).toEqualTypeOf<{ message: string } | null>()688+ }689+ })690+691+ it('response is ok', async () => {692+ const res = await client.index.$get()693+ if (res.ok) {694+ const json = await res.json()695+ expectTypeOf(json).toEqualTypeOf<{ data: string } | null>()696+ }697+ })698+699+ it('response is not ok', async () => {700+ const res = await client.index.$get()701+ if (!res.ok) {702+ const json = await res.json()703+ expectTypeOf(json).toEqualTypeOf<{ message: string } | null>()704+ }705+ })706+})707+708+describe('Infer the response type with different status codes', () => {709+ const condition = () => true710+ const app = new Hono().get('/', async (c) => {711+ const ok = condition()712+ if (ok) {713+ return c.json({ data: 'foo' }, 200)714+ }715+ if (!ok) {716+ return c.json({ message: 'error' }, 400)717+ }718+ return c.json(null)719+ })720+721+ const client = hc<typeof app>('', { fetch: app.request })722+723+ it('Should infer response type correctly', () => {724+ const req = client.index.$get725+726+ type Actual = InferResponseType<typeof req>727+ type Expected =728+ | {729+ data: string730+ }731+ | {732+ message: string733+ }734+ | null735+ type verify = Expect<Equal<Expected, Actual>>736+ })737+738+ it('Should infer response type of status 200 correctly', () => {739+ const req = client.index.$get740+741+ type Actual = InferResponseType<typeof req, 200>742+ type Expected = {743+ data: string744+ } | null745+ type verify = Expect<Equal<Expected, Actual>>746+ })747+})748+749 describe('$url() with a param option', () => {750 const app = new Hono().get('/posts/:id/comments', (c) => c.json({ ok: true }))751 type AppType = typeof app752 const client = hc<AppType>('http://localhost')74 unmodified lines827 expect(data.requestDynamic).toEqual('two')828 })829 })830 831+describe('RequestInit work as expected', () => {832+ const app = new Hono()833+834+ const route = app835+ .get('/credentials', (c) => {836+ return c.text('' as RequestCredentials)837+ })838+ .get('/headers', (c) => {839+ return c.json({} as Record<string, string>)840+ })841+ .post('/headers', (c) => c.text('Not found', 404))842+843+ type AppType = typeof route844+845+ const server = setupServer(846+ rest.get('http://localhost/credentials', async (req, res, ctx) => {847+ return res(ctx.status(200), ctx.text(req.credentials))848+ }),849+ rest.get('http://localhost/headers', async (req, res, ctx) => {850+ const allHeaders: Record<string, string> = {}851+ for (const [k, v] of req.headers.entries()) {852+ allHeaders[k] = v853+ }854+855+ return res(ctx.status(200), ctx.json(allHeaders))856+ }),857+ rest.post('http://localhost/headers', async (req, res, ctx) => {858+ return res(ctx.status(400), ctx.text('Should not be here'))859+ })860+ )861+862+ beforeAll(() => server.listen())863+ afterEach(() => server.resetHandlers())864+ afterAll(() => server.close())865+866+ const client = hc<AppType>('http://localhost', {867+ headers: { 'x-hono': 'fire' },868+ init: {869+ credentials: 'include',870+ },871+ })872+873+ it('Should overwrite method and fail', async () => {874+ const res = await client.headers.$get(undefined, { init: { method: 'POST' } })875+876+ expect(res.ok).toBe(false)877+ })878+879+ it('Should clear headers', async () => {880+ const res = await client.headers.$get(undefined, { init: { headers: undefined } })881+882+ expect(res.ok).toBe(true)883+ const data = await res.json()884+ expect(data).toEqual({})885+ })886+887+ it('Should overwrite headers', async () => {888+ const res = await client.headers.$get(undefined, {889+ init: { headers: new Headers({ 'x-hono': 'awesome' }) },890+ })891+892+ expect(res.ok).toBe(true)893+ const data = await res.json()894+ expect(data).toEqual({ 'x-hono': 'awesome' })895+ })896+897+ it('credentials is include', async () => {898+ const res = await client.credentials.$get()899+900+ expect(res.ok).toBe(true)901+ const data = await res.text()902+ expect(data).toEqual('include')903+ })904+905+ it('deepMerge should works and not unset credentials', async () => {906+ const res = await client.credentials.$get(undefined, { init: { headers: { hi: 'hello' } } })907+908+ expect(res.ok).toBe(true)909+ const data = await res.text()910+ expect(data).toEqual('include')911+ })912+913+ it('Should unset credentials', async () => {914+ const res = await client.credentials.$get(undefined, { init: { credentials: undefined } })915+916+ expect(res.ok).toBe(true)917+ const data = await res.text()918+ expect(data).toEqual('same-origin')919+ })920+})921+922 describe('WebSocket URL Protocol Translation', () => {923 const app = new Hono()924 const route = app.get(925 '/',70 unmodified lines996 const client = hc('http://localhost')997 expect(client.posts.toString()).toMatch('function proxyCallback')998 })999 })1000+1001+describe('Text response', () => {1002+ const text = 'My name is Hono'1003+ const obj = { ok: true }1004+ const server = setupServer(1005+ rest.get('http://localhost/about/me', async (_req, res, ctx) => {1006+ return res(ctx.text(text))1007+ }),1008+ rest.get('http://localhost/api', async (_req, res, ctx) => {1009+ return res(ctx.json(obj))1010+ })1011+ )1012+1013+ beforeAll(() => server.listen())1014+ afterEach(() => server.resetHandlers())1015+ afterAll(() => server.close())1016+1017+ const app = new Hono().get('/about/me', (c) => c.text(text)).get('/api', (c) => c.json(obj))1018+ const client = hc<typeof app>('http://localhost/')1019+1020+ it('Should be never with res.json() - /about/me', async () => {1021+ const res = await client.about.me.$get()1022+ type Actual = ReturnType<typeof res.json>1023+ type Expected = Promise<never>1024+ type verify = Expect<Equal<Expected, Actual>>1025+ })1026+1027+ it('Should be "Hello, World!" with res.text() - /about/me', async () => {1028+ const res = await client.about.me.$get()1029+ const data = await res.text()1030+ expectTypeOf(data).toEqualTypeOf<'My name is Hono'>()1031+ expect(data).toBe(text)1032+ })1033+1034+ /**1035+ * Also check the type of JSON response with res.text().1036+ */1037+ it('Should be string with res.text() - /api', async () => {1038+ const res = await client.api.$get()1039+ type Actual = ReturnType<typeof res.text>1040+ type Expected = Promise<string>1041+ type verify = Expect<Equal<Expected, Actual>>1042+ })1043+})modified:src/client/client.ts+1 added
121 unmodified lines122 return (opt?.fetch || fetch)(url, {123 body: setBody ? this.rBody : undefined,124 method: methodUpperCase,125 headers: headers,126+ ...opt?.init,127 })128 }129 }130 60 unmodified linesmodified:src/client/types.ts+66 added-22 removed
1-import type { UpgradedWebSocketResponseInputJSONType } from '../helper/websocket'1 import type { Hono } from '../hono'3-import type { Schema } from '../types'2+import type { Endpoint, ResponseFormat, Schema } from '../types'3+import type { StatusCode, SuccessStatusCode } from '../utils/http-status'4 import type { HasRequiredKeys } from '../utils/types'5 6 type HonoRequest = (typeof Hono.prototype)['request']7 8-export type ClientRequestOptions<T = unknown> = keyof T extends never8+export type ClientRequestOptions<T = unknown> = {9+ fetch?: typeof fetch | HonoRequest10+ /**11+ * Standard `RequestInit`, caution that this take highest priority12+ * and could be used to overwrite things that Hono sets for you, like `body | method | headers`.13+ *14+ * If you want to add some headers, use in `headers` instead of `init`15+ */16+ init?: RequestInit17+} & (keyof T extends never18 ? {19 headers?:20 | Record<string, string>21 | (() => Record<string, string> | Promise<Record<string, string>>)13- fetch?: typeof fetch | HonoRequest22 }23 : {24 headers: T | (() => T | Promise<T>)17- fetch?: typeof fetch | HonoRequest18- }25+ })26 27 export type ClientRequest<S extends Schema> = {21- [M in keyof S]: S[M] extends { input: infer R; output: infer O }28+ [M in keyof S]: S[M] extends Endpoint & { input: infer R }29 ? R extends object30 ? HasRequiredKeys<R> extends true24- ? (args: R, options?: ClientRequestOptions) => Promise<ClientResponse<O>>25- : (args?: R, options?: ClientRequestOptions) => Promise<ClientResponse<O>>31+ ? (args: R, options?: ClientRequestOptions) => Promise<ClientResponseOfEndpoint<S[M]>>32+ : (args?: R, options?: ClientRequestOptions) => Promise<ClientResponseOfEndpoint<S[M]>>33 : never34 : never35 } & {36 $url: (2 unmodified lines39 ? { param: P }40 : {}41 : {}42 ) => URL36-} & (S['$get'] extends { input: { json: UpgradedWebSocketResponseInputJSONType } }43+} & (S['$get'] extends { outputFormat: 'ws' }44 ? S['$get'] extends { input: infer I }45 ? {39- $ws: (args?: Omit<I, 'json'>) => WebSocket46+ $ws: (args?: I) => WebSocket47 }48 : {}49 : {})50 5 unmodified lines56 ? never57 : T58 : never59 60+type ClientResponseOfEndpoint<T extends Endpoint = Endpoint> = T extends {61+ output: infer O62+ outputFormat: infer F63+ status: infer S64+}65+ ? ClientResponse<O, S extends number ? S : never, F extends ResponseFormat ? F : never>66+ : never67+53-export interface ClientResponse<T> {68+export interface ClientResponse<69+ T,70+ U extends number = StatusCode,71+ F extends ResponseFormat = ResponseFormat72+> extends globalThis.Response {73 readonly body: ReadableStream | null74 readonly bodyUsed: boolean75+ ok: U extends SuccessStatusCode76+ ? true77+ : U extends Exclude<StatusCode, SuccessStatusCode>78+ ? false56- ok: boolean57- status: number79+ : boolean80+ status: U81 statusText: string82 headers: Headers83 url: string84 redirect(url: string, status: number): Response85 clone(): Response63- json(): Promise<BlankRecordToNever<T>>64- text(): Promise<string>86+ json(): F extends 'text'87+ ? Promise<never>88+ : F extends 'json'89+ ? Promise<BlankRecordToNever<T>>90+ : Promise<unknown>91+ text(): F extends 'text' ? (T extends string ? Promise<T> : Promise<never>) : Promise<string>92 blob(): Promise<Blob>93 formData(): Promise<FormData>94 arrayBuffer(): Promise<ArrayBuffer>95 }2 unmodified lines98 99 export type Fetch<T> = (100 args?: InferRequestType<T>,101 opt?: ClientRequestOptions75-) => Promise<ClientResponse<InferResponseType<T>>>102+) => Promise<ClientResponseOfEndpoint<InferEndpointType<T>>>103 77-export type InferResponseType<T> = T extends (104+type InferEndpointType<T> = T extends (105+ args: infer R,106 // eslint-disable-next-line @typescript-eslint/no-explicit-any79- args: any | undefined,80- // eslint-disable-next-line @typescript-eslint/no-explicit-any107 options: any | undefined82-) => Promise<ClientResponse<infer O>>83- ? O108+) => Promise<infer U>109+ ? U extends ClientResponse<infer O, infer S, infer F>110+ ? { input: NonNullable<R>; output: O; outputFormat: F; status: S } extends Endpoint111+ ? { input: NonNullable<R>; output: O; outputFormat: F; status: S }112+ : never113+ : never114 : never115 116+export type InferResponseType<T, U extends StatusCode = StatusCode> = InferResponseTypeFromEndpoint<117+ InferEndpointType<T>,118+ U119+>120+121+type InferResponseTypeFromEndpoint<T extends Endpoint, U extends StatusCode> = T extends {122+ output: infer O123+ status: infer S124+}125+ ? S extends U126+ ? O127+ : never128+ : never129+130 export type InferRequestType<T> = T extends (131 args: infer R,132 // eslint-disable-next-line @typescript-eslint/no-explicit-any133 options: any | undefined46 unmodified linesmodified:src/helper/cookie/index.test.ts+14 added
414 unmodified lines415 expect(res2.status).toBe(200)416 const header2 = res2.headers.get('Set-Cookie')417 expect(header2).toBe('delicious_cookie=; Max-Age=0; Domain=example.com; Path=/; Secure')418 })419+420+ app.get('/delete-cookie-with-deleted-value', (c) => {421+ const deleted = deleteCookie(c, 'delicious_cookie')422+ return c.text(deleted || '')423+ })424+425+ it('Get deleted value', async () => {426+ const cookieString = 'delicious_cookie=choco'427+ const req = new Request('http://localhost/delete-cookie-with-deleted-value')428+ req.headers.set('Cookie', cookieString)429+ const res = await app.request(req)430+ expect(res.status).toBe(200)431+ expect(await res.text()).toBe('choco')432+ })433 })434 })modified:src/helper/cookie/index.ts+3 added-1 removed
116 unmodified lines117 }118 c.header('set-cookie', cookie, { append: true })119 }120 121-export const deleteCookie = (c: Context, name: string, opt?: CookieOptions): void => {121+export const deleteCookie = (c: Context, name: string, opt?: CookieOptions) => {122+ const deletedCookie = getCookie(c, name)123 setCookie(c, name, '', { ...opt, maxAge: 0 })124+ return deletedCookie125 }modified:src/helper/factory/index.test.ts+47 added-18 removed
1 import { expectTypeOf } from 'vitest'2 import { hc } from '../../client'3 import type { ClientRequest } from '../../client/types'4 import { Hono } from '../../index'5-import type { ToSchema } from '../../types'5+import type { ToSchema, TypedResponse } from '../../types'6+import type { StatusCode } from '../../utils/http-status'7 import { validator } from '../../validator'8 import { createMiddleware, createFactory } from './index'9 10 describe('createMiddleware', () => {65 unmodified lines76 expectTypeOf(client).toEqualTypeOf<{77 a: ClientRequest<{78 $get: {79 input: {}79- output: {}80+ output: 'A'81+ outputFormat: 'text'82+ status: StatusCode83 }84 }>85 }>()86 })24 unmodified lines111 ToSchema<112 'get',113 '/posts',114 {115+ in: {112- query: {113- page: string116+ query: {117+ page: string118+ }119 }120 },116- {121+ TypedResponse<{122 page: string123 foo: string119- }124+ }>125 >,126 '/'127 >128 42 unmodified lines171 ToSchema<172 'get',173 '/posts',174 {175+ in: {170- header: {171- auth: string176+ header: {177+ auth: string178+ }179+ } & {180+ query: {181+ page: string182+ }183+ } & {184+ json: {185+ id: number186+ }187 }173- } & {174- query: {175- page: string176- }177- } & {178- json: {179- id: number180- }188 },182- {189+ TypedResponse<{190 auth: string191 page: string192 foo: string193 id: number187- }194+ }>195 >,196 '/'197 >198 1 unmodified line200 expectTypeOf(routes).toEqualTypeOf<Expected>()201 })202 })203 })204+205+describe('createApp', () => {206+ type Env = { Variables: { foo: string } }207+ const factory = createFactory<Env>({208+ initApp: (app) => {209+ app.use((c, next) => {210+ c.set('foo', 'bar')211+ return next()212+ })213+ },214+ })215+ const app = factory.createApp()216+ it('Should set the correct type and initialize the app', async () => {217+ app.get('/', (c) => {218+ expectTypeOf(c.var.foo).toEqualTypeOf<string>()219+ return c.text(c.var.foo)220+ })221+ const res = await app.request('/')222+ expect(res.status).toBe(200)223+ expect(await res.text()).toBe('bar')224+ })225+})modified:src/helper/factory/index.ts+24 added-1 removed
1 /* eslint-disable @typescript-eslint/no-explicit-any */2+import { Hono } from '../../hono'3 import type { Env, H, HandlerResponse, Input, MiddlewareHandler } from '../../types'4 5+type InitApp<E extends Env = Env> = (app: Hono<E>) => void6+7 export class Factory<E extends Env = any, P extends string = any> {8+ private initApp?: InitApp<E>9+10+ constructor(init?: { initApp?: InitApp<E> }) {11+ this.initApp = init?.initApp12+ }13+14+ /**15+ * @experimental16+ * `createApp` is an experimental feature.17+ */18+ createApp = () => {19+ const app = new Hono<E>()20+ if (this.initApp) {21+ this.initApp(app)22+ }23+ return app24+ }25+26 createMiddleware = <I extends Input = {}>(middleware: MiddlewareHandler<E, P, I>) => middleware27 28 createHandlers<I extends Input = {}, R extends HandlerResponse<any> = any>(29 handler1: H<E, P, I, R>199 unmodified lines229 return handlers.filter((handler) => handler !== undefined)230 }231 }232 212-export const createFactory = <E extends Env = any, P extends string = any>() => new Factory<E, P>()233+export const createFactory = <E extends Env = any, P extends string = any>(init?: {234+ initApp?: InitApp<E>235+}) => new Factory<E, P>(init)236 237 export const createMiddleware = <E extends Env = any, P extends string = any, I extends Input = {}>(238 middleware: MiddlewareHandler<E, P, I>239 ) => createFactory<E, P>().createMiddleware<I>(middleware)modified:src/helper/websocket/index.ts+1 added-5 removed
10 unmodified lines11 onClose?: (evt: CloseEvent, ws: WSContext) => void12 onError?: (evt: Event, ws: WSContext) => void13 }14 15-export type UpgradedWebSocketResponseInputJSONType = '__websocket'16-15 /**16 * Upgrade WebSocket Type17 */18 export type UpgradeWebSocket = (1 unmodified line20 ) => MiddlewareHandler<21 any,22 string,23 {26- in: {27- json: UpgradedWebSocketResponseInputJSONType28- }24+ outputFormat: 'ws'25 }26 >27 28 export type WSReadyState = 0 | 1 | 2 | 323 unmodified linesmodified:src/jsx/dom/context.test.tsx+30 added-1 removed
4 unmodified lines5 // hono/jsx/jsx-runtime and hono/jsx/dom/jsx-runtime are tested in their respective settings6 // eslint-disable-next-line @typescript-eslint/no-unused-vars7 import { jsx, Fragment } from '..'8 import { createContext as createContextDom, useContext as useContextDom } from '.' // for dom9-import { render } from '.'9+import { render, useState } from '.'10 11 runner('Common', createContextCommon, useContextCommon)12 runner('DOM', createContextDom, useContextDom)13 37 unmodified lines51 render(App, root)52 expect(root.innerHTML).toBe('<p>1</p>')53 })54 55+ it('simple context with state', async () => {56+ const Context = createContext(0)57+ const Content = () => {58+ const [count, setCount] = useState(0)59+ const num = useContext(Context)60+ return (61+ <>62+ <p>63+ {num} - {count}64+ </p>65+ <button onClick={() => setCount(count + 1)}>+</button>66+ </>67+ )68+ }69+ const Component = () => {70+ return (71+ <Context.Provider value={1}>72+ <Content />73+ </Context.Provider>74+ )75+ }76+ const App = <Component />77+ render(App, root)78+ expect(root.innerHTML).toBe('<p>1 - 0</p><button>+</button>')79+ root.querySelector('button')?.click()80+ await Promise.resolve()81+ expect(root.innerHTML).toBe('<p>1 - 1</p><button>+</button>')82+ })83+84 it('multiple provider', async () => {85 const Context = createContext(0)86 const Content = () => {87 const num = useContext(Context)77 unmodified linesmodified:src/jsx/dom/context.ts+25 added-13 removed
1 unmodified line2 import { DOM_ERROR_HANDLER } from '../constants'3 import type { Context } from '../context'4 import { globalContexts } from '../context'5 import { Fragment } from './jsx-runtime'6+import { setInternalTagFlag } from './utils'7 7-export const createContextProviderFunction =8- <T>(values: T[]) =>9- ({ value, children }: { value: T; children: Child[] }) => {10- const res = Fragment({8+export const createContextProviderFunction = <T>(values: T[]) =>9+ setInternalTagFlag(({ value, children }: { value: T; children: Child[] }) => {10+ if (!children) {11+ return undefined12+ }13+14+ // eslint-disable-next-line @typescript-eslint/no-explicit-any15+ const props: { children: any } = {16 children: [17 {13- tag: () => {18+ tag: setInternalTagFlag(() => {19 values.push(value)15- },20+ }),21+ props: {},22 },17- ...(children as Child[]),18- {19- tag: () => {20- values.pop()21- },22- },23 ],24+ }25+ if (Array.isArray(children)) {26+ props.children.push(...children.flat())27+ } else {28+ props.children.push(children)29+ }30+ props.children.push({31+ tag: setInternalTagFlag(() => {32+ values.pop()33+ }),34+ props: {},35 })36+ const res = Fragment(props)37 // eslint-disable-next-line @typescript-eslint/no-explicit-any38 ;(res as any)[DOM_ERROR_HANDLER] = (err: unknown) => {39 values.pop()40 throw err41 }42 return res31- }43+ })44 45 export const createContext = <T>(defaultValue: T): Context<T> => {46 const values = [defaultValue]47 const context = {7 unmodified linesmodified:src/jsx/dom/css.ts+8 added-4 removed
108 unmodified lines109 // eslint-disable-next-line @typescript-eslint/no-explicit-any110 const Style: FC<PropsWithChildren<void>> = ({ children }) =>111 ({112 tag: 'style',113+ props: {114+ id,115+ children:116+ children &&113- children: (Array.isArray(children) ? children : [children]).map(114- (c) => (c as unknown as CssClassName)[STYLE_STRING]115- ),116- props: { id },117+ (Array.isArray(children) ? children : [children]).map(118+ (c) => (c as unknown as CssClassName)[STYLE_STRING]119+ ),120+ },121 // eslint-disable-next-line @typescript-eslint/no-explicit-any122 } as any)123 124 return [cssObject, Style] as const86 unmodified linesmodified:src/jsx/dom/index.test.tsx+291 added-6 removed
1 import { JSDOM } from 'jsdom'2-import type { FC } from '..'2+import type { FC, Child } from '..'3 // run tests by old style jsx default4 // hono/jsx/jsx-runtime and hono/jsx/dom/jsx-runtime are tested in their respective settings5 // eslint-disable-next-line @typescript-eslint/no-unused-vars6 import { jsx, Fragment, createElement } from '..'7-import DefaultExport from '..'7 import type { RefObject } from '../hooks'9-import { useState, useEffect, useLayoutEffect, useCallback, useRef, useMemo } from '../hooks'8+import {9+ useState,10+ useEffect,11+ useLayoutEffect,12+ useCallback,13+ useRef,14+ useMemo,15+ createRef,16+} from '../hooks'17+import DefaultExport from '.'18 import { memo, isValidElement, cloneElement } from '.'11-import { render, createElement as createElementForDom, cloneElement as cloneElementForDom } from '.'19+import {20+ render,21+ flushSync,22+ createPortal,23+ createElement as createElementForDom,24+ cloneElement as cloneElementForDom,25+} from '.'26 27+describe('Common', () => {28+ ;[createElement, createElementForDom].forEach((createElement) => {29+ describe('createElement', () => {30+ it('simple', () => {31+ const element = createElement('div', { id: 'app' })32+ expect(element).toEqual(expect.objectContaining({ tag: 'div', props: { id: 'app' } }))33+ })34+35+ it('children', () => {36+ const element = createElement('div', { id: 'app' }, 'Hello')37+ expect(element).toEqual(38+ expect.objectContaining({ tag: 'div', props: { id: 'app', children: 'Hello' } })39+ )40+ })41+42+ it('multiple children', () => {43+ const element = createElement('div', { id: 'app' }, 'Hello', 'World')44+ expect(element).toEqual(45+ expect.objectContaining({46+ tag: 'div',47+ props: { id: 'app', children: ['Hello', 'World'] },48+ })49+ )50+ })51+52+ it('key', () => {53+ const element = createElement('div', { id: 'app', key: 'key' })54+ expect(element).toEqual(55+ expect.objectContaining({ tag: 'div', props: { id: 'app' }, key: 'key' })56+ )57+ })58+59+ it('ref', () => {60+ const ref = { current: null }61+ const element = createElement('div', { id: 'app', ref })62+ expect(element).toEqual(expect.objectContaining({ tag: 'div', props: { id: 'app', ref } }))63+ expect(element.ref).toBe(ref)64+ })65+66+ it('type', () => {67+ const element = createElement('div', { id: 'app' })68+ expect(element.type).toBe('div')69+ })70+71+ it('null props', () => {72+ const element = createElement('div', null)73+ expect(element).toEqual(expect.objectContaining({ tag: 'div', props: {} }))74+ })75+ })76+ })77+})78+79 describe('DOM', () => {80 beforeAll(() => {81 global.requestAnimationFrame = (cb) => setTimeout(cb)82 })54 unmodified lines137 render(<App />, root)138 expect(root.innerHTML).toBe('<div style="font-size: 10px;"></div>')139 })140 141+ it('style with CSS variables - 1', () => {142+ const App = () => <div style={{ '--my-var-1': '15px' }} />143+ render(<App />, root)144+ expect(root.innerHTML).toBe('<div style="--my-var-1: 15px;"></div>')145+ })146+147+ it('style with CSS variables - 2', () => {148+ const App = () => <div style={{ '--myVar-2': '20px' }} />149+ render(<App />, root)150+ expect(root.innerHTML).toBe('<div style="--myVar-2: 20px;"></div>')151+ })152+153 it('style with string', async () => {154 const App = () => {155 const [style, setStyle] = useState<{ fontSize?: string; color?: string }>({156 fontSize: '10px',30 unmodified lines187 render(<App />, root)188 expect(root.innerHTML).toBe('<div></div>')189 expect(ref.current).toBeInstanceOf(HTMLElement)190 })191+192+ it('ref with null', () => {193+ const App = () => {194+ return <div ref={null} />195+ }196+ render(<App />, root)197+ expect(root.innerHTML).toBe('<div></div>')198+ })199+200+ it('remove node with ref object', async () => {201+ const ref = createRef<HTMLDivElement>()202+ const App = () => {203+ const [show, setShow] = useState(true)204+ return (205+ <>206+ {show && <div ref={ref} />}207+ <button onClick={() => setShow(false)}>remove</button>208+ </>209+ )210+ }211+ render(<App />, root)212+ expect(root.innerHTML).toBe('<div></div><button>remove</button>')213+ expect(ref.current).toBeInstanceOf(dom.window.HTMLDivElement)214+ root.querySelector('button')?.click()215+ await Promise.resolve()216+ expect(root.innerHTML).toBe('<button>remove</button>')217+ expect(ref.current).toBe(null)218+ })219+220+ it('remove node with ref function', async () => {221+ const ref = vi.fn()222+ const App = () => {223+ const [show, setShow] = useState(true)224+ return (225+ <>226+ {show && <div ref={ref} />}227+ <button onClick={() => setShow(false)}>remove</button>228+ </>229+ )230+ }231+ render(<App />, root)232+ expect(root.innerHTML).toBe('<div></div><button>remove</button>')233+ expect(ref).toHaveBeenLastCalledWith(expect.any(dom.window.HTMLDivElement))234+ root.querySelector('button')?.click()235+ await Promise.resolve()236+ expect(root.innerHTML).toBe('<button>remove</button>')237+ expect(ref).toHaveBeenLastCalledWith(null)238+ })239 })240 241+ describe('defaultProps', () => {242+ it('simple', () => {243+ const App: FC<{ name?: string }> = ({ name }) => <div>{name}</div>244+ App.defaultProps = { name: 'default' }245+ render(<App />, root)246+ expect(root.innerHTML).toBe('<div>default</div>')247+ })248+249+ it('override', () => {250+ const App: FC<{ name: string }> = ({ name }) => <div>{name}</div>251+ App.defaultProps = { name: 'default' }252+ render(<App name='override' />, root)253+ expect(root.innerHTML).toBe('<div>override</div>')254+ })255+ })256+257 describe('replace content', () => {258 it('text to text', async () => {259 let setCount: (count: number) => void = () => {}260 const App = () => {492 unmodified lines753 expect.any(Function),754 false755 )756 })757+758 it('onGotPointerCaptureCapture', async () => {759 const App = () => {760 return <div onGotPointerCaptureCapture={() => {}}></div>761 }5 unmodified lines767 expect.any(Function),768 true769 )770 })771+772+ it('undefined', async () => {773+ const App = () => {774+ return <div onClick={undefined}></div>775+ }776+ const addEventListenerSpy = vi.spyOn(dom.window.Node.prototype, 'addEventListener')777+ render(<App />, root)778+ expect(addEventListenerSpy).not.toHaveBeenCalled()779+ })780 })781 782 it('simple Counter', async () => {783 const Counter = () => {138 unmodified lines922 expect(root.innerHTML).toBe(923 '<div><p>Count: 0</p><button>+</button><div><p>Child Count: 0</p><button>+</button></div></div>'924 )925 const [button, childButton] = root.querySelectorAll('button')774- for (let i = 0; i < 5; i++) {926+ for (let i = 0; i < 3; i++) {927+ childButton.click()928+ await Promise.resolve()929+ }930+ for (let i = 0; i < 2; i++) {931 button.click()932 await Promise.resolve()933 }778- for (let i = 0; i < 6; i++) {934+ for (let i = 0; i < 3; i++) {935 childButton.click()936 await Promise.resolve()937 }938+ for (let i = 0; i < 3; i++) {939+ button.click()940+ await Promise.resolve()941+ }942 expect(root.innerHTML).toBe(943 '<div><p>Count: 5</p><button>+</button><div><p>Child Count: 6</p><button>+</button></div></div>'944 )945 })946 947+ it('nested useState() with children', async () => {948+ const ChildCounter = () => {949+ const [count, setCount] = useState(0)950+ return (951+ <div>952+ <p>Child Count: {count}</p>953+ <button onClick={() => setCount(count + 1)}>+</button>954+ </div>955+ )956+ }957+ const Counter = ({ children }: { children: Child }) => {958+ const [count, setCount] = useState(0)959+ return (960+ <div>961+ <p>Count: {count}</p>962+ <button onClick={() => setCount(count + 1)}>+</button>963+ {children}964+ </div>965+ )966+ }967+ const app = (968+ <Counter>969+ <ChildCounter />970+ </Counter>971+ )972+ render(app, root)973+ expect(root.innerHTML).toBe(974+ '<div><p>Count: 0</p><button>+</button><div><p>Child Count: 0</p><button>+</button></div></div>'975+ )976+ const [button, childButton] = root.querySelectorAll('button')977+ for (let i = 0; i < 3; i++) {978+ childButton.click()979+ await Promise.resolve()980+ }981+ for (let i = 0; i < 2; i++) {982+ button.click()983+ await Promise.resolve()984+ }985+ for (let i = 0; i < 3; i++) {986+ childButton.click()987+ await Promise.resolve()988+ }989+ for (let i = 0; i < 3; i++) {990+ button.click()991+ await Promise.resolve()992+ }993+ expect(root.innerHTML).toBe(994+ '<div><p>Count: 5</p><button>+</button><div><p>Child Count: 6</p><button>+</button></div></div>'995+ )996+ })997+998 it('switch child component', async () => {999 const Even = () => <p>Even</p>1000 const Odd = () => <div>Odd</div>1001 const Counter = () => {601 unmodified lines1603 expect(root.innerHTML).toBe('<div><p>1</p></div>')1604 })1605 })1606 1607+ describe('flushSync', () => {1608+ it('simple', async () => {1609+ const SubApp = ({ id }: { id: string }) => {1610+ const [count, setCount] = useState(0)1611+ return (1612+ <div id={id}>1613+ <p>{count}</p>1614+ <button onClick={() => setCount(count + 1)}>+</button>1615+ </div>1616+ )1617+ }1618+ const App = () => {1619+ return (1620+ <div>1621+ <SubApp id='a' />1622+ <SubApp id='b' />1623+ </div>1624+ )1625+ }1626+ const app = <App />1627+ render(app, root)1628+ expect(root.innerHTML).toBe(1629+ '<div><div id="a"><p>0</p><button>+</button></div><div id="b"><p>0</p><button>+</button></div></div>'1630+ )1631+ root.querySelector<HTMLButtonElement>('#b button')?.click()1632+ flushSync(() => {1633+ root.querySelector<HTMLButtonElement>('#a button')?.click()1634+ })1635+ expect(root.innerHTML).toBe(1636+ '<div><div id="a"><p>1</p><button>+</button></div><div id="b"><p>0</p><button>+</button></div></div>'1637+ )1638+ await Promise.resolve()1639+ expect(root.innerHTML).toBe(1640+ '<div><div id="a"><p>1</p><button>+</button></div><div id="b"><p>1</p><button>+</button></div></div>'1641+ )1642+ })1643+ })1644+1645+ describe('createPortal', () => {1646+ it('simple', async () => {1647+ const App = () => {1648+ const [count, setCount] = useState(0)1649+ return (1650+ <div>1651+ <button onClick={() => setCount(count + 1)}>+</button>1652+ {count <= 1 && createPortal(<p>{count}</p>, document.body)}1653+ </div>1654+ )1655+ }1656+ const app = <App />1657+ render(app, root)1658+ expect(root.innerHTML).toBe('<div><button>+</button></div>')1659+ expect(document.body.innerHTML).toBe(1660+ '<div id="root"><div><button>+</button></div></div><p>0</p>'1661+ )1662+ document.body.querySelector('button')?.click()1663+ await Promise.resolve()1664+ expect(root.innerHTML).toBe('<div><button>+</button></div>')1665+ expect(document.body.innerHTML).toBe(1666+ '<div id="root"><div><button>+</button></div></div><p>1</p>'1667+ )1668+ document.body.querySelector('button')?.click()1669+ await Promise.resolve()1670+ expect(document.body.innerHTML).toBe('<div id="root"><div><button>+</button></div></div>')1671+ })1672+ })1673+1674 describe('SVG', () => {1675 it('simple', () => {1676 const App = () => {1677 return (74 unmodified lines1752 'useRef',1753 'useCallback',1754 'useReducer',1755 'useDebugValue',1756+ 'createRef',1757+ 'forwardRef',1758+ 'useImperativeHandle',1759+ 'useSyncExternalStore',1760 'use',1761 'startTransition',1762 'useTransition',1763 'useDeferredValue',1 unmodified line1765 'useViewTransition',1766 'useMemo',1767 'useLayoutEffect',1768 'Suspense',1769+ 'Fragment',1770+ 'flushSync',1771+ 'createPortal',1772 ].forEach((key) => {1773 it(key, () => {1774 // eslint-disable-next-line @typescript-eslint/no-explicit-any1775 expect((DefaultExport as any)[key]).toBeDefined()3 unmodified linesmodified:src/jsx/dom/index.ts+36 added-5 removed
1-import type { Props, Child, JSXNode } from '../base'1+import type { Props, Child, DOMAttributes, JSXNode } from '../base'2 import { memo, isValidElement } from '../base'3+import { Children } from '../children'4 import { useContext } from '../context'5 import {6 useState,7 useEffect,9 unmodified lines17 useLayoutEffect,18 useReducer,19 useId,20 useDebugValue,21+ createRef,22+ forwardRef,23+ useImperativeHandle,24+ useSyncExternalStore,25 } from '../hooks'26 import { Suspense, ErrorBoundary } from './components'27 import { createContext } from './context'23-import { jsx } from './jsx-runtime'28+import { jsx, Fragment } from './jsx-runtime'29+import { flushSync, createPortal } from './render'30 31 export { render } from './render'32 33 const createElement = (34 tag: string | ((props: Props) => JSXNode),29- props: Props,35+ props: Props | null,36 ...children: Child[]37 ): JSXNode => {32- const jsxProps: Props = { ...props, children }38+ const jsxProps: Props = props ? { ...props } : {}39+ if (children.length) {40+ jsxProps.children = children.length === 1 ? children[0] : children41+ }42+43 let key = undefined44 if ('key' in jsxProps) {45 key = jsxProps.key46 delete jsxProps.key11 unmodified lines58 (element as JSXNode).tag,59 {60 ...(element as JSXNode).props,61 ...props,52- children: children.length ? children : (element as JSXNode).children,62+ children: children.length ? children : (element as JSXNode).props.children,63 },64 (element as JSXNode).key65 ) as T66 }14 unmodified lines81 useLayoutEffect,82 useReducer,83 useId,84 useDebugValue,85+ createRef,86+ forwardRef,87+ useImperativeHandle,88+ useSyncExternalStore,89 Suspense,90 ErrorBoundary,91 createContext,92 useContext,93 memo,94 isValidElement,95 createElement,96 cloneElement,97+ Children,98+ Fragment,99+ DOMAttributes,100+ flushSync,101+ createPortal,102 }103 104 export default {105 useState,10 unmodified lines116 useLayoutEffect,117 useReducer,118 useId,119 useDebugValue,120+ createRef,121+ forwardRef,122+ useImperativeHandle,123+ useSyncExternalStore,124 Suspense,125 ErrorBoundary,126 createContext,127 useContext,128 memo,129 isValidElement,130 createElement,131 cloneElement,132+ Children,133+ Fragment,134+ flushSync,135+ createPortal,136 }137 138 export type { Context } from '../context'139+140+// TODO: change to `export type *` after denoify bug is fixed141+// https://github.com/garronej/denoify/issues/124142+export * from '../types'modified:src/jsx/dom/jsx-dev-runtime.ts+23 added-15 removed
1-import type { Props } from '../base'1+import type { Props, JSXNode } from '../base'2 import { normalizeIntrinsicElementProps } from '../utils'3 4+const JSXNodeCompatPrototype = {5+ type: {6+ get(this: { tag: string | Function }): string | Function {7+ return this.tag8+ },9+ },10+ ref: {11+ get(this: { props?: { ref: unknown } }): unknown {12+ return this.props?.ref13+ },14+ },15+}16+4-export const jsxDEV = (tag: string | Function, props: Props, key?: string) => {17+export const jsxDEV = (tag: string | Function, props: Props, key?: string): JSXNode => {18 if (typeof tag === 'string') {19 normalizeIntrinsicElementProps(props)20 }8- let children9- if (props && 'children' in props) {10- children = props.children11- delete props['children']12- } else {13- children = []14- }15- return {16- tag,17- props,18- key,19- children: Array.isArray(children) ? children : [children],20- }21+ return Object.defineProperties(22+ {23+ tag,24+ props,25+ key,26+ },27+ JSXNodeCompatPrototype28+ ) as JSXNode29 }30 31 export const Fragment = (props: Record<string, unknown>) => jsxDEV('', props, undefined)modified:src/jsx/dom/render.ts+130 added-51 removed
1 import type { JSXNode } from '../base'2 import type { FC, Child, Props } from '../base'3+import { toArray } from '../children'3-import { DOM_RENDERER, DOM_ERROR_HANDLER, DOM_STASH } from '../constants'4+import { DOM_RENDERER, DOM_ERROR_HANDLER, DOM_STASH, DOM_INTERNAL_TAG } from '../constants'5 import type { Context as JSXContext } from '../context'6 import { globalContexts as globalJSXContexts, useContext } from '../context'7 import type { EffectData } from '../hooks'8 import { STASH_EFFECT } from '../hooks'9+import { styleObjectForEach } from '../utils'10 import { createContext } from './context' // import dom-specific versions11 12+const HONO_PORTAL_ELEMENT = '_hp'13+14 const eventAliasMap: Record<string, string> = {15 Change: 'Input',16 DoubleClick: 'DblClick',17 } as const2 unmodified lines20 svg: 'http://www.w3.org/2000/svg',21 math: 'http://www.w3.org/1998/Math/MathML',22 } as const23 24+const skipProps = new Set(['children'])25+26 // eslint-disable-next-line @typescript-eslint/no-explicit-any27 export type HasRenderToDom = FC<any> & { [DOM_RENDERER]: FC<any> }28 // eslint-disable-next-line @typescript-eslint/no-explicit-any29 export type ErrorHandler = (error: any, retry: () => void) => Child | undefined23 unmodified lines53 // eslint-disable-next-line @typescript-eslint/no-explicit-any54 any[][]55 ]56 } & JSXNode51-type NodeString = [52- string, // text content53- boolean // is dirty54-] & {57+type NodeString = {58+ t: string // text content59+ d: boolean // is dirty60+} & {61 e?: Text62 // like a NodeObject63 vC: undefined64 nN: undefined27 unmodified lines92 export const buildDataStack: [Context, Node][] = []93 94 let nameSpaceContext: JSXContext<string> | undefined = undefined95 90-const isNodeString = (node: Node): node is NodeString => Array.isArray(node)96+const isNodeString = (node: Node): node is NodeString => 't' in (node as NodeString)97 98 const getEventSpec = (key: string): [string, boolean] | undefined => {99 const match = key.match(/^on([A-Z][a-zA-Z]+?(?:PointerCapture)?)(Capture)?$/)100 if (match) {5 unmodified lines106 107 const applyProps = (container: SupportedElement, attributes: Props, oldAttributes?: Props) => {108 attributes ||= {}109 for (const [key, value] of Object.entries(attributes)) {104- if (!oldAttributes || oldAttributes[key] !== value) {110+ if (!skipProps.has(key) && (!oldAttributes || oldAttributes[key] !== value)) {111 const eventSpec = getEventSpec(key)112 if (eventSpec) {107- if (typeof value !== 'function') {108- throw new Error(`Event handler for "${key}" is not a function`)109- }110-113 if (oldAttributes) {114 container.removeEventListener(eventSpec[0], oldAttributes[key], eventSpec[1])115 }116+ if (value != null) {117+ if (typeof value !== 'function') {118+ throw new Error(`Event handler for "${key}" is not a function`)119+ }114- container.addEventListener(eventSpec[0], value, eventSpec[1])120+ container.addEventListener(eventSpec[0], value, eventSpec[1])121+ }122 } else if (key === 'dangerouslySetInnerHTML' && value) {123 container.innerHTML = value.__html124 } else if (key === 'ref') {125 if (typeof value === 'function') {126 value(container)120- } else if ('current' in value) {127+ } else if (value && 'current' in value) {128 value.current = container129 }130 } else if (key === 'style') {131+ const style = container.style132 if (typeof value === 'string') {125- container.style.cssText = value133+ style.cssText = value134 } else {127- container.style.cssText = ''128- Object.assign(container.style, value)135+ style.cssText = ''136+ if (value != null) {137+ styleObjectForEach(value, style.setProperty.bind(style))138+ }139 }140 } else {141 const nodeName = container.nodeName142 if (key === 'value') {32 unmodified lines175 }176 }177 if (oldAttributes) {178 for (const [key, value] of Object.entries(oldAttributes)) {169- if (!(key in attributes)) {179+ if (!skipProps.has(key) && !(key in attributes)) {180 const eventSpec = getEventSpec(key)181 if (eventSpec) {182 container.removeEventListener(eventSpec[0], value, eventSpec[1])183 } else if (key === 'ref') {22 unmodified lines206 const func = (node.tag as HasRenderToDom)[DOM_RENDERER] || node.tag207 try {208 return [209 func.call(null, {210+ // eslint-disable-next-line @typescript-eslint/no-explicit-any211+ ...((func as any).defaultProps || {}),212 ...node.props,201- children: node.children,213 }),214 ]215 } finally {216 buildDataStack.pop()47 unmodified lines264 265 const removeNode = (node: Node) => {266 if (!isNodeString(node)) {267 node[DOM_STASH]?.[1][STASH_EFFECT]?.forEach((data: EffectData) => data[2]?.())268+269+ if (node.e && node.props?.ref) {270+ if (typeof node.props.ref === 'function') {271+ node.props.ref(null)272+ } else {273+ node.props.ref.current = null274+ }275+ }276 node.vC?.forEach(removeNode)277 }259- node.e?.remove()260- node.tag = undefined278+ if (node.tag !== HONO_PORTAL_ELEMENT) {279+ node.e?.remove()280+ }281+ if (typeof node.tag === 'function') {282+ updateMap.delete(node)283+ fallbackUpdateFnArrayMap.delete(node)284+ }285 }286 287 const apply = (node: NodeObject, container: Container) => {264- if (node.tag === undefined) {265- return266- }267-288 node.c = container289 applyNodeObject(node, container)290 }291 292 const applyNode = (node: Node, container: Container) => {293 if (isNodeString(node)) {274- container.textContent = node[0]294+ container.textContent = node.t295 } else {296 applyNodeObject(node, container)297 }298 }31 unmodified lines330 const child = next[i]331 332 let el: SupportedElement | Text333 if (isNodeString(child)) {314- if (child.e && child[1]) {315- child.e.textContent = child[0]334+ if (child.e && child.d) {335+ child.e.textContent = child.t336 }317- child[1] = false318- el = child.e ||= document.createTextNode(child[0])337+ child.d = false338+ el = child.e ||= document.createTextNode(child.t)339 } else {340 el = child.e ||= child.n341 ? (document.createElementNS(child.n, child.tag as string) as SVGElement | MathMLElement)342 : document.createElement(child.tag as string)343 applyProps(el as HTMLElement, child.props, child.pP)344 applyNode(child, el as HTMLElement)345 }326- if (childNodes[offset] !== el && childNodes[offset - 1] !== child.e) {346+ if (347+ childNodes[offset] !== el &&348+ childNodes[offset - 1] !== child.e &&349+ child.tag !== HONO_PORTAL_ELEMENT350+ ) {351 container.insertBefore(el, childNodes[offset] || null)352 }353 }354 remove.forEach(removeNode)2 unmodified lines357 callbacks.forEach(([, , , cb]) => cb?.())358 })359 }360 361+const fallbackUpdateFnArrayMap = new WeakMap<362+ NodeObject,363+ Array<() => Promise<NodeObject | undefined>>364+>()365 export const build = (366 context: Context,367 node: NodeObject,368 topLevelErrorHandlerNode: NodeObject | undefined,369 children?: Child[]370 ): void => {343- if (node.tag === undefined) {344- return345- }346-371 let errorHandler: ErrorHandler | undefined348- children ||= typeof node.tag == 'function' ? invokeTag(context, node) : node.children372+ children ||=373+ typeof node.tag == 'function' ? invokeTag(context, node) : toArray(node.props.children)374 if ((children[0] as JSXNode)?.tag === '') {375 // eslint-disable-next-line @typescript-eslint/no-explicit-any376 errorHandler = (children[0] as any)[DOM_ERROR_HANDLER] as ErrorHandler377 topLevelErrorHandlerNode ||= node10 unmodified lines388 prevNode.nN = child389 }390 prevNode = child391 367- if (typeof child.tag === 'function' && globalJSXContexts.length > 0) {392+ if (393+ typeof child.tag === 'function' &&394+ // eslint-disable-next-line @typescript-eslint/no-explicit-any395+ !(child.tag as any)[DOM_INTERNAL_TAG] &&396+ globalJSXContexts.length > 0397+ ) {398 child[DOM_STASH][2] = globalJSXContexts.map((c) => [c, c.values.at(-1)])399 }400 401 let oldChild: Node | undefined7 unmodified lines409 if (isNodeString(child)) {410 if (!isNodeString(oldChild)) {411 vChildrenToRemove.push(oldChild)412 } else {383- if (oldChild[0] !== child[0]) {384- oldChild[0] = child[0] // update text content385- oldChild[1] = true413+ if (oldChild.t !== child.t) {414+ oldChild.t = child.t // update text content415+ oldChild.d = true416 }417 child = oldChild418 }419 } else if (oldChild.tag !== child.tag) {420 vChildrenToRemove.push(oldChild)421 } else {422 oldChild.pP = oldChild.props423 oldChild.props = child.props394- oldChild.children = child.children424+ if (typeof child.tag === 'function') {425+ oldChild[DOM_STASH][2] = child[DOM_STASH][2] || []426+ }427 child = oldChild428 }429 } else if (!isNodeString(child) && nameSpaceContext) {430 const ns = useContext(nameSpaceContext)12 unmodified lines443 vChildrenToRemove.push(...oldVChildren)444 node.vR = vChildrenToRemove445 } catch (e) {446 if (errorHandler) {415- const fallback = errorHandler(e, () =>447+ const fallbackUpdateFn = () =>448 update([0, false, context[2] as UpdateHook], topLevelErrorHandlerNode as NodeObject)417- )449+ const fallbackUpdateFnArray =450+ fallbackUpdateFnArrayMap.get(topLevelErrorHandlerNode as NodeObject) || []451+ fallbackUpdateFnArray.push(fallbackUpdateFn)452+ fallbackUpdateFnArrayMap.set(topLevelErrorHandlerNode as NodeObject, fallbackUpdateFnArray)453+ const fallback = errorHandler(e, () => {454+ const fnArray = fallbackUpdateFnArrayMap.get(topLevelErrorHandlerNode as NodeObject)455+ if (fnArray) {456+ const i = fnArray.indexOf(fallbackUpdateFn)457+ if (i !== -1) {458+ fnArray.splice(i, 1)459+ return fallbackUpdateFn()460+ }461+ }462+ })463 if (fallback) {464 if (context[0] === 1) {465 context[1] = true466 } else {9 unmodified lines476 const buildNode = (node: Child): Node | undefined => {477 if (node === undefined || node === null || typeof node === 'boolean') {478 return undefined479 } else if (typeof node === 'string' || typeof node === 'number') {435- return [node.toString(), true] as NodeString480+ return { t: node.toString(), d: true } as NodeString481 } else {482 if (typeof (node as JSXNode).tag === 'function') {483+ if ((node as NodeObject)[DOM_STASH]) {484+ node = { ...node } as NodeObject485+ }486 ;(node as NodeObject)[DOM_STASH] = [0, []]487 } else {488 const ns = nameSpaceMap[(node as JSXNode).tag as string]489 if (ns) {490 ;(node as NodeObject).n = ns491 nameSpaceContext ||= createContext('')444- ;(node as JSXNode).children = [492+ ;(node as JSXNode).props.children = [493 {494 tag: nameSpaceContext.Provider,495 props: {496 value: ns,497+ children: (node as JSXNode).props.children,498 },450- children: (node as JSXNode).children,499 },500 // eslint-disable-next-line @typescript-eslint/no-explicit-any501 ] as any502 }23 unmodified lines526 }527 528 type UpdateMapResolve = (node: NodeObject | undefined) => void529 const updateMap = new WeakMap<NodeObject, [UpdateMapResolve, Function]>()530+const currentUpdateSets: Set<NodeObject>[] = []531 export const update = async (532 context: Context,533 node: NodeObject534 ): Promise<NodeObject | undefined> => {18 unmodified lines553 }554 },555 ])556 557+ if (currentUpdateSets.length) {558+ ;(currentUpdateSets.at(-1) as Set<NodeObject>).add(node)559+ } else {508- await Promise.resolve()560+ await Promise.resolve()561 510- const latest = updateMap.get(node)511- if (latest) {512- updateMap.delete(node)513- latest[1]()562+ const latest = updateMap.get(node)563+ if (latest) {564+ updateMap.delete(node)565+ latest[1]()566+ }567 }568 569 return promise570 }571 572 export const render = (jsxNode: unknown, container: Container) => {573+ // eslint-disable-next-line @typescript-eslint/no-explicit-any520- const node = buildNode({ tag: '', children: [jsxNode] } as JSXNode) as NodeObject574+ const node = buildNode({ tag: '', props: { children: jsxNode } } as any) as NodeObject575 build([], node, undefined)576 577 const fragment = document.createDocumentFragment()578 apply(node, fragment)579 replaceContainer(node, fragment, container)580 container.replaceChildren(fragment)581 }582+583+export const flushSync = (callback: () => void) => {584+ const set = new Set<NodeObject>()585+ currentUpdateSets.push(set)586+ callback()587+ set.forEach((node) => {588+ const latest = updateMap.get(node)589+ if (latest) {590+ updateMap.delete(node)591+ latest[1]()592+ }593+ })594+ currentUpdateSets.pop()595+}596+597+export const createPortal = (children: Child, container: HTMLElement, key?: string): Child =>598+ ({599+ tag: HONO_PORTAL_ELEMENT,600+ props: {601+ children,602+ },603+ key,604+ e: container,605+ // eslint-disable-next-line @typescript-eslint/no-explicit-any606+ } as any)added:src/jsx/dom/utils.ts+7 added
1+import { DOM_INTERNAL_TAG } from '../constants'2+3+export const setInternalTagFlag = (fn: Function) => {4+ // eslint-disable-next-line @typescript-eslint/no-explicit-any5+ ;(fn as any)[DOM_INTERNAL_TAG] = true6+ return fn7+}modified:src/jsx/hooks/dom.test.tsx+94 added
14 unmodified lines15 startViewTransition,16 useViewTransition,17 useId,18 useDebugValue,19+ createRef,20+ forwardRef,21+ useImperativeHandle,22+ useSyncExternalStore,23 } from '.'24 25 describe('Hooks', () => {26 beforeAll(() => {446 unmodified lines473 expect(root.innerHTML).toBe('<div></div>')474 expect(spy).not.toBeCalled()475 })476 })477+478+ describe('createRef()', () => {479+ it('simple', () => {480+ const ref: { current: HTMLElement | null } = createRef<HTMLDivElement>()481+ const App = () => {482+ return <div ref={ref} />483+ }484+ render(<App />, root)485+ expect(root.innerHTML).toBe('<div></div>')486+ expect(ref.current).toBeInstanceOf(HTMLElement)487+ })488+ })489+490+ describe('forwardRef()', () => {491+ it('simple', () => {492+ const ref: { current: HTMLElement | null } = createRef<HTMLDivElement>()493+ const App = forwardRef((props, ref) => {494+ return <div {...props} ref={ref} />495+ })496+ render(<App ref={ref} />, root)497+ expect(root.innerHTML).toBe('<div></div>')498+ expect(ref.current).toBeInstanceOf(HTMLElement)499+ })500+ })501+502+ describe('useImperativeHandle()', () => {503+ it('simple', async () => {504+ const ref: { current: { focus: () => void } | null } = createRef()505+ const SubApp = () => {506+ useImperativeHandle(507+ ref,508+ () => ({509+ focus: () => {510+ console.log('focus')511+ },512+ }),513+ []514+ )515+ return <div />516+ }517+ const App = () => {518+ const [show, setShow] = useState(true)519+ return (520+ <>521+ {show && <SubApp />}522+ <button onClick={() => setShow((s) => !s)}>toggle</button>523+ </>524+ )525+ }526+ render(<App />, root)527+ expect(ref.current).toBe(null)528+ await new Promise((r) => setTimeout(r))529+ expect(ref.current).toEqual({ focus: expect.any(Function) })530+ root.querySelector('button')?.click()531+ await new Promise((r) => setTimeout(r))532+ expect(ref.current).toBe(null)533+ })534+ })535+536+ describe('useSyncExternalStore()', () => {537+ it('simple', async () => {538+ let count = 0539+ const unsubscribe = vi.fn()540+ const subscribe = vi.fn(() => unsubscribe)541+ const getSnapshot = vi.fn(() => count++)542+ const SubApp = () => {543+ const count = useSyncExternalStore(subscribe, getSnapshot)544+ return <div>{count}</div>545+ }546+ const App = () => {547+ const [show, setShow] = useState(true)548+ return (549+ <>550+ {show && <SubApp />}551+ <button onClick={() => setShow((s) => !s)}>toggle</button>552+ </>553+ )554+ }555+ render(<App />, root)556+ expect(root.innerHTML).toBe('<div>0</div><button>toggle</button>')557+ await new Promise((r) => setTimeout(r))558+ root.querySelector('button')?.click()559+ await new Promise((r) => setTimeout(r))560+ expect(root.innerHTML).toBe('<button>toggle</button>')561+ expect(unsubscribe).toBeCalled()562+ root.querySelector('button')?.click()563+ await new Promise((r) => setTimeout(r))564+ expect(root.innerHTML).toBe('<div>1</div><button>toggle</button>')565+ })566+ })567 })modified:src/jsx/hooks/index.ts+50 added-1 removed
164 unmodified lines165 if (typeof newState === 'function') {166 newState = (newState as (currentState: T) => T)(stateData[0])167 }168 169- if (newState !== stateData[0]) {169+ if (!Object.is(newState, stateData[0])) {170 stateData[0] = newState171 if (pendingStack.length) {172 const pendingType = pendingStack.at(-1) as PendingType173 update([pendingType, false, localUpdateHook as UpdateHook], node).then((node) => {186 unmodified lines360 361 // Define to avoid errors. This hook currently does nothing.362 // eslint-disable-next-line @typescript-eslint/no-unused-vars363 export const useDebugValue = (_value: unknown, _formatter?: (value: unknown) => string): void => {}364+365+export const createRef = <T>(): RefObject<T> => {366+ return { current: null }367+}368+369+export const forwardRef = <T, P = {}>(370+ Component: (props: P, ref: RefObject<T>) => JSX.Element371+): ((props: P & { ref: RefObject<T> }) => JSX.Element) => {372+ return (props) => {373+ const { ref, ...rest } = props374+ return Component(rest as P, ref)375+ }376+}377+378+export const useImperativeHandle = <T>(379+ ref: RefObject<T>,380+ createHandle: () => T,381+ deps: readonly unknown[]382+): void => {383+ useEffect(() => {384+ ref.current = createHandle()385+ return () => {386+ ref.current = null387+ }388+ }, deps)389+}390+391+let useSyncExternalStoreGetServerSnapshotNotified = false392+export const useSyncExternalStore = <T>(393+ subscribe: (callback: (value: T) => void) => () => void,394+ getSnapshot: () => T,395+ getServerSnapshot?: () => T396+): T => {397+ const [state, setState] = useState(getSnapshot())398+ useEffect(399+ () =>400+ subscribe(() => {401+ setState(getSnapshot())402+ }),403+ []404+ )405+406+ if (getServerSnapshot && !useSyncExternalStoreGetServerSnapshotNotified) {407+ useSyncExternalStoreGetServerSnapshotNotified = true408+ console.info('`getServerSnapshot` is not supported yet.')409+ }410+411+ return state412+}modified:src/jsx/base.ts+44 added-29 removed
2 unmodified lines3 import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../utils/html'4 import type { Context } from './context'5 import { globalContexts } from './context'6 import type { IntrinsicElements as IntrinsicElementsDefined } from './intrinsic-elements'7-import { normalizeIntrinsicElementProps } from './utils'7+import { normalizeIntrinsicElementProps, styleObjectForEach } from './utils'8 9 // eslint-disable-next-line @typescript-eslint/no-explicit-any10 export type Props = Record<string, any>11-export type FC<T = Props> = (props: T) => HtmlEscapedString | Promise<HtmlEscapedString>11+export type FC<P = Props> = {12+ (props: P): HtmlEscapedString | Promise<HtmlEscapedString>13+ defaultProps?: Partial<P> | undefined14+ displayName?: string | undefined15+}16+export type DOMAttributes = Hono.HTMLAttributes17 18 declare global {19 // eslint-disable-next-line @typescript-eslint/no-namespace20 namespace JSX {97 unmodified lines118 this.props = props119 this.children = children120 }121 122+ get type(): string | Function {123+ return this.tag as string124+ }125+126+ // Added for compatibility with libraries that rely on React's internal structure127+ // eslint-disable-next-line @typescript-eslint/no-explicit-any128+ get ref(): any {129+ return this.props.ref || null130+ }131+132 toString(): string | Promise<string> {133 const buffer: StringBuffer = ['']134 this.localContexts?.forEach(([context, value]) => {135 context.values.push(value)19 unmodified lines155 156 for (let i = 0, len = propsKeys.length; i < len; i++) {157 const key = propsKeys[i]158 const v = props[key]144- // object to style strings145- if (key === 'style' && typeof v === 'object') {146- const styles = Object.keys(v)147- .map((k) => {148- const property = k.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`)149- return `${property}:${v[k]}`150- })151- .join(';')159+ if (key === 'children') {160+ // skip children161+ } else if (key === 'style' && typeof v === 'object') {162+ // object to style strings163+ let styleStr = ''164+ styleObjectForEach(v, (property, value) => {165+ if (value != null) {166+ styleStr += `${styleStr ? ';' : ''}${property}:${value}`167+ }168+ })169 buffer[0] += ' style="'153- escapeToBuffer(styles, buffer)170+ escapeToBuffer(styleStr, buffer)171 buffer[0] += '"'172 } else if (typeof v === 'string') {173 buffer[0] += ` ${key}="`174 escapeToBuffer(v, buffer)82 unmodified lines257 }258 259 export const jsx = (260 tag: string | Function,244- props: Props,245- ...children: (string | HtmlEscapedString)[]261+ props: Props | null,262+ ...children: (string | number | HtmlEscapedString)[]263 ): JSXNode => {247- let key248- if (props) {249- key = props?.key250- delete props['key']264+ props ??= {}265+ if (children.length) {266+ props.children = children.length === 1 ? children[0] : children267 }268+269+ const key = props.key270+ delete props['key']271+272 const node = jsxFn(tag, props, children)273 node.key = key274 return node275 }276 277 export const jsxFn = (278 tag: string | Function,279 props: Props,260- children: (string | HtmlEscapedString)[]280+ children: (string | number | HtmlEscapedString)[]281 ): JSXNode => {282 if (typeof tag === 'function') {283 return new JSXFunctionNode(tag, props, children)284 } else {51 unmodified lines336 children?: Child | HtmlEscapedString337 }): HtmlEscapedString => {338 return new JSXFragmentNode(339 '',320- {},340+ {341+ children,342+ },343 Array.isArray(children) ? children : children ? [children] : []344 ) as never345 }346 347 export const isValidElement = (element: unknown): element is JSXNode => {326- return !!(327- element &&328- typeof element === 'object' &&329- 'tag' in element &&330- 'props' in element &&331- 'children' in element332- )348+ return !!(element && typeof element === 'object' && 'tag' in element && 'props' in element)349 }350 351 export const cloneElement = <T extends JSXNode | JSX.Element>(352 element: T,353 props: Partial<Props>,354 ...children: Child[]355 ): T => {340- return jsxFn(356+ return jsx(357 (element as JSXNode).tag,358 { ...(element as JSXNode).props, ...props },343- // eslint-disable-next-line @typescript-eslint/no-explicit-any344- children.length ? children : ((element as JSXNode).children as any) || []359+ ...(children as (string | number | HtmlEscapedString)[])360 ) as T361 }added:src/jsx/children.test.ts+52 added
1+import { Children } from './children'2+import { createElement } from '.'3+4+describe('map', () => {5+ it('should map children', () => {6+ const element = createElement('div', null, 1, 2, 3)7+ const result = Children.map(element.children, (child) => (child as number) * 2)8+ expect(result).toEqual([2, 4, 6])9+ })10+})11+12+describe('forEach', () => {13+ it('should iterate children', () => {14+ const element = createElement('div', null, 1, 2, 3)15+ const result: number[] = []16+ Children.forEach(element.children, (child) => {17+ result.push(child as number)18+ })19+ expect(result).toEqual([1, 2, 3])20+ })21+})22+23+describe('count', () => {24+ it('should count children', () => {25+ const element = createElement('div', null, 1, 2, 3)26+ const result = Children.count(element.children)27+ expect(result).toBe(3)28+ })29+})30+31+describe('only', () => {32+ it('should return the only child', () => {33+ const element = createElement('div', null, 1)34+ const result = Children.only(element.children)35+ expect(result).toBe(1)36+ })37+38+ it('should throw an error if there are multiple children', () => {39+ const element = createElement('div', null, 1, 2)40+ expect(() => Children.only(element.children)).toThrowError(41+ 'Children.only() expects only one child'42+ )43+ })44+})45+46+describe('toArray', () => {47+ it('should convert children to an array', () => {48+ const element = createElement('div', null, 1, 2, 3)49+ const result = Children.toArray(element.children)50+ expect(result).toEqual([1, 2, 3])51+ })52+})added:src/jsx/children.ts+20 added
1+import type { Child } from './base'2+3+export const toArray = (children: Child): Child[] =>4+ Array.isArray(children) ? children : [children]5+export const Children = {6+ map: (children: Child[], fn: (child: Child, index: number) => Child): Child[] =>7+ toArray(children).map(fn),8+ forEach: (children: Child[], fn: (child: Child, index: number) => void): void => {9+ toArray(children).forEach(fn)10+ },11+ count: (children: Child[]): number => toArray(children).length,12+ only: (_children: Child[]): Child => {13+ const children = toArray(_children)14+ if (children.length !== 1) {15+ throw new Error('Children.only() expects only one child')16+ }17+ return children[0]18+ },19+ toArray,20+}modified:src/jsx/constants.ts+1 added
1 export const DOM_RENDERER = Symbol('RENDERER')2 export const DOM_ERROR_HANDLER = Symbol('ERROR_HANDLER')3 export const DOM_STASH = Symbol('STASH')4+export const DOM_INTERNAL_TAG = Symbol('INTERNAL')modified:src/jsx/index.test.tsx+8 added
383 unmodified lines384 it('should not convert the strings', () => {385 const template = <h1 style='color:red;font-size:small'>Hello</h1>386 expect(template.toString()).toBe('<h1 style="color:red;font-size:small">Hello</h1>')387 })388+ it('should render variable without any name conversion', () => {389+ const template = <h1 style={{ '--myVar': 1 }}>Hello</h1>390+ expect(template.toString()).toBe('<h1 style="--myVar:1px">Hello</h1>')391+ })392 })393 394 describe('HtmlEscaped in props', () => {395 it('should not be double-escaped', () => {349 unmodified lines745 'useRef',746 'useCallback',747 'useReducer',748 'useDebugValue',749+ 'createRef',750+ 'forwardRef',751+ 'useImperativeHandle',752+ 'useSyncExternalStore',753 'use',754 'startTransition',755 'useTransition',756 'useDeferredValue',12 unmodified linesmodified:src/jsx/index.ts+17 added
1 import { jsx, memo, Fragment, isValidElement, cloneElement } from './base'2+import type { DOMAttributes } from './base'3+import { Children } from './children'4 import { ErrorBoundary } from './components'5 import { createContext, useContext } from './context'6 import {7 useState,10 unmodified lines18 useLayoutEffect,19 useReducer,20 useId,21 useDebugValue,22+ createRef,23+ forwardRef,24+ useImperativeHandle,25+ useSyncExternalStore,26 } from './hooks'27 import { Suspense } from './streaming'28 29 export {20 unmodified lines50 startViewTransition,51 useViewTransition,52 useMemo,53 useLayoutEffect,54+ createRef,55+ forwardRef,56+ useImperativeHandle,57+ useSyncExternalStore,58 Suspense,59+ Children,60+ DOMAttributes,61 }62 63 export default {64 memo,18 unmodified lines83 startViewTransition,84 useViewTransition,85 useMemo,86 useLayoutEffect,87+ createRef,88+ forwardRef,89+ useImperativeHandle,90+ useSyncExternalStore,91 Suspense,92+ Children,93 }94 95 // TODO: change to `export type *` after denoify bug is fixed96 // https://github.com/garronej/denoify/issues/1241 unmodified linemodified:src/jsx/jsx-dev-runtime.ts-1 removed
11 unmodified lines12 if (!props || !('children' in props)) {13 node = jsxFn(tag, props, [])14 } else {15 const children = props.children as string | HtmlEscapedString16- delete props['children']16 node = Array.isArray(children) ? jsxFn(tag, props, children) : jsxFn(tag, props, [children])17 }18 node.key = key19 return node1 unmodified linemodified:src/jsx/types.ts+30 added-1 removed
1 /**2 * All types exported from "hono/jsx" are in this file.3 */4-import type { Child } from './base'4+import type { Child, JSXNode } from './base'5 6 export type { Child, JSXNode, FC } from './base'7 export type { RefObject } from './hooks'8 export type { Context } from './context'9 10 export type PropsWithChildren<P = unknown> = P & { children?: Child | undefined }11 export type CSSProperties = Hono.CSSProperties12+13+/**14+ * React types15+ */16+17+// eslint-disable-next-line @typescript-eslint/no-explicit-any18+type ReactElement<P = any, T = string | Function> = JSXNode & {19+ type: T20+ props: P21+ key: string | null22+}23+type ReactNode = ReactElement | string | number | boolean | null | undefined24+// eslint-disable-next-line @typescript-eslint/no-unused-vars25+type ComponentClass<P = {}, S = {}> = unknown26+27+export type { ReactElement, ReactNode, ComponentClass }28+29+export type Event = globalThis.Event30+export type MouseEvent = globalThis.MouseEvent31+export type KeyboardEvent = globalThis.KeyboardEvent32+export type FocusEvent = globalThis.FocusEvent33+export type ClipboardEvent = globalThis.ClipboardEvent34+export type InputEvent = globalThis.InputEvent35+export type PointerEvent = globalThis.PointerEvent36+export type TouchEvent = globalThis.TouchEvent37+export type WheelEvent = globalThis.WheelEvent38+export type AnimationEvent = globalThis.AnimationEvent39+export type TransitionEvent = globalThis.TransitionEvent40+export type DragEvent = globalThis.DragEventmodified:src/jsx/utils.ts+14 added
2 unmodified lines3 props['class'] = props['className']4 delete props['className']5 }6 }7+8+export const styleObjectForEach = (9+ style: Record<string, string>,10+ fn: (key: string, value: string | null) => void11+): void => {12+ for (const [k, v] of Object.entries(style)) {13+ fn(14+ k[0] === '-'15+ ? k // CSS variable16+ : k.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`), // style property. convert to kebab-case17+ v == null ? null : typeof v === 'number' ? v + 'px' : (v as string)18+ )19+ }20+}modified:src/middleware/bearer-auth/index.test.ts+26 added
54 unmodified lines55 app.get('/auth-verify-token/*', (c) => {56 handlerExecuted = true57 return c.text('auth-verify-token')58 })59+60+ app.use('/auth-custom-header/*', bearerAuth({ token: tokens, headerName: 'X-Auth' }))61+ app.get('/auth-custom-header/*', (c) => {62+ handlerExecuted = true63+ return c.text('auth-custom-header')64+ })65 })66 67 it('Should authorize', async () => {68 const req = new Request('http://localhost/auth/a')112 unmodified lines181 expect(res).not.toBeNull()182 expect(handlerExecuted).toBeFalsy()183 expect(res.status).toBe(401)184 })185+186+ it('Should authorize - custom header', async () => {187+ const req = new Request('http://localhost/auth-custom-header/a')188+ req.headers.set('X-Auth', 'Bearer abcdefg12345-._~+/=')189+ const res = await app.request(req)190+ expect(res).not.toBeNull()191+ expect(res.status).toBe(200)192+ expect(handlerExecuted).toBeTruthy()193+ expect(await res.text()).toBe('auth-custom-header')194+ })195+196+ it('Should not authorize - custom header', async () => {197+ const req = new Request('http://localhost/auth-custom-header/a')198+ req.headers.set('X-Auth', 'Bearer invalid-token')199+ const res = await app.request(req)200+ expect(res).not.toBeNull()201+ expect(handlerExecuted).toBeFalsy()202+ expect(res.status).toBe(401)203+ expect(await res.text()).toBe('Unauthorized')204+ })205 })modified:src/middleware/bearer-auth/index.ts+4 added-1 removed
3 unmodified lines4 import { timingSafeEqual } from '../../utils/buffer'5 6 const TOKEN_STRINGS = '[A-Za-z0-9._~+/-]+=*'7 const PREFIX = 'Bearer'8+const HEADER = 'Authorization'9 10 type BearerAuthOptions =11 | {12 token: string | string[]13 realm?: string14 prefix?: string15+ headerName?: string16 hashFunction?: Function17 }18 | {19 realm?: string20 prefix?: string21+ headerName?: string22 verifyToken: (token: string, c: Context) => boolean | Promise<boolean>23 hashFunction?: Function24 }25 10 unmodified lines36 37 const realm = options.realm?.replace(/"/g, '\\"')38 39 return async function bearerAuth(c, next) {37- const headerToken = c.req.header('Authorization')40+ const headerToken = c.req.header(options.headerName || HEADER)41 42 if (!headerToken) {43 // No Authorization header44 const res = new Response('Unauthorized', {47 unmodified linesmodified:src/middleware/secure-headers/index.test.ts+84 added-1 removed
1 /* eslint-disable quotes */2 import { Hono } from '../../hono'3 import { poweredBy } from '../powered-by'4-import { secureHeaders } from '.'4+import { secureHeaders, NONCE } from '.'5+import type { ContentSecurityPolicyOptionHandler } from '.'6 7+declare module '../../context' {8+ interface ContextVariableMap {9+ ['test-scriptSrc-nonce']?: string10+ ['test-styleSrc-nonce']?: string11+ }12+}13+14 describe('Secure Headers Middleware', () => {15 it('default middleware', async () => {16 const app = new Hono()17 app.use('*', secureHeaders())311 unmodified lines329 'e1="https://a.example.com/reports", e2="https://b.example.com/reports"'330 )331 expect(res4.headers.get('Content-Security-Policy')).toEqual("default-src 'self'; report-to e1")332 })333+334+ it('CSP nonce for script-src', async () => {335+ const app = new Hono()336+ app.use(337+ '/test',338+ secureHeaders({339+ contentSecurityPolicy: {340+ scriptSrc: ["'self'", NONCE],341+ },342+ })343+ )344+345+ app.all('*', async (c) => {346+ return c.text(`nonce: ${c.get('secureHeadersNonce')}`)347+ })348+349+ const res = await app.request('/test')350+ const csp = res.headers.get('Content-Security-Policy')351+ const nonce = csp?.match(/script-src 'self' 'nonce-([a-zA-Z0-9+/]+=*)'/)?.[1] || ''352+ expect(csp).toMatch(`script-src 'self' 'nonce-${nonce}'`)353+ expect(await res.text()).toEqual(`nonce: ${nonce}`)354+ })355+356+ it('CSP nonce for script-src and style-src', async () => {357+ const app = new Hono()358+ app.use(359+ '/test',360+ secureHeaders({361+ contentSecurityPolicy: {362+ scriptSrc: ["'self'", NONCE],363+ styleSrc: ["'self'", NONCE],364+ },365+ })366+ )367+368+ app.all('*', async (c) => {369+ return c.text(`nonce: ${c.get('secureHeadersNonce')}`)370+ })371+372+ const res = await app.request('/test')373+ const csp = res.headers.get('Content-Security-Policy')374+ const nonce = csp?.match(/script-src 'self' 'nonce-([a-zA-Z0-9+/]+=*)'/)?.[1] || ''375+ expect(csp).toMatch(`script-src 'self' 'nonce-${nonce}'`)376+ expect(csp).toMatch(`style-src 'self' 'nonce-${nonce}'`)377+ expect(await res.text()).toEqual(`nonce: ${nonce}`)378+ })379+380+ it('CSP nonce by app own function', async () => {381+ const app = new Hono()382+ const setNonce: ContentSecurityPolicyOptionHandler = (ctx, directive) => {383+ ctx.set(`test-${directive}-nonce`, directive)384+ return `'nonce-${directive}'`385+ }386+ app.use(387+ '/test',388+ secureHeaders({389+ contentSecurityPolicy: {390+ scriptSrc: ["'self'", setNonce],391+ styleSrc: ["'self'", setNonce],392+ },393+ })394+ )395+396+ app.all('*', async (c) => {397+ return c.text(398+ `script: ${c.get('test-scriptSrc-nonce')}, style: ${c.get('test-styleSrc-nonce')}`399+ )400+ })401+402+ const res = await app.request('/test')403+ const csp = res.headers.get('Content-Security-Policy')404+ expect(csp).toMatch(`script-src 'self' 'nonce-scriptSrc'`)405+ expect(csp).toMatch(`style-src 'self' 'nonce-styleSrc'`)406+ expect(await res.text()).toEqual('script: scriptSrc, style: styleSrc')407+ })408 })modified:src/middleware/secure-headers/index.ts+107 added-32 removed
1 import type { Context } from '../../context'2 import type { MiddlewareHandler } from '../../types'3 4+declare module '../../context' {5+ interface ContextVariableMap {6+ secureHeadersNonce?: string7+ }8+}9+10+export type ContentSecurityPolicyOptionHandler = (ctx: Context, directive: string) => string11+type ContentSecurityPolicyOptionValue = (string | ContentSecurityPolicyOptionHandler)[]12+13 interface ContentSecurityPolicyOptions {5- defaultSrc?: string[]6- baseUri?: string[]7- childSrc?: string[]8- connectSrc?: string[]9- fontSrc?: string[]10- formAction?: string[]11- frameAncestors?: string[]12- frameSrc?: string[]13- imgSrc?: string[]14- manifestSrc?: string[]15- mediaSrc?: string[]16- objectSrc?: string[]14+ defaultSrc?: ContentSecurityPolicyOptionValue15+ baseUri?: ContentSecurityPolicyOptionValue16+ childSrc?: ContentSecurityPolicyOptionValue17+ connectSrc?: ContentSecurityPolicyOptionValue18+ fontSrc?: ContentSecurityPolicyOptionValue19+ formAction?: ContentSecurityPolicyOptionValue20+ frameAncestors?: ContentSecurityPolicyOptionValue21+ frameSrc?: ContentSecurityPolicyOptionValue22+ imgSrc?: ContentSecurityPolicyOptionValue23+ manifestSrc?: ContentSecurityPolicyOptionValue24+ mediaSrc?: ContentSecurityPolicyOptionValue25+ objectSrc?: ContentSecurityPolicyOptionValue26 reportTo?: string18- sandbox?: string[]19- scriptSrc?: string[]20- scriptSrcAttr?: string[]21- scriptSrcElem?: string[]22- styleSrc?: string[]23- styleSrcAttr?: string[]24- styleSrcElem?: string[]25- upgradeInsecureRequests?: string[]26- workerSrc?: string[]27+ sandbox?: ContentSecurityPolicyOptionValue28+ scriptSrc?: ContentSecurityPolicyOptionValue29+ scriptSrcAttr?: ContentSecurityPolicyOptionValue30+ scriptSrcElem?: ContentSecurityPolicyOptionValue31+ styleSrc?: ContentSecurityPolicyOptionValue32+ styleSrcAttr?: ContentSecurityPolicyOptionValue33+ styleSrcElem?: ContentSecurityPolicyOptionValue34+ upgradeInsecureRequests?: ContentSecurityPolicyOptionValue35+ workerSrc?: ContentSecurityPolicyOptionValue36 }37 38 interface ReportToOptions {39 group: string63 unmodified lines103 xPermittedCrossDomainPolicies: true,104 xXssProtection: true,105 }106 107+type SecureHeadersCallback = (108+ ctx: Context,109+ headersToSet: [string, string | string[]][]110+) => [string, string][]111+112+const generateNonce = () => {113+ const buffer = new Uint8Array(16)114+ crypto.getRandomValues(buffer)115+ return Buffer.from(buffer).toString('base64')116+}117+export const NONCE: ContentSecurityPolicyOptionHandler = (ctx) => {118+ const nonce =119+ ctx.get('secureHeadersNonce') ||120+ (() => {121+ const newNonce = generateNonce()122+ ctx.set('secureHeadersNonce', newNonce)123+ return newNonce124+ })()125+ return `'nonce-${nonce}'`126+}127+128 export const secureHeaders = (customOptions?: Partial<SecureHeadersOptions>): MiddlewareHandler => {129 const options = { ...DEFAULT_OPTIONS, ...customOptions }130 const headersToSet = getFilteredHeaders(options)131+ const callbacks: SecureHeadersCallback[] = []132 133 if (options.contentSecurityPolicy) {103- headersToSet.push(['Content-Security-Policy', getCSPDirectives(options.contentSecurityPolicy)])134+ const [callback, value] = getCSPDirectives(options.contentSecurityPolicy)135+ if (callback) {136+ callbacks.push(callback)137+ }138+ headersToSet.push(['Content-Security-Policy', value as string])139 }140 141 if (options.reportingEndpoints) {142 headersToSet.push(['Reporting-Endpoints', getReportingEndpoints(options.reportingEndpoints)])3 unmodified lines146 headersToSet.push(['Report-To', getReportToOptions(options.reportTo)])147 }148 149 return async function secureHeaders(ctx, next) {150+ // should evaluate callbacks before next()151+ // some callback calls ctx.set() for embedding nonce to the page152+ const headersToSetForReq =153+ callbacks.length === 0154+ ? headersToSet155+ : callbacks.reduce((acc, cb) => cb(ctx, acc), headersToSet)156 await next()116- setHeaders(ctx, headersToSet)157+ setHeaders(ctx, headersToSetForReq)158 ctx.res.headers.delete('X-Powered-By')159 }160 }161 6 unmodified lines168 })169 }170 171 function getCSPDirectives(131- contentSecurityPolicy: SecureHeadersOptions['contentSecurityPolicy']132-): string {133- return Object.entries(contentSecurityPolicy || [])134- .map(([directive, value]) => {135- const kebabCaseDirective = directive.replace(/[A-Z]+(?![a-z])|[A-Z]/g, (match, offset) =>136- offset ? '-' + match.toLowerCase() : match.toLowerCase()137- )138- return `${kebabCaseDirective} ${Array.isArray(value) ? value.join(' ') : value}`172+ contentSecurityPolicy: ContentSecurityPolicyOptions173+): [SecureHeadersCallback | undefined, string | string[]] {174+ const callbacks: ((ctx: Context, values: string[]) => void)[] = []175+ const resultValues: string[] = []176+177+ for (const [directive, value] of Object.entries(contentSecurityPolicy)) {178+ const valueArray = Array.isArray(value) ? value : [value]179+180+ valueArray.forEach((value, i) => {181+ if (typeof value === 'function') {182+ const index = i * 2 + 2 + resultValues.length183+ callbacks.push((ctx, values) => {184+ values[index] = value(ctx, directive)185+ })186+ }187 })140- .join('; ')188+189+ resultValues.push(190+ directive.replace(/[A-Z]+(?![a-z])|[A-Z]/g, (match, offset) =>191+ offset ? '-' + match.toLowerCase() : match.toLowerCase()192+ ),193+ ...valueArray.flatMap((value) => [' ', value]),194+ '; '195+ )196+ }197+ resultValues.pop()198+199+ return callbacks.length === 0200+ ? [undefined, resultValues.join('')]201+ : [202+ (ctx, headersToSet) =>203+ headersToSet.map((values) => {204+ if (values[0] === 'Content-Security-Policy') {205+ const clone = values[1].slice() as unknown as string[]206+ callbacks.forEach((cb) => {207+ cb(ctx, clone)208+ })209+ return [values[0], clone.join('')]210+ } else {211+ return values as [string, string]212+ }213+ }),214+ resultValues,215+ ]216 }217 218 function getReportingEndpoints(219 reportingEndpoints: SecureHeadersOptions['reportingEndpoints'] = []13 unmodified linesmodified:src/middleware/serve-static/index.test.ts+30 added-14 removed
1-import { createMiddleware } from '../../helper'1 import { Hono } from '../../hono'2 import { serveStatic as baseServeStatic } from '.'3 4 describe('Serve Static Middleware', () => {5 const app = new Hono()6 8- const serveStatic = createMiddleware(async (c, next) => {9- const mw = baseServeStatic({10- getContent: (path) => {11- if (path.endsWith('not-found.txt')) {12- return undefined13- }14- return `Hello in ${path}`15- },16- pathResolve: (path) => {17- return `./${path}`18- },7+ const serveStatic = baseServeStatic({8+ getContent: async (path) => {9+ if (path.endsWith('not-found.txt')) {10+ return null11+ }12+ return `Hello in ${path}`13+ },14+ pathResolve: (path) => {15+ return `./${path}`16+ },19- })20- return await mw(c, next)17 })18 19 app.get('/static/*', serveStatic)20 30 unmodified lines51 } as Request)52 expect(res.status).toBe(404)53 expect(await res.text()).toBe('404 Not Found')54 })55+56+ it('Should return response object content as-is', async () => {57+ const body = new ReadableStream()58+ const response = new Response(body)59+ const app = new Hono().use(60+ '*',61+ baseServeStatic({62+ getContent: async () => {63+ return response64+ },65+ })66+ )67+68+ const res = await app.fetch({69+ method: 'GET',70+ url: 'http://localhost',71+ } as Request)72+ expect(res.status).toBe(200)73+ expect(res.body).toBe(body)74+ })75 })modified:src/middleware/serve-static/index.ts+8 added-5 removed
1-import type { Context } from '../../context'1+import type { Context, Data } from '../../context'2 import type { Env, MiddlewareHandler } from '../../types'3 import { getFilePath, getFilePathWithoutDefaultDocument } from '../../utils/filepath'4 import { getMimeType } from '../../utils/mime'5 12 unmodified lines18 * This middleware is not directly used by the user. Create a wrapper specifying `getContent()` by the environment such as Deno or Bun.19 */20 export const serveStatic = <E extends Env = Env>(21 options: ServeStaticOptions<E> & {22- // eslint-disable-next-line @typescript-eslint/no-explicit-any23- getContent: (path: string) => any22+ getContent: (path: string, c: Context<E>) => Promise<Data | Response | null>23 pathResolve?: (path: string) => string24 }25 ): MiddlewareHandler => {26 return async (c, next) => {20 unmodified lines47 const getContent = options.getContent48 const pathResolve = options.pathResolve ?? defaultPathResolve49 50 path = pathResolve(path)52- let content = await getContent(path)51+ let content = await getContent(path, c)52 53 if (!content) {54 let pathWithOutDefaultDocument = getFilePathWithoutDefaultDocument({55 filename,2 unmodified lines58 if (!pathWithOutDefaultDocument) {59 return await next()60 }61 pathWithOutDefaultDocument = pathResolve(pathWithOutDefaultDocument)63- content = await getContent(pathWithOutDefaultDocument)62+ content = await getContent(pathWithOutDefaultDocument, c)63 if (content) {64 path = pathWithOutDefaultDocument65 }66 }67 68+ if (content instanceof Response) {69+ return c.newResponse(content.body, content)70+ }71+72 if (content) {73 let mimeType: string | undefined74 if (options.mimes) {75 mimeType = getMimeType(path, options.mimes) ?? getMimeType(path)14 unmodified linesmodified:src/middleware/timing/index.test.ts+85 added
53 unmodified lines54 ).toBeTruthy()55 expect(res.headers.get('server-timing')?.includes(region)).toBeTruthy()56 expect(res.headers.get('server-timing')?.includes(regionDesc)).toBeTruthy()57 })58+59+ describe('Should handle crossOrigin setting', async () => {60+ it('Should do nothing when crossOrigin is falsy', async () => {61+ const crossOriginApp = new Hono()62+63+ crossOriginApp.use(64+ '*',65+ timing({66+ crossOrigin: false,67+ })68+ )69+70+ crossOriginApp.get('/', (c) => c.text('/'))71+72+ const res = await crossOriginApp.request('http://localhost/')73+74+ expect(res).not.toBeNull()75+ expect(res.headers.has('server-timing')).toBeTruthy()76+ expect(res.headers.has('timing-allow-origin')).toBeFalsy()77+ })78+79+ it('Should set Timing-Allow-Origin to * when crossOrigin is true', async () => {80+ const crossOriginApp = new Hono()81+82+ crossOriginApp.use(83+ '*',84+ timing({85+ crossOrigin: true,86+ })87+ )88+89+ crossOriginApp.get('/', (c) => c.text('/'))90+91+ const res = await crossOriginApp.request('http://localhost/')92+93+ expect(res).not.toBeNull()94+ expect(res.headers.has('server-timing')).toBeTruthy()95+ expect(res.headers.has('timing-allow-origin')).toBeTruthy()96+ expect(res.headers.get('timing-allow-origin')).toBe('*')97+ })98+99+ it('Should set Timing-Allow-Origin to the value of crossOrigin when it is a string', async () => {100+ const crossOriginApp = new Hono()101+102+ crossOriginApp.use(103+ '*',104+ timing({105+ crossOrigin: 'https://example.com',106+ })107+ )108+109+ crossOriginApp.get('/', (c) => c.text('/'))110+111+ const res = await crossOriginApp.request('http://localhost/')112+113+ expect(res).not.toBeNull()114+ expect(res.headers.has('server-timing')).toBeTruthy()115+ expect(res.headers.has('timing-allow-origin')).toBeTruthy()116+ expect(res.headers.get('timing-allow-origin')).toBe('https://example.com')117+ })118+119+ it('Should set Timing-Allow-Origin to the return value of crossOrigin when it is a function', async () => {120+ const crossOriginApp = new Hono()121+122+ crossOriginApp.use(123+ '*',124+ timing({125+ crossOrigin: (c) => c.req.header('origin') ?? '*',126+ })127+ )128+129+ crossOriginApp.get('/', (c) => c.text('/'))130+131+ const res = await crossOriginApp.request('http://localhost/', {132+ headers: {133+ origin: 'https://example.com',134+ },135+ })136+137+ expect(res).not.toBeNull()138+ expect(res.headers.has('server-timing')).toBeTruthy()139+ expect(res.headers.has('timing-allow-origin')).toBeTruthy()140+ expect(res.headers.get('timing-allow-origin')).toBe('https://example.com')141+ })142+ })143 })modified:src/middleware/timing/index.ts+7 added-3 removed
19 unmodified lines20 total: boolean21 enabled: boolean | ((c: Context) => boolean)22 totalDescription: string23 autoEnd: boolean24- crossOrigin: boolean | string24+ crossOrigin: boolean | string | ((c: Context) => boolean | string)25 }26 27 const getTime = () => {28 try {34 unmodified lines63 const enabled = typeof options.enabled === 'function' ? options.enabled(c) : options.enabled64 65 if (enabled) {66 c.res.headers.append('Server-Timing', headers.join(','))67+68+ const crossOrigin =69+ typeof options.crossOrigin === 'function' ? options.crossOrigin(c) : options.crossOrigin70+67- if (options.crossOrigin) {71+ if (crossOrigin) {72 c.res.headers.append(73 'Timing-Allow-Origin',70- typeof options.crossOrigin === 'string' ? options.crossOrigin : '*'74+ typeof crossOrigin === 'string' ? crossOrigin : '*'75 )76 }77 }78 }61 unmodified linesmodified:src/utils/mime.ts+1 added
17 unmodified lines18 }19 }20 }21 22+export { baseMimes as mimes }23 const baseMimes: Record<string, string> = {24 aac: 'audio/aac',25 avi: 'video/x-msvideo',26 avif: 'image/avif',53 unmodified linesmodified:src/utils/types.ts+3 added
34 unmodified lines35 : T extends object36 ? { [K in keyof T]: JSONParsed<T[K]> }37 : never38 39+// from sindresorhus/type-fest40+export type Simplify<T> = { [KeyType in keyof T]: T[KeyType] } & {}41+42 export type InterfaceToType<T> = T extends Function ? T : { [K in keyof T]: InterfaceToType<T[K]> }43 44 export type RequiredKeysOf<BaseType extends object> = Exclude<45 {14 unmodified linesmodified:src/validator/validator.test.ts+19 added-2 removed
2 unmodified lines3 import { z } from 'zod'4 import { Hono } from '../hono'5 import { HTTPException } from '../http-exception'6 import type { ErrorHandler, ExtractSchema, MiddlewareHandler, ValidationTargets } from '../types'7+import type { StatusCode } from '../utils/http-status'8 import type { Equal, Expect } from '../utils/types'9 import type { ValidationFunction } from './validator'10 import { validator } from './validator'11 44 unmodified lines56 $get: {57 input: {58 query: undefined59 }59- output: {}60+ output: 'Valid!'61+ outputFormat: 'text'62+ status: StatusCode63 }64 }65 }66 222 unmodified lines289 post: {290 id: number291 }292 }293+ outputFormat: 'json'294+ status: StatusCode295 }296 }297 }298 53 unmodified lines352 id: number353 title: string354 }355 }356+ outputFormat: 'json'357+ status: StatusCode358 }359 }360 }361 279 unmodified lines641 output: {642 page: number643 title: string644 }645+ outputFormat: 'json'646+ status: StatusCode647 }648 }649 }650 48 unmodified lines699 param: {700 id: string701 }702 }694- output: {}703+ output: 'Valid!'704+ outputFormat: 'text'705+ status: StatusCode706 }707 }708 }709 38 unmodified lines748 }749 output: {750 success: boolean751 }752+ outputFormat: 'json'753+ status: StatusCode754 }755 }756 }757 182 unmodified lines940 }941 output: {942 message: string943 }944+ outputFormat: 'json'945+ status: 201946 }947 }948 }>()949 })25 unmodified lines975 }976 output: {977 page: number978 }979+ outputFormat: 'json'980+ status: StatusCode981 }982 }983 }984 4 unmodified linesmodified:src/context.ts+30 added-26 removed
1 import type { HonoRequest } from './request'2 import type { Env, FetchEventLike, NotFoundHandler, Input, TypedResponse } from './types'3 import { resolveCallback, HtmlEscapedCallbackPhase } from './utils/html'4 import type { RedirectStatusCode, StatusCode } from './utils/http-status'5-import type { JSONValue, InterfaceToType, JSONParsed, IsAny } from './utils/types'5+import type { JSONValue, JSONParsed, IsAny, Simplify } from './utils/types'6 7 type HeaderRecord = Record<string, string | string[]>8-type Data = string | ArrayBuffer | ReadableStream8+export type Data = string | ArrayBuffer | ReadableStream9 10 export interface ExecutionContext {11 waitUntil(promise: Promise<unknown>): void12 passThroughOnException(): void31 unmodified lines44 45 interface BodyRespond extends NewResponse {}46 47 interface TextRespond {48- (text: string, status?: StatusCode, headers?: HeaderRecord): Response49- (text: string, init?: ResponseInit): Response48+ <T extends string, U extends StatusCode>(text: T, status?: U, headers?: HeaderRecord): Response &49+ TypedResponse<T, U, 'text'>50+ <T extends string, U extends StatusCode>(text: T, init?: ResponseInit): Response &51+ TypedResponse<T, U, 'text'>52 }53 54 interface JSONRespond {53- <T>(54- object: InterfaceToType<T> extends JSONValue ? T : JSONValue,55- status?: StatusCode,55+ <T extends JSONValue | Simplify<any>, U extends StatusCode>(56+ object: T,57+ status?: U,58 headers?: HeaderRecord59 ): Response &60 TypedResponse<59- InterfaceToType<T> extends JSONValue60- ? JSONValue extends InterfaceToType<T>61+ Simplify<T> extends JSONValue62+ ? JSONValue extends Simplify<T>63 ? never64 : JSONParsed<T>63- : never65+ : never,66+ U,67+ 'json'68 >65- <T>(object: InterfaceToType<T> extends JSONValue ? T : JSONValue, init?: ResponseInit): Response &69+ <T extends JSONValue | Simplify<any>, U extends StatusCode>(70+ object: Simplify<T> extends JSONValue ? T : Simplify<T>,71+ init?: ResponseInit72+ ): Response &73 TypedResponse<67- InterfaceToType<T> extends JSONValue68- ? JSONValue extends InterfaceToType<T>74+ Simplify<T> extends JSONValue75+ ? JSONValue extends Simplify<T>76 ? never77 : JSONParsed<T>71- : never78+ : never,79+ U,80+ 'json'81 >82 }83 84 interface HTMLRespond {375 unmodified lines460 text: TextRespond = (461 text: string,462 arg?: StatusCode | ResponseInit,463 headers?: HeaderRecord455- ): Response => {464+ ): ReturnType<TextRespond> => {465 // If the header is empty, return Response immediately.466 // Content-Type will be added automatically as `text/plain`.467 if (!this.#preparedHeaders) {468 if (this.#isFresh && !headers && !arg) {469+ // @ts-expect-error `Response` due to missing some types-only keys470 return new Response(text)471 }472 this.#preparedHeaders = {}473 }474 this.#preparedHeaders['content-type'] = TEXT_PLAIN475+ // @ts-expect-error `Response` due to missing some types-only keys476 return typeof arg === 'number'477 ? this.newResponse(text, arg, headers)478 : this.newResponse(text, arg)479 }7 unmodified lines487 * })488 * ```489 * @see https://hono.dev/api/context#json490 */480- json: JSONRespond = <T>(481- object: InterfaceToType<T> extends JSONValue ? T : JSONValue,482- arg?: StatusCode | ResponseInit,491+ json: JSONRespond = <T extends JSONValue | Simplify<any>, U extends StatusCode>(492+ object: T,493+ arg?: U | ResponseInit,494 headers?: HeaderRecord484- ): Response &485- TypedResponse<486- InterfaceToType<T> extends JSONValue487- ? JSONValue extends InterfaceToType<T>488- ? never489- : JSONParsed<T>490- : never491- > => {495+ ): ReturnType<JSONRespond> => {496 const body = JSON.stringify(object)497 this.#preparedHeaders ??= {}498 this.#preparedHeaders['content-type'] = 'application/json; charset=UTF-8'499 /* eslint-disable @typescript-eslint/no-explicit-any */66 unmodified linesmodified:src/hono.test.ts+2 added-2 removed
2111 unmodified lines2112 describe('Parse Body', () => {2113 const app = new Hono()2114 2115 app.post('/json', async (c) => {2116- return c.json<{}>(await c.req.parseBody(), 200)2116+ return c.json<{}, 200>(await c.req.parseBody(), 200)2117 })2118 app.post('/form', async (c) => {2119- return c.json<{}>(await c.req.parseBody(), 200)2119+ return c.json<{}, 200>(await c.req.parseBody(), 200)2120 })2121 2122 it('POST with JSON', async () => {2123 const req = new Request('http://localhost/json', {1255 unmodified linesmodified:src/types.test.ts+317 added-46 removed
15 unmodified lines16 MiddlewareHandler,17 ParamKeys,18 ParamKeyToRecord,19 RemoveQuestion,20+ ResponseFormat,21 ToSchema,22+ TypedResponse,23 } from './types'24+import type { StatusCode } from './utils/http-status'25 import type { Expect, Equal } from './utils/types'26 import { validator } from './validator'27 28 describe('Env', () => {66 unmodified lines95 }96 output: {97 message: string98 }99+ outputFormat: 'json'100+ status: StatusCode101 }102 }103 }104 type verify = Expect<Equal<Expected, Actual>>29 unmodified lines134 }135 output: {136 message: string137 }138+ outputFormat: 'json'139+ status: StatusCode140 }141 }142 }143 type verify = Expect<Equal<Expected, Actual>>17 unmodified lines161 param: {162 id: string163 }164 }158- output: {}165+ output: 'foo'166+ outputFormat: 'text'167+ status: StatusCode168 }169 }170 }171 type verify = Expect<Equal<Expected, Actual>>18 unmodified lines190 param: {191 foo: string192 }193 }185- output: {}194+ output: string195+ outputFormat: 'text'196+ status: StatusCode197 }198 }199 }200 type verify = Expect<Equal<Expected, Actual>>14 unmodified lines215 } & {216 foo: string217 }218 }208- output: {}219+ output: string220+ outputFormat: 'text'221+ status: StatusCode222 }223 }224 } & {225 '/foo/:foo/books/:id': {5 unmodified lines231 foo: string232 }233 }234 output: {}235+ outputFormat: ResponseFormat236+ status: StatusCode237 }238 }239 }240 type verify = Expect<Equal<Expected, Actual>>29 unmodified lines270 }271 output: {272 success: boolean273 }274+ outputFormat: 'json'275+ status: StatusCode276 }277 }278 }279 type verify = Expect<Equal<Expected, Actual>>280 })281 })282 283+describe('TypedResponse', () => {284+ test('unknown', () => {285+ type Actual = TypedResponse286+ type Expected = {287+ data: unknown288+ status: StatusCode289+ format: ResponseFormat290+ }291+ type verify = Expect<Equal<Expected, Actual>>292+ })293+294+ test('text auto infer', () => {295+ type Actual = TypedResponse<string>296+ type Expected = {297+ data: string298+ status: StatusCode299+ format: 'text'300+ }301+ type verify = Expect<Equal<Expected, Actual>>302+ })303+304+ test('json auto infer', () => {305+ type Actual = TypedResponse<{ ok: true }>306+ type Expected = {307+ data: { ok: true }308+ status: StatusCode309+ format: 'json'310+ }311+ type verify = Expect<Equal<Expected, Actual>>312+ })313+})314+315 describe('Schema', () => {316 test('Schema', () => {317 type AppType = Hono<318 Env,319 ToSchema<320 'post',321 '/api/posts/:id',322 {323+ in: {274- json: {275- id: number276- title: string324+ json: {325+ id: number326+ title: string327+ }328 }329 },330+ TypedResponse<279- {280- message: string281- success: boolean282- }331+ {332+ message: string333+ success: boolean334+ },335+ StatusCode,336+ 'json'337+ >338 >339 >340 341 type Actual = ExtractSchema<AppType>13 unmodified lines355 output: {356 message: string357 success: boolean358 }359+ outputFormat: 'json'360+ status: StatusCode361 }362 }363 }364 type verify = Expect<Equal<Expected, Actual>>10 unmodified lines375 '/this/is/a/test': {376 $get: {377 input: {}378 output: undefined379+ outputFormat: 'json'380+ status: StatusCode381 }382 }383 }384 type verify = Expect<Equal<Expected, Actual>>54 unmodified lines439 })440 441 describe('`json()`', () => {442 const app = new Hono<{ Variables: { foo: string } }>()384-443 app.get('/post/:id', (c) => {444 c.req.param('id')445 const id = c.req.param('id')446 return c.text('foo')447 })448 449+ test('json', () => {391- const route = app.get('/hello', (c) => {392- return c.json({393- message: 'Hello!',450+ const route = app.get('/hello', (c) => {451+ return c.json({452+ message: 'Hello!',453+ })454 })455+ type Actual = ExtractSchema<typeof route>456+ type Expected = {457+ '/hello': {458+ $get: {459+ input: {}460+ output: {461+ message: string462+ }463+ outputFormat: 'json'464+ status: StatusCode465+ }466+ }467+ }468+ type verify = Expect<Equal<Expected, Actual>>469 })470 397- test('json', () => {471+ test('json with specific status code', () => {472+ const route = app.get('/hello', (c) => {473+ return c.json(474+ {475+ message: 'Hello!',476+ },477+ 200478+ )479+ })480 type Actual = ExtractSchema<typeof route>399-481 type Expected = {482 '/hello': {483 $get: {484 input: {}485 output: {486 message: string487 }488+ outputFormat: 'json'489+ status: 200490 }491 }492 }410-493 type verify = Expect<Equal<Expected, Actual>>494 })495 })496 97 unmodified lines594 })595 596 describe('ToSchema', () => {597 it('Should convert parameters to schema correctly', () => {516- type Actual = ToSchema<'get', '/:id', { param: { id: string }; query: { page: string } }, {}>598+ type Actual = ToSchema<599+ 'get',600+ '/:id',601+ { in: { param: { id: string }; query: { page: string } } },602+ TypedResponse<{}>603+ >604 type Expected = {605 '/:id': {606 $get: {607 input: {4 unmodified lines612 page: string613 }614 }615 output: {}616+ outputFormat: 'json'617+ status: StatusCode618 }619 }620 }621 type verify = Expect<Equal<Expected, Actual>>26 unmodified lines648 type Sub = ToSchema<649 'post',650 '/posts',651 {652+ in: {563- json: {564- id: number565- title: string653+ json: {654+ id: number655+ title: string656+ }657 }658 },568- {659+ TypedResponse<{660 message: string570- }661+ }>662 > &663 ToSchema<664 'get',665 '/posts',666 {},576- {667+ TypedResponse<{668 ok: boolean578- }669+ }>670 >671 672 type Actual = MergeSchemaPath<Sub, '/api'>673 8 unmodified lines682 }683 output: {684 message: string685 }686+ outputFormat: 'json'687+ status: StatusCode688 }689 $get: {690 input: {}691 output: {692 ok: boolean693 }694+ outputFormat: 'json'695+ status: StatusCode696 }697 }698 }699 13 unmodified lines713 page: string714 }715 }716 output: {}717+ outputFormat: 'json'718+ status: StatusCode719 }720 }721 },722 '/something'9 unmodified lines732 page: string733 }734 }735 output: {}736+ outputFormat: 'json'737+ status: StatusCode738 }739 }740 }741 type verify = Expect<Equal<Expected, Actual>>1 unmodified line743 744 type GetKey<T> = T extends Record<infer K, unknown> ? K : never745 746 it('Should remove a slash - `/` + `/`', () => {648- type Sub = ToSchema<'get', '/', {}, {}>747+ type Sub = ToSchema<'get', '/', {}, TypedResponse<{}>>748 type Actual = MergeSchemaPath<Sub, '/'>749 type verify = Expect<Equal<'/', GetKey<Actual>>>750 })751 752 it('Should remove a slash - `/tags` + `/`', () => {654- type Sub = ToSchema<'get', '/tags', {}, {}>753+ type Sub = ToSchema<'get', '/tags', {}, TypedResponse<{}>>754 type Actual = MergeSchemaPath<Sub, '/'>755 type verify = Expect<Equal<'/tags', GetKey<Actual>>>756 })757 758 it('Should remove a slash - `/` + `/tags`', () => {660- type Sub = ToSchema<'get', '/', {}, {}>759+ type Sub = ToSchema<'get', '/', {}, TypedResponse<{}>>760 type Actual = MergeSchemaPath<Sub, '/tags'>761 type verify = Expect<Equal<'/tags', GetKey<Actual>>>762 })763 764 test('MergeSchemaPath - SubPath has path params', () => {666- type Actual = MergeSchemaPath<ToSchema<'get', '/', {}, {}>, '/a/:b'>765+ type Actual = MergeSchemaPath<ToSchema<'get', '/', {}, TypedResponse>, '/a/:b'>766 type Expected = {767 '/a/:b': {768 $get: {769 input: {1 unmodified line771 b: string772 }773 }774 output: {}775+ outputFormat: ResponseFormat776+ status: StatusCode777 }778 }779 }780 type verify = Expect<Equal<Expected, Actual>>781 })782 783 test('MergeSchemaPath - Path and SubPath have path params', () => {683- type Actual = MergeSchemaPath<ToSchema<'get', '/c/:d', {}, {}>, '/a/:b'>784+ type Actual = MergeSchemaPath<ToSchema<'get', '/c/:d', {}, TypedResponse<{}>>, '/a/:b'>785 type Expected = {786 '/a/:b/c/:d': {787 $get: {788 input: {3 unmodified lines792 b: string793 }794 }795 output: {}796+ outputFormat: 'json'797+ status: StatusCode798 }799 }800 }801 type verify = Expect<Equal<Expected, Actual>>802 })803 804 test('MergeSchemaPath - Path and SubPath have regexp path params', () => {702- type Actual = MergeSchemaPath<ToSchema<'get', '/c/:d{.+}', {}, {}>, '/a/:b{.+}'>805+ type Actual = MergeSchemaPath<ToSchema<'get', '/c/:d{.+}', {}, TypedResponse<{}>>, '/a/:b{.+}'>806 type Expected = {807 '/a/:b{.+}/c/:d{.+}': {808 $get: {809 input: {3 unmodified lines813 b: string814 }815 }816 output: {}817+ outputFormat: 'json'818+ status: StatusCode819 }820 }821 }822 type verify = Expect<Equal<Expected, Actual>>2 unmodified lines825 826 describe('Different types using json()', () => {827 describe('no path pattern', () => {828 const app = new Hono()829+830 test('Three different types', () => {831 const route = app.get((c) => {832 const flag = false833 if (flag) {12 unmodified lines846 })847 type Actual = ExtractSchema<typeof route>848 type Expected = {849 '/': {744- $get: {745- input: {}746- output:747- | {850+ $get:851+ | {852+ input: {}853+ output: {854 ng: boolean855 }856+ outputFormat: 'json'857+ status: StatusCode858+ }750- | {859+ | {860+ input: {}861+ output: {862 ok: boolean863 }864+ outputFormat: 'json'865+ status: StatusCode866+ }753- | {867+ | {868+ input: {}869+ output: {870 default: boolean871 }872+ outputFormat: 'json'873+ status: StatusCode756- }874+ }875 }876 }877 type verify = Expect<Equal<Expected, Actual>>878 })879+880+ test('Three different types and status codes', () => {881+ const route = app.get((c) => {882+ const flag = false883+ if (flag) {884+ return c.json(885+ {886+ ng: true,887+ },888+ 400889+ )890+ }891+ if (!flag) {892+ return c.json(893+ {894+ ok: true,895+ },896+ 200897+ )898+ }899+ return c.json({900+ default: true,901+ })902+ })903+ type Actual = ExtractSchema<typeof route>904+ type Expected = {905+ '/': {906+ $get:907+ | {908+ input: {}909+ output: {910+ ng: boolean911+ }912+ outputFormat: 'json'913+ status: 400914+ }915+ | {916+ input: {}917+ output: {918+ ok: boolean919+ }920+ outputFormat: 'json'921+ status: 200922+ }923+ | {924+ input: {}925+ output: {926+ default: boolean927+ }928+ outputFormat: 'json'929+ status: StatusCode930+ }931+ }932+ }933+ type verify = Expect<Equal<Expected, Actual>>934+ })935 })936 937 describe('path pattern', () => {938 const app = new Hono()939+940 test('Three different types', () => {941 const route = app.get('/foo', (c) => {942 const flag = false943 if (flag) {12 unmodified lines956 })957 type Actual = ExtractSchema<typeof route>958 type Expected = {959 '/foo': {785- $get: {786- input: {}787- output:788- | {960+ $get:961+ | {962+ input: {}963+ output: {964 ng: boolean965 }966+ outputFormat: 'json'967+ status: StatusCode968+ }791- | {969+ | {970+ input: {}971+ output: {972 ok: boolean973 }974+ outputFormat: 'json'975+ status: StatusCode976+ }794- | {977+ | {978+ input: {}979+ output: {980 default: boolean981 }982+ outputFormat: 'json'983+ status: StatusCode797- }984+ }985 }986 }987 type verify = Expect<Equal<Expected, Actual>>988 })989+990+ test('Three different types and status codes', () => {991+ const route = app.get('/foo', (c) => {992+ const flag = false993+ if (flag) {994+ return c.json(995+ {996+ ng: true,997+ },998+ 400999+ )1000+ }1001+ if (!flag) {1002+ return c.json(1003+ {1004+ ok: true,1005+ },1006+ 2001007+ )1008+ }1009+ return c.json({1010+ default: true,1011+ })1012+ })1013+ type Actual = ExtractSchema<typeof route>1014+ type Expected = {1015+ '/foo': {1016+ $get:1017+ | {1018+ input: {}1019+ output: {1020+ ng: boolean1021+ }1022+ outputFormat: 'json'1023+ status: 4001024+ }1025+ | {1026+ input: {}1027+ output: {1028+ ok: boolean1029+ }1030+ outputFormat: 'json'1031+ status: 2001032+ }1033+ | {1034+ input: {}1035+ output: {1036+ default: boolean1037+ }1038+ outputFormat: 'json'1039+ status: StatusCode1040+ }1041+ }1042+ }1043+ type verify = Expect<Equal<Expected, Actual>>1044+ })1045 })1046 })1047 1048 describe('json() in an async handler', () => {1049 const app = new Hono()807- test('Three different types', () => {1050+1051+ test('json', () => {1052 const route = app.get(async (c) => {1053 return c.json({1054 ok: true,1055 })5 unmodified lines1061 input: {}1062 output: {1063 ok: boolean1064 }1065+ outputFormat: 'json'1066+ status: StatusCode1067 }1068 }1069 }1070 type verify = Expect<Equal<Expected, Actual>>1071 })1072+1073+ test('json with specific status code', () => {1074+ const route = app.get(async (c) => {1075+ return c.json(1076+ {1077+ ok: true,1078+ },1079+ 2001080+ )1081+ })1082+ type Actual = ExtractSchema<typeof route>1083+ type Expected = {1084+ '/': {1085+ $get: {1086+ input: {}1087+ output: {1088+ ok: boolean1089+ }1090+ outputFormat: 'json'1091+ status: 2001092+ }1093+ }1094+ }1095+ type verify = Expect<Equal<Expected, Actual>>1096+ })1097 })1098 1099 /**1100 * Other tests for `c.var` are written in `hono.test.ts`.552 unmodified linesmodified:src/types.ts+100 added-85 removed
1 unmodified line2 /* eslint-disable @typescript-eslint/no-explicit-any */3 /* eslint-disable @typescript-eslint/ban-types */4 import type { Context } from './context'5 import type { Hono } from './hono'6+import type { StatusCode } from './utils/http-status'7 import type {8 IfAnyThenEmptyObject,9+ JSONValue,10 Prettify,11 RemoveBlankRecord,12 UnionToIntersection,13 } from './utils/types'16 unmodified lines30 31 export type Input = {32 in?: {}33 out?: {}34+ outputFormat?: ResponseFormat35 }36 37 export type BlankSchema = {}38 export type BlankInput = {}63 unmodified lines102 R extends HandlerResponse<any> = any,103 E2 extends Env = E104 >(105 handler: H<E2, P, I, R>103- ): Hono<104- IntersectNonAnyTypes<[E, E2]>,105- S & ToSchema<M, P, I['in'], MergeTypedResponseData<R>>,106- BasePath107- >106+ ): Hono<IntersectNonAnyTypes<[E, E2]>, S & ToSchema<M, P, I, MergeTypedResponse<R>>, BasePath>107 108 // app.get(path, handler)109 <110 P extends string,5 unmodified lines116 path: P,117 handler: H<E2, MergedPath, I, R>118 ): Hono<119 IntersectNonAnyTypes<[E, E2]>,121- S & ToSchema<M, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>,120+ S & ToSchema<M, MergePath<BasePath, P>, I, MergeTypedResponse<R>>,121 BasePath122 >123 124 // app.get(handler x2)7 unmodified lines132 >(133 ...handlers: [H<E2, P, I>, H<E3, P, I2, R>]134 ): Hono<135 IntersectNonAnyTypes<[E, E2, E3]>,137- S & ToSchema<M, P, I2['in'], MergeTypedResponseData<R>>,136+ S & ToSchema<M, P, I2, MergeTypedResponse<R>>,137 BasePath138 >139 140 // app.get(path, handler x2)9 unmodified lines150 path: P,151 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2, R>]152 ): Hono<153 IntersectNonAnyTypes<[E, E2, E3]>,155- S & ToSchema<M, MergePath<BasePath, P>, I2['in'], MergeTypedResponseData<R>>,154+ S & ToSchema<M, MergePath<BasePath, P>, I2, MergeTypedResponse<R>>,155 BasePath156 >157 158 // app.get(handler x 3)9 unmodified lines168 >(169 ...handlers: [H<E2, P, I>, H<E3, P, I2>, H<E4, P, I3, R>]170 ): Hono<171 IntersectNonAnyTypes<[E, E2, E3, E4]>,173- S & ToSchema<M, P, I3['in'], MergeTypedResponseData<R>>,172+ S & ToSchema<M, P, I3, MergeTypedResponse<R>>,173 BasePath174 >175 176 // app.get(path, handler x3)11 unmodified lines188 path: P,189 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2>, H<E4, MergedPath, I3, R>]190 ): Hono<191 IntersectNonAnyTypes<[E, E2, E3, E4]>,193- S & ToSchema<M, MergePath<BasePath, P>, I3['in'], MergeTypedResponseData<R>>,192+ S & ToSchema<M, MergePath<BasePath, P>, I3, MergeTypedResponse<R>>,193 BasePath194 >195 196 // app.get(handler x 4)11 unmodified lines208 >(209 ...handlers: [H<E2, P, I>, H<E3, P, I2>, H<E4, P, I3>, H<E5, P, I4, R>]210 ): Hono<211 IntersectNonAnyTypes<[E, E2, E3, E4, E5]>,213- S & ToSchema<M, P, I4['in'], MergeTypedResponseData<R>>,212+ S & ToSchema<M, P, I4, MergeTypedResponse<R>>,213 BasePath214 >215 216 // app.get(path, handler x4)18 unmodified lines235 H<E5, MergedPath, I4, R>236 ]237 ): Hono<238 IntersectNonAnyTypes<[E, E2, E3, E4, E5]>,240- S & ToSchema<M, MergePath<BasePath, P>, I4['in'], MergeTypedResponseData<R>>,239+ S & ToSchema<M, MergePath<BasePath, P>, I4, MergeTypedResponse<R>>,240 BasePath241 >242 243 // app.get(handler x 5)13 unmodified lines257 >(258 ...handlers: [H<E2, P, I>, H<E3, P, I2>, H<E4, P, I3>, H<E5, P, I4>, H<E6, P, I5, R>]259 ): Hono<260 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>,262- S & ToSchema<M, P, I5['in'], MergeTypedResponseData<R>>,261+ S & ToSchema<M, P, I5, MergeTypedResponse<R>>,262 BasePath263 >264 265 // app.get(path, handler x5)21 unmodified lines287 H<E6, MergedPath, I5, R>288 ]289 ): Hono<290 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>,292- S & ToSchema<M, MergePath<BasePath, P>, I5['in'], MergeTypedResponseData<R>>,291+ S & ToSchema<M, MergePath<BasePath, P>, I5, MergeTypedResponse<R>>,292 BasePath293 >294 295 // app.get(handler x 6)22 unmodified lines318 H<E7, P, I6, R>319 ]320 ): Hono<321 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>,323- S & ToSchema<M, P, I6['in'], MergeTypedResponseData<R>>,322+ S & ToSchema<M, P, I6, MergeTypedResponse<R>>,323 BasePath324 >325 326 // app.get(path, handler x6)24 unmodified lines351 H<E7, MergedPath, I6, R>352 ]353 ): Hono<354 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>,356- S & ToSchema<M, MergePath<BasePath, P>, I6['in'], MergeTypedResponseData<R>>,355+ S & ToSchema<M, MergePath<BasePath, P>, I6, MergeTypedResponse<R>>,356 BasePath357 >358 359 // app.get(handler x 7)25 unmodified lines385 H<E8, P, I7, R>386 ]387 ): Hono<388 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>,390- S & ToSchema<M, P, I7['in'], MergeTypedResponseData<R>>,389+ S & ToSchema<M, P, I7, MergeTypedResponse<R>>,390 BasePath391 >392 393 // app.get(path, handler x7)27 unmodified lines421 H<E8, MergedPath, I7, R>422 ]423 ): Hono<424 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>,426- S & ToSchema<M, MergePath<BasePath, P>, I7['in'], MergeTypedResponseData<R>>,425+ S & ToSchema<M, MergePath<BasePath, P>, I7, MergeTypedResponse<R>>,426 BasePath427 >428 429 // app.get(handler x 8)28 unmodified lines458 H<E9, P, I8, R>459 ]460 ): Hono<461 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>,463- S & ToSchema<M, P, I8['in'], MergeTypedResponseData<R>>,462+ S & ToSchema<M, P, I8, MergeTypedResponse<R>>,463 BasePath464 >465 466 // app.get(path, handler x8)30 unmodified lines497 H<E9, MergedPath, I8, R>498 ]499 ): Hono<500 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>,502- S & ToSchema<M, MergePath<BasePath, P>, I8['in'], MergeTypedResponseData<R>>,501+ S & ToSchema<M, MergePath<BasePath, P>, I8, MergeTypedResponse<R>>,502 BasePath503 >504 505 // app.get(handler x 9)31 unmodified lines537 H<E10, P, I9, R>538 ]539 ): Hono<540 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>,542- S & ToSchema<M, P, I9['in'], MergeTypedResponseData<R>>,541+ S & ToSchema<M, P, I9, MergeTypedResponse<R>>,542 BasePath543 >544 545 // app.get(path, handler x9)33 unmodified lines579 H<E10, MergedPath, I9, R>580 ]581 ): Hono<582 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>,584- S & ToSchema<M, MergePath<BasePath, P>, I9['in'], MergeTypedResponseData<R>>,583+ S & ToSchema<M, MergePath<BasePath, P>, I9, MergeTypedResponse<R>>,584 BasePath585 >586 587 // app.get(handler x 10)34 unmodified lines622 H<E11, P, I10, R>623 ]624 ): Hono<625 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11]>,627- S & ToSchema<M, P, I10['in'], MergeTypedResponseData<R>>,626+ S & ToSchema<M, P, I10, MergeTypedResponse<R>>,627 BasePath628 >629 630 // app.get(path, handler x10)36 unmodified lines667 H<E11, MergedPath, I10, R>668 ]669 ): Hono<670 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11]>,672- S & ToSchema<M, MergePath<BasePath, P>, I10['in'], MergeTypedResponseData<R>>,671+ S & ToSchema<M, MergePath<BasePath, P>, I10, MergeTypedResponse<R>>,672 BasePath673 >674 675 // app.get(...handlers[])2 unmodified lines678 I extends Input = BlankInput,679 R extends HandlerResponse<any> = any680 >(681 ...handlers: H<E, P, I, R>[]683- ): Hono<E, S & ToSchema<M, P, I['in'], MergeTypedResponseData<R>>, BasePath>682+ ): Hono<E, S & ToSchema<M, P, I, MergeTypedResponse<R>>, BasePath>683 684 // app.get(path, ...handlers[])685 <P extends string, I extends Input = BlankInput, R extends HandlerResponse<any> = any>(686 path: P,687 ...handlers: H<E, MergePath<BasePath, P>, I, R>[]689- ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>, BasePath>688+ ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I, MergeTypedResponse<R>>, BasePath>689 690 // app.get(path)691 <P extends string, R extends HandlerResponse<any> = any, I extends Input = {}>(path: P): Hono<692 E,694- S & ToSchema<M, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>,693+ S & ToSchema<M, MergePath<BasePath, P>, I, MergeTypedResponse<R>>,694 BasePath695 >696 }697 224 unmodified lines922 path: P,923 handler: H<E2, MergedPath, I, R>924 ): Hono<925 IntersectNonAnyTypes<[E, E2]>,927- S & ToSchema<M, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>,926+ S & ToSchema<M, MergePath<BasePath, P>, I, MergeTypedResponse<R>>,927 BasePath928 >929 930 // app.on(method, path, handler x2)11 unmodified lines942 path: P,943 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2, R>]944 ): Hono<945 IntersectNonAnyTypes<[E, E2, E3]>,947- S & ToSchema<M, MergePath<BasePath, P>, I2['in'], MergeTypedResponseData<R>>,946+ S & ToSchema<M, MergePath<BasePath, P>, I2, MergeTypedResponse<R>>,947 BasePath948 >949 950 // app.on(method, path, handler x3)13 unmodified lines964 path: P,965 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2>, H<E4, MergedPath, I3, R>]966 ): Hono<967 IntersectNonAnyTypes<[E, E2, E3, E4]>,969- S & ToSchema<M, MergePath<BasePath, P>, I3['in'], MergeTypedResponseData<R>>,968+ S & ToSchema<M, MergePath<BasePath, P>, I3, MergeTypedResponse<R>>,969 BasePath970 >971 972 // app.on(method, path, handler x4)20 unmodified lines993 H<E5, MergedPath, I4, R>994 ]995 ): Hono<996 IntersectNonAnyTypes<[E, E2, E3, E4, E5]>,998- S & ToSchema<M, MergePath<BasePath, P>, I4['in'], MergeTypedResponseData<R>>,997+ S & ToSchema<M, MergePath<BasePath, P>, I4, MergeTypedResponse<R>>,998 BasePath999 >1000 1001 // app.on(method, path, handler x5)23 unmodified lines1025 H<E6, MergedPath, I5, R>1026 ]1027 ): Hono<1028 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>,1030- S & ToSchema<M, MergePath<BasePath, P>, I5['in'], MergeTypedResponseData<R>>,1029+ S & ToSchema<M, MergePath<BasePath, P>, I5, MergeTypedResponse<R>>,1030 BasePath1031 >1032 1033 // app.on(method, path, handler x6)26 unmodified lines1060 H<E7, MergedPath, I6, R>1061 ]1062 ): Hono<1063 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>,1065- S & ToSchema<M, MergePath<BasePath, P>, I6['in'], MergeTypedResponseData<R>>,1064+ S & ToSchema<M, MergePath<BasePath, P>, I6, MergeTypedResponse<R>>,1065 BasePath1066 >1067 1068 // app.on(method, path, handler x7)29 unmodified lines1098 H<E8, MergedPath, I7, R>1099 ]1100 ): Hono<1101 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>,1103- S & ToSchema<M, MergePath<BasePath, P>, I7['in'], MergeTypedResponseData<R>>,1102+ S & ToSchema<M, MergePath<BasePath, P>, I7, MergeTypedResponse<R>>,1103 BasePath1104 >1105 1106 // app.on(method, path, handler x8)32 unmodified lines1139 H<E9, MergedPath, I8, R>1140 ]1141 ): Hono<1142 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>,1144- S & ToSchema<M, MergePath<BasePath, P>, I8['in'], MergeTypedResponseData<R>>,1143+ S & ToSchema<M, MergePath<BasePath, P>, I8, MergeTypedResponse<R>>,1144 BasePath1145 >1146 1147 // app.on(method, path, handler x9)35 unmodified lines1183 H<E10, MergedPath, I9, R>1184 ]1185 ): Hono<1186 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>,1188- S & ToSchema<M, MergePath<BasePath, P>, I9['in'], MergeTypedResponseData<R>>,1187+ S & ToSchema<M, MergePath<BasePath, P>, I9, MergeTypedResponse<R>>,1188 BasePath1189 >1190 1191 // app.on(method, path, handler x10)37 unmodified lines1229 H<E11, MergedPath, I10>1230 ]1231 ): Hono<1232 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11]>,1234- S &1235- ToSchema<M, MergePath<BasePath, P>, I10['in'], MergeTypedResponseData<HandlerResponse<any>>>,1233+ S & ToSchema<M, MergePath<BasePath, P>, I10, MergeTypedResponse<HandlerResponse<any>>>,1234 BasePath1235 >1236 1237 // app.get(method, path, ...handler)1238 <M extends string, P extends string, R extends HandlerResponse<any> = any, I extends Input = {}>(1239 method: M,1240 path: P,1241 ...handlers: H<E, MergePath<BasePath, P>, I, R>[]1244- ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>, BasePath>1242+ ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I, MergeTypedResponse<R>>, BasePath>1243 1244 // app.get(method[], path, handler)1245 <1246 Ms extends string[],7 unmodified lines1254 path: P,1255 handler: H<E2, MergedPath, I, R>1256 ): Hono<1257 IntersectNonAnyTypes<[E, E2]>,1260- S & ToSchema<Ms[number], MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>,1258+ S & ToSchema<Ms[number], MergePath<BasePath, P>, I, MergeTypedResponse<R>>,1259 BasePath1260 >1261 1262 // app.get(method[], path, handler x2)11 unmodified lines1274 path: P,1275 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2, R>]1276 ): Hono<1277 IntersectNonAnyTypes<[E, E2, E3]>,1280- S & ToSchema<Ms[number], MergePath<BasePath, P>, I2['in'], MergeTypedResponseData<R>>,1278+ S & ToSchema<Ms[number], MergePath<BasePath, P>, I2, MergeTypedResponse<R>>,1279 BasePath1280 >1281 1282 // app.get(method[], path, handler x3)13 unmodified lines1296 path: P,1297 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2>, H<E4, MergedPath, I3, R>]1298 ): Hono<1299 IntersectNonAnyTypes<[E, E2, E3, E4]>,1302- S & ToSchema<Ms[number], MergePath<BasePath, P>, I3['in'], MergeTypedResponseData<R>>,1300+ S & ToSchema<Ms[number], MergePath<BasePath, P>, I3, MergeTypedResponse<R>>,1301 BasePath1302 >1303 1304 // app.get(method[], path, handler x4)20 unmodified lines1325 H<E5, MergedPath, I4, R>1326 ]1327 ): Hono<1328 IntersectNonAnyTypes<[E, E2, E3, E4, E5]>,1331- S & ToSchema<Ms[number], MergePath<BasePath, P>, I4['in'], MergeTypedResponseData<R>>,1329+ S & ToSchema<Ms[number], MergePath<BasePath, P>, I4, MergeTypedResponse<R>>,1330 BasePath1331 >1332 1333 // app.get(method[], path, handler x5)23 unmodified lines1357 H<E6, MergedPath, I5, R>1358 ]1359 ): Hono<1360 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>,1363- S & ToSchema<Ms[number], MergePath<BasePath, P>, I5['in'], MergeTypedResponseData<R>>,1361+ S & ToSchema<Ms[number], MergePath<BasePath, P>, I5, MergeTypedResponse<R>>,1362 BasePath1363 >1364 1365 // app.get(method[], path, handler x6)26 unmodified lines1392 H<E7, MergedPath, I6, R>1393 ]1394 ): Hono<1395 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>,1398- S & ToSchema<Ms[number], MergePath<BasePath, P>, I6['in'], MergeTypedResponseData<R>>,1396+ S & ToSchema<Ms[number], MergePath<BasePath, P>, I6, MergeTypedResponse<R>>,1397 BasePath1398 >1399 1400 // app.get(method[], path, handler x7)29 unmodified lines1430 H<E8, MergedPath, I7, R>1431 ]1432 ): Hono<1433 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>,1436- S & ToSchema<Ms[number], MergePath<BasePath, P>, I7['in'], MergeTypedResponseData<R>>,1434+ S & ToSchema<Ms[number], MergePath<BasePath, P>, I7, MergeTypedResponse<R>>,1435 BasePath1436 >1437 1438 // app.get(method[], path, handler x8)32 unmodified lines1471 H<E9, MergedPath, I8, R>1472 ]1473 ): Hono<1474 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>,1477- S & ToSchema<Ms[number], MergePath<BasePath, P>, I8['in'], MergeTypedResponseData<R>>,1475+ S & ToSchema<Ms[number], MergePath<BasePath, P>, I8, MergeTypedResponse<R>>,1476 BasePath1477 >1478 1479 // app.get(method[], path, handler x9)34 unmodified lines1514 H<E10, MergedPath, I9>1515 ]1516 ): Hono<1517 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>,1520- S &1521- ToSchema<1522- Ms[number],1523- MergePath<BasePath, P>,1524- I9['in'],1525- MergeTypedResponseData<HandlerResponse<any>>1526- >,1518+ S & ToSchema<Ms[number], MergePath<BasePath, P>, I9, MergeTypedResponse<HandlerResponse<any>>>,1519 BasePath1520 >1521 1522 // app.get(method[], path, handler x10)37 unmodified lines1560 H<E11, MergedPath, I10>1561 ]1562 ): Hono<1563 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11]>,1572- S &1573- ToSchema<1574- Ms[number],1575- MergePath<BasePath, P>,1576- I10['in'],1577- MergeTypedResponseData<HandlerResponse<any>>1578- >,1564+ S & ToSchema<Ms[number], MergePath<BasePath, P>, I10, MergeTypedResponse<HandlerResponse<any>>>,1565 BasePath1566 >1567 1568 // app.on(method[], path, ...handler)1569 <P extends string, R extends HandlerResponse<any> = any, I extends Input = {}>(1570 methods: string[],1571 path: P,1572 ...handlers: H<E, MergePath<BasePath, P>, I, R>[]1587- ): Hono<1588- E,1589- S & ToSchema<string, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>,1590- BasePath1591- >1573+ ): Hono<E, S & ToSchema<string, MergePath<BasePath, P>, I, MergeTypedResponse<R>>, BasePath>1574 1575 // app.on(method | method[], path[], ...handlers[])1576 <I extends Input = BlankInput, R extends HandlerResponse<any> = any>(1577 methods: string | string[],1578 paths: string[],1579 ...handlers: H<E, any, I, R>[]1598- ): Hono<E, S & ToSchema<string, string, I['in'], MergeTypedResponseData<R>>, BasePath>1580+ ): Hono<E, S & ToSchema<string, string, I, MergeTypedResponse<R>>, BasePath>1581 }1582 1583 type ExtractKey<S> = S extends Record<infer Key, unknown>1584 ? Key extends string6 unmodified lines1591 ////// ToSchema //////1592 ////// //////1593 ////////////////////////////////////////1594 1613-export type ToSchema<M extends string, P extends string, I extends Input['in'], O> = Prettify<{1595+export type ToSchema<1596+ M extends string,1597+ P extends string,1598+ I extends Input,1599+ R extends TypedResponse1600+> = Prettify<{1601 [K in P]: {1615- [K2 in M as AddDollar<K2>]: {1616- input: unknown extends I ? AddParam<{}, P> : AddParam<I, P>1617- output: unknown extends O ? {} : O1618- }1602+ [K2 in M as AddDollar<K2>]: R extends TypedResponse<infer T, infer U, infer F>1603+ ? {1604+ input: unknown extends I['in'] ? AddParam<{}, P> : AddParam<I['in'], P>1605+ output: unknown extends T ? {} : T1606+ outputFormat: I extends { outputFormat: string }1607+ ? I['outputFormat']1608+ : unknown extends F1609+ ? never1610+ : F1611+ status: U1612+ }1613+ : never1614 }1615 }>1616 1617 export type Schema = {1618 [Path: string]: {1624- [Method: `$${Lowercase<string>}`]: {1625- input: Partial<ValidationTargets>1626- output: any1627- }1619+ [Method: `$${Lowercase<string>}`]: Endpoint1620 }1621 }1622 1623+export type Endpoint = {1624+ input: Partial<ValidationTargets>1625+ output: any1626+ outputFormat: ResponseFormat1627+ status: StatusCode1628+}1629+1630 type ExtractParams<Path extends string> = string extends Path1631 ? Record<string, string>1632 : Path extends `${infer _Start}:${infer Param}/${infer Rest}`1633 ? { [K in Param | keyof ExtractParams<`/${Rest}`>]: string }7 unmodified lines1641 [P in keyof OrigSchema as MergePath<SubPath, P & string>]: {1642 [M in keyof OrigSchema[P]]: OrigSchema[P][M] extends {1643 input: infer Input1644 output: infer Output1645+ outputFormat: infer OutputFormat1646+ status: infer Status1647 }1648 ? {1649 input: Input extends { param: infer _ }1650 ? ExtractParams<SubPath> extends never18 unmodified lines1669 : K]: string1670 }1671 }1672 output: Output1673+ outputFormat: OutputFormat1674+ status: Status1675 }1676 : never1677 }1678 }>27 unmodified lines1706 ////// TypedResponse //////1707 ////// //////1708 ////////////////////////////////////////1709 1707-export type TypedResponse<T = unknown> = {1710+export type KnownResponseFormat = 'json' | 'text'1711+export type ResponseFormat = KnownResponseFormat | string1712+1713+export type TypedResponse<1714+ T = unknown,1715+ U extends StatusCode = StatusCode,1716+ F extends ResponseFormat = T extends string1717+ ? 'text'1718+ : T extends JSONValue1719+ ? 'json'1720+ : ResponseFormat1721+> = {1722 data: T1709- format: 'json' // Currently, support only `json` with `c.json()`1723+ status: U1724+ format: F1725 }1726 1712-type MergeTypedResponseData<T> = T extends Promise<infer T2>1713- ? T2 extends TypedResponse<infer U>1714- ? U1715- : {}1716- : T extends TypedResponse<infer U>1717- ? U1718- : {}1727+type MergeTypedResponse<T> = T extends Promise<infer T2>1728+ ? T2 extends TypedResponse1729+ ? T21730+ : TypedResponse1731+ : T extends TypedResponse1732+ ? T1733+ : TypedResponse1734 1735 ////////////////////////////////////////1736 ////// /////1737 ////// ValidationTargets /////80 unmodified linesmodified:bun.lockbbinary
A binary file, modified.
modified:package.json+8 added
277 unmodified lines278 "types": "./dist/types/helper/factory/index.d.ts",279 "import": "./dist/helper/factory/index.js",280 "require": "./dist/cjs/helper/factory/index.js"281 },282+ "./serve-static": {283+ "types": "./dist/types/middleware/serve-static/index.d.ts",284+ "import": "./dist/middleware/serve-static/index.js",285+ "require": "./dist/cjs/middleware/serve-static/index.js"286+ },287 "./cloudflare-workers": {288 "types": "./dist/types/adapter/cloudflare-workers/index.d.ts",289 "import": "./dist/adapter/cloudflare-workers/index.js",290 "require": "./dist/cjs/adapter/cloudflare-workers/index.js"188 unmodified lines479 ],480 "factory": [481 "./dist/types/helper/factory/index.d.ts"482 ],483+ "serve-static": [484+ "./dist/types/middleware/serve-static"485+ ],486 "cloudflare-workers": [487 "./dist/types/adapter/cloudflare-workers"488 ],489 "cloudflare-pages": [92 unmodified lines