Skip to content
Myr

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

74 files+2911 added−695 removed

modified:deno_dist/adapter/deno/serve-static.ts+1 added-1 removed
modified:deno_dist/client/client.ts+1 added
121 unmodified lines
122 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 lines
modified:deno_dist/client/types.ts+66 added-22 removed
modified:deno_dist/helper/cookie/index.ts+3 added-1 removed
116 unmodified lines
117 }118 c.header('set-cookie', cookie, { append: true })119}120121export const deleteCookie = (c: Context, name: string, opt?: CookieOptions): void => {121export 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 */2import { Hono } from '../../hono.ts'3import type { Env, H, HandlerResponse, Input, MiddlewareHandler } from '../../types.ts'45type InitApp<E extends Env = Env> = (app: Hono<E>) => void67export class Factory<E extends Env = any, P extends string = any> {8 private initApp?: InitApp<E>910 constructor(init?: { initApp?: InitApp<E> }) {11 this.initApp = init?.initApp12 }1314 /**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 }2526 createMiddleware = <I extends Input = {}>(middleware: MiddlewareHandler<E, P, I>) => middleware2728 createHandlers<I extends Input = {}, R extends HandlerResponse<any> = any>(29 handler1: H<E, P, I, R>
199 unmodified lines
229 return handlers.filter((handler) => handler !== undefined)230 }231}232212export const createFactory = <E extends Env = any, P extends string = any>() => new Factory<E, P>()233export const createFactory = <E extends Env = any, P extends string = any>(init?: {234 initApp?: InitApp<E>235}) => new Factory<E, P>(init)236237export 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 lines
11 onClose?: (evt: CloseEvent, ws: WSContext) => void12 onError?: (evt: Event, ws: WSContext) => void13}1415export type UpgradedWebSocketResponseInputJSONType = '__websocket'1615/**16 * Upgrade WebSocket Type17 */18export type UpgradeWebSocket = (
1 unmodified line
20) => MiddlewareHandler<21 any,22 string,23 {26 in: {27 json: UpgradedWebSocketResponseInputJSONType28 }24 outputFormat: 'ws'25 }26>2728export type WSReadyState = 0 | 1 | 2 | 3
23 unmodified lines
modified:deno_dist/jsx/dom/context.ts+25 added-13 removed
1 unmodified line
2import { DOM_ERROR_HANDLER } from '../constants.ts'3import type { Context } from '../context.ts'4import { globalContexts } from '../context.ts'5import { Fragment } from './jsx-runtime.ts'6import { setInternalTagFlag } from './utils.ts'77export const createContextProviderFunction =8 <T>(values: T[]) =>9 ({ value, children }: { value: T; children: Child[] }) => {10 const res = Fragment({8export const createContextProviderFunction = <T>(values: T[]) =>9 setInternalTagFlag(({ value, children }: { value: T; children: Child[] }) => {10 if (!children) {11 return undefined12 }1314 // 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 })4445export const createContext = <T>(defaultValue: T): Context<T> => {46 const values = [defaultValue]47 const context = {
7 unmodified lines
modified:deno_dist/jsx/dom/css.ts+8 added-4 removed
108 unmodified lines
109 // 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)123124 return [cssObject, Style] as const
86 unmodified lines
modified:deno_dist/jsx/dom/index.ts+36 added-5 removed
1import type { Props, Child, JSXNode } from '../base.ts'1import type { Props, Child, DOMAttributes, JSXNode } from '../base.ts'2import { memo, isValidElement } from '../base.ts'3import { Children } from '../children.ts'4import { useContext } from '../context.ts'5import {6 useState,7 useEffect,
9 unmodified lines
17 useLayoutEffect,18 useReducer,19 useId,20 useDebugValue,21 createRef,22 forwardRef,23 useImperativeHandle,24 useSyncExternalStore,25} from '../hooks/index.ts'26import { Suspense, ErrorBoundary } from './components.ts'27import { createContext } from './context.ts'23import { jsx } from './jsx-runtime.ts'28import { jsx, Fragment } from './jsx-runtime.ts'29import { flushSync, createPortal } from './render.ts'3031export { render } from './render.ts'3233const 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 }4243 let key = undefined44 if ('key' in jsxProps) {45 key = jsxProps.key46 delete jsxProps.key
11 unmodified lines
58 (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 lines
81 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}103104export default {105 useState,
10 unmodified lines
116 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}137138export type { Context } from '../context.ts'139140// TODO: change to `export type *` after denoify bug is fixed141// https://github.com/garronej/denoify/issues/124142export * from '../types.ts'
modified:deno_dist/jsx/dom/jsx-dev-runtime.ts+23 added-15 removed
1import type { Props } from '../base.ts'1import type { Props, JSXNode } from '../base.ts'2import { normalizeIntrinsicElementProps } from '../utils.ts'34const 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}164export const jsxDEV = (tag: string | Function, props: Props, key?: string) => {17export 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}3031export const Fragment = (props: Record<string, unknown>) => jsxDEV('', props, undefined)
modified:deno_dist/jsx/dom/render.ts+130 added-51 removed
1import type { JSXNode } from '../base.ts'2import type { FC, Child, Props } from '../base.ts'3import { toArray } from '../children.ts'3import { DOM_RENDERER, DOM_ERROR_HANDLER, DOM_STASH } from '../constants.ts'4import { DOM_RENDERER, DOM_ERROR_HANDLER, DOM_STASH, DOM_INTERNAL_TAG } from '../constants.ts'5import type { Context as JSXContext } from '../context.ts'6import { globalContexts as globalJSXContexts, useContext } from '../context.ts'7import type { EffectData } from '../hooks/index.ts'8import { STASH_EFFECT } from '../hooks/index.ts'9import { styleObjectForEach } from '../utils.ts'10import { createContext } from './context.ts' // import dom-specific versions1112const HONO_PORTAL_ELEMENT = '_hp'1314const eventAliasMap: Record<string, string> = {15 Change: 'Input',16 DoubleClick: 'DblClick',17} as const
2 unmodified lines
20 svg: 'http://www.w3.org/2000/svg',21 math: 'http://www.w3.org/1998/Math/MathML',22} as const2324const skipProps = new Set(['children'])2526// eslint-disable-next-line @typescript-eslint/no-explicit-any27export type HasRenderToDom = FC<any> & { [DOM_RENDERER]: FC<any> }28// eslint-disable-next-line @typescript-eslint/no-explicit-any29export type ErrorHandler = (error: any, retry: () => void) => Child | undefined
23 unmodified lines
53 // eslint-disable-next-line @typescript-eslint/no-explicit-any54 any[][]55 ]56} & JSXNode51type NodeString = [52 string, // text content53 boolean // is dirty54] & {57type NodeString = {58 t: string // text content59 d: boolean // is dirty60} & {61 e?: Text62 // like a NodeObject63 vC: undefined64 nN: undefined
27 unmodified lines
92export const buildDataStack: [Context, Node][] = []9394let nameSpaceContext: JSXContext<string> | undefined = undefined9590const isNodeString = (node: Node): node is NodeString => Array.isArray(node)96const isNodeString = (node: Node): node is NodeString => 't' in (node as NodeString)9798const getEventSpec = (key: string): [string, boolean] | undefined => {99 const match = key.match(/^on([A-Z][a-zA-Z]+?(?:PointerCapture)?)(Capture)?$/)100 if (match) {
5 unmodified lines
106107const 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 }110113 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 lines
175 }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 lines
206 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 lines
264265const removeNode = (node: Node) => {266 if (!isNodeString(node)) {267 node[DOM_STASH]?.[1][STASH_EFFECT]?.forEach((data: EffectData) => data[2]?.())268269 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}286287const apply = (node: NodeObject, container: Container) => {264 if (node.tag === undefined) {265 return266 }267288 node.c = container289 applyNodeObject(node, container)290}291292const 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 lines
330 const child = next[i]331332 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 lines
357 callbacks.forEach(([, , , cb]) => cb?.())358 })359}360361const fallbackUpdateFnArrayMap = new WeakMap<362 NodeObject,363 Array<() => Promise<NodeObject | undefined>>364>()365export const build = (366 context: Context,367 node: NodeObject,368 topLevelErrorHandlerNode: NodeObject | undefined,369 children?: Child[]370): void => {343 if (node.tag === undefined) {344 return345 }346371 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 ||= node
10 unmodified lines
388 prevNode.nN = child389 }390 prevNode = child391367 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 }400401 let oldChild: Node | undefined
7 unmodified lines
409 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 lines
443 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 lines
476const 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 lines
526}527528type UpdateMapResolve = (node: NodeObject | undefined) => void529const updateMap = new WeakMap<NodeObject, [UpdateMapResolve, Function]>()530const currentUpdateSets: Set<NodeObject>[] = []531export const update = async (532 context: Context,533 node: NodeObject534): Promise<NodeObject | undefined> => {
18 unmodified lines
553 }554 },555 ])556557 if (currentUpdateSets.length) {558 ;(currentUpdateSets.at(-1) as Set<NodeObject>).add(node)559 } else {508 await Promise.resolve()560 await Promise.resolve()561510 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 }568569 return promise570}571572export 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)576577 const fragment = document.createDocumentFragment()578 apply(node, fragment)579 replaceContainer(node, fragment, container)580 container.replaceChildren(fragment)581}582583export 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}596597export 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
1import { DOM_INTERNAL_TAG } from '../constants.ts'23export 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 lines
165 if (typeof newState === 'function') {166 newState = (newState as (currentState: T) => T)(stateData[0])167 }168169 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 lines
360361// Define to avoid errors. This hook currently does nothing.362// eslint-disable-next-line @typescript-eslint/no-unused-vars363export const useDebugValue = (_value: unknown, _formatter?: (value: unknown) => string): void => {}364365export const createRef = <T>(): RefObject<T> => {366 return { current: null }367}368369export 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}377378export 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}390391let useSyncExternalStoreGetServerSnapshotNotified = false392export 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 )405406 if (getServerSnapshot && !useSyncExternalStoreGetServerSnapshotNotified) {407 useSyncExternalStoreGetServerSnapshotNotified = true408 console.info('`getServerSnapshot` is not supported yet.')409 }410411 return state412}
modified:deno_dist/jsx/base.ts+44 added-29 removed
2 unmodified lines
3import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../utils/html.ts'4import type { Context } from './context.ts'5import { globalContexts } from './context.ts'6import type { IntrinsicElements as IntrinsicElementsDefined } from './intrinsic-elements.ts'7import { normalizeIntrinsicElementProps } from './utils.ts'7import { normalizeIntrinsicElementProps, styleObjectForEach } from './utils.ts'89// eslint-disable-next-line @typescript-eslint/no-explicit-any10export type Props = Record<string, any>11export type FC<T = Props> = (props: T) => HtmlEscapedString | Promise<HtmlEscapedString>11export type FC<P = Props> = {12 (props: P): HtmlEscapedString | Promise<HtmlEscapedString>13 defaultProps?: Partial<P> | undefined14 displayName?: string | undefined15}16export type DOMAttributes = Hono.HTMLAttributes1718declare global {19 // eslint-disable-next-line @typescript-eslint/no-namespace20 namespace JSX {
97 unmodified lines
118 this.props = props119 this.children = children120 }121122 get type(): string | Function {123 return this.tag as string124 }125126 // 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 }131132 toString(): string | Promise<string> {133 const buffer: StringBuffer = ['']134 this.localContexts?.forEach(([context, value]) => {135 context.values.push(value)
19 unmodified lines
155156 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 lines
257}258259export 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 }268269 const key = props.key270 delete props['key']271272 const node = jsxFn(tag, props, children)273 node.key = key274 return node275}276277export 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 lines
336 children?: Child | HtmlEscapedString337}): HtmlEscapedString => {338 return new JSXFragmentNode(339 '',320 {},340 {341 children,342 },343 Array.isArray(children) ? children : children ? [children] : []344 ) as never345}346347export 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}350351export 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
1import type { Child } from './base.ts'23export const toArray = (children: Child): Child[] =>4 Array.isArray(children) ? children : [children]5export 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
1export const DOM_RENDERER = Symbol('RENDERER')2export const DOM_ERROR_HANDLER = Symbol('ERROR_HANDLER')3export const DOM_STASH = Symbol('STASH')4export const DOM_INTERNAL_TAG = Symbol('INTERNAL')
modified:deno_dist/jsx/index.ts+17 added
1import { jsx, memo, Fragment, isValidElement, cloneElement } from './base.ts'2import type { DOMAttributes } from './base.ts'3import { Children } from './children.ts'4import { ErrorBoundary } from './components.ts'5import { createContext, useContext } from './context.ts'6import {7 useState,
10 unmodified lines
18 useLayoutEffect,19 useReducer,20 useId,21 useDebugValue,22 createRef,23 forwardRef,24 useImperativeHandle,25 useSyncExternalStore,26} from './hooks/index.ts'27import { Suspense } from './streaming.ts'2829export {
20 unmodified lines
50 startViewTransition,51 useViewTransition,52 useMemo,53 useLayoutEffect,54 createRef,55 forwardRef,56 useImperativeHandle,57 useSyncExternalStore,58 Suspense,59 Children,60 DOMAttributes,61}6263export default {64 memo,
18 unmodified lines
83 startViewTransition,84 useViewTransition,85 useMemo,86 useLayoutEffect,87 createRef,88 forwardRef,89 useImperativeHandle,90 useSyncExternalStore,91 Suspense,92 Children,93}9495// TODO: change to `export type *` after denoify bug is fixed96// https://github.com/garronej/denoify/issues/124
1 unmodified line
modified:deno_dist/jsx/jsx-dev-runtime.ts-1 removed
11 unmodified lines
12 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 node
1 unmodified line
modified:deno_dist/jsx/types.ts+30 added-1 removed
1/**2 * All types exported from "hono/jsx" are in this file.3 */4import type { Child } from './base.ts'4import type { Child, JSXNode } from './base.ts'56export type { Child, JSXNode, FC } from './base.ts'7export type { RefObject } from './hooks/index.ts'8export type { Context } from './context.ts'910export type PropsWithChildren<P = unknown> = P & { children?: Child | undefined }11export type CSSProperties = Hono.CSSProperties1213/**14 * React types15 */1617// eslint-disable-next-line @typescript-eslint/no-explicit-any18type ReactElement<P = any, T = string | Function> = JSXNode & {19 type: T20 props: P21 key: string | null22}23type ReactNode = ReactElement | string | number | boolean | null | undefined24// eslint-disable-next-line @typescript-eslint/no-unused-vars25type ComponentClass<P = {}, S = {}> = unknown2627export type { ReactElement, ReactNode, ComponentClass }2829export type Event = globalThis.Event30export type MouseEvent = globalThis.MouseEvent31export type KeyboardEvent = globalThis.KeyboardEvent32export type FocusEvent = globalThis.FocusEvent33export type ClipboardEvent = globalThis.ClipboardEvent34export type InputEvent = globalThis.InputEvent35export type PointerEvent = globalThis.PointerEvent36export type TouchEvent = globalThis.TouchEvent37export type WheelEvent = globalThis.WheelEvent38export type AnimationEvent = globalThis.AnimationEvent39export type TransitionEvent = globalThis.TransitionEvent40export type DragEvent = globalThis.DragEvent
modified:deno_dist/jsx/utils.ts+14 added
2 unmodified lines
3 props['class'] = props['className']4 delete props['className']5 }6}78export 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 lines
4import { timingSafeEqual } from '../../utils/buffer.ts'56const TOKEN_STRINGS = '[A-Za-z0-9._~+/-]+=*'7const PREFIX = 'Bearer'8const HEADER = 'Authorization'910type 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 lines
3637 const realm = options.realm?.replace(/"/g, '\\"')3839 return async function bearerAuth(c, next) {37 const headerToken = c.req.header('Authorization')40 const headerToken = c.req.header(options.headerName || HEADER)4142 if (!headerToken) {43 // No Authorization header44 const res = new Response('Unauthorized', {
47 unmodified lines
modified:deno_dist/middleware/secure-headers/index.ts+108 added-32 removed
1import { Buffer } from "node:buffer";2import type { Context } from '../../context.ts'3import type { MiddlewareHandler } from '../../types.ts'45declare module '../../context.ts' {6 interface ContextVariableMap {7 secureHeadersNonce?: string8 }9}1011export type ContentSecurityPolicyOptionHandler = (ctx: Context, directive: string) => string12type ContentSecurityPolicyOptionValue = (string | ContentSecurityPolicyOptionHandler)[]1314interface 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}3839interface ReportToOptions {40 group: string
63 unmodified lines
104 xPermittedCrossDomainPolicies: true,105 xXssProtection: true,106}107108type SecureHeadersCallback = (109 ctx: Context,110 headersToSet: [string, string | string[]][]111) => [string, string][]112113const generateNonce = () => {114 const buffer = new Uint8Array(16)115 crypto.getRandomValues(buffer)116 return Buffer.from(buffer).toString('base64')117}118export 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}128129export const secureHeaders = (customOptions?: Partial<SecureHeadersOptions>): MiddlewareHandler => {130 const options = { ...DEFAULT_OPTIONS, ...customOptions }131 const headersToSet = getFilteredHeaders(options)132 const callbacks: SecureHeadersCallback[] = []133134 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 }141142 if (options.reportingEndpoints) {143 headersToSet.push(['Reporting-Endpoints', getReportingEndpoints(options.reportingEndpoints)])
3 unmodified lines
147 headersToSet.push(['Report-To', getReportToOptions(options.reportTo)])148 }149150 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 lines
169 })170}171172function 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[] = []177178 for (const [directive, value] of Object.entries(contentSecurityPolicy)) {179 const valueArray = Array.isArray(value) ? value : [value]180181 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('; ')189190 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()199200 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}218219function getReportingEndpoints(220 reportingEndpoints: SecureHeadersOptions['reportingEndpoints'] = []
13 unmodified lines
modified:deno_dist/middleware/serve-static/index.ts+8 added-5 removed
1import type { Context } from '../../context.ts'1import type { Context, Data } from '../../context.ts'2import type { Env, MiddlewareHandler } from '../../types.ts'3import { getFilePath, getFilePathWithoutDefaultDocument } from '../../utils/filepath.ts'4import { getMimeType } from '../../utils/mime.ts'5
12 unmodified lines
18 * This middleware is not directly used by the user. Create a wrapper specifying `getContent()` by the environment such as Deno or Bun.19 */20export 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 lines
47 const getContent = options.getContent48 const pathResolve = options.pathResolve ?? defaultPathResolve4950 path = pathResolve(path)52 let content = await getContent(path)51 let content = await getContent(path, c)5253 if (!content) {54 let pathWithOutDefaultDocument = getFilePathWithoutDefaultDocument({55 filename,
2 unmodified lines
58 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 }6768 if (content instanceof Response) {69 return c.newResponse(content.body, content)70 }7172 if (content) {73 let mimeType: string | undefined74 if (options.mimes) {75 mimeType = getMimeType(path, options.mimes) ?? getMimeType(path)
14 unmodified lines
modified:deno_dist/middleware/timing/index.ts+7 added-3 removed
19 unmodified lines
20 total: boolean21 enabled: boolean | ((c: Context) => boolean)22 totalDescription: string23 autoEnd: boolean24 crossOrigin: boolean | string24 crossOrigin: boolean | string | ((c: Context) => boolean | string)25}2627const getTime = () => {28 try {
34 unmodified lines
63 const enabled = typeof options.enabled === 'function' ? options.enabled(c) : options.enabled6465 if (enabled) {66 c.res.headers.append('Server-Timing', headers.join(','))6768 const crossOrigin =69 typeof options.crossOrigin === 'function' ? options.crossOrigin(c) : options.crossOrigin7067 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 lines
modified:deno_dist/utils/mime.ts+1 added
17 unmodified lines
18 }19 }20}2122export { baseMimes as mimes }23const baseMimes: Record<string, string> = {24 aac: 'audio/aac',25 avi: 'video/x-msvideo',26 avif: 'image/avif',
53 unmodified lines
modified:deno_dist/utils/types.ts+3 added
34 unmodified lines
35 : T extends object36 ? { [K in keyof T]: JSONParsed<T[K]> }37 : never3839// from sindresorhus/type-fest40export type Simplify<T> = { [KeyType in keyof T]: T[KeyType] } & {}4142export type InterfaceToType<T> = T extends Function ? T : { [K in keyof T]: InterfaceToType<T[K]> }4344export type RequiredKeysOf<BaseType extends object> = Exclude<45 {
14 unmodified lines
modified:deno_dist/context.ts+30 added-26 removed
1import type { HonoRequest } from './request.ts'2import type { Env, FetchEventLike, NotFoundHandler, Input, TypedResponse } from './types.ts'3import { resolveCallback, HtmlEscapedCallbackPhase } from './utils/html.ts'4import type { RedirectStatusCode, StatusCode } from './utils/http-status.ts'5import type { JSONValue, InterfaceToType, JSONParsed, IsAny } from './utils/types.ts'5import type { JSONValue, JSONParsed, IsAny, Simplify } from './utils/types.ts'67type HeaderRecord = Record<string, string | string[]>8type Data = string | ArrayBuffer | ReadableStream8export type Data = string | ArrayBuffer | ReadableStream910export interface ExecutionContext {11 waitUntil(promise: Promise<unknown>): void12 passThroughOnException(): void
31 unmodified lines
4445interface BodyRespond extends NewResponse {}4647interface 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}5354interface 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}8384interface HTMLRespond {
375 unmodified lines
460 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 lines
487 * })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 lines
modified:deno_dist/types.ts+100 added-85 removed
1 unmodified line
2/* eslint-disable @typescript-eslint/no-explicit-any */3/* eslint-disable @typescript-eslint/ban-types */4import type { Context } from './context.ts'5import type { Hono } from './hono.ts'6import type { StatusCode } from './utils/http-status.ts'7import type {8 IfAnyThenEmptyObject,9 JSONValue,10 Prettify,11 RemoveBlankRecord,12 UnionToIntersection,13} from './utils/types.ts'
16 unmodified lines
3031export type Input = {32 in?: {}33 out?: {}34 outputFormat?: ResponseFormat35}3637export type BlankSchema = {}38export type BlankInput = {}
63 unmodified lines
102 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>107108 // app.get(path, handler)109 <110 P extends string,
5 unmodified lines
116 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 >123124 // app.get(handler x2)
7 unmodified lines
132 >(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 >139140 // app.get(path, handler x2)
9 unmodified lines
150 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 >157158 // app.get(handler x 3)
9 unmodified lines
168 >(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 >175176 // app.get(path, handler x3)
11 unmodified lines
188 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 >195196 // app.get(handler x 4)
11 unmodified lines
208 >(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 >215216 // app.get(path, handler x4)
18 unmodified lines
235 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 >242243 // app.get(handler x 5)
13 unmodified lines
257 >(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 >264265 // app.get(path, handler x5)
21 unmodified lines
287 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 >294295 // app.get(handler x 6)
22 unmodified lines
318 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 >325326 // app.get(path, handler x6)
24 unmodified lines
351 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 >358359 // app.get(handler x 7)
25 unmodified lines
385 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 >392393 // app.get(path, handler x7)
27 unmodified lines
421 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 >428429 // app.get(handler x 8)
28 unmodified lines
458 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 >465466 // app.get(path, handler x8)
30 unmodified lines
497 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 >504505 // app.get(handler x 9)
31 unmodified lines
537 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 >544545 // app.get(path, handler x9)
33 unmodified lines
579 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 >586587 // app.get(handler x 10)
34 unmodified lines
622 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 >629630 // app.get(path, handler x10)
36 unmodified lines
667 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 >674675 // app.get(...handlers[])
2 unmodified lines
678 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>683684 // 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>689690 // 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 lines
922 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 >929930 // app.on(method, path, handler x2)
11 unmodified lines
942 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 >949950 // app.on(method, path, handler x3)
13 unmodified lines
964 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 >971972 // app.on(method, path, handler x4)
20 unmodified lines
993 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 >10001001 // app.on(method, path, handler x5)
23 unmodified lines
1025 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 >10321033 // app.on(method, path, handler x6)
26 unmodified lines
1060 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 >10671068 // app.on(method, path, handler x7)
29 unmodified lines
1098 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 >11051106 // app.on(method, path, handler x8)
32 unmodified lines
1139 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 >11461147 // app.on(method, path, handler x9)
35 unmodified lines
1183 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 >11901191 // app.on(method, path, handler x10)
37 unmodified lines
1229 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 >12361237 // 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>12431244 // app.get(method[], path, handler)1245 <1246 Ms extends string[],
7 unmodified lines
1254 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 >12611262 // app.get(method[], path, handler x2)
11 unmodified lines
1274 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 >12811282 // app.get(method[], path, handler x3)
13 unmodified lines
1296 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 >13031304 // app.get(method[], path, handler x4)
20 unmodified lines
1325 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 >13321333 // app.get(method[], path, handler x5)
23 unmodified lines
1357 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 >13641365 // app.get(method[], path, handler x6)
26 unmodified lines
1392 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 >13991400 // app.get(method[], path, handler x7)
29 unmodified lines
1430 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 >14371438 // app.get(method[], path, handler x8)
32 unmodified lines
1471 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 >14781479 // app.get(method[], path, handler x9)
34 unmodified lines
1514 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 >15211522 // app.get(method[], path, handler x10)
37 unmodified lines
1560 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 >15671568 // 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>15741575 // 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}15821583type ExtractKey<S> = S extends Record<infer Key, unknown>1584 ? Key extends string
6 unmodified lines
1591////// ToSchema //////1592////// //////1593////////////////////////////////////////15941613export type ToSchema<M extends string, P extends string, I extends Input['in'], O> = Prettify<{1595export 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}>16161617export type Schema = {1618 [Path: string]: {1624 [Method: `$${Lowercase<string>}`]: {1625 input: Partial<ValidationTargets>1626 output: any1627 }1619 [Method: `$${Lowercase<string>}`]: Endpoint1620 }1621}16221623export type Endpoint = {1624 input: Partial<ValidationTargets>1625 output: any1626 outputFormat: ResponseFormat1627 status: StatusCode1628}16291630type 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 lines
1641 [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 never
18 unmodified lines
1669 : K]: string1670 }1671 }1672 output: Output1673 outputFormat: OutputFormat1674 status: Status1675 }1676 : never1677 }1678}>
27 unmodified lines
1706////// TypedResponse //////1707////// //////1708////////////////////////////////////////17091707export type TypedResponse<T = unknown> = {1710export type KnownResponseFormat = 'json' | 'text'1711export type ResponseFormat = KnownResponseFormat | string17121713export 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}17261712type MergeTypedResponseData<T> = T extends Promise<infer T2>1713 ? T2 extends TypedResponse<infer U>1714 ? U1715 : {}1716 : T extends TypedResponse<infer U>1717 ? U1718 : {}1727type MergeTypedResponse<T> = T extends Promise<infer T2>1728 ? T2 extends TypedResponse1729 ? T21730 : TypedResponse1731 : T extends TypedResponse1732 ? T1733 : TypedResponse17341735////////////////////////////////////////1736////// /////1737////// ValidationTargets /////
80 unmodified lines
modified:src/adapter/cloudflare-workers/serve-static.ts+6 added-1 removed
8 unmodified lines
9 namespace?: KVNamespace10 manifest: object | string11}1213// 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 */19export const serveStatic = <E extends Env = Env>(20 options: ServeStaticOptions<E>21): MiddlewareHandler => {22 return async function serveStatic(c, next) {
18 unmodified lines
modified:src/adapter/deno/serve-static.ts+1 added-1 removed
16 unmodified lines
17 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 lines
modified:src/client/client.test.ts+275 added
72 unmodified lines
73 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 )9192 beforeAll(() => server.listen())
42 unmodified lines
135 const data = await res.json()136 expectTypeOf(data).toMatchTypeOf<null>()137 expect(data).toBe(null)138 })139140 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)167168 // using .text() on json endpoint should return string169 type textTest = Expect<Equal<Promise<string>, ReturnType<typeof genericFetch.text>>>170 })171})172173describe('Basic - query, queries, form, path params, header and cookie', () => {174 const app = new Hono()
335 unmodified lines
510511 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 lines
650 expectTypeOf(json).toEqualTypeOf<{ data: string } | { message: string }>()651 })652})653654describe('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 })666667 const client = hc<typeof app>('', { fetch: app.request })668669 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 })674675 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 })682683 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 })690691 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 })698699 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})707708describe('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 })720721 const client = hc<typeof app>('', { fetch: app.request })722723 it('Should infer response type correctly', () => {724 const req = client.index.$get725726 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 })737738 it('Should infer response type of status 200 correctly', () => {739 const req = client.index.$get740741 type Actual = InferResponseType<typeof req, 200>742 type Expected = {743 data: string744 } | null745 type verify = Expect<Equal<Expected, Actual>>746 })747})748749describe('$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 lines
827 expect(data.requestDynamic).toEqual('two')828 })829})830831describe('RequestInit work as expected', () => {832 const app = new Hono()833834 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))842843 type AppType = typeof route844845 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 }854855 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 )861862 beforeAll(() => server.listen())863 afterEach(() => server.resetHandlers())864 afterAll(() => server.close())865866 const client = hc<AppType>('http://localhost', {867 headers: { 'x-hono': 'fire' },868 init: {869 credentials: 'include',870 },871 })872873 it('Should overwrite method and fail', async () => {874 const res = await client.headers.$get(undefined, { init: { method: 'POST' } })875876 expect(res.ok).toBe(false)877 })878879 it('Should clear headers', async () => {880 const res = await client.headers.$get(undefined, { init: { headers: undefined } })881882 expect(res.ok).toBe(true)883 const data = await res.json()884 expect(data).toEqual({})885 })886887 it('Should overwrite headers', async () => {888 const res = await client.headers.$get(undefined, {889 init: { headers: new Headers({ 'x-hono': 'awesome' }) },890 })891892 expect(res.ok).toBe(true)893 const data = await res.json()894 expect(data).toEqual({ 'x-hono': 'awesome' })895 })896897 it('credentials is include', async () => {898 const res = await client.credentials.$get()899900 expect(res.ok).toBe(true)901 const data = await res.text()902 expect(data).toEqual('include')903 })904905 it('deepMerge should works and not unset credentials', async () => {906 const res = await client.credentials.$get(undefined, { init: { headers: { hi: 'hello' } } })907908 expect(res.ok).toBe(true)909 const data = await res.text()910 expect(data).toEqual('include')911 })912913 it('Should unset credentials', async () => {914 const res = await client.credentials.$get(undefined, { init: { credentials: undefined } })915916 expect(res.ok).toBe(true)917 const data = await res.text()918 expect(data).toEqual('same-origin')919 })920})921922describe('WebSocket URL Protocol Translation', () => {923 const app = new Hono()924 const route = app.get(925 '/',
70 unmodified lines
996 const client = hc('http://localhost')997 expect(client.posts.toString()).toMatch('function proxyCallback')998 })999})10001001describe('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 )10121013 beforeAll(() => server.listen())1014 afterEach(() => server.resetHandlers())1015 afterAll(() => server.close())10161017 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/')10191020 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 })10261027 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 })10331034 /**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 lines
122 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 lines
modified:src/client/types.ts+66 added-22 removed
1import type { UpgradedWebSocketResponseInputJSONType } from '../helper/websocket'1import type { Hono } from '../hono'3import type { Schema } from '../types'2import type { Endpoint, ResponseFormat, Schema } from '../types'3import type { StatusCode, SuccessStatusCode } from '../utils/http-status'4import type { HasRequiredKeys } from '../utils/types'56type HonoRequest = (typeof Hono.prototype)['request']78export type ClientRequestOptions<T = unknown> = keyof T extends never8export 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 })2627export 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 lines
39 ? { 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 lines
56 ? never57 : T58 : never5960type 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 : never6753export interface ClientResponse<T> {68export 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 lines
9899export type Fetch<T> = (100 args?: InferRequestType<T>,101 opt?: ClientRequestOptions75) => Promise<ClientResponse<InferResponseType<T>>>102) => Promise<ClientResponseOfEndpoint<InferEndpointType<T>>>10377export type InferResponseType<T> = T extends (104type 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 : never115116export type InferResponseType<T, U extends StatusCode = StatusCode> = InferResponseTypeFromEndpoint<117 InferEndpointType<T>,118 U119>120121type InferResponseTypeFromEndpoint<T extends Endpoint, U extends StatusCode> = T extends {122 output: infer O123 status: infer S124}125 ? S extends U126 ? O127 : never128 : never129130export type InferRequestType<T> = T extends (131 args: infer R,132 // eslint-disable-next-line @typescript-eslint/no-explicit-any133 options: any | undefined
46 unmodified lines
modified:src/helper/cookie/index.test.ts+14 added
414 unmodified lines
415 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 })419420 app.get('/delete-cookie-with-deleted-value', (c) => {421 const deleted = deleteCookie(c, 'delicious_cookie')422 return c.text(deleted || '')423 })424425 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 lines
117 }118 c.header('set-cookie', cookie, { append: true })119}120121export const deleteCookie = (c: Context, name: string, opt?: CookieOptions): void => {121export 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
1import { expectTypeOf } from 'vitest'2import { hc } from '../../client'3import type { ClientRequest } from '../../client/types'4import { Hono } from '../../index'5import type { ToSchema } from '../../types'5import type { ToSchema, TypedResponse } from '../../types'6import type { StatusCode } from '../../utils/http-status'7import { validator } from '../../validator'8import { createMiddleware, createFactory } from './index'910describe('createMiddleware', () => {
65 unmodified lines
76 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 lines
111 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 lines
171 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 line
200 expectTypeOf(routes).toEqualTypeOf<Expected>()201 })202 })203})204205describe('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 */2import { Hono } from '../../hono'3import type { Env, H, HandlerResponse, Input, MiddlewareHandler } from '../../types'45type InitApp<E extends Env = Env> = (app: Hono<E>) => void67export class Factory<E extends Env = any, P extends string = any> {8 private initApp?: InitApp<E>910 constructor(init?: { initApp?: InitApp<E> }) {11 this.initApp = init?.initApp12 }1314 /**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 }2526 createMiddleware = <I extends Input = {}>(middleware: MiddlewareHandler<E, P, I>) => middleware2728 createHandlers<I extends Input = {}, R extends HandlerResponse<any> = any>(29 handler1: H<E, P, I, R>
199 unmodified lines
229 return handlers.filter((handler) => handler !== undefined)230 }231}232212export const createFactory = <E extends Env = any, P extends string = any>() => new Factory<E, P>()233export const createFactory = <E extends Env = any, P extends string = any>(init?: {234 initApp?: InitApp<E>235}) => new Factory<E, P>(init)236237export 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 lines
11 onClose?: (evt: CloseEvent, ws: WSContext) => void12 onError?: (evt: Event, ws: WSContext) => void13}1415export type UpgradedWebSocketResponseInputJSONType = '__websocket'1615/**16 * Upgrade WebSocket Type17 */18export type UpgradeWebSocket = (
1 unmodified line
20) => MiddlewareHandler<21 any,22 string,23 {26 in: {27 json: UpgradedWebSocketResponseInputJSONType28 }24 outputFormat: 'ws'25 }26>2728export type WSReadyState = 0 | 1 | 2 | 3
23 unmodified lines
modified:src/jsx/dom/context.test.tsx+30 added-1 removed
4 unmodified lines
5// hono/jsx/jsx-runtime and hono/jsx/dom/jsx-runtime are tested in their respective settings6// eslint-disable-next-line @typescript-eslint/no-unused-vars7import { jsx, Fragment } from '..'8import { createContext as createContextDom, useContext as useContextDom } from '.' // for dom9import { render } from '.'9import { render, useState } from '.'1011runner('Common', createContextCommon, useContextCommon)12runner('DOM', createContextDom, useContextDom)13
37 unmodified lines
51 render(App, root)52 expect(root.innerHTML).toBe('<p>1</p>')53 })5455 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 })8384 it('multiple provider', async () => {85 const Context = createContext(0)86 const Content = () => {87 const num = useContext(Context)
77 unmodified lines
modified:src/jsx/dom/context.ts+25 added-13 removed
1 unmodified line
2import { DOM_ERROR_HANDLER } from '../constants'3import type { Context } from '../context'4import { globalContexts } from '../context'5import { Fragment } from './jsx-runtime'6import { setInternalTagFlag } from './utils'77export const createContextProviderFunction =8 <T>(values: T[]) =>9 ({ value, children }: { value: T; children: Child[] }) => {10 const res = Fragment({8export const createContextProviderFunction = <T>(values: T[]) =>9 setInternalTagFlag(({ value, children }: { value: T; children: Child[] }) => {10 if (!children) {11 return undefined12 }1314 // 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 })4445export const createContext = <T>(defaultValue: T): Context<T> => {46 const values = [defaultValue]47 const context = {
7 unmodified lines
modified:src/jsx/dom/css.ts+8 added-4 removed
108 unmodified lines
109 // 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)123124 return [cssObject, Style] as const
86 unmodified lines
modified:src/jsx/dom/index.test.tsx+291 added-6 removed
1import { JSDOM } from 'jsdom'2import type { FC } from '..'2import 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-vars6import { jsx, Fragment, createElement } from '..'7import DefaultExport from '..'7import type { RefObject } from '../hooks'9import { useState, useEffect, useLayoutEffect, useCallback, useRef, useMemo } from '../hooks'8import {9 useState,10 useEffect,11 useLayoutEffect,12 useCallback,13 useRef,14 useMemo,15 createRef,16} from '../hooks'17import DefaultExport from '.'18import { memo, isValidElement, cloneElement } from '.'11import { render, createElement as createElementForDom, cloneElement as cloneElementForDom } from '.'19import {20 render,21 flushSync,22 createPortal,23 createElement as createElementForDom,24 cloneElement as cloneElementForDom,25} from '.'2627describe('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 })3435 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 })4142 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 })5152 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 })5859 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 })6566 it('type', () => {67 const element = createElement('div', { id: 'app' })68 expect(element.type).toBe('div')69 })7071 it('null props', () => {72 const element = createElement('div', null)73 expect(element).toEqual(expect.objectContaining({ tag: 'div', props: {} }))74 })75 })76 })77})7879describe('DOM', () => {80 beforeAll(() => {81 global.requestAnimationFrame = (cb) => setTimeout(cb)82 })
54 unmodified lines
137 render(<App />, root)138 expect(root.innerHTML).toBe('<div style="font-size: 10px;"></div>')139 })140141 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 })146147 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 })152153 it('style with string', async () => {154 const App = () => {155 const [style, setStyle] = useState<{ fontSize?: string; color?: string }>({156 fontSize: '10px',
30 unmodified lines
187 render(<App />, root)188 expect(root.innerHTML).toBe('<div></div>')189 expect(ref.current).toBeInstanceOf(HTMLElement)190 })191192 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 })199200 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 })219220 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 })240241 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 })248249 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 })256257 describe('replace content', () => {258 it('text to text', async () => {259 let setCount: (count: number) => void = () => {}260 const App = () => {
492 unmodified lines
753 expect.any(Function),754 false755 )756 })757758 it('onGotPointerCaptureCapture', async () => {759 const App = () => {760 return <div onGotPointerCaptureCapture={() => {}}></div>761 }
5 unmodified lines
767 expect.any(Function),768 true769 )770 })771772 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 })781782 it('simple Counter', async () => {783 const Counter = () => {
138 unmodified lines
922 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 })946947 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 })997998 it('switch child component', async () => {999 const Even = () => <p>Even</p>1000 const Odd = () => <div>Odd</div>1001 const Counter = () => {
601 unmodified lines
1603 expect(root.innerHTML).toBe('<div><p>1</p></div>')1604 })1605 })16061607 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 })16441645 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 })16731674 describe('SVG', () => {1675 it('simple', () => {1676 const App = () => {1677 return (
74 unmodified lines
1752 '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 line
1765 '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 lines
modified:src/jsx/dom/index.ts+36 added-5 removed
1import type { Props, Child, JSXNode } from '../base'1import type { Props, Child, DOMAttributes, JSXNode } from '../base'2import { memo, isValidElement } from '../base'3import { Children } from '../children'4import { useContext } from '../context'5import {6 useState,7 useEffect,
9 unmodified lines
17 useLayoutEffect,18 useReducer,19 useId,20 useDebugValue,21 createRef,22 forwardRef,23 useImperativeHandle,24 useSyncExternalStore,25} from '../hooks'26import { Suspense, ErrorBoundary } from './components'27import { createContext } from './context'23import { jsx } from './jsx-runtime'28import { jsx, Fragment } from './jsx-runtime'29import { flushSync, createPortal } from './render'3031export { render } from './render'3233const 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 }4243 let key = undefined44 if ('key' in jsxProps) {45 key = jsxProps.key46 delete jsxProps.key
11 unmodified lines
58 (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 lines
81 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}103104export default {105 useState,
10 unmodified lines
116 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}137138export type { Context } from '../context'139140// TODO: change to `export type *` after denoify bug is fixed141// https://github.com/garronej/denoify/issues/124142export * from '../types'
modified:src/jsx/dom/jsx-dev-runtime.ts+23 added-15 removed
1import type { Props } from '../base'1import type { Props, JSXNode } from '../base'2import { normalizeIntrinsicElementProps } from '../utils'34const 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}164export const jsxDEV = (tag: string | Function, props: Props, key?: string) => {17export 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}3031export const Fragment = (props: Record<string, unknown>) => jsxDEV('', props, undefined)
modified:src/jsx/dom/render.ts+130 added-51 removed
1import type { JSXNode } from '../base'2import type { FC, Child, Props } from '../base'3import { toArray } from '../children'3import { DOM_RENDERER, DOM_ERROR_HANDLER, DOM_STASH } from '../constants'4import { DOM_RENDERER, DOM_ERROR_HANDLER, DOM_STASH, DOM_INTERNAL_TAG } from '../constants'5import type { Context as JSXContext } from '../context'6import { globalContexts as globalJSXContexts, useContext } from '../context'7import type { EffectData } from '../hooks'8import { STASH_EFFECT } from '../hooks'9import { styleObjectForEach } from '../utils'10import { createContext } from './context' // import dom-specific versions1112const HONO_PORTAL_ELEMENT = '_hp'1314const eventAliasMap: Record<string, string> = {15 Change: 'Input',16 DoubleClick: 'DblClick',17} as const
2 unmodified lines
20 svg: 'http://www.w3.org/2000/svg',21 math: 'http://www.w3.org/1998/Math/MathML',22} as const2324const skipProps = new Set(['children'])2526// eslint-disable-next-line @typescript-eslint/no-explicit-any27export type HasRenderToDom = FC<any> & { [DOM_RENDERER]: FC<any> }28// eslint-disable-next-line @typescript-eslint/no-explicit-any29export type ErrorHandler = (error: any, retry: () => void) => Child | undefined
23 unmodified lines
53 // eslint-disable-next-line @typescript-eslint/no-explicit-any54 any[][]55 ]56} & JSXNode51type NodeString = [52 string, // text content53 boolean // is dirty54] & {57type NodeString = {58 t: string // text content59 d: boolean // is dirty60} & {61 e?: Text62 // like a NodeObject63 vC: undefined64 nN: undefined
27 unmodified lines
92export const buildDataStack: [Context, Node][] = []9394let nameSpaceContext: JSXContext<string> | undefined = undefined9590const isNodeString = (node: Node): node is NodeString => Array.isArray(node)96const isNodeString = (node: Node): node is NodeString => 't' in (node as NodeString)9798const getEventSpec = (key: string): [string, boolean] | undefined => {99 const match = key.match(/^on([A-Z][a-zA-Z]+?(?:PointerCapture)?)(Capture)?$/)100 if (match) {
5 unmodified lines
106107const 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 }110113 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 lines
175 }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 lines
206 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 lines
264265const removeNode = (node: Node) => {266 if (!isNodeString(node)) {267 node[DOM_STASH]?.[1][STASH_EFFECT]?.forEach((data: EffectData) => data[2]?.())268269 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}286287const apply = (node: NodeObject, container: Container) => {264 if (node.tag === undefined) {265 return266 }267288 node.c = container289 applyNodeObject(node, container)290}291292const 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 lines
330 const child = next[i]331332 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 lines
357 callbacks.forEach(([, , , cb]) => cb?.())358 })359}360361const fallbackUpdateFnArrayMap = new WeakMap<362 NodeObject,363 Array<() => Promise<NodeObject | undefined>>364>()365export const build = (366 context: Context,367 node: NodeObject,368 topLevelErrorHandlerNode: NodeObject | undefined,369 children?: Child[]370): void => {343 if (node.tag === undefined) {344 return345 }346371 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 ||= node
10 unmodified lines
388 prevNode.nN = child389 }390 prevNode = child391367 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 }400401 let oldChild: Node | undefined
7 unmodified lines
409 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 lines
443 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 lines
476const 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 lines
526}527528type UpdateMapResolve = (node: NodeObject | undefined) => void529const updateMap = new WeakMap<NodeObject, [UpdateMapResolve, Function]>()530const currentUpdateSets: Set<NodeObject>[] = []531export const update = async (532 context: Context,533 node: NodeObject534): Promise<NodeObject | undefined> => {
18 unmodified lines
553 }554 },555 ])556557 if (currentUpdateSets.length) {558 ;(currentUpdateSets.at(-1) as Set<NodeObject>).add(node)559 } else {508 await Promise.resolve()560 await Promise.resolve()561510 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 }568569 return promise570}571572export 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)576577 const fragment = document.createDocumentFragment()578 apply(node, fragment)579 replaceContainer(node, fragment, container)580 container.replaceChildren(fragment)581}582583export 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}596597export 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
1import { DOM_INTERNAL_TAG } from '../constants'23export 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 lines
15 startViewTransition,16 useViewTransition,17 useId,18 useDebugValue,19 createRef,20 forwardRef,21 useImperativeHandle,22 useSyncExternalStore,23} from '.'2425describe('Hooks', () => {26 beforeAll(() => {
446 unmodified lines
473 expect(root.innerHTML).toBe('<div></div>')474 expect(spy).not.toBeCalled()475 })476 })477478 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 })489490 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 })501502 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 })535536 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 lines
165 if (typeof newState === 'function') {166 newState = (newState as (currentState: T) => T)(stateData[0])167 }168169 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 lines
360361// Define to avoid errors. This hook currently does nothing.362// eslint-disable-next-line @typescript-eslint/no-unused-vars363export const useDebugValue = (_value: unknown, _formatter?: (value: unknown) => string): void => {}364365export const createRef = <T>(): RefObject<T> => {366 return { current: null }367}368369export 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}377378export 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}390391let useSyncExternalStoreGetServerSnapshotNotified = false392export 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 )405406 if (getServerSnapshot && !useSyncExternalStoreGetServerSnapshotNotified) {407 useSyncExternalStoreGetServerSnapshotNotified = true408 console.info('`getServerSnapshot` is not supported yet.')409 }410411 return state412}
modified:src/jsx/base.ts+44 added-29 removed
2 unmodified lines
3import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../utils/html'4import type { Context } from './context'5import { globalContexts } from './context'6import type { IntrinsicElements as IntrinsicElementsDefined } from './intrinsic-elements'7import { normalizeIntrinsicElementProps } from './utils'7import { normalizeIntrinsicElementProps, styleObjectForEach } from './utils'89// eslint-disable-next-line @typescript-eslint/no-explicit-any10export type Props = Record<string, any>11export type FC<T = Props> = (props: T) => HtmlEscapedString | Promise<HtmlEscapedString>11export type FC<P = Props> = {12 (props: P): HtmlEscapedString | Promise<HtmlEscapedString>13 defaultProps?: Partial<P> | undefined14 displayName?: string | undefined15}16export type DOMAttributes = Hono.HTMLAttributes1718declare global {19 // eslint-disable-next-line @typescript-eslint/no-namespace20 namespace JSX {
97 unmodified lines
118 this.props = props119 this.children = children120 }121122 get type(): string | Function {123 return this.tag as string124 }125126 // 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 }131132 toString(): string | Promise<string> {133 const buffer: StringBuffer = ['']134 this.localContexts?.forEach(([context, value]) => {135 context.values.push(value)
19 unmodified lines
155156 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 lines
257}258259export 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 }268269 const key = props.key270 delete props['key']271272 const node = jsxFn(tag, props, children)273 node.key = key274 return node275}276277export 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 lines
336 children?: Child | HtmlEscapedString337}): HtmlEscapedString => {338 return new JSXFragmentNode(339 '',320 {},340 {341 children,342 },343 Array.isArray(children) ? children : children ? [children] : []344 ) as never345}346347export 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}350351export 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
1import { Children } from './children'2import { createElement } from '.'34describe('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})1112describe('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})2223describe('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})3031describe('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 })3738 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})4546describe('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
1import type { Child } from './base'23export const toArray = (children: Child): Child[] =>4 Array.isArray(children) ? children : [children]5export 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
1export const DOM_RENDERER = Symbol('RENDERER')2export const DOM_ERROR_HANDLER = Symbol('ERROR_HANDLER')3export const DOM_STASH = Symbol('STASH')4export const DOM_INTERNAL_TAG = Symbol('INTERNAL')
modified:src/jsx/index.test.tsx+8 added
383 unmodified lines
384 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 })393394 describe('HtmlEscaped in props', () => {395 it('should not be double-escaped', () => {
349 unmodified lines
745 '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 lines
modified:src/jsx/index.ts+17 added
1import { jsx, memo, Fragment, isValidElement, cloneElement } from './base'2import type { DOMAttributes } from './base'3import { Children } from './children'4import { ErrorBoundary } from './components'5import { createContext, useContext } from './context'6import {7 useState,
10 unmodified lines
18 useLayoutEffect,19 useReducer,20 useId,21 useDebugValue,22 createRef,23 forwardRef,24 useImperativeHandle,25 useSyncExternalStore,26} from './hooks'27import { Suspense } from './streaming'2829export {
20 unmodified lines
50 startViewTransition,51 useViewTransition,52 useMemo,53 useLayoutEffect,54 createRef,55 forwardRef,56 useImperativeHandle,57 useSyncExternalStore,58 Suspense,59 Children,60 DOMAttributes,61}6263export default {64 memo,
18 unmodified lines
83 startViewTransition,84 useViewTransition,85 useMemo,86 useLayoutEffect,87 createRef,88 forwardRef,89 useImperativeHandle,90 useSyncExternalStore,91 Suspense,92 Children,93}9495// TODO: change to `export type *` after denoify bug is fixed96// https://github.com/garronej/denoify/issues/124
1 unmodified line
modified:src/jsx/jsx-dev-runtime.ts-1 removed
11 unmodified lines
12 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 node
1 unmodified line
modified:src/jsx/types.ts+30 added-1 removed
1/**2 * All types exported from "hono/jsx" are in this file.3 */4import type { Child } from './base'4import type { Child, JSXNode } from './base'56export type { Child, JSXNode, FC } from './base'7export type { RefObject } from './hooks'8export type { Context } from './context'910export type PropsWithChildren<P = unknown> = P & { children?: Child | undefined }11export type CSSProperties = Hono.CSSProperties1213/**14 * React types15 */1617// eslint-disable-next-line @typescript-eslint/no-explicit-any18type ReactElement<P = any, T = string | Function> = JSXNode & {19 type: T20 props: P21 key: string | null22}23type ReactNode = ReactElement | string | number | boolean | null | undefined24// eslint-disable-next-line @typescript-eslint/no-unused-vars25type ComponentClass<P = {}, S = {}> = unknown2627export type { ReactElement, ReactNode, ComponentClass }2829export type Event = globalThis.Event30export type MouseEvent = globalThis.MouseEvent31export type KeyboardEvent = globalThis.KeyboardEvent32export type FocusEvent = globalThis.FocusEvent33export type ClipboardEvent = globalThis.ClipboardEvent34export type InputEvent = globalThis.InputEvent35export type PointerEvent = globalThis.PointerEvent36export type TouchEvent = globalThis.TouchEvent37export type WheelEvent = globalThis.WheelEvent38export type AnimationEvent = globalThis.AnimationEvent39export type TransitionEvent = globalThis.TransitionEvent40export type DragEvent = globalThis.DragEvent
modified:src/jsx/utils.ts+14 added
2 unmodified lines
3 props['class'] = props['className']4 delete props['className']5 }6}78export 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 lines
55 app.get('/auth-verify-token/*', (c) => {56 handlerExecuted = true57 return c.text('auth-verify-token')58 })5960 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 })6667 it('Should authorize', async () => {68 const req = new Request('http://localhost/auth/a')
112 unmodified lines
181 expect(res).not.toBeNull()182 expect(handlerExecuted).toBeFalsy()183 expect(res.status).toBe(401)184 })185186 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 })195196 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 lines
4import { timingSafeEqual } from '../../utils/buffer'56const TOKEN_STRINGS = '[A-Za-z0-9._~+/-]+=*'7const PREFIX = 'Bearer'8const HEADER = 'Authorization'910type 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 lines
3637 const realm = options.realm?.replace(/"/g, '\\"')3839 return async function bearerAuth(c, next) {37 const headerToken = c.req.header('Authorization')40 const headerToken = c.req.header(options.headerName || HEADER)4142 if (!headerToken) {43 // No Authorization header44 const res = new Response('Unauthorized', {
47 unmodified lines
modified:src/middleware/secure-headers/index.test.ts+84 added-1 removed
1/* eslint-disable quotes */2import { Hono } from '../../hono'3import { poweredBy } from '../powered-by'4import { secureHeaders } from '.'4import { secureHeaders, NONCE } from '.'5import type { ContentSecurityPolicyOptionHandler } from '.'67declare module '../../context' {8 interface ContextVariableMap {9 ['test-scriptSrc-nonce']?: string10 ['test-styleSrc-nonce']?: string11 }12}1314describe('Secure Headers Middleware', () => {15 it('default middleware', async () => {16 const app = new Hono()17 app.use('*', secureHeaders())
311 unmodified lines
329 '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 })333334 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 )344345 app.all('*', async (c) => {346 return c.text(`nonce: ${c.get('secureHeadersNonce')}`)347 })348349 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 })355356 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 )367368 app.all('*', async (c) => {369 return c.text(`nonce: ${c.get('secureHeadersNonce')}`)370 })371372 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 })379380 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 )395396 app.all('*', async (c) => {397 return c.text(398 `script: ${c.get('test-scriptSrc-nonce')}, style: ${c.get('test-styleSrc-nonce')}`399 )400 })401402 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
1import type { Context } from '../../context'2import type { MiddlewareHandler } from '../../types'34declare module '../../context' {5 interface ContextVariableMap {6 secureHeadersNonce?: string7 }8}910export type ContentSecurityPolicyOptionHandler = (ctx: Context, directive: string) => string11type ContentSecurityPolicyOptionValue = (string | ContentSecurityPolicyOptionHandler)[]1213interface 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}3738interface ReportToOptions {39 group: string
63 unmodified lines
103 xPermittedCrossDomainPolicies: true,104 xXssProtection: true,105}106107type SecureHeadersCallback = (108 ctx: Context,109 headersToSet: [string, string | string[]][]110) => [string, string][]111112const generateNonce = () => {113 const buffer = new Uint8Array(16)114 crypto.getRandomValues(buffer)115 return Buffer.from(buffer).toString('base64')116}117export 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}127128export const secureHeaders = (customOptions?: Partial<SecureHeadersOptions>): MiddlewareHandler => {129 const options = { ...DEFAULT_OPTIONS, ...customOptions }130 const headersToSet = getFilteredHeaders(options)131 const callbacks: SecureHeadersCallback[] = []132133 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 }140141 if (options.reportingEndpoints) {142 headersToSet.push(['Reporting-Endpoints', getReportingEndpoints(options.reportingEndpoints)])
3 unmodified lines
146 headersToSet.push(['Report-To', getReportToOptions(options.reportTo)])147 }148149 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 lines
168 })169}170171function 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[] = []176177 for (const [directive, value] of Object.entries(contentSecurityPolicy)) {178 const valueArray = Array.isArray(value) ? value : [value]179180 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('; ')188189 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()198199 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}217218function getReportingEndpoints(219 reportingEndpoints: SecureHeadersOptions['reportingEndpoints'] = []
13 unmodified lines
modified:src/middleware/serve-static/index.test.ts+30 added-14 removed
1import { createMiddleware } from '../../helper'1import { Hono } from '../../hono'2import { serveStatic as baseServeStatic } from '.'34describe('Serve Static Middleware', () => {5 const app = new Hono()68 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 })1819 app.get('/static/*', serveStatic)20
30 unmodified lines
51 } as Request)52 expect(res.status).toBe(404)53 expect(await res.text()).toBe('404 Not Found')54 })5556 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 )6768 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
1import type { Context } from '../../context'1import type { Context, Data } from '../../context'2import type { Env, MiddlewareHandler } from '../../types'3import { getFilePath, getFilePathWithoutDefaultDocument } from '../../utils/filepath'4import { getMimeType } from '../../utils/mime'5
12 unmodified lines
18 * This middleware is not directly used by the user. Create a wrapper specifying `getContent()` by the environment such as Deno or Bun.19 */20export 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 lines
47 const getContent = options.getContent48 const pathResolve = options.pathResolve ?? defaultPathResolve4950 path = pathResolve(path)52 let content = await getContent(path)51 let content = await getContent(path, c)5253 if (!content) {54 let pathWithOutDefaultDocument = getFilePathWithoutDefaultDocument({55 filename,
2 unmodified lines
58 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 }6768 if (content instanceof Response) {69 return c.newResponse(content.body, content)70 }7172 if (content) {73 let mimeType: string | undefined74 if (options.mimes) {75 mimeType = getMimeType(path, options.mimes) ?? getMimeType(path)
14 unmodified lines
modified:src/middleware/timing/index.test.ts+85 added
53 unmodified lines
54 ).toBeTruthy()55 expect(res.headers.get('server-timing')?.includes(region)).toBeTruthy()56 expect(res.headers.get('server-timing')?.includes(regionDesc)).toBeTruthy()57 })5859 describe('Should handle crossOrigin setting', async () => {60 it('Should do nothing when crossOrigin is falsy', async () => {61 const crossOriginApp = new Hono()6263 crossOriginApp.use(64 '*',65 timing({66 crossOrigin: false,67 })68 )6970 crossOriginApp.get('/', (c) => c.text('/'))7172 const res = await crossOriginApp.request('http://localhost/')7374 expect(res).not.toBeNull()75 expect(res.headers.has('server-timing')).toBeTruthy()76 expect(res.headers.has('timing-allow-origin')).toBeFalsy()77 })7879 it('Should set Timing-Allow-Origin to * when crossOrigin is true', async () => {80 const crossOriginApp = new Hono()8182 crossOriginApp.use(83 '*',84 timing({85 crossOrigin: true,86 })87 )8889 crossOriginApp.get('/', (c) => c.text('/'))9091 const res = await crossOriginApp.request('http://localhost/')9293 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 })9899 it('Should set Timing-Allow-Origin to the value of crossOrigin when it is a string', async () => {100 const crossOriginApp = new Hono()101102 crossOriginApp.use(103 '*',104 timing({105 crossOrigin: 'https://example.com',106 })107 )108109 crossOriginApp.get('/', (c) => c.text('/'))110111 const res = await crossOriginApp.request('http://localhost/')112113 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 })118119 it('Should set Timing-Allow-Origin to the return value of crossOrigin when it is a function', async () => {120 const crossOriginApp = new Hono()121122 crossOriginApp.use(123 '*',124 timing({125 crossOrigin: (c) => c.req.header('origin') ?? '*',126 })127 )128129 crossOriginApp.get('/', (c) => c.text('/'))130131 const res = await crossOriginApp.request('http://localhost/', {132 headers: {133 origin: 'https://example.com',134 },135 })136137 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 lines
20 total: boolean21 enabled: boolean | ((c: Context) => boolean)22 totalDescription: string23 autoEnd: boolean24 crossOrigin: boolean | string24 crossOrigin: boolean | string | ((c: Context) => boolean | string)25}2627const getTime = () => {28 try {
34 unmodified lines
63 const enabled = typeof options.enabled === 'function' ? options.enabled(c) : options.enabled6465 if (enabled) {66 c.res.headers.append('Server-Timing', headers.join(','))6768 const crossOrigin =69 typeof options.crossOrigin === 'function' ? options.crossOrigin(c) : options.crossOrigin7067 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 lines
modified:src/utils/mime.ts+1 added
17 unmodified lines
18 }19 }20}2122export { baseMimes as mimes }23const baseMimes: Record<string, string> = {24 aac: 'audio/aac',25 avi: 'video/x-msvideo',26 avif: 'image/avif',
53 unmodified lines
modified:src/utils/types.ts+3 added
34 unmodified lines
35 : T extends object36 ? { [K in keyof T]: JSONParsed<T[K]> }37 : never3839// from sindresorhus/type-fest40export type Simplify<T> = { [KeyType in keyof T]: T[KeyType] } & {}4142export type InterfaceToType<T> = T extends Function ? T : { [K in keyof T]: InterfaceToType<T[K]> }4344export type RequiredKeysOf<BaseType extends object> = Exclude<45 {
14 unmodified lines
modified:src/validator/validator.test.ts+19 added-2 removed
2 unmodified lines
3import { z } from 'zod'4import { Hono } from '../hono'5import { HTTPException } from '../http-exception'6import type { ErrorHandler, ExtractSchema, MiddlewareHandler, ValidationTargets } from '../types'7import type { StatusCode } from '../utils/http-status'8import type { Equal, Expect } from '../utils/types'9import type { ValidationFunction } from './validator'10import { validator } from './validator'11
44 unmodified lines
56 $get: {57 input: {58 query: undefined59 }59 output: {}60 output: 'Valid!'61 outputFormat: 'text'62 status: StatusCode63 }64 }65 }66
222 unmodified lines
289 post: {290 id: number291 }292 }293 outputFormat: 'json'294 status: StatusCode295 }296 }297 }298
53 unmodified lines
352 id: number353 title: string354 }355 }356 outputFormat: 'json'357 status: StatusCode358 }359 }360 }361
279 unmodified lines
641 output: {642 page: number643 title: string644 }645 outputFormat: 'json'646 status: StatusCode647 }648 }649 }650
48 unmodified lines
699 param: {700 id: string701 }702 }694 output: {}703 output: 'Valid!'704 outputFormat: 'text'705 status: StatusCode706 }707 }708 }709
38 unmodified lines
748 }749 output: {750 success: boolean751 }752 outputFormat: 'json'753 status: StatusCode754 }755 }756 }757
182 unmodified lines
940 }941 output: {942 message: string943 }944 outputFormat: 'json'945 status: 201946 }947 }948 }>()949 })
25 unmodified lines
975 }976 output: {977 page: number978 }979 outputFormat: 'json'980 status: StatusCode981 }982 }983 }984
4 unmodified lines
modified:src/context.ts+30 added-26 removed
1import type { HonoRequest } from './request'2import type { Env, FetchEventLike, NotFoundHandler, Input, TypedResponse } from './types'3import { resolveCallback, HtmlEscapedCallbackPhase } from './utils/html'4import type { RedirectStatusCode, StatusCode } from './utils/http-status'5import type { JSONValue, InterfaceToType, JSONParsed, IsAny } from './utils/types'5import type { JSONValue, JSONParsed, IsAny, Simplify } from './utils/types'67type HeaderRecord = Record<string, string | string[]>8type Data = string | ArrayBuffer | ReadableStream8export type Data = string | ArrayBuffer | ReadableStream910export interface ExecutionContext {11 waitUntil(promise: Promise<unknown>): void12 passThroughOnException(): void
31 unmodified lines
4445interface BodyRespond extends NewResponse {}4647interface 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}5354interface 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}8384interface HTMLRespond {
375 unmodified lines
460 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 lines
487 * })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 lines
modified:src/hono.test.ts+2 added-2 removed
2111 unmodified lines
2112describe('Parse Body', () => {2113 const app = new Hono()21142115 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 })21212122 it('POST with JSON', async () => {2123 const req = new Request('http://localhost/json', {
1255 unmodified lines
modified:src/types.test.ts+317 added-46 removed
15 unmodified lines
16 MiddlewareHandler,17 ParamKeys,18 ParamKeyToRecord,19 RemoveQuestion,20 ResponseFormat,21 ToSchema,22 TypedResponse,23} from './types'24import type { StatusCode } from './utils/http-status'25import type { Expect, Equal } from './utils/types'26import { validator } from './validator'2728describe('Env', () => {
66 unmodified lines
95 }96 output: {97 message: string98 }99 outputFormat: 'json'100 status: StatusCode101 }102 }103 }104 type verify = Expect<Equal<Expected, Actual>>
29 unmodified lines
134 }135 output: {136 message: string137 }138 outputFormat: 'json'139 status: StatusCode140 }141 }142 }143 type verify = Expect<Equal<Expected, Actual>>
17 unmodified lines
161 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 lines
190 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 lines
215 } & {216 foo: string217 }218 }208 output: {}219 output: string220 outputFormat: 'text'221 status: StatusCode222 }223 }224 } & {225 '/foo/:foo/books/:id': {
5 unmodified lines
231 foo: string232 }233 }234 output: {}235 outputFormat: ResponseFormat236 status: StatusCode237 }238 }239 }240 type verify = Expect<Equal<Expected, Actual>>
29 unmodified lines
270 }271 output: {272 success: boolean273 }274 outputFormat: 'json'275 status: StatusCode276 }277 }278 }279 type verify = Expect<Equal<Expected, Actual>>280 })281})282283describe('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 })293294 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 })303304 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})314315describe('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 >340341 type Actual = ExtractSchema<AppType>
13 unmodified lines
355 output: {356 message: string357 success: boolean358 }359 outputFormat: 'json'360 status: StatusCode361 }362 }363 }364 type verify = Expect<Equal<Expected, Actual>>
10 unmodified lines
375 '/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 lines
439})440441describe('`json()`', () => {442 const app = new Hono<{ Variables: { foo: string } }>()384443 app.get('/post/:id', (c) => {444 c.req.param('id')445 const id = c.req.param('id')446 return c.text('foo')447 })448449 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 })470397 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>399481 type Expected = {482 '/hello': {483 $get: {484 input: {}485 output: {486 message: string487 }488 outputFormat: 'json'489 status: 200490 }491 }492 }410493 type verify = Expect<Equal<Expected, Actual>>494 })495})496
97 unmodified lines
594})595596describe('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 lines
612 page: string613 }614 }615 output: {}616 outputFormat: 'json'617 status: StatusCode618 }619 }620 }621 type verify = Expect<Equal<Expected, Actual>>
26 unmodified lines
648 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 >671672 type Actual = MergeSchemaPath<Sub, '/api'>673
8 unmodified lines
682 }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 lines
713 page: string714 }715 }716 output: {}717 outputFormat: 'json'718 status: StatusCode719 }720 }721 },722 '/something'
9 unmodified lines
732 page: string733 }734 }735 output: {}736 outputFormat: 'json'737 status: StatusCode738 }739 }740 }741 type verify = Expect<Equal<Expected, Actual>>
1 unmodified line
743744 type GetKey<T> = T extends Record<infer K, unknown> ? K : never745746 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 })751752 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 })757758 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 })763764 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 line
771 b: string772 }773 }774 output: {}775 outputFormat: ResponseFormat776 status: StatusCode777 }778 }779 }780 type verify = Expect<Equal<Expected, Actual>>781 })782783 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 lines
792 b: string793 }794 }795 output: {}796 outputFormat: 'json'797 status: StatusCode798 }799 }800 }801 type verify = Expect<Equal<Expected, Actual>>802 })803804 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 lines
813 b: string814 }815 }816 output: {}817 outputFormat: 'json'818 status: StatusCode819 }820 }821 }822 type verify = Expect<Equal<Expected, Actual>>
2 unmodified lines
825826describe('Different types using json()', () => {827 describe('no path pattern', () => {828 const app = new Hono()829830 test('Three different types', () => {831 const route = app.get((c) => {832 const flag = false833 if (flag) {
12 unmodified lines
846 })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 })879880 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 })936937 describe('path pattern', () => {938 const app = new Hono()939940 test('Three different types', () => {941 const route = app.get('/foo', (c) => {942 const flag = false943 if (flag) {
12 unmodified lines
956 })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 })989990 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})10471048describe('json() in an async handler', () => {1049 const app = new Hono()807 test('Three different types', () => {10501051 test('json', () => {1052 const route = app.get(async (c) => {1053 return c.json({1054 ok: true,1055 })
5 unmodified lines
1061 input: {}1062 output: {1063 ok: boolean1064 }1065 outputFormat: 'json'1066 status: StatusCode1067 }1068 }1069 }1070 type verify = Expect<Equal<Expected, Actual>>1071 })10721073 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})10981099/**1100 * Other tests for `c.var` are written in `hono.test.ts`.
552 unmodified lines
modified:src/types.ts+100 added-85 removed
1 unmodified line
2/* eslint-disable @typescript-eslint/no-explicit-any */3/* eslint-disable @typescript-eslint/ban-types */4import type { Context } from './context'5import type { Hono } from './hono'6import type { StatusCode } from './utils/http-status'7import type {8 IfAnyThenEmptyObject,9 JSONValue,10 Prettify,11 RemoveBlankRecord,12 UnionToIntersection,13} from './utils/types'
16 unmodified lines
3031export type Input = {32 in?: {}33 out?: {}34 outputFormat?: ResponseFormat35}3637export type BlankSchema = {}38export type BlankInput = {}
63 unmodified lines
102 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>107108 // app.get(path, handler)109 <110 P extends string,
5 unmodified lines
116 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 >123124 // app.get(handler x2)
7 unmodified lines
132 >(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 >139140 // app.get(path, handler x2)
9 unmodified lines
150 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 >157158 // app.get(handler x 3)
9 unmodified lines
168 >(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 >175176 // app.get(path, handler x3)
11 unmodified lines
188 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 >195196 // app.get(handler x 4)
11 unmodified lines
208 >(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 >215216 // app.get(path, handler x4)
18 unmodified lines
235 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 >242243 // app.get(handler x 5)
13 unmodified lines
257 >(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 >264265 // app.get(path, handler x5)
21 unmodified lines
287 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 >294295 // app.get(handler x 6)
22 unmodified lines
318 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 >325326 // app.get(path, handler x6)
24 unmodified lines
351 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 >358359 // app.get(handler x 7)
25 unmodified lines
385 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 >392393 // app.get(path, handler x7)
27 unmodified lines
421 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 >428429 // app.get(handler x 8)
28 unmodified lines
458 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 >465466 // app.get(path, handler x8)
30 unmodified lines
497 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 >504505 // app.get(handler x 9)
31 unmodified lines
537 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 >544545 // app.get(path, handler x9)
33 unmodified lines
579 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 >586587 // app.get(handler x 10)
34 unmodified lines
622 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 >629630 // app.get(path, handler x10)
36 unmodified lines
667 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 >674675 // app.get(...handlers[])
2 unmodified lines
678 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>683684 // 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>689690 // 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 lines
922 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 >929930 // app.on(method, path, handler x2)
11 unmodified lines
942 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 >949950 // app.on(method, path, handler x3)
13 unmodified lines
964 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 >971972 // app.on(method, path, handler x4)
20 unmodified lines
993 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 >10001001 // app.on(method, path, handler x5)
23 unmodified lines
1025 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 >10321033 // app.on(method, path, handler x6)
26 unmodified lines
1060 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 >10671068 // app.on(method, path, handler x7)
29 unmodified lines
1098 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 >11051106 // app.on(method, path, handler x8)
32 unmodified lines
1139 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 >11461147 // app.on(method, path, handler x9)
35 unmodified lines
1183 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 >11901191 // app.on(method, path, handler x10)
37 unmodified lines
1229 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 >12361237 // 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>12431244 // app.get(method[], path, handler)1245 <1246 Ms extends string[],
7 unmodified lines
1254 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 >12611262 // app.get(method[], path, handler x2)
11 unmodified lines
1274 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 >12811282 // app.get(method[], path, handler x3)
13 unmodified lines
1296 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 >13031304 // app.get(method[], path, handler x4)
20 unmodified lines
1325 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 >13321333 // app.get(method[], path, handler x5)
23 unmodified lines
1357 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 >13641365 // app.get(method[], path, handler x6)
26 unmodified lines
1392 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 >13991400 // app.get(method[], path, handler x7)
29 unmodified lines
1430 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 >14371438 // app.get(method[], path, handler x8)
32 unmodified lines
1471 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 >14781479 // app.get(method[], path, handler x9)
34 unmodified lines
1514 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 >15211522 // app.get(method[], path, handler x10)
37 unmodified lines
1560 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 >15671568 // 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>15741575 // 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}15821583type ExtractKey<S> = S extends Record<infer Key, unknown>1584 ? Key extends string
6 unmodified lines
1591////// ToSchema //////1592////// //////1593////////////////////////////////////////15941613export type ToSchema<M extends string, P extends string, I extends Input['in'], O> = Prettify<{1595export 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}>16161617export type Schema = {1618 [Path: string]: {1624 [Method: `$${Lowercase<string>}`]: {1625 input: Partial<ValidationTargets>1626 output: any1627 }1619 [Method: `$${Lowercase<string>}`]: Endpoint1620 }1621}16221623export type Endpoint = {1624 input: Partial<ValidationTargets>1625 output: any1626 outputFormat: ResponseFormat1627 status: StatusCode1628}16291630type 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 lines
1641 [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 never
18 unmodified lines
1669 : K]: string1670 }1671 }1672 output: Output1673 outputFormat: OutputFormat1674 status: Status1675 }1676 : never1677 }1678}>
27 unmodified lines
1706////// TypedResponse //////1707////// //////1708////////////////////////////////////////17091707export type TypedResponse<T = unknown> = {1710export type KnownResponseFormat = 'json' | 'text'1711export type ResponseFormat = KnownResponseFormat | string17121713export 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}17261712type MergeTypedResponseData<T> = T extends Promise<infer T2>1713 ? T2 extends TypedResponse<infer U>1714 ? U1715 : {}1716 : T extends TypedResponse<infer U>1717 ? U1718 : {}1727type MergeTypedResponse<T> = T extends Promise<infer T2>1728 ? T2 extends TypedResponse1729 ? T21730 : TypedResponse1731 : T extends TypedResponse1732 ? T1733 : TypedResponse17341735////////////////////////////////////////1736////// /////1737////// ValidationTargets /////
80 unmodified lines
modified:bun.lockbbinary

A binary file, modified.

modified:package.json+8 added
277 unmodified lines
278 "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 lines
479 ],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