Merge pull request #1895 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 254f338, 8ba8569 · Browse files · 62 files·+2338 added−332 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
62 files+2338 added−332 removed
- tests:+1059 added−85 removed
- other:+1279 added−247 removed
Provenance
- Commit
be9f4ca- Tree
1af102d- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent 1
254f338- Parent 2
8ba8569
62 files changed+2338 added−332 removed
modified:deno_dist/adapter/deno/serve-static.ts+10 added-7 removed
1223456789101011121314151617181819192021222324252625 unmodified lines5253545553545556575859606162import type { Context } from '../../context.ts'import type { Next } from '../../types.ts'import type { Env, MiddlewareHandler } from '../../types.ts'import { getFilePath } from '../../utils/filepath.ts'import { getMimeType } from '../../utils/mime.ts'
// eslint-disable-next-line @typescript-eslint/ban-ts-comment// @ts-ignoreconst { open } = Deno
export type ServeStaticOptions = {export type ServeStaticOptions<E extends Env = Env> = { root?: string path?: string rewriteRequestPath?: (path: string) => string onNotFound?: (path: string, c: Context<E>) => void | Promise<void>}
const DEFAULT_DOCUMENT = 'index.html'
export const serveStatic = (options: ServeStaticOptions = { root: '' }) => { return async (c: Context, next: Next) => {export const serveStatic = <E extends Env = Env>( options: ServeStaticOptions<E> = { root: '' }): MiddlewareHandler => { return async (c, next) => { // Do nothing if Response is already set if (c.finalized) { await next() return25 unmodified lines c.header('Content-Type', mimeType) } // Return Response object with stream return c.body(file.readable) } else { console.warn(`Static file: ${path} is not found`) await next() }
await options.onNotFound?.(path, c) await next() return }}modified:deno_dist/client/client.ts+3 added
140 unmodified lines141 142 const path = parts.join('/')143 const url = mergePath(baseUrl, path)144 if (method === 'url') {145+ if (opts.args[0] && opts.args[0].param) {146+ return new URL(replaceUrlParam(url, opts.args[0].param))147+ }148 return new URL(url)149 }150 151 const req = new ClientRequestImpl(url, method)7 unmodified linesmodified:deno_dist/client/types.ts+7 added-1 removed
21 unmodified lines2223242526262728293031323334353684 unmodified lines21 unmodified lines : (args?: R, options?: ClientRequestOptions) => Promise<ClientResponse<O>> : never : never} & { $url: () => URL $url: ( arg?: S[keyof S] extends { input: infer R } ? R extends { param: infer P } ? { param: P } : {} : {} ) => URL}
// eslint-disable-next-line @typescript-eslint/no-explicit-anytype BlankRecordToNever<T> = T extends any ? (keyof T extends never ? never : T) : never84 unmodified linesadded:deno_dist/helper/css/index.ts+306 added
1+import { raw } from '../../helper/html/index.ts'2+import type { HtmlEscapedCallback, HtmlEscapedString } from '../../utils/html.ts'3+4+const IS_CSS_CLASS_NAME = Symbol('IS_CSS_CLASS_NAME')5+const STYLE_STRING = Symbol('STYLE_STRING')6+const SELECTORS = Symbol('SELECTORS')7+const EXTERNAL_CLASS_NAMES = Symbol('EXTERNAL_CLASS_NAMES')8+type CssClassName = HtmlEscapedString & {9+ [IS_CSS_CLASS_NAME]: true10+ [STYLE_STRING]: string11+ // eslint-disable-next-line @typescript-eslint/ban-types12+ [SELECTORS]: String[]13+ [EXTERNAL_CLASS_NAMES]: string[]14+}15+16+type CssEscaped = {17+ isCssEscaped: true18+}19+type CssEscapedString = string & CssEscaped20+21+/**22+ * @experimental23+ * `rawCssString` is an experimental feature.24+ * The API might be changed.25+ */26+export const rawCssString = (value: string): CssEscapedString => {27+ const escapedString = new String(value) as CssEscapedString28+ escapedString.isCssEscaped = true29+ return escapedString30+}31+32+const DEFAULT_STYLE_ID = 'hono-css'33+34+/**35+ * Used the goober'code as a reference:36+ * https://github.com/cristianbote/goober/blob/master/src/core/to-hash.js37+ * MIT License, Copyright (c) 2019 Cristian Bote38+ */39+const toHash = (str: string): string => {40+ let i = 0,41+ out = 1142+ while (i < str.length) {43+ out = (101 * out + str.charCodeAt(i++)) >>> 044+ }45+ return 'css-' + out46+}47+48+const cssStringReStr = [49+ '"(?:(?:\\\\[\\s\\S]|[^"\\\\])*)"', // double quoted string50+ // eslint-disable-next-line quotes51+ "'(?:(?:\\\\[\\s\\S]|[^'\\\\])*)'", // single quoted string52+].join('|')53+const minifyCssRe = new RegExp(54+ [55+ '(' + cssStringReStr + ')', // $1: quoted string56+57+ '(?:' +58+ [59+ '^\\s+', // head whitespace60+ '\\/\\*.*?\\*\\/\\s*', // multi-line comment61+ '\\/\\/.*\\n\\s*', // single-line comment62+ '\\s+$', // tail whitespace63+ ].join('|') +64+ ')',65+66+ ';\\s*(}|$)\\s*', // $2: trailing semicolon67+ '\\s*([{};:,])\\s*', // $3: whitespace around { } : , ;68+ '(\\s)\\s+', // $4: 2+ spaces69+ ].join('|'),70+ 'g'71+)72+73+const minify = (css: string): string => {74+ return css.replace(minifyCssRe, (_, $1, $2, $3, $4) => $1 || $2 || $3 || $4 || '')75+}76+77+type usedClassNameData = [78+ Record<string, string>, // class name to add79+ Record<string, true> // class name already added80+]81+// eslint-disable-next-line @typescript-eslint/ban-types82+type CssVariableBasicType = string | String | number | boolean | null | undefined83+type CssVariableAsyncType = Promise<CssVariableBasicType>84+type CssVariableArrayType = (CssVariableBasicType | CssVariableAsyncType)[]85+type CssVariableType = CssVariableBasicType | CssVariableAsyncType | CssVariableArrayType86+87+const buildStyleString = async (88+ strings: TemplateStringsArray,89+ values: CssVariableType[],90+ // eslint-disable-next-line @typescript-eslint/ban-types91+ selectors: String[],92+ externalClassNames: string[]93+): Promise<string> => {94+ let styleString = ''95+ for (let i = 0; i < strings.length; i++) {96+ styleString += strings[i]97+ let vArray = values[i]98+ if (typeof vArray === 'boolean' || vArray === null || vArray === undefined) {99+ continue100+ }101+102+ if (!Array.isArray(vArray)) {103+ vArray = [vArray] as CssVariableArrayType104+ }105+ for (let j = 0; j < vArray.length; j++) {106+ let value = (107+ vArray[j] instanceof Promise ? await vArray[j] : vArray[j]108+ ) as CssVariableBasicType109+ if (typeof value === 'boolean' || value === null || value === undefined) {110+ continue111+ }112+ if (typeof value === 'number') {113+ styleString += value114+ } else if (value.startsWith('@keyframes ')) {115+ selectors.push(value)116+ styleString += ` ${value.substring(11)} `117+ } else {118+ if ((value as CssClassName)[IS_CSS_CLASS_NAME]) {119+ selectors.push(...(value as CssClassName)[SELECTORS])120+ externalClassNames.push(...(value as CssClassName)[EXTERNAL_CLASS_NAMES])121+ value = (value as CssClassName)[STYLE_STRING]122+ if (value.length > 0) {123+ const lastChar = value[value.length - 1]124+ if (lastChar !== ';' && lastChar !== '}') {125+ value += ';'126+ }127+ }128+ } else if (129+ !(value as CssEscapedString).isCssEscaped &&130+ /([\\"'\/])/.test(value as string)131+ ) {132+ value = value.replace(/([\\"']|(?<=<)\/)/g, '\\$1')133+ }134+ styleString += `${value || ''}`135+ }136+ }137+ }138+139+ return minify(styleString)140+}141+142+/**143+ * @experimental144+ * `createCssContext` is an experimental feature.145+ * The API might be changed.146+ */147+export const createCssContext = ({ id }: { id: Readonly<string> }) => {148+ const contextMap: WeakMap<object, usedClassNameData> = new WeakMap()149+150+ const replaceStyleRe = new RegExp(`(<style id="${id}">.*?)(</style>)`)151+152+ const css = async (153+ strings: TemplateStringsArray,154+ ...values: CssVariableType[]155+ ): Promise<string> => {156+ // eslint-disable-next-line @typescript-eslint/ban-types157+ const selectors: String[] = []158+ const externalClassNames: string[] = []159+ const thisStyleString = await buildStyleString(strings, values, selectors, externalClassNames)160+ const thisSelector = toHash(thisStyleString)161+ const className = new String([thisSelector, ...externalClassNames].join(' ')) as CssClassName162+163+ const appendStyle: HtmlEscapedCallback = ({ buffer, context }): Promise<string> | undefined => {164+ const [toAdd, added] = contextMap.get(context) as usedClassNameData165+ const names = Object.keys(toAdd)166+167+ if (!names.length) {168+ return169+ }170+171+ let stylesStr = ''172+ names.forEach((className) => {173+ added[className] = true174+ stylesStr += `${className[0] === '@' ? '' : '.'}${className}{${toAdd[className]}}`175+ })176+ contextMap.set(context, [{}, added])177+178+ if (buffer && replaceStyleRe.test(buffer[0])) {179+ buffer[0] = buffer[0].replace(replaceStyleRe, (_, pre, post) => `${pre}${stylesStr}${post}`)180+ return181+ }182+183+ const appendStyleScript = `<script>document.querySelector('#${id}').textContent+=${JSON.stringify(184+ stylesStr185+ )}</script>`186+ if (buffer) {187+ buffer[0] = `${appendStyleScript}${buffer[0]}`188+ return189+ }190+191+ return Promise.resolve(appendStyleScript)192+ }193+194+ const addClassNameToContext: HtmlEscapedCallback = ({ context }) => {195+ if (!contextMap.get(context)) {196+ contextMap.set(context, [{}, {}])197+ }198+ const [toAdd, added] = contextMap.get(context) as usedClassNameData199+ let allAdded = true200+ if (!added[thisSelector]) {201+ allAdded = false202+ toAdd[thisSelector] = thisStyleString203+ }204+ selectors.forEach((className) => {205+ if (!added[`${className}`]) {206+ allAdded = false207+ toAdd[`${className}`] = (className as CssClassName)[STYLE_STRING]208+ }209+ })210+ if (allAdded) {211+ return212+ }213+214+ return Promise.resolve(raw('', [appendStyle]))215+ }216+217+ Object.assign(className, {218+ isEscaped: true,219+ callbacks: [addClassNameToContext],220+ [IS_CSS_CLASS_NAME]: true,221+ [STYLE_STRING]: thisStyleString,222+ [SELECTORS]: selectors,223+ [EXTERNAL_CLASS_NAMES]: externalClassNames,224+ })225+226+ return className as string227+ }228+229+ const cx = async (230+ ...args: (string | boolean | null | undefined | Promise<string | boolean | null | undefined>)[]231+ ): Promise<string> => {232+ const resolvedArgs = await Promise.all(args)233+ for (let i = 0; i < resolvedArgs.length; i++) {234+ const arg = resolvedArgs[i]235+ if (typeof arg === 'string' && !(arg as CssClassName)[IS_CSS_CLASS_NAME]) {236+ const externalClassName = new String(arg) as CssClassName237+ resolvedArgs[i] = Object.assign(externalClassName, {238+ isEscaped: true,239+ [IS_CSS_CLASS_NAME]: true,240+ [STYLE_STRING]: '',241+ [SELECTORS]: [],242+ [EXTERNAL_CLASS_NAMES]: [arg],243+ })244+ }245+ }246+247+ // eslint-disable-next-line @typescript-eslint/no-explicit-any248+ return css(Array(resolvedArgs.length).fill('') as any, ...resolvedArgs)249+ }250+251+ const keyframes = async (252+ strings: TemplateStringsArray,253+ ...values: CssVariableType[]254+ ): // eslint-disable-next-line @typescript-eslint/ban-types255+ Promise<String> => {256+ const styleString = await buildStyleString(strings, values, [], [])257+ const className = new String(`@keyframes ${toHash(styleString)}`)258+ Object.assign(className as CssClassName, {259+ isEscaped: true,260+ [IS_CSS_CLASS_NAME]: true,261+ [STYLE_STRING]: styleString,262+ [SELECTORS]: [],263+ [EXTERNAL_CLASS_NAMES]: [],264+ })265+ return className266+ }267+268+ const Style = () => raw(`<style id="${id}"></style>`)269+270+ return {271+ css,272+ cx,273+ keyframes,274+ Style,275+ }276+}277+278+const defaultContext = createCssContext({ id: DEFAULT_STYLE_ID })279+280+/**281+ * @experimental282+ * `css` is an experimental feature.283+ * The API might be changed.284+ */285+export const css = defaultContext.css286+287+/**288+ * @experimental289+ * `cx` is an experimental feature.290+ * The API might be changed.291+ */292+export const cx = defaultContext.cx293+294+/**295+ * @experimental296+ * `keyframes` is an experimental feature.297+ * The API might be changed.298+ */299+export const keyframes = defaultContext.keyframes300+301+/**302+ * @experimental303+ * `Style` is an experimental feature.304+ * The API might be changed.305+ */306+export const Style = defaultContext.Stylemodified:deno_dist/helper/dev/index.ts+8 added-1 removed
2 unmodified lines3 import type { Env, RouterRoute } from '../../types.ts'4 5 interface ShowRoutesOptions {6 verbose?: boolean7+ colorize?: boolean8 }9 10 interface RouteData {11 path: string48 unmodified lines60 return61 }62 const { method, path, routes } = data63 64+ const methodStr = opts?.colorize ?? true ? `\x1b[32m${method}\x1b[0m` : method63- console.log(`\x1b[32m${method}\x1b[0m ${' '.repeat(maxMethodLength - method.length)} ${path}`)65+ console.log(`${methodStr} ${' '.repeat(maxMethodLength - method.length)} ${path}`)66 67 if (!opts?.verbose) {68 return69 }2 unmodified lines72 console.log(`${' '.repeat(maxMethodLength + 3)} ${name}`)73 })74 })75 }76+77+export const getRouterName = <E extends Env>(app: Hono<E>) => {78+ app.router.match('GET', '/')79+ return app.router.name80+}modified:deno_dist/helper/streaming/index.ts+4 added-59 removed
1-import type { Context } from '../../context.ts'2-import { StreamingApi } from '../../utils/stream.ts'3-4-interface SSEMessage {5- data: string6- event?: string7- id?: string8-}9-10-class SSEStreamingApi extends StreamingApi {11- constructor(writable: WritableStream) {12- super(writable)13- }14-15- async writeSSE(message: SSEMessage) {16- const data = message.data17- .split('\n')18- .map((line) => {19- return `data: ${line}`20- })21- .join('\n')22-23- const sseData =24- [message.event && `event: ${message.event}`, data, message.id && `id: ${message.id}`]25- .filter(Boolean)26- .join('\n') + '\n\n'27-28- await this.write(sseData)29- }30-}31-32-const setSSEHeaders = (context: Context) => {33- context.header('Transfer-Encoding', 'chunked')34- context.header('Content-Type', 'text/event-stream')35- context.header('Cache-Control', 'no-cache')36- context.header('Connection', 'keep-alive')37-}38-39-export const streamSSE = (c: Context, cb: (stream: SSEStreamingApi) => Promise<void>) => {40- return c.stream(async (originalStream: StreamingApi) => {41- const { readable, writable } = new TransformStream()42- const stream = new SSEStreamingApi(writable)43-44- originalStream.pipe(readable).catch((err) => {45- console.error('Error in stream piping: ', err)46- stream.close()47- })48-49- setSSEHeaders(c)50-51- try {52- await cb(stream)53- } catch (err) {54- console.error('Error during streaming: ', err)55- } finally {56- await stream.close()57- }58- })59-}1+export { stream } from './stream.ts'2+export type { SSEMessage } from './sse.ts'3+export { streamSSE, SSEStreamingApi } from './sse.ts'4+export { streamText } from './text.ts'added:deno_dist/helper/streaming/sse.ts+60 added
1+import type { Context } from '../../context.ts'2+import { StreamingApi } from '../../utils/stream.ts'3+import { stream } from './index.ts'4+5+export interface SSEMessage {6+ data: string7+ event?: string8+ id?: string9+}10+11+export class SSEStreamingApi extends StreamingApi {12+ constructor(writable: WritableStream, readable: ReadableStream) {13+ super(writable, readable)14+ }15+16+ async writeSSE(message: SSEMessage) {17+ const data = message.data18+ .split('\n')19+ .map((line) => {20+ return `data: ${line}`21+ })22+ .join('\n')23+24+ const sseData =25+ [message.event && `event: ${message.event}`, data, message.id && `id: ${message.id}`]26+ .filter(Boolean)27+ .join('\n') + '\n\n'28+29+ await this.write(sseData)30+ }31+}32+33+const setSSEHeaders = (context: Context) => {34+ context.header('Transfer-Encoding', 'chunked')35+ context.header('Content-Type', 'text/event-stream')36+ context.header('Cache-Control', 'no-cache')37+ context.header('Connection', 'keep-alive')38+}39+40+export const streamSSE = (c: Context, cb: (stream: SSEStreamingApi) => Promise<void>) => {41+ return stream(c, async (originalStream: StreamingApi) => {42+ const { readable, writable } = new TransformStream()43+ const stream = new SSEStreamingApi(writable, readable)44+45+ originalStream.pipe(stream.responseReadable).catch((err) => {46+ console.error('Error in stream piping: ', err)47+ stream.close()48+ })49+50+ setSSEHeaders(c)51+52+ try {53+ await cb(stream)54+ } catch (err) {55+ console.error('Error during streaming: ', err)56+ } finally {57+ await stream.close()58+ }59+ })60+}added:deno_dist/helper/streaming/stream.ts+9 added
123456789import type { Context } from '../../context.ts'import { StreamingApi } from '../../utils/stream.ts'
export const stream = (c: Context, cb: (stream: StreamingApi) => Promise<void>): Response => { const { readable, writable } = new TransformStream() const stream = new StreamingApi(writable, readable) cb(stream).finally(() => stream.close()) return c.newResponse(stream.responseReadable)}added:deno_dist/helper/streaming/text.ts+11 added
1234567891011import type { Context } from '../../context.ts'import { TEXT_PLAIN } from '../../context.ts'import type { StreamingApi } from '../../utils/stream.ts'import { stream } from './index.ts'
export const streamText = (c: Context, cb: (stream: StreamingApi) => Promise<void>): Response => { c.header('Content-Type', TEXT_PLAIN) c.header('X-Content-Type-Options', 'nosniff') c.header('Transfer-Encoding', 'chunked') return stream(c, cb)}modified:deno_dist/jsx/components.ts+29 added-9 removed
1 import { raw } from '../helper/html/index.ts'2-import type { HtmlEscapedString } from '../utils/html.ts'2+import {3+ HtmlEscapedCallbackPhase,4+ resolveCallback,5+ type HtmlEscapedString,6+ type HtmlEscapedCallback,7+} from '../utils/html.ts'8 import type { FC, Child } from './index.ts'9 10 let errorBoundaryCounter = 011 30 unmodified lines42 if (!Array.isArray(children)) {43 children = [children]44 }45 46+ let fallbackStr: string | undefined47 const fallbackRes = (error: Error): HtmlEscapedString => {48 onError?.(error)43- return (fallback || fallbackRender?.(error) || '').toString() as HtmlEscapedString49+ return (fallbackStr || fallbackRender?.(error) || '').toString() as HtmlEscapedString50 }51 let resArray: HtmlEscapedString[] | Promise<HtmlEscapedString[]>[] = []52 try {53 resArray = children.map((c) => c.toString()) as HtmlEscapedString[]54 } catch (e) {55+ fallbackStr = await fallback?.toString()56 if (e instanceof Promise) {57 resArray = [58 e.then(() => childrenToString(children as Child[])).catch((e) => fallbackRes(e)),59 ] as Promise<HtmlEscapedString[]>[]2 unmodified lines62 }63 }64 65 if (resArray.some((res) => (res as {}) instanceof Promise)) {66+ fallbackStr ||= await fallback?.toString()67 const index = errorBoundaryCounter++68 const replaceRe = RegExp(`(<template id="E:${index}"></template>.*?)(.*?)(<!--E:${index}-->)`)69 const caught = false70 const catchCallback = ({ error, buffer }: { error: Error; buffer?: [string] }) => {17 unmodified lines88 })(document)89 </script>`90 }91 return raw(`<template id="E:${index}"></template><!--E:${index}-->`, [84- ({ buffer }) => {92+ ({ phase, buffer, context }) => {93+ if (phase === HtmlEscapedCallbackPhase.BeforeStream) {94+ return95+ }96 return Promise.all(resArray)86- .then((htmlArray) => {97+ .then(async (htmlArray) => {98 htmlArray = htmlArray.flat()99 const content = htmlArray.join('')89- const html = buffer100+ let html = buffer101 ? ''102 : `<template>${content}</template><script>103 ((d,c) => {104 c=d.currentScript.previousSibling20 unmodified lines125 const callbacks = htmlArray126 .map((html) => (html as HtmlEscapedString).callbacks || [])127 .flat()128 129+ if (phase === HtmlEscapedCallbackPhase.Stream) {130+ html = await resolveCallback(131+ html,132+ HtmlEscapedCallbackPhase.BeforeStream,133+ true,134+ context135+ )136+ }137+138 let resolvedCount = 0119- const promises = callbacks.map(139+ const promises = callbacks.map<HtmlEscapedCallback>(140 (c) =>121- ({ buffer }: { buffer: [string] }) =>122- c({ buffer })123- .then((content) => {141+ (...args) =>142+ c(...args)143+ ?.then((content) => {144 resolvedCount++145 146 if (buffer) {147 if (resolvedCount === callbacks.length) {36 unmodified linesmodified:deno_dist/jsx/index.ts+3 added
143 unmodified lines144 throw 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'145 }146 147 children = [raw(v.__html)]148+ } else if (v instanceof Promise) {149+ buffer[0] += ` ${key}="`150+ buffer.unshift('"', v)151 } else {152 buffer[0] += ` ${key}="`153 escapeToBuffer(v.toString(), buffer)154 buffer[0] += '"'139 unmodified linesmodified:deno_dist/jsx/intrinsic-elements.ts+1 added-1 removed
21 unmodified lines22 23 interface HTMLAttributes extends JSXAttributes, AnyAttributes {24 accesskey?: string | undefined25 autofocus?: boolean | undefined26- class?: string | undefined26+ class?: string | Promise<string> | undefined27 contenteditable?: boolean | 'inherit' | undefined28 contextmenu?: string | undefined29 dir?: string | undefined30 draggable?: boolean | undefined576 unmodified linesmodified:deno_dist/jsx/streaming.ts+40 added-16 removed
1 import { raw } from '../helper/html/index.ts'2+import { HtmlEscapedCallbackPhase, resolveCallback } from '../utils/html.ts'3 import type { HtmlEscapedString } from '../utils/html.ts'4 import { childrenToString } from './components.ts'5 import type { FC, Child } from './index.ts'6 27 unmodified lines34 }35 36 if (resArray.some((res) => (res as {}) instanceof Promise)) {37 const index = suspenseCounter++37- return raw(`<template id="H:${index}"></template>${fallback.toString()}<!--/$-->`, [38- ({ buffer }) => {39- return Promise.all(resArray).then((htmlArray) => {38+ const fallbackStr = await fallback.toString()39+ return raw(`<template id="H:${index}"></template>${fallbackStr}<!--/$-->`, [40+ ...(fallbackStr.callbacks || []),41+ ({ phase, buffer, context }) => {42+ if (phase === HtmlEscapedCallbackPhase.BeforeStream) {43+ return44+ }45+ return Promise.all(resArray).then(async (htmlArray) => {46 htmlArray = htmlArray.flat()47 const content = htmlArray.join('')48 if (buffer) {49 buffer[0] = buffer[0].replace(50 new RegExp(`<template id="H:${index}"></template>.*?<!--/\\$-->`),51 content52 )53 }48- const html = buffer54+ let html = buffer55 ? ''56 : `<template>${content}</template><script>57 ((d,c,n) => {58 c=d.currentScript.previousSibling2 unmodified lines61 do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')62 d.replaceWith(c.content)63 })(document)64 </script>`59- if (htmlArray.every((html) => !(html as HtmlEscapedString).callbacks?.length)) {65+66+ const callbacks = htmlArray67+ .map((html) => (html as HtmlEscapedString).callbacks || [])68+ .flat()69+ if (!callbacks.length) {70 return html71 }72 63- return raw(64- html,65- htmlArray.map((html) => (html as HtmlEscapedString).callbacks || []).flat()66- )73+ if (phase === HtmlEscapedCallbackPhase.Stream) {74+ html = await resolveCallback(html, HtmlEscapedCallbackPhase.BeforeStream, true, context)75+ }76+77+ return raw(html, callbacks)78 })79 },80 ])81 } else {11 unmodified lines93 str: HtmlEscapedString | Promise<HtmlEscapedString>94 ): ReadableStream<Uint8Array> => {95 const reader = new ReadableStream<Uint8Array>({96 async start(controller) {86- const resolved = str instanceof Promise ? await str : await str.toString()97+ const tmp = str instanceof Promise ? await str : await str.toString()98+ const context = typeof tmp === 'object' ? tmp : {}99+ const resolved = await resolveCallback(100+ tmp,101+ HtmlEscapedCallbackPhase.BeforeStream,102+ true,103+ context104+ )105 controller.enqueue(textEncoder.encode(resolved))106 107 let resolvedCount = 0108 const callbacks: Promise<void>[] = []3 unmodified lines112 .catch((err) => {113 console.trace(err)114 return ''115 })98- .then((res) => {99- if ((res as HtmlEscapedString).callbacks) {100- const callbacks = (res as HtmlEscapedString).callbacks || []101- callbacks.map((c) => c({})).forEach(then)102- }116+ .then(async (res) => {117+ res = await resolveCallback(res, HtmlEscapedCallbackPhase.BeforeStream, true, context)118+ ;(res as HtmlEscapedString).callbacks119+ ?.map((c) => c({ phase: HtmlEscapedCallbackPhase.Stream, context }))120+ // eslint-disable-next-line @typescript-eslint/no-explicit-any121+ .filter<Promise<string>>(Boolean as any)122+ .forEach(then)123 resolvedCount++124 controller.enqueue(textEncoder.encode(res))125 })126 )127 }108- ;(resolved as HtmlEscapedString).callbacks?.map((c) => c({})).forEach(then)128+ ;(resolved as HtmlEscapedString).callbacks129+ ?.map((c) => c({ phase: HtmlEscapedCallbackPhase.Stream, context }))130+ // eslint-disable-next-line @typescript-eslint/no-explicit-any131+ .filter<Promise<string>>(Boolean as any)132+ .forEach(then)133 while (resolvedCount !== callbacks.length) {134 await Promise.all(callbacks)135 }136 5 unmodified linesadded:deno_dist/middleware/csrf/index.ts+48 added
1+import type { Context } from '../../context.ts'2+import { HTTPException } from '../../http-exception.ts'3+import type { MiddlewareHandler } from '../../types.ts'4+5+type IsAllowedOriginHandler = (origin: string, context: Context) => boolean6+interface CSRFOptions {7+ origin?: string | string[] | IsAllowedOriginHandler8+}9+10+const isSafeMethodRe = /^(GET|HEAD)$/11+const isRequestedByFormElementRe =12+ /^\b(application\/x-www-form-urlencoded|multipart\/form-data|text\/plain)\b/13+14+export const csrf = (options?: CSRFOptions): MiddlewareHandler => {15+ const handler: IsAllowedOriginHandler = ((optsOrigin) => {16+ if (!optsOrigin) {17+ return (origin, c) => origin === new URL(c.req.url).origin18+ } else if (typeof optsOrigin === 'string') {19+ return (origin) => origin === optsOrigin20+ } else if (typeof optsOrigin === 'function') {21+ return optsOrigin22+ } else {23+ return (origin) => optsOrigin.includes(origin)24+ }25+ })(options?.origin)26+ const isAllowedOrigin = (origin: string | undefined, c: Context) => {27+ if (origin === undefined) {28+ // denied always when origin header is not present29+ return false30+ }31+ return handler(origin, c)32+ }33+34+ return async function cors(c, next) {35+ if (36+ !isSafeMethodRe.test(c.req.method) &&37+ isRequestedByFormElementRe.test(c.req.header('content-type') || '') &&38+ !isAllowedOrigin(c.req.header('origin'), c)39+ ) {40+ const res = new Response('Forbidden', {41+ status: 403,42+ })43+ throw new HTTPException(403, { res })44+ }45+46+ await next()47+ }48+}modified:deno_dist/utils/html.ts+31 added-7 removed
1-type HtmlEscapedCallbackOpts = { error?: Error; buffer?: [string] }2-export type HtmlEscapedCallback = (opts: HtmlEscapedCallbackOpts) => Promise<string>1+export const HtmlEscapedCallbackPhase = {2+ Stringify: 1,3+ BeforeStream: 2,4+ Stream: 3,5+} as const6+type HtmlEscapedCallbackOpts = {7+ buffer?: [string]8+ phase: typeof HtmlEscapedCallbackPhase[keyof typeof HtmlEscapedCallbackPhase]9+ context: object // An object unique to each JSX tree. This object is used as the WeakMap key.10+}11+export type HtmlEscapedCallback = (opts: HtmlEscapedCallbackOpts) => Promise<string> | undefined12 export type HtmlEscaped = {13 isEscaped: true14 callbacks?: HtmlEscapedCallback[]15 }93 unmodified lines109 110 buffer[0] += str.substring(lastIndex, index)111 }112 104-export const resolveStream = (113+export const resolveCallback = async (114 str: string | HtmlEscapedString,115+ phase: typeof HtmlEscapedCallbackPhase[keyof typeof HtmlEscapedCallbackPhase],116+ preserveCallbacks: boolean,117+ context: object,118 buffer?: [string]119 ): Promise<string> => {108- if (!(str as HtmlEscapedString).callbacks?.length) {120+ const callbacks = (str as HtmlEscapedString).callbacks as HtmlEscapedCallback[]121+ if (!callbacks?.length) {122 return Promise.resolve(str)123 }111- const callbacks = (str as HtmlEscapedString).callbacks as HtmlEscapedCallback[]124 if (buffer) {125 buffer[0] += str126 } else {127 buffer = [str]128 }117- return Promise.all(callbacks.map((c) => c({ buffer }))).then((res) =>118- Promise.all(res.map((str) => resolveStream(str, buffer))).then(() => (buffer as [string])[0])129+130+ const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then((res) =>131+ Promise.all(132+ res133+ // eslint-disable-next-line @typescript-eslint/no-explicit-any134+ .filter<string>(Boolean as any)135+ .map((str) => resolveCallback(str, phase, false, context, buffer))136+ ).then(() => (buffer as [string])[0])137 )138+139+ if (preserveCallbacks) {140+ return raw(await resStr, callbacks)141+ } else {142+ return resStr143+ }144 }modified:deno_dist/utils/stream.ts+23 added-1 removed
1 export class StreamingApi {2 private writer: WritableStreamDefaultWriter<Uint8Array>3 private encoder: TextEncoder4 private writable: WritableStream5+ private abortSubscribers: (() => void | Promise<void>)[] = []6+ responseReadable: ReadableStream7 6- constructor(writable: WritableStream) {8+ constructor(writable: WritableStream, _readable: ReadableStream) {9 this.writable = writable10 this.writer = writable.getWriter()11 this.encoder = new TextEncoder()12+13+ const reader = _readable.getReader()14+15+ this.responseReadable = new ReadableStream({16+ async pull(controller) {17+ const { done, value } = await reader.read()18+ if (done) {19+ controller.close()20+ } else {21+ controller.enqueue(value)22+ }23+ },24+ cancel: () => {25+ this.abortSubscribers.forEach((subscriber) => subscriber())26+ },27+ })28 }29 30 async write(input: Uint8Array | string) {31 try {28 unmodified lines60 this.writer.releaseLock()61 await body.pipeTo(this.writable, { preventClose: true })62 this.writer = this.writable.getWriter()63 }64+65+ async onAbort(listener: () => void | Promise<void>) {66+ this.abortSubscribers.push(listener)67+ }68 }modified:deno_dist/context.ts+12 added-6 removed
1 unmodified line2 import type { HonoRequest } from './request.ts'3 import type { Env, FetchEventLike, NotFoundHandler, Input, TypedResponse } from './types.ts'4 import type { CookieOptions } from './utils/cookie.ts'5 import { serialize } from './utils/cookie.ts'6-import { resolveStream } from './utils/html.ts'6+import { resolveCallback, HtmlEscapedCallbackPhase } from './utils/html.ts'7 import type { StatusCode } from './utils/http-status.ts'8 import { StreamingApi } from './utils/stream.ts'9 import type { JSONValue, InterfaceToType, JSONParsed } from './utils/types.ts'10 71 unmodified lines82 executionCtx?: FetchEventLike | ExecutionContext | undefined83 notFoundHandler?: NotFoundHandler<E>84 }85 86-const TEXT_PLAIN = 'text/plain; charset=UTF-8'86+export const TEXT_PLAIN = 'text/plain; charset=UTF-8'87 88 export class Context<89 // eslint-disable-next-line @typescript-eslint/no-explicit-any90 E extends Env = any,263 unmodified lines354 html = (html as string).toString() // HtmlEscapedString object to string355 }356 if ((html as string | Promise<string>) instanceof Promise) {357 return (html as unknown as Promise<string>)358- .then((html) => resolveStream(html))358+ .then((html) => resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}))359 .then((html) => {360 return typeof arg === 'number'361 ? this.newResponse(html, arg, headers)362 : this.newResponse(html, arg)11 unmodified lines374 this.#headers.set('Location', location)375 return this.newResponse(null, status)376 }377 378+ /** @deprecated379+ * Use `streamText()` in `hono/streaming` instead of `c.streamText()`. The `c.streamText()` will be removed in v4.380+ */381 streamText = (382 cb: (stream: StreamingApi) => Promise<void>,383 arg?: StatusCode | ResponseInit,384 headers?: HeaderRecord4 unmodified lines389 this.header('transfer-encoding', 'chunked')390 return this.stream(cb, arg, headers)391 }392 393+ /** @deprecated394+ * Use `stream()` in `hono/streaming` instead of `c.stream()`. The `c.stream()` will be removed in v4.395+ */396 stream = (397 cb: (stream: StreamingApi) => Promise<void>,398 arg?: StatusCode | ResponseInit,399 headers?: HeaderRecord400 ): Response => {401 const { readable, writable } = new TransformStream()396- const stream = new StreamingApi(writable)402+ const stream = new StreamingApi(writable, readable)403 cb(stream).finally(() => stream.close())404 405 return typeof arg === 'number'400- ? this.newResponse(readable, arg, headers)401- : this.newResponse(readable, arg)406+ ? this.newResponse(stream.responseReadable, arg, headers)407+ : this.newResponse(stream.responseReadable, arg)408 }409 410 /** @deprecated411 * Use Cookie Middleware instead of `c.cookie()`. The `c.cookie()` will be removed in v4.68 unmodified linesmodified:deno_dist/helper.ts+1 added
1 // This file is for Deno to import helpers from `hono/helper.ts`.2 export * from './helper/adapter/index.ts'3 export * from './helper/cookie/index.ts'4+export * from './helper/css/index.ts'5 export * from './helper/factory/index.ts'6 export * from './helper/html/index.ts'7 export * from './helper/streaming/index.ts'8 export * from './helper/testing/index.ts'1 unmodified linemodified:deno_dist/hono-base.ts+5 added
241 unmodified lines242 this.addRoute(METHOD_NAME_ALL, mergePath(path, '*'), handler)243 return this244 }245 246+ /**247+ * @deprecated248+ * `app.routerName()` will be removed in v4.249+ * Use `getRouterName()` in `hono/dev` instead of `app.routerName()`.250+ */251 get routerName() {252 this.matchRoute('GET', '/')253 return this.router.name254 }137 unmodified linesmodified:deno_dist/middleware.ts+1 added
3 unmodified lines4 export * from './middleware/cache/index.ts'5 export * from './helper/cookie/index.ts' // will be moved to helper.ts in v46 export * from './middleware/compress/index.ts'7 export * from './middleware/cors/index.ts'8+export * from './middleware/csrf/index.ts'9 export * from './middleware/etag/index.ts'10 export * from './helper/html/index.ts' // will be moved to helper.ts in v411 export * from './jsx/index.ts'12 export * from './middleware/jsx-renderer/index.ts'7 unmodified linesmodified:runtime_tests/bun/index.test.tsx+11 added-2 removed
1-import { describe, expect, it } from 'bun:test'1+import { describe, expect, it, mock, beforeEach } from 'bun:test'2 import { serveStatic } from '../../src/adapter/bun'3 import { Context } from '../../src/context'4 import { env, getRuntimeKey } from '../../src/helper/adapter'5 import { Hono } from '../../src/index'69 unmodified lines75 })76 77 describe('Serve Static Middleware', () => {78 const app = new Hono()79+ const onNotFound = mock(() => {})80 app.all('/favicon.ico', serveStatic({ path: './runtime_tests/bun/favicon.ico' }))81 app.all(82 '/favicon-notfound.ico',82- serveStatic({ path: './runtime_tests/bun/favicon-notfound.ico' })83+ serveStatic({ path: './runtime_tests/bun/favicon-notfound.ico', onNotFound })84 )85 app.use('/favicon-notfound.ico', async (c, next) => {86 await next()87 c.header('X-Custom', 'Bun')1 unmodified line89 app.get(90 '/static/*',91 serveStatic({92 root: './runtime_tests/bun/',93+ onNotFound,94 })95 )96 app.get(97 '/dot-static/*',2 unmodified lines100 rewriteRequestPath: (path) => path.replace(/^\/dot-static/, './.static'),101 })102 )103 104+ beforeEach(() => onNotFound.mockClear())105+106 it('Should return static file correctly', async () => {107 const res = await app.request(new Request('http://localhost/favicon.ico'))108 await res.arrayBuffer()109 expect(res.status).toBe(200)3 unmodified lines113 it('Should return 404 response', async () => {114 const res = await app.request(new Request('http://localhost/favicon-notfound.ico'))115 expect(res.status).toBe(404)116 expect(res.headers.get('X-Custom')).toBe('Bun')117+ expect(onNotFound).toHaveBeenCalledWith(118+ './runtime_tests/bun/favicon-notfound.ico',119+ expect.anything()120+ )121 })122 123 it('Should return 200 response - /static/plain.txt', async () => {124 const res = await app.request(new Request('http://localhost/static/plain.txt'))125 expect(res.status).toBe(200)126 expect(await res.text()).toBe('Bun!')127+ expect(onNotFound).not.toHaveBeenCalled()128 })129 130 it('Should return 200 response - /dot-static/plain.txt', async () => {131 const res = await app.request(new Request('http://localhost/dot-static/plain.txt'))78 unmodified linesmodified:runtime_tests/deno/deps.ts+1 added
1 export { assert, assertEquals, assertMatch } from 'https://deno.land/std@0.147.0/testing/asserts.ts'2+export { assertSpyCall, assertSpyCalls, spy } from 'https://deno.land/std@0.147.0/testing/mock.ts'modified:runtime_tests/deno/middleware.test.tsx+6 added-2 removed
1 /** @jsx jsx */2 /** @jsxFrag Fragment */3 import { basicAuth, jsx, Fragment, serveStatic, jwt } from '../../deno_dist/middleware.ts'4 import { Hono } from '../../deno_dist/mod.ts'5-import { assertEquals, assertMatch } from './deps.ts'5+import { assertEquals, assertMatch, assertSpyCall, assertSpyCalls, spy } from './deps.ts'6 7 // Test just only minimal patterns.8 // Because others are already tested well in Cloudflare Workers environment.9 55 unmodified lines65 })66 67 Deno.test('Serve Static middleware', async () => {68 const app = new Hono()69+ const onNotFound = spy(() => {})70 app.all('/favicon.ico', serveStatic({ path: './runtime_tests/deno/favicon.ico' }))71 app.all(72 '/favicon-notfound.ico',72- serveStatic({ path: './runtime_tests/deno/favicon-notfound.ico' })73+ serveStatic({ path: './runtime_tests/deno/favicon-notfound.ico', onNotFound })74 )75 app.use('/favicon-notfound.ico', async (c, next) => {76 await next()77 c.header('X-Custom', 'Deno')2 unmodified lines80 app.get(81 '/static/*',82 serveStatic({83 root: './runtime_tests/deno',84+ onNotFound,85 })86 )87 88 app.get(12 unmodified lines101 res = await app.request('http://localhost/favicon-notfound.ico')102 assertEquals(res.status, 404)103 assertMatch(res.headers.get('Content-Type') || '', /^text\/plain/)104 assertEquals(res.headers.get('X-Custom'), 'Deno')105+ assertSpyCall(onNotFound, 0)106 107 res = await app.request('http://localhost/static/plain.txt')108 assertEquals(res.status, 200)109 assertEquals(await res.text(), 'Deno!')110 111 res = await app.request('http://localhost/dot-static/plain.txt')112 assertEquals(res.status, 200)113 assertEquals(await res.text(), 'Deno!!')114+ assertSpyCalls(onNotFound, 1)115 })116 117 Deno.test('JWT Authentication middleware', async () => {118 const app = new Hono<{ Variables: { 'x-foo': string } }>()25 unmodified linesmodified:src/adapter/bun/serve-static.ts+8 added-5 removed
1 // @denoify-ignore2 /* eslint-disable @typescript-eslint/ban-ts-comment */3 import { existsSync } from 'fs'4 import type { Context } from '../../context'5-import type { Next } from '../../types'5+import type { Env, MiddlewareHandler } from '../../types'6 import { getFilePath } from '../../utils/filepath'7 import { getMimeType } from '../../utils/mime'8 9 // @ts-ignore10 const { file } = Bun11 12-export type ServeStaticOptions = {12+export type ServeStaticOptions<E extends Env = Env> = {13 root?: string14 path?: string15 rewriteRequestPath?: (path: string) => string16+ onNotFound?: (path: string, c: Context<E>) => void | Promise<void>17 }18 19 const DEFAULT_DOCUMENT = 'index.html'20 20-export const serveStatic = (options: ServeStaticOptions = { root: '' }) => {21- return async (c: Context, next: Next) => {21+export const serveStatic = <E extends Env = Env>(22+ options: ServeStaticOptions<E> = { root: '' }23+): MiddlewareHandler => {24+ return async (c, next) => {25 // Do nothing if Response is already set26 if (c.finalized) {27 await next()28 return22 unmodified lines51 return c.body(content)52 }53 }54 52- console.warn(`Static file: ${path} is not found`)55+ await options.onNotFound?.(path, c)56 await next()57 return58 }59 }modified:src/adapter/cloudflare-workers/index.ts+1 added-1 removed
1 // @denoify-ignore2-export { serveStatic } from './server-static-module'2+export { serveStatic } from './serve-static-module'added:src/adapter/cloudflare-workers/serve-static-module.ts+17 added
1+// @denoify-ignore2+// eslint-disable-next-line @typescript-eslint/ban-ts-comment3+// @ts-ignore4+// For ES module mode5+import manifest from '__STATIC_CONTENT_MANIFEST'6+import type { Env } from '../../types'7+import type { ServeStaticOptions } from './serve-static'8+import { serveStatic } from './serve-static'9+10+const module = <E extends Env = Env>(11+ options: Omit<ServeStaticOptions<E>, 'namespace'> = { root: '' }12+) => {13+ options.manifest ??= manifest14+ return serveStatic<E>(options)15+}16+17+export { module as serveStatic }modified:src/adapter/cloudflare-workers/serve-static.test.ts+27 added-1 removed
29 unmodified lines30 })31 32 describe('ServeStatic Middleware', () => {33 const app = new Hono()34+ const onNotFound = vi.fn(() => {})34- app.use('/static/*', serveStatic({ root: './assets' }))35+ app.use('/static/*', serveStatic({ root: './assets', onNotFound }))36 app.use('/static-no-root/*', serveStatic())37 app.use(38 '/dot-static/*',39 serveStatic({1 unmodified line41 rewriteRequestPath: (path) => path.replace(/^\/dot-static/, '/.static'),42 })43 )44 45+ beforeEach(() => onNotFound.mockClear())46+47 it('Should return plain.txt', async () => {48 const res = await app.request('http://localhost/static/plain.txt')49 expect(res.status).toBe(200)50 expect(await res.text()).toBe('This is plain.txt')51 expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')52+ expect(onNotFound).not.toHaveBeenCalled()53 })54 55 it('Should return hono.html', async () => {56 const res = await app.request('http://localhost/static/hono.html')57 expect(res.status).toBe(200)58 expect(await res.text()).toBe('<h1>Hono!</h1>')59 expect(res.headers.get('Content-Type')).toBe('text/html; charset=utf-8')60+ expect(onNotFound).not.toHaveBeenCalled()61 })62 63 it('Should return 404 response', async () => {64 const res = await app.request('http://localhost/static/not-found.html')65 expect(res.status).toBe(404)66+ expect(onNotFound).toHaveBeenCalledWith('assets/static/not-found.html', expect.anything())67 })68 69 it('Should return plan.txt', async () => {70 const res = await app.request('http://localhost/static-no-root/plain.txt')83 unmodified lines154 expect(res.status).toBe(200)155 expect(await res.text()).toBe('bar')156 })157 })158+159+describe('Types of middleware', () => {160+ it('Should pass env type from generics of serveStatic', async () => {161+ type Env = {162+ Bindings: {163+ HOGE: string164+ }165+ }166+ const app = new Hono<Env>()167+ app.use(168+ '/static/*',169+ serveStatic<Env>({170+ root: './assets',171+ onNotFound: (_, c) => {172+ expectTypeOf(c.env).toEqualTypeOf<Env['Bindings']>()173+ },174+ })175+ )176+ })177+})modified:src/adapter/cloudflare-workers/serve-static.ts+11 added-6 removed
1 // @denoify-ignore2 import type { KVNamespace } from '@cloudflare/workers-types'3+import type { Context } from '../../context'3-import type { MiddlewareHandler } from '../../types'4+import type { Env, MiddlewareHandler } from '../../types'5 import { getFilePath } from '../../utils/filepath'6 import { getMimeType } from '../../utils/mime'7 import { getContentFromKVAsset } from './utils'8 8-export type ServeStaticOptions = {9+export type ServeStaticOptions<E extends Env = Env> = {10 root?: string11 path?: string12 manifest?: object | string13 namespace?: KVNamespace14 rewriteRequestPath?: (path: string) => string15+ onNotFound?: (path: string, c: Context<E>) => void | Promise<void>16 }17 18 const DEFAULT_DOCUMENT = 'index.html'19 20 // This middleware is available only on Cloudflare Workers.19-export const serveStatic = (options: ServeStaticOptions = { root: '' }): MiddlewareHandler => {21+export const serveStatic = <E extends Env = Env>(22+ options: ServeStaticOptions<E> = { root: '' }23+): MiddlewareHandler => {24 return async (c, next) => {25 // Do nothing if Response is already set26 if (c.finalized) {27 await next()15 unmodified lines43 // eslint-disable-next-line @typescript-eslint/ban-ts-comment44 // @ts-ignore45 namespace: options.namespace ? options.namespace : c.env ? c.env.__STATIC_CONTENT : undefined,46 })47+48 if (content) {49 const mimeType = getMimeType(path)50 if (mimeType) {51 c.header('Content-Type', mimeType)52 }53 // Return Response object54 return c.body(content)50- } else {51- console.warn(`Static file: ${path} is not found`)52- await next()55 }56+57+ await options.onNotFound?.(path, c)58+ await next()59 return60 }61 }deleted:src/adapter/cloudflare-workers/server-static-module.ts-18 removed
1-// @denoify-ignore2-// eslint-disable-next-line @typescript-eslint/ban-ts-comment3-// @ts-ignore4-// For ES module mode5-import manifest from '__STATIC_CONTENT_MANIFEST'6-import type { ServeStaticOptions } from './serve-static'7-import { serveStatic } from './serve-static'8-9-const module = (options: ServeStaticOptions = { root: '' }) => {10- return serveStatic({11- root: options.root,12- path: options.path,13- manifest: options.manifest ? options.manifest : manifest,14- rewriteRequestPath: options.rewriteRequestPath,15- })16-}17-18-export { module as serveStatic }modified:src/adapter/deno/serve-static.ts+10 added-7 removed
1 import type { Context } from '../../context'2-import type { Next } from '../../types'2+import type { Env, MiddlewareHandler } from '../../types'3 import { getFilePath } from '../../utils/filepath'4 import { getMimeType } from '../../utils/mime'5 6 // eslint-disable-next-line @typescript-eslint/ban-ts-comment7 // @ts-ignore8 const { open } = Deno9 10-export type ServeStaticOptions = {10+export type ServeStaticOptions<E extends Env = Env> = {11 root?: string12 path?: string13 rewriteRequestPath?: (path: string) => string14+ onNotFound?: (path: string, c: Context<E>) => void | Promise<void>15 }16 17 const DEFAULT_DOCUMENT = 'index.html'18 18-export const serveStatic = (options: ServeStaticOptions = { root: '' }) => {19- return async (c: Context, next: Next) => {19+export const serveStatic = <E extends Env = Env>(20+ options: ServeStaticOptions<E> = { root: '' }21+): MiddlewareHandler => {22+ return async (c, next) => {23 // Do nothing if Response is already set24 if (c.finalized) {25 await next()26 return25 unmodified lines52 c.header('Content-Type', mimeType)53 }54 // Return Response object with stream55 return c.body(file.readable)53- } else {54- console.warn(`Static file: ${path} is not found`)55- await next()56 }57+58+ await options.onNotFound?.(path, c)59+ await next()60 return61 }62 }modified:src/client/client.test.ts+20 added
603 unmodified lines604 const json = await res.json()605 expectTypeOf(json).toEqualTypeOf<{ data: string } | { message: string }>()606 })607 })608+609+describe('$url() with a param option', () => {610+ const app = new Hono().get('/posts/:id/comments', (c) => c.json({ ok: true }))611+ type AppType = typeof app612+ const client = hc<AppType>('http://localhost')613+614+ it('Should return the correct path - /posts/123/comments', async () => {615+ const url = client.posts[':id'].comments.$url({616+ param: {617+ id: '123',618+ },619+ })620+ expect(url.pathname).toBe('/posts/123/comments')621+ })622+623+ it('Should return the correct path - /posts/:id/comments', async () => {624+ const url = client.posts[':id'].comments.$url()625+ expect(url.pathname).toBe('/posts/:id/comments')626+ })627+})modified:src/client/client.ts+3 added
140 unmodified lines141 142 const path = parts.join('/')143 const url = mergePath(baseUrl, path)144 if (method === 'url') {145+ if (opts.args[0] && opts.args[0].param) {146+ return new URL(replaceUrlParam(url, opts.args[0].param))147+ }148 return new URL(url)149 }150 151 const req = new ClientRequestImpl(url, method)7 unmodified linesmodified:src/client/types.ts+7 added-1 removed
21 unmodified lines22 : (args?: R, options?: ClientRequestOptions) => Promise<ClientResponse<O>>23 : never24 : never25 } & {26- $url: () => URL26+ $url: (27+ arg?: S[keyof S] extends { input: infer R }28+ ? R extends { param: infer P }29+ ? { param: P }30+ : {}31+ : {}32+ ) => URL33 }34 35 // eslint-disable-next-line @typescript-eslint/no-explicit-any36 type BlankRecordToNever<T> = T extends any ? (keyof T extends never ? never : T) : never84 unmodified linesadded:src/helper/css/index.test.tsx+473 added
1+import { Hono } from '../../'2+import { html } from '../../helper/html'3+import { jsx, Fragment, JSXNode } from '../../jsx'4+import { Suspense, renderToReadableStream } from '../../jsx/streaming'5+import type { HtmlEscapedString } from '../../utils/html'6+import { HtmlEscapedCallbackPhase, resolveCallback } from '../../utils/html'7+import { css, cx, keyframes, rawCssString, Style, createCssContext } from './index'8+9+async function toString(10+ template: JSXNode | Promise<HtmlEscapedString> | Promise<string> | HtmlEscapedString11+) {12+ if (template instanceof Promise) template = (await template) as HtmlEscapedString13+ if (template instanceof JSXNode) template = template.toString() as Promise<HtmlEscapedString>14+ return resolveCallback(await template, HtmlEscapedCallbackPhase.Stringify, false, template)15+}16+17+async function toCSS(18+ template: JSXNode | Promise<HtmlEscapedString> | Promise<string> | HtmlEscapedString19+) {20+ return (await toString(template))21+ .replace(/.*?=(".*")<\/script.*/, '$1')22+ .replace(/\.css-\d+/g, '.css-123')23+}24+25+describe('CSS Helper', () => {26+ describe('render css', () => {27+ it('Should render CSS styles with JSX', async () => {28+ const headerClass = css`29+ background-color: blue;30+ `31+ const template = (32+ <>33+ <Style />34+ <h1 class={headerClass}>Hello!</h1>35+ </>36+ )37+ expect(await toString(template)).toBe(38+ '<style id="hono-css">.css-2458908649{background-color:blue}</style><h1 class="css-2458908649">Hello!</h1>'39+ )40+ })41+42+ it('Should render CSS styles with `html` tag function', async () => {43+ const headerClass = css`44+ background-color: blue;45+ `46+ const template = html`${Style()}47+ <h1 class="${headerClass}">Hello!</h1>`48+ expect(await toString(template)).toBe(49+ `<style id="hono-css">.css-2458908649{background-color:blue}</style>50+ <h1 class="css-2458908649">Hello!</h1>`51+ )52+ })53+54+ it('Should render CSS with keyframes', async () => {55+ const animation = keyframes`56+ from {57+ opacity: 0;58+ }59+ to {60+ opacity: 1;61+ }62+ `63+ const headerClass = css`64+ background-color: blue;65+ animation: ${animation} 1s ease-in-out;66+ `67+ const template = (68+ <>69+ <Style />70+ <h1 class={headerClass}>Hello!</h1>71+ </>72+ )73+ expect(await toString(template)).toBe(74+ '<style id="hono-css">.css-1580801783{background-color:blue;animation:css-9294673 1s ease-in-out}@keyframes css-9294673{from{opacity:0}to{opacity:1}}</style><h1 class="css-1580801783">Hello!</h1>'75+ )76+ })77+78+ it('Should not output the same class name multiple times.', async () => {79+ const headerClass = css`80+ background-color: blue;81+ `82+ const headerClass2 = css`83+ background-color: blue;84+ `85+ const template = (86+ <>87+ <Style />88+ <h1 class={headerClass}>Hello!</h1>89+ <h1 class={headerClass2}>Hello2!</h1>90+ </>91+ )92+ expect(await toString(template)).toBe(93+ '<style id="hono-css">.css-2458908649{background-color:blue}</style><h1 class="css-2458908649">Hello!</h1><h1 class="css-2458908649">Hello2!</h1>'94+ )95+ })96+97+ it('Should render CSS with variable', async () => {98+ const headerClass = css`99+ background-color: blue;100+ content: '${'I\'m a variable!'}';101+ `102+ const template = (103+ <>104+ <Style />105+ <h1 class={headerClass}>Hello!</h1>106+ </>107+ )108+ expect(await toString(template)).toBe(109+ '<style id="hono-css">.css-4027435072{background-color:blue;content:\'I\\\'m a variable!\'}</style><h1 class="css-4027435072">Hello!</h1>'110+ )111+ })112+113+ it('Should escape </style>', async () => {114+ const headerClass = css`115+ background-color: blue;116+ content: '${'</style>'}';117+ `118+ const template = (119+ <>120+ <Style />121+ <h1 class={headerClass}>Hello!</h1>122+ </>123+ )124+ expect(await toString(template)).toBe(125+ '<style id="hono-css">.css-372954897{background-color:blue;content:\'<\\/style>\'}</style><h1 class="css-372954897">Hello!</h1>'126+ )127+ })128+129+ it('Should not escape URL', async () => {130+ const headerClass = css`131+ background-color: blue;132+ background: url('${'http://www.example.com/path/to/file.jpg'}');133+ `134+ const template = (135+ <>136+ <Style />137+ <h1 class={headerClass}>Hello!</h1>138+ </>139+ )140+ expect(await toString(template)).toBe(141+ '<style id="hono-css">.css-1321888780{background-color:blue;background:url(\'http://www.example.com/path/to/file.jpg\')}</style><h1 class="css-1321888780">Hello!</h1>'142+ )143+ })144+145+ it('Should render CSS with escaped variable', async () => {146+ const headerClass = css`147+ background-color: blue;148+ content: '${rawCssString('say "Hello!"')}';149+ `150+ const template = (151+ <>152+ <Style />153+ <h1 class={headerClass}>Hello!</h1>154+ </>155+ )156+ expect(await toString(template)).toBe(157+ '<style id="hono-css">.css-2238574885{background-color:blue;content:\'say "Hello!"\'}</style><h1 class="css-2238574885">Hello!</h1>'158+ )159+ })160+161+ it('Should render CSS with async variable', async () => {162+ const headerClass = css`163+ background-color: blue;164+ content: '${(async () => {165+ await new Promise((resolve) => setTimeout(resolve, 100))166+ return 'I\'m an async variable!'167+ })()}';168+ `169+ const template = (170+ <>171+ <Style />172+ <h1 class={headerClass}>Hello!</h1>173+ </>174+ )175+ expect(await toString(template)).toBe(176+ '<style id="hono-css">.css-1399451752{background-color:blue;content:\'I\\\'m an async variable!\'}</style><h1 class="css-1399451752">Hello!</h1>'177+ )178+ })179+180+ it('Should render CSS with number', async () => {181+ const headerClass = css`182+ background-color: blue;183+ font-size: ${1}rem;184+ `185+ const template = (186+ <>187+ <Style />188+ <h1 class={headerClass}>Hello!</h1>189+ </>190+ )191+ expect(await toString(template)).toBe(192+ '<style id="hono-css">.css-1847536026{background-color:blue;font-size:1rem}</style><h1 class="css-1847536026">Hello!</h1>'193+ )194+ })195+196+ it('Should render CSS with array', async () => {197+ const animation = keyframes`198+ from {199+ opacity: 0;200+ }201+ to {202+ opacity: 1;203+ }204+ `205+ const headerClass = css`206+ background-color: blue;207+ animation: ${animation} 1s ease-in-out;208+ `209+ const extendedHeaderClass = css`210+ ${headerClass}211+ color: red;212+ `213+ const template = (214+ <>215+ <Style />216+ <h1 class={extendedHeaderClass}>Hello!</h1>217+ </>218+ )219+ expect(await toString(template)).toBe(220+ '<style id="hono-css">.css-2558359670{background-color:blue;animation:css-9294673 1s ease-in-out;color:red}@keyframes css-9294673{from{opacity:0}to{opacity:1}}</style><h1 class="css-2558359670">Hello!</h1>'221+ )222+ })223+224+ describe('Booleans, Null, and Undefined Are Ignored', () => {225+ it.each([true, false, undefined, null])('%s', async (value) => {226+ const headerClass = css`227+ ${value}228+ background-color: blue;229+ `230+ const template = (231+ <>232+ <Style />233+ <h1 class={headerClass}>Hello!</h1>234+ </>235+ )236+ expect(await toString(template)).toBe(237+ '<style id="hono-css">.css-2458908649{background-color:blue}</style><h1 class="css-2458908649">Hello!</h1>'238+ )239+ })240+241+ it('falsy value', async () => {242+ const value = 0243+ const headerClass = css`244+ padding: ${value};245+ `246+ const template = (247+ <>248+ <Style />249+ <h1 class={headerClass}>Hello!</h1>250+ </>251+ )252+ expect(await toString(template)).toBe(253+ '<style id="hono-css">.css-478287868{padding:0}</style><h1 class="css-478287868">Hello!</h1>'254+ )255+ })256+ })257+ })258+259+ it('Should render sub CSS with keyframe', async () => {260+ const headerClass = css`261+ background-color: blue;262+ ${[1, 2].map(263+ (i) =>264+ css`265+ :nth-child(${i}) {266+ color: red;267+ }268+ `269+ )}270+ `271+ const template = (272+ <>273+ <Style />274+ <h1 class={headerClass}>Hello!</h1>275+ </>276+ )277+ expect(await toString(template)).toBe(278+ '<style id="hono-css">.css-1539881271{background-color:blue;:nth-child(1){color:red}:nth-child(2){color:red}}</style><h1 class="css-1539881271">Hello!</h1>'279+ )280+ })281+282+ describe('cx()', () => {283+ it('Should render CSS with cx()', async () => {284+ const btn = css`285+ border-radius: 4px;286+ `287+ const btnPrimary = css`288+ background-color: blue;289+ color: white;290+ `291+292+ const template = (293+ <>294+ <Style />295+ <h1 class={cx(btn, btnPrimary)}>Hello!</h1>296+ </>297+ )298+ expect(await toString(template)).toBe(299+ '<style id="hono-css">.css-2395710522{border-radius:4px;background-color:blue;color:white}</style><h1 class="css-2395710522">Hello!</h1>'300+ )301+ })302+303+ it('Should render CSS with cx() includes external class name', async () => {304+ const btn = css`305+ border-radius: 4px;306+ `307+308+ const template = (309+ <>310+ <Style />311+ <h1 class={cx(btn, 'external-class')}>Hello!</h1>312+ </>313+ )314+ expect(await toString(template)).toBe(315+ '<style id="hono-css">.css-3467431616{border-radius:4px}</style><h1 class="css-3467431616 external-class">Hello!</h1>'316+ )317+ })318+319+ it('Should render CSS with cx() includes nested external class name', async () => {320+ const btn = css`321+ border-radius: 4px;322+ `323+ const btn2 = cx(btn, 'external-class')324+ const btn3 = css`325+ ${btn2}326+ color: white;327+ `328+ const btn4 = cx(btn3, 'external-class2')329+ const template = (330+ <>331+ <Style />332+ <h1 class={btn4}>Hello!</h1>333+ </>334+ )335+ expect(await toString(template)).toBe(336+ '<style id="hono-css">.css-3358636561{border-radius:4px;color:white}</style><h1 class="css-3358636561 external-class external-class2">Hello!</h1>'337+ )338+ })339+ })340+341+ describe('minify', () => {342+ const data: [string, Promise<string>, string][] = [343+ [344+ 'basic CSS styles',345+ css`346+ background-color: blue;347+ color: white;348+ padding: 1rem;349+ `,350+ '.css-123{background-color:blue;color:white;padding:1rem}',351+ ],352+ [353+ 'remove comments',354+ css`355+ /* background-color: blue; */356+ color: white;357+ padding: 1rem;358+ // inline comment359+ margin: 1rem;360+ `,361+ '.css-123{color:white;padding:1rem;margin:1rem}',362+ ],363+ [364+ 'preserve string',365+ css`366+ background-color: blue;367+ color: white;368+ padding: 1rem;369+ content: "Hel \\\n \\' lo!";370+ content: 'Hel \\\n \\" lo!';371+ `,372+ '.css-123{background-color:blue;color:white;padding:1rem;content:"Hel \\\n \\\' lo!";content:\'Hel \\\n \\" lo!\'}',373+ ],374+ [375+ 'preserve nested selectors',376+ css`377+ padding: 1rem;378+ &:hover {379+ padding: 2rem;380+ }381+ `,382+ '.css-123{padding:1rem;&:hover{padding:2rem}}',383+ ],384+ ]385+ data.forEach(([name, str, expected]) => {386+ it(`Should be minified while preserving content accurately: ${name}`, async () => {387+ expect(JSON.parse(await toCSS(str))).toBe(expected)388+ })389+ })390+ })391+392+ describe('createCssContext()', () => {393+ it('Should create a new CSS context', async () => {394+ const { css: css1, Style: Style1 } = createCssContext({ id: 'context1' })395+ const { css: css2, Style: Style2 } = createCssContext({ id: 'context2' })396+ const headerClass1 = css1`397+ background-color: blue;398+ `399+ const headerClass2 = css2`400+ background-color: red;401+ `402+ const template = (403+ <>404+ <Style1 />405+ <Style2 />406+ <h1 class={headerClass1}>Hello!</h1>407+ <h1 class={headerClass2}>Hello!</h1>408+ </>409+ )410+ expect(await toString(template)).toBe(411+ '<style id="context1">.css-2458908649{background-color:blue}</style><style id="context2">.css-960045552{background-color:red}</style><h1 class="css-2458908649">Hello!</h1><h1 class="css-960045552">Hello!</h1>'412+ )413+ })414+ })415+416+ describe('with application', () => {417+ const app = new Hono()418+419+ const headerClass = css`420+ background-color: blue;421+ `422+423+ app.get('/sync', (c) =>424+ c.html(425+ <>426+ <Style />427+ <h1 class={headerClass}>Hello!</h1>428+ </>429+ )430+ )431+432+ app.get('/stream', (c) => {433+ const stream = renderToReadableStream(434+ <>435+ <Style />436+ <Suspense fallback={<p>Loading...</p>}>437+ <h1 class={headerClass}>Hello!</h1>438+ </Suspense>439+ </>440+ )441+ return c.body(stream, {442+ headers: {443+ 'Content-Type': 'text/html; charset=UTF-8',444+ 'Transfer-Encoding': 'chunked',445+ },446+ })447+ })448+449+ it('/sync', async () => {450+ const res = await app.request('http://localhost/sync')451+ expect(res).not.toBeNull()452+ expect(await res.text()).toBe(453+ '<style id="hono-css">.css-2458908649{background-color:blue}</style><h1 class="css-2458908649">Hello!</h1>'454+ )455+ })456+457+ it('/stream', async () => {458+ const res = await app.request('http://localhost/stream')459+ expect(res).not.toBeNull()460+ expect(await res.text()).toBe(461+ `<style id="hono-css"></style><template id="H:0"></template><p>Loading...</p><!--/$--><script>document.querySelector('#hono-css').textContent+=".css-2458908649{background-color:blue}"</script><template><h1 class="css-2458908649">Hello!</h1></template><script>462+((d,c,n) => {463+c=d.currentScript.previousSibling464+d=d.getElementById('H:0')465+if(!d)return466+do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')467+d.replaceWith(c.content)468+})(document)469+</script>`470+ )471+ })472+ })473+})added:src/helper/css/index.ts+306 added
1+import { raw } from '../../helper/html'2+import type { HtmlEscapedCallback, HtmlEscapedString } from '../../utils/html'3+4+const IS_CSS_CLASS_NAME = Symbol('IS_CSS_CLASS_NAME')5+const STYLE_STRING = Symbol('STYLE_STRING')6+const SELECTORS = Symbol('SELECTORS')7+const EXTERNAL_CLASS_NAMES = Symbol('EXTERNAL_CLASS_NAMES')8+type CssClassName = HtmlEscapedString & {9+ [IS_CSS_CLASS_NAME]: true10+ [STYLE_STRING]: string11+ // eslint-disable-next-line @typescript-eslint/ban-types12+ [SELECTORS]: String[]13+ [EXTERNAL_CLASS_NAMES]: string[]14+}15+16+type CssEscaped = {17+ isCssEscaped: true18+}19+type CssEscapedString = string & CssEscaped20+21+/**22+ * @experimental23+ * `rawCssString` is an experimental feature.24+ * The API might be changed.25+ */26+export const rawCssString = (value: string): CssEscapedString => {27+ const escapedString = new String(value) as CssEscapedString28+ escapedString.isCssEscaped = true29+ return escapedString30+}31+32+const DEFAULT_STYLE_ID = 'hono-css'33+34+/**35+ * Used the goober'code as a reference:36+ * https://github.com/cristianbote/goober/blob/master/src/core/to-hash.js37+ * MIT License, Copyright (c) 2019 Cristian Bote38+ */39+const toHash = (str: string): string => {40+ let i = 0,41+ out = 1142+ while (i < str.length) {43+ out = (101 * out + str.charCodeAt(i++)) >>> 044+ }45+ return 'css-' + out46+}47+48+const cssStringReStr = [49+ '"(?:(?:\\\\[\\s\\S]|[^"\\\\])*)"', // double quoted string50+ // eslint-disable-next-line quotes51+ "'(?:(?:\\\\[\\s\\S]|[^'\\\\])*)'", // single quoted string52+].join('|')53+const minifyCssRe = new RegExp(54+ [55+ '(' + cssStringReStr + ')', // $1: quoted string56+57+ '(?:' +58+ [59+ '^\\s+', // head whitespace60+ '\\/\\*.*?\\*\\/\\s*', // multi-line comment61+ '\\/\\/.*\\n\\s*', // single-line comment62+ '\\s+$', // tail whitespace63+ ].join('|') +64+ ')',65+66+ ';\\s*(}|$)\\s*', // $2: trailing semicolon67+ '\\s*([{};:,])\\s*', // $3: whitespace around { } : , ;68+ '(\\s)\\s+', // $4: 2+ spaces69+ ].join('|'),70+ 'g'71+)72+73+const minify = (css: string): string => {74+ return css.replace(minifyCssRe, (_, $1, $2, $3, $4) => $1 || $2 || $3 || $4 || '')75+}76+77+type usedClassNameData = [78+ Record<string, string>, // class name to add79+ Record<string, true> // class name already added80+]81+// eslint-disable-next-line @typescript-eslint/ban-types82+type CssVariableBasicType = string | String | number | boolean | null | undefined83+type CssVariableAsyncType = Promise<CssVariableBasicType>84+type CssVariableArrayType = (CssVariableBasicType | CssVariableAsyncType)[]85+type CssVariableType = CssVariableBasicType | CssVariableAsyncType | CssVariableArrayType86+87+const buildStyleString = async (88+ strings: TemplateStringsArray,89+ values: CssVariableType[],90+ // eslint-disable-next-line @typescript-eslint/ban-types91+ selectors: String[],92+ externalClassNames: string[]93+): Promise<string> => {94+ let styleString = ''95+ for (let i = 0; i < strings.length; i++) {96+ styleString += strings[i]97+ let vArray = values[i]98+ if (typeof vArray === 'boolean' || vArray === null || vArray === undefined) {99+ continue100+ }101+102+ if (!Array.isArray(vArray)) {103+ vArray = [vArray] as CssVariableArrayType104+ }105+ for (let j = 0; j < vArray.length; j++) {106+ let value = (107+ vArray[j] instanceof Promise ? await vArray[j] : vArray[j]108+ ) as CssVariableBasicType109+ if (typeof value === 'boolean' || value === null || value === undefined) {110+ continue111+ }112+ if (typeof value === 'number') {113+ styleString += value114+ } else if (value.startsWith('@keyframes ')) {115+ selectors.push(value)116+ styleString += ` ${value.substring(11)} `117+ } else {118+ if ((value as CssClassName)[IS_CSS_CLASS_NAME]) {119+ selectors.push(...(value as CssClassName)[SELECTORS])120+ externalClassNames.push(...(value as CssClassName)[EXTERNAL_CLASS_NAMES])121+ value = (value as CssClassName)[STYLE_STRING]122+ if (value.length > 0) {123+ const lastChar = value[value.length - 1]124+ if (lastChar !== ';' && lastChar !== '}') {125+ value += ';'126+ }127+ }128+ } else if (129+ !(value as CssEscapedString).isCssEscaped &&130+ /([\\"'\/])/.test(value as string)131+ ) {132+ value = value.replace(/([\\"']|(?<=<)\/)/g, '\\$1')133+ }134+ styleString += `${value || ''}`135+ }136+ }137+ }138+139+ return minify(styleString)140+}141+142+/**143+ * @experimental144+ * `createCssContext` is an experimental feature.145+ * The API might be changed.146+ */147+export const createCssContext = ({ id }: { id: Readonly<string> }) => {148+ const contextMap: WeakMap<object, usedClassNameData> = new WeakMap()149+150+ const replaceStyleRe = new RegExp(`(<style id="${id}">.*?)(</style>)`)151+152+ const css = async (153+ strings: TemplateStringsArray,154+ ...values: CssVariableType[]155+ ): Promise<string> => {156+ // eslint-disable-next-line @typescript-eslint/ban-types157+ const selectors: String[] = []158+ const externalClassNames: string[] = []159+ const thisStyleString = await buildStyleString(strings, values, selectors, externalClassNames)160+ const thisSelector = toHash(thisStyleString)161+ const className = new String([thisSelector, ...externalClassNames].join(' ')) as CssClassName162+163+ const appendStyle: HtmlEscapedCallback = ({ buffer, context }): Promise<string> | undefined => {164+ const [toAdd, added] = contextMap.get(context) as usedClassNameData165+ const names = Object.keys(toAdd)166+167+ if (!names.length) {168+ return169+ }170+171+ let stylesStr = ''172+ names.forEach((className) => {173+ added[className] = true174+ stylesStr += `${className[0] === '@' ? '' : '.'}${className}{${toAdd[className]}}`175+ })176+ contextMap.set(context, [{}, added])177+178+ if (buffer && replaceStyleRe.test(buffer[0])) {179+ buffer[0] = buffer[0].replace(replaceStyleRe, (_, pre, post) => `${pre}${stylesStr}${post}`)180+ return181+ }182+183+ const appendStyleScript = `<script>document.querySelector('#${id}').textContent+=${JSON.stringify(184+ stylesStr185+ )}</script>`186+ if (buffer) {187+ buffer[0] = `${appendStyleScript}${buffer[0]}`188+ return189+ }190+191+ return Promise.resolve(appendStyleScript)192+ }193+194+ const addClassNameToContext: HtmlEscapedCallback = ({ context }) => {195+ if (!contextMap.get(context)) {196+ contextMap.set(context, [{}, {}])197+ }198+ const [toAdd, added] = contextMap.get(context) as usedClassNameData199+ let allAdded = true200+ if (!added[thisSelector]) {201+ allAdded = false202+ toAdd[thisSelector] = thisStyleString203+ }204+ selectors.forEach((className) => {205+ if (!added[`${className}`]) {206+ allAdded = false207+ toAdd[`${className}`] = (className as CssClassName)[STYLE_STRING]208+ }209+ })210+ if (allAdded) {211+ return212+ }213+214+ return Promise.resolve(raw('', [appendStyle]))215+ }216+217+ Object.assign(className, {218+ isEscaped: true,219+ callbacks: [addClassNameToContext],220+ [IS_CSS_CLASS_NAME]: true,221+ [STYLE_STRING]: thisStyleString,222+ [SELECTORS]: selectors,223+ [EXTERNAL_CLASS_NAMES]: externalClassNames,224+ })225+226+ return className as string227+ }228+229+ const cx = async (230+ ...args: (string | boolean | null | undefined | Promise<string | boolean | null | undefined>)[]231+ ): Promise<string> => {232+ const resolvedArgs = await Promise.all(args)233+ for (let i = 0; i < resolvedArgs.length; i++) {234+ const arg = resolvedArgs[i]235+ if (typeof arg === 'string' && !(arg as CssClassName)[IS_CSS_CLASS_NAME]) {236+ const externalClassName = new String(arg) as CssClassName237+ resolvedArgs[i] = Object.assign(externalClassName, {238+ isEscaped: true,239+ [IS_CSS_CLASS_NAME]: true,240+ [STYLE_STRING]: '',241+ [SELECTORS]: [],242+ [EXTERNAL_CLASS_NAMES]: [arg],243+ })244+ }245+ }246+247+ // eslint-disable-next-line @typescript-eslint/no-explicit-any248+ return css(Array(resolvedArgs.length).fill('') as any, ...resolvedArgs)249+ }250+251+ const keyframes = async (252+ strings: TemplateStringsArray,253+ ...values: CssVariableType[]254+ ): // eslint-disable-next-line @typescript-eslint/ban-types255+ Promise<String> => {256+ const styleString = await buildStyleString(strings, values, [], [])257+ const className = new String(`@keyframes ${toHash(styleString)}`)258+ Object.assign(className as CssClassName, {259+ isEscaped: true,260+ [IS_CSS_CLASS_NAME]: true,261+ [STYLE_STRING]: styleString,262+ [SELECTORS]: [],263+ [EXTERNAL_CLASS_NAMES]: [],264+ })265+ return className266+ }267+268+ const Style = () => raw(`<style id="${id}"></style>`)269+270+ return {271+ css,272+ cx,273+ keyframes,274+ Style,275+ }276+}277+278+const defaultContext = createCssContext({ id: DEFAULT_STYLE_ID })279+280+/**281+ * @experimental282+ * `css` is an experimental feature.283+ * The API might be changed.284+ */285+export const css = defaultContext.css286+287+/**288+ * @experimental289+ * `cx` is an experimental feature.290+ * The API might be changed.291+ */292+export const cx = defaultContext.cx293+294+/**295+ * @experimental296+ * `keyframes` is an experimental feature.297+ * The API might be changed.298+ */299+export const keyframes = defaultContext.keyframes300+301+/**302+ * @experimental303+ * `Style` is an experimental feature.304+ * The API might be changed.305+ */306+export const Style = defaultContext.Stylemodified:src/helper/dev/index.test.ts+25 added-1 removed
1 import { Hono } from '../../hono'2+import { RegExpRouter } from '../../router/reg-exp-router'3 import type { Handler, MiddlewareHandler } from '../../types'3-import { inspectRoutes, showRoutes } from '.'4+import { inspectRoutes, showRoutes, getRouterName } from '.'5 6 const namedMiddleware: MiddlewareHandler = (_, next) => next()7 const namedHandler: Handler = (c) => c.text('hi')8 const app = new Hono()100 unmodified lines109 '\x1b[32mGET\x1b[0m /static',110 ' [handler]',111 ])112 })113+114+ it('should render not colorized output', async () => {115+ showRoutes(app, { colorize: false })116+ expect(logs).toEqual([117+ 'GET /',118+ 'GET /named',119+ 'POST /',120+ 'PUT /',121+ 'PATCH /',122+ 'DELETE /',123+ 'OPTIONS /',124+ 'GET /static',125+ ])126+ })127 })128+129+describe('geRouterName()', () => {130+ it('Should return the correct router name', async () => {131+ const app = new Hono({132+ router: new RegExpRouter(),133+ })134+ expect(getRouterName(app)).toBe('RegExpRouter')135+ })136+})modified:src/helper/dev/index.ts+8 added-1 removed
2 unmodified lines3 import type { Env, RouterRoute } from '../../types'4 5 interface ShowRoutesOptions {6 verbose?: boolean7+ colorize?: boolean8 }9 10 interface RouteData {11 path: string48 unmodified lines60 return61 }62 const { method, path, routes } = data63 64+ const methodStr = opts?.colorize ?? true ? `\x1b[32m${method}\x1b[0m` : method63- console.log(`\x1b[32m${method}\x1b[0m ${' '.repeat(maxMethodLength - method.length)} ${path}`)65+ console.log(`${methodStr} ${' '.repeat(maxMethodLength - method.length)} ${path}`)66 67 if (!opts?.verbose) {68 return69 }2 unmodified lines72 console.log(`${' '.repeat(maxMethodLength + 3)} ${name}`)73 })74 })75 }76+77+export const getRouterName = <E extends Env>(app: Hono<E>) => {78+ app.router.match('GET', '/')79+ return app.router.name80+}deleted:src/helper/streaming/index.test.ts-45 removed
1-import { Hono } from '../../hono'2-import { streamSSE } from '.'3-4-describe('SSE Streaming headers', () => {5- it('Check SSE Response', async () => {6- const app = new Hono()7- app.get('/sse', async (c) => {8- return streamSSE(c, async (stream) => {9- let id = 010- const maxIterations = 511-12- while (id < maxIterations) {13- const message = `Message\nIt is ${id}`14- await stream.writeSSE({ data: message, event: 'time-update', id: String(id++) })15- await stream.sleep(100)16- }17- })18- })19-20- const res = await app.request('/sse')21- expect(res).not.toBeNull()22- expect(res.status).toBe(200)23- expect(res.headers.get('Transfer-Encoding')).toEqual('chunked')24- expect(res.headers.get('Content-Type')).toEqual('text/event-stream')25- expect(res.headers.get('Cache-Control')).toEqual('no-cache')26- expect(res.headers.get('Connection')).toEqual('keep-alive')27-28- if (!res.body) {29- throw new Error('Body is null')30- }31- const reader = res.body.getReader()32- const decoder = new TextDecoder()33- for (let i = 0; i < 5; i++) {34- const { value } = await reader.read()35- const decodedValue = decoder.decode(value)36-37- // Check the structure and content of the SSE message38- let expectedValue = 'event: time-update\n'39- expectedValue += 'data: Message\n'40- expectedValue += `data: It is ${i}\n`41- expectedValue += `id: ${i}\n\n`42- expect(decodedValue).toBe(expectedValue)43- }44- })45-})modified:src/helper/streaming/index.ts+4 added-59 removed
1-import type { Context } from '../../context'2-import { StreamingApi } from '../../utils/stream'3-4-interface SSEMessage {5- data: string6- event?: string7- id?: string8-}9-10-class SSEStreamingApi extends StreamingApi {11- constructor(writable: WritableStream) {12- super(writable)13- }14-15- async writeSSE(message: SSEMessage) {16- const data = message.data17- .split('\n')18- .map((line) => {19- return `data: ${line}`20- })21- .join('\n')22-23- const sseData =24- [message.event && `event: ${message.event}`, data, message.id && `id: ${message.id}`]25- .filter(Boolean)26- .join('\n') + '\n\n'27-28- await this.write(sseData)29- }30-}31-32-const setSSEHeaders = (context: Context) => {33- context.header('Transfer-Encoding', 'chunked')34- context.header('Content-Type', 'text/event-stream')35- context.header('Cache-Control', 'no-cache')36- context.header('Connection', 'keep-alive')37-}38-39-export const streamSSE = (c: Context, cb: (stream: SSEStreamingApi) => Promise<void>) => {40- return c.stream(async (originalStream: StreamingApi) => {41- const { readable, writable } = new TransformStream()42- const stream = new SSEStreamingApi(writable)43-44- originalStream.pipe(readable).catch((err) => {45- console.error('Error in stream piping: ', err)46- stream.close()47- })48-49- setSSEHeaders(c)50-51- try {52- await cb(stream)53- } catch (err) {54- console.error('Error during streaming: ', err)55- } finally {56- await stream.close()57- }58- })59-}1+export { stream } from './stream'2+export type { SSEMessage } from './sse'3+export { streamSSE, SSEStreamingApi } from './sse'4+export { streamText } from './text'added:src/helper/streaming/sse.test.ts+48 added
1+import { Context } from '../../context'2+import { HonoRequest } from '../../request'3+import { streamSSE } from '.'4+5+describe('SSE Streaming helper', () => {6+ const req = new HonoRequest(new Request('http://localhost/'))7+ let c: Context8+ beforeEach(() => {9+ c = new Context(req)10+ })11+12+ it('Check streamSSE Response', async () => {13+ const res = streamSSE(c, async (stream) => {14+ let id = 015+ const maxIterations = 516+17+ while (id < maxIterations) {18+ const message = `Message\nIt is ${id}`19+ await stream.writeSSE({ data: message, event: 'time-update', id: String(id++) })20+ await stream.sleep(100)21+ }22+ })23+24+ expect(res).not.toBeNull()25+ expect(res.status).toBe(200)26+ expect(res.headers.get('Transfer-Encoding')).toEqual('chunked')27+ expect(res.headers.get('Content-Type')).toEqual('text/event-stream')28+ expect(res.headers.get('Cache-Control')).toEqual('no-cache')29+ expect(res.headers.get('Connection')).toEqual('keep-alive')30+31+ if (!res.body) {32+ throw new Error('Body is null')33+ }34+ const reader = res.body.getReader()35+ const decoder = new TextDecoder()36+ for (let i = 0; i < 5; i++) {37+ const { value } = await reader.read()38+ const decodedValue = decoder.decode(value)39+40+ // Check the structure and content of the SSE message41+ let expectedValue = 'event: time-update\n'42+ expectedValue += 'data: Message\n'43+ expectedValue += `data: It is ${i}\n`44+ expectedValue += `id: ${i}\n\n`45+ expect(decodedValue).toBe(expectedValue)46+ }47+ })48+})added:src/helper/streaming/sse.ts+60 added
1+import type { Context } from '../../context'2+import { StreamingApi } from '../../utils/stream'3+import { stream } from '.'4+5+export interface SSEMessage {6+ data: string7+ event?: string8+ id?: string9+}10+11+export class SSEStreamingApi extends StreamingApi {12+ constructor(writable: WritableStream, readable: ReadableStream) {13+ super(writable, readable)14+ }15+16+ async writeSSE(message: SSEMessage) {17+ const data = message.data18+ .split('\n')19+ .map((line) => {20+ return `data: ${line}`21+ })22+ .join('\n')23+24+ const sseData =25+ [message.event && `event: ${message.event}`, data, message.id && `id: ${message.id}`]26+ .filter(Boolean)27+ .join('\n') + '\n\n'28+29+ await this.write(sseData)30+ }31+}32+33+const setSSEHeaders = (context: Context) => {34+ context.header('Transfer-Encoding', 'chunked')35+ context.header('Content-Type', 'text/event-stream')36+ context.header('Cache-Control', 'no-cache')37+ context.header('Connection', 'keep-alive')38+}39+40+export const streamSSE = (c: Context, cb: (stream: SSEStreamingApi) => Promise<void>) => {41+ return stream(c, async (originalStream: StreamingApi) => {42+ const { readable, writable } = new TransformStream()43+ const stream = new SSEStreamingApi(writable, readable)44+45+ originalStream.pipe(stream.responseReadable).catch((err) => {46+ console.error('Error in stream piping: ', err)47+ stream.close()48+ })49+50+ setSSEHeaders(c)51+52+ try {53+ await cb(stream)54+ } catch (err) {55+ console.error('Error during streaming: ', err)56+ } finally {57+ await stream.close()58+ }59+ })60+}added:src/helper/streaming/stream.test.ts+28 added
1+import { Context } from '../../context'2+import { HonoRequest } from '../../request'3+import { stream } from '.'4+5+describe('Basic Streaming Helper', () => {6+ const req = new HonoRequest(new Request('http://localhost/'))7+ let c: Context8+ beforeEach(() => {9+ c = new Context(req)10+ })11+12+ it('Check SSE Response', async () => {13+ const res = stream(c, async (stream) => {14+ for (let i = 0; i < 3; i++) {15+ await stream.write(new Uint8Array([i]))16+ await stream.sleep(1)17+ }18+ })19+ if (!res.body) {20+ throw new Error('Body is null')21+ }22+ const reader = res.body.getReader()23+ for (let i = 0; i < 3; i++) {24+ const { value } = await reader.read()25+ expect(value).toEqual(new Uint8Array([i]))26+ }27+ })28+})added:src/helper/streaming/stream.ts+9 added
1+import type { Context } from '../../context'2+import { StreamingApi } from '../../utils/stream'3+4+export const stream = (c: Context, cb: (stream: StreamingApi) => Promise<void>): Response => {5+ const { readable, writable } = new TransformStream()6+ const stream = new StreamingApi(writable, readable)7+ cb(stream).finally(() => stream.close())8+ return c.newResponse(stream.responseReadable)9+}added:src/helper/streaming/text.test.ts+35 added
1+import { Context } from '../../context'2+import { HonoRequest } from '../../request'3+import { streamText } from '.'4+5+describe('Text Streaming Helper', () => {6+ const req = new HonoRequest(new Request('http://localhost/'))7+ let c: Context8+ beforeEach(() => {9+ c = new Context(req)10+ })11+12+ it('Check streamText Response', async () => {13+ const res = streamText(c, async (stream) => {14+ for (let i = 0; i < 3; i++) {15+ await stream.write(`${i}`)16+ await stream.sleep(1)17+ }18+ })19+20+ expect(res.status).toBe(200)21+ expect(res.headers.get('content-type')).toMatch(/^text\/plain/)22+ expect(res.headers.get('x-content-type-options')).toBe('nosniff')23+ expect(res.headers.get('transfer-encoding')).toBe('chunked')24+25+ if (!res.body) {26+ throw new Error('Body is null')27+ }28+ const reader = res.body.getReader()29+ const decoder = new TextDecoder()30+ for (let i = 0; i < 3; i++) {31+ const { value } = await reader.read()32+ expect(decoder.decode(value)).toEqual(`${i}`)33+ }34+ })35+})added:src/helper/streaming/text.ts+11 added
1+import type { Context } from '../../context'2+import { TEXT_PLAIN } from '../../context'3+import type { StreamingApi } from '../../utils/stream'4+import { stream } from '.'5+6+export const streamText = (c: Context, cb: (stream: StreamingApi) => Promise<void>): Response => {7+ c.header('Content-Type', TEXT_PLAIN)8+ c.header('X-Content-Type-Options', 'nosniff')9+ c.header('Transfer-Encoding', 'chunked')10+ return stream(c, cb)11+}modified:src/jsx/components.test.tsx+19 added-14 removed
1 import { JSDOM } from 'jsdom'2-import { resolveStream } from '../utils/html'2+import type { HtmlEscapedString } from '../utils/html'3+import { HtmlEscapedCallbackPhase, resolveCallback as rawResolveCallback } from '../utils/html'4 import { ErrorBoundary } from './components'5 import { Suspense, renderToReadableStream } from './streaming'6 // eslint-disable-next-line @typescript-eslint/no-unused-vars6-import { jsx, Fragment } from './index'7+import { jsx } from './index'8 9+function resolveCallback(template: string | HtmlEscapedString) {10+ return rawResolveCallback(template, HtmlEscapedCallbackPhase.Stream, false, {})11+}12+13 function replacementResult(html: string) {14 const document = new JSDOM(html, { runScripts: 'dangerously' }).window.document15 document.querySelectorAll('template, script').forEach((e) => e.remove())16 return document.body.innerHTML23 unmodified lines40 <Component />41 </ErrorBoundary>42 )43 39- expect((await resolveStream(await html.toString())).toString()).toEqual('<div>Hello</div>')44+ expect((await resolveCallback(await html.toString())).toString()).toEqual('<div>Hello</div>')45 46 errorBoundaryCounter--47 suspenseCounter--48 })4 unmodified lines53 <Component error={true} />54 </ErrorBoundary>55 )56 52- expect((await resolveStream(await html.toString())).toString()).toEqual(57+ expect((await resolveCallback(await html.toString())).toString()).toEqual(58 '<div>Out Of Service</div>'59 )60 61 suspenseCounter--15 unmodified lines77 <Component />78 </ErrorBoundary>79 )80 76- expect((await resolveStream(await html.toString())).toString()).toEqual('<div>Hello</div>')81+ expect((await resolveCallback(await html.toString())).toString()).toEqual('<div>Hello</div>')82 83 errorBoundaryCounter--84 suspenseCounter--85 })4 unmodified lines90 <Component error={true} />91 </ErrorBoundary>92 )93 89- expect((await resolveStream(await html.toString())).toString()).toEqual(94+ expect((await resolveCallback(await html.toString())).toString()).toEqual(95 '<div>Out Of Service</div>'96 )97 98 suspenseCounter--18 unmodified lines117 ).toString()118 119 Object.values(handlers).forEach(({ resolve }) => resolve(undefined))120 116- expect((await resolveStream(await html)).toString()).toEqual('<div>1</div><div>2</div>')121+ expect((await resolveCallback(await html)).toString()).toEqual('<div>1</div><div>2</div>')122 123 errorBoundaryCounter++124 suspenseCounter--125 })10 unmodified lines136 137 handlers[2].resolve(undefined)138 handlers[1].reject()139 135- expect((await resolveStream(await html)).toString()).toEqual('<div>Out Of Service</div>')140+ expect((await resolveCallback(await html)).toString()).toEqual('<div>Out Of Service</div>')141 142 errorBoundaryCounter++143 suspenseCounter--144 })10 unmodified lines155 156 handlers[1].resolve(undefined)157 handlers[2].reject()158 154- expect((await resolveStream(await html)).toString()).toEqual(159+ expect((await resolveCallback(await html)).toString()).toEqual(160 '<div>1</div><div>Out Of Service</div>'161 )162 163 errorBoundaryCounter++65 unmodified lines229 <Component error={true} />230 </ErrorBoundary>231 )232 228- expect((await resolveStream(await html.toString())).toString()).toEqual(233+ expect((await resolveCallback(await html.toString())).toString()).toEqual(234 '<div>Out Of Service</div>'235 )236 })237 })170 unmodified lines408 <Component />409 </ErrorBoundary>410 )411 407- expect((await resolveStream(await html.toString())).toString()).toEqual('<div>Hello</div>')412+ expect((await resolveCallback(await html.toString())).toString()).toEqual('<div>Hello</div>')413 414 errorBoundaryCounter--415 suspenseCounter--416 7 unmodified lines424 <Component error={true} />425 </ErrorBoundary>426 )427 423- expect((await resolveStream(await html.toString())).toString()).toEqual(428+ expect((await resolveCallback(await html.toString())).toString()).toEqual(429 '<div>Out Of Service</div>'430 )431 432 suspenseCounter--18 unmodified lines451 <Component />452 </ErrorBoundary>453 )454 450- expect((await resolveStream(await html.toString())).toString()).toEqual('<div>Hello</div>')455+ expect((await resolveCallback(await html.toString())).toString()).toEqual('<div>Hello</div>')456 457 errorBoundaryCounter--458 suspenseCounter--459 6 unmodified lines466 <Component error={true} />467 </ErrorBoundary>468 )469 465- expect((await resolveStream(await html.toString())).toString()).toEqual(470+ expect((await resolveCallback(await html.toString())).toString()).toEqual(471 '<div data-error="true">Error</div>'472 )473 474 suspenseCounter--3 unmodified linesmodified:src/jsx/components.ts+29 added-9 removed
1 import { raw } from '../helper/html'2-import type { HtmlEscapedString } from '../utils/html'2+import {3+ HtmlEscapedCallbackPhase,4+ resolveCallback,5+ type HtmlEscapedString,6+ type HtmlEscapedCallback,7+} from '../utils/html'8 import type { FC, Child } from './index'9 10 let errorBoundaryCounter = 011 30 unmodified lines42 if (!Array.isArray(children)) {43 children = [children]44 }45 46+ let fallbackStr: string | undefined47 const fallbackRes = (error: Error): HtmlEscapedString => {48 onError?.(error)43- return (fallback || fallbackRender?.(error) || '').toString() as HtmlEscapedString49+ return (fallbackStr || fallbackRender?.(error) || '').toString() as HtmlEscapedString50 }51 let resArray: HtmlEscapedString[] | Promise<HtmlEscapedString[]>[] = []52 try {53 resArray = children.map((c) => c.toString()) as HtmlEscapedString[]54 } catch (e) {55+ fallbackStr = await fallback?.toString()56 if (e instanceof Promise) {57 resArray = [58 e.then(() => childrenToString(children as Child[])).catch((e) => fallbackRes(e)),59 ] as Promise<HtmlEscapedString[]>[]2 unmodified lines62 }63 }64 65 if (resArray.some((res) => (res as {}) instanceof Promise)) {66+ fallbackStr ||= await fallback?.toString()67 const index = errorBoundaryCounter++68 const replaceRe = RegExp(`(<template id="E:${index}"></template>.*?)(.*?)(<!--E:${index}-->)`)69 const caught = false70 const catchCallback = ({ error, buffer }: { error: Error; buffer?: [string] }) => {17 unmodified lines88 })(document)89 </script>`90 }91 return raw(`<template id="E:${index}"></template><!--E:${index}-->`, [84- ({ buffer }) => {92+ ({ phase, buffer, context }) => {93+ if (phase === HtmlEscapedCallbackPhase.BeforeStream) {94+ return95+ }96 return Promise.all(resArray)86- .then((htmlArray) => {97+ .then(async (htmlArray) => {98 htmlArray = htmlArray.flat()99 const content = htmlArray.join('')89- const html = buffer100+ let html = buffer101 ? ''102 : `<template>${content}</template><script>103 ((d,c) => {104 c=d.currentScript.previousSibling20 unmodified lines125 const callbacks = htmlArray126 .map((html) => (html as HtmlEscapedString).callbacks || [])127 .flat()128 129+ if (phase === HtmlEscapedCallbackPhase.Stream) {130+ html = await resolveCallback(131+ html,132+ HtmlEscapedCallbackPhase.BeforeStream,133+ true,134+ context135+ )136+ }137+138 let resolvedCount = 0119- const promises = callbacks.map(139+ const promises = callbacks.map<HtmlEscapedCallback>(140 (c) =>121- ({ buffer }: { buffer: [string] }) =>122- c({ buffer })123- .then((content) => {141+ (...args) =>142+ c(...args)143+ ?.then((content) => {144 resolvedCount++145 146 if (buffer) {147 if (resolvedCount === callbacks.length) {36 unmodified linesmodified:src/jsx/index.ts+3 added
143 unmodified lines144 throw 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'145 }146 147 children = [raw(v.__html)]148+ } else if (v instanceof Promise) {149+ buffer[0] += ` ${key}="`150+ buffer.unshift('"', v)151 } else {152 buffer[0] += ` ${key}="`153 escapeToBuffer(v.toString(), buffer)154 buffer[0] += '"'139 unmodified linesmodified:src/jsx/intrinsic-elements.ts+1 added-1 removed
21 unmodified lines22 23 interface HTMLAttributes extends JSXAttributes, AnyAttributes {24 accesskey?: string | undefined25 autofocus?: boolean | undefined26- class?: string | undefined26+ class?: string | Promise<string> | undefined27 contenteditable?: boolean | 'inherit' | undefined28 contextmenu?: string | undefined29 dir?: string | undefined30 draggable?: boolean | undefined576 unmodified linesmodified:src/jsx/streaming.test.tsx+11 added-6 removed
1 import { JSDOM } from 'jsdom'2 import { raw } from '../helper/html'3-import { resolveStream } from '../utils/html'3+import { HtmlEscapedCallbackPhase, resolveCallback } from '../utils/html'4 import type { HtmlEscapedString } from '../utils/html'5 import { Suspense, renderToReadableStream } from './streaming'6 // eslint-disable-next-line @typescript-eslint/no-unused-vars7 import { jsx, Fragment } from './index'510 unmodified lines518 )519 return content520 }521 522+ const str = await resolveCallback(522- const str = await resolveStream(await (523- <Suspense fallback={<p>Loading...</p>}>524- <Content />525- </Suspense>526- ).toString())523+ await (524+ <Suspense fallback={<p>Loading...</p>}>525+ <Content />526+ </Suspense>527+ ).toString(),528+ HtmlEscapedCallbackPhase.Stream,529+ false,530+ {}531+ )532 533 expect(str).toEqual('<h1>Hello</h1>')534 expect(contentEvaluatedCount).toEqual(1)535 })26 unmodified linesmodified:src/jsx/streaming.ts+40 added-16 removed
1 import { raw } from '../helper/html'2+import { HtmlEscapedCallbackPhase, resolveCallback } from '../utils/html'3 import type { HtmlEscapedString } from '../utils/html'4 import { childrenToString } from './components'5 import type { FC, Child } from './index'6 27 unmodified lines34 }35 36 if (resArray.some((res) => (res as {}) instanceof Promise)) {37 const index = suspenseCounter++37- return raw(`<template id="H:${index}"></template>${fallback.toString()}<!--/$-->`, [38- ({ buffer }) => {39- return Promise.all(resArray).then((htmlArray) => {38+ const fallbackStr = await fallback.toString()39+ return raw(`<template id="H:${index}"></template>${fallbackStr}<!--/$-->`, [40+ ...(fallbackStr.callbacks || []),41+ ({ phase, buffer, context }) => {42+ if (phase === HtmlEscapedCallbackPhase.BeforeStream) {43+ return44+ }45+ return Promise.all(resArray).then(async (htmlArray) => {46 htmlArray = htmlArray.flat()47 const content = htmlArray.join('')48 if (buffer) {49 buffer[0] = buffer[0].replace(50 new RegExp(`<template id="H:${index}"></template>.*?<!--/\\$-->`),51 content52 )53 }48- const html = buffer54+ let html = buffer55 ? ''56 : `<template>${content}</template><script>57 ((d,c,n) => {58 c=d.currentScript.previousSibling2 unmodified lines61 do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')62 d.replaceWith(c.content)63 })(document)64 </script>`59- if (htmlArray.every((html) => !(html as HtmlEscapedString).callbacks?.length)) {65+66+ const callbacks = htmlArray67+ .map((html) => (html as HtmlEscapedString).callbacks || [])68+ .flat()69+ if (!callbacks.length) {70 return html71 }72 63- return raw(64- html,65- htmlArray.map((html) => (html as HtmlEscapedString).callbacks || []).flat()66- )73+ if (phase === HtmlEscapedCallbackPhase.Stream) {74+ html = await resolveCallback(html, HtmlEscapedCallbackPhase.BeforeStream, true, context)75+ }76+77+ return raw(html, callbacks)78 })79 },80 ])81 } else {11 unmodified lines93 str: HtmlEscapedString | Promise<HtmlEscapedString>94 ): ReadableStream<Uint8Array> => {95 const reader = new ReadableStream<Uint8Array>({96 async start(controller) {86- const resolved = str instanceof Promise ? await str : await str.toString()97+ const tmp = str instanceof Promise ? await str : await str.toString()98+ const context = typeof tmp === 'object' ? tmp : {}99+ const resolved = await resolveCallback(100+ tmp,101+ HtmlEscapedCallbackPhase.BeforeStream,102+ true,103+ context104+ )105 controller.enqueue(textEncoder.encode(resolved))106 107 let resolvedCount = 0108 const callbacks: Promise<void>[] = []3 unmodified lines112 .catch((err) => {113 console.trace(err)114 return ''115 })98- .then((res) => {99- if ((res as HtmlEscapedString).callbacks) {100- const callbacks = (res as HtmlEscapedString).callbacks || []101- callbacks.map((c) => c({})).forEach(then)102- }116+ .then(async (res) => {117+ res = await resolveCallback(res, HtmlEscapedCallbackPhase.BeforeStream, true, context)118+ ;(res as HtmlEscapedString).callbacks119+ ?.map((c) => c({ phase: HtmlEscapedCallbackPhase.Stream, context }))120+ // eslint-disable-next-line @typescript-eslint/no-explicit-any121+ .filter<Promise<string>>(Boolean as any)122+ .forEach(then)123 resolvedCount++124 controller.enqueue(textEncoder.encode(res))125 })126 )127 }108- ;(resolved as HtmlEscapedString).callbacks?.map((c) => c({})).forEach(then)128+ ;(resolved as HtmlEscapedString).callbacks129+ ?.map((c) => c({ phase: HtmlEscapedCallbackPhase.Stream, context }))130+ // eslint-disable-next-line @typescript-eslint/no-explicit-any131+ .filter<Promise<string>>(Boolean as any)132+ .forEach(then)133 while (resolvedCount !== callbacks.length) {134 await Promise.all(callbacks)135 }136 5 unmodified linesadded:src/middleware/csrf/index.test.ts+306 added
1+import type { Context } from '../../context'2+import { Hono } from '../../hono'3+import { csrf } from '../../middleware/csrf'4+5+const simplePostHandler = vi.fn(async (c: Context) => {6+ if (c.req.header('content-type') === 'application/json') {7+ return c.text((await c.req.json<{ name: string }>())['name'])8+ } else {9+ const body = await c.req.parseBody<{ name: string }>()10+ return c.text(body['name'])11+ }12+})13+14+const buildSimplePostRequestData = (origin?: string) => ({15+ method: 'POST',16+ headers: Object.assign(17+ {18+ 'content-type': 'application/x-www-form-urlencoded',19+ },20+ origin ? { origin } : {}21+ ) as Record<string, string>,22+ body: 'name=hono',23+})24+25+describe('CSRF by Middleware', () => {26+ beforeEach(() => {27+ simplePostHandler.mockClear()28+ })29+30+ describe('simple usage', () => {31+ const app = new Hono()32+33+ app.use('*', csrf())34+ app.get('/form', (c) => c.html('<form></form>'))35+ app.post('/form', simplePostHandler)36+ app.put('/form', (c) => c.text('OK'))37+ app.delete('/form', (c) => c.text('OK'))38+ app.patch('/form', (c) => c.text('OK'))39+40+ describe('GET /form', async () => {41+ it('should be 200 for any request', async () => {42+ const res = await app.request('http://localhost/form')43+44+ expect(res.status).toBe(200)45+ expect(await res.text()).toBe('<form></form>')46+ })47+ })48+49+ describe('HEAD /form', async () => {50+ it('should be 200 for any request', async () => {51+ const res = await app.request('http://localhost/form', { method: 'HEAD' })52+53+ expect(res.status).toBe(200)54+ })55+ })56+57+ describe('POST /form', async () => {58+ it('should be 200 for local request', async () => {59+ /*60+ * <form action="/form" method="POST"><input name="name" value="hono" /></form>61+ * or62+ * <script>63+ * fetch('/form', {64+ * method: 'POST',65+ * headers: {66+ * 'content-type': 'application/x-www-form-urlencoded',67+ * },68+ * body: 'name=hono',69+ * });70+ * </script>71+ */72+ const res = await app.request(73+ 'http://localhost/form',74+ buildSimplePostRequestData('http://localhost')75+ )76+77+ expect(res.status).toBe(200)78+ expect(await res.text()).toBe('hono')79+ })80+81+ it('should be 403 for "application/x-www-form-urlencoded" cross origin', async () => {82+ /*83+ * via http://example.com84+ *85+ * <form action="http://localhost/form" method="POST">86+ * <input name="name" value="hono" />87+ * </form>88+ * or89+ * <script>90+ * fetch('http://localhost/form', {91+ * method: 'POST',92+ * headers: {93+ * 'content-type': 'application/x-www-form-urlencoded',94+ * },95+ * body: 'name=hono',96+ * });97+ * </script>98+ */99+ const res = await app.request(100+ 'http://localhost/form',101+ buildSimplePostRequestData('http://example.com')102+ )103+104+ expect(res.status).toBe(403)105+ expect(simplePostHandler).not.toHaveBeenCalled()106+ })107+ })108+109+ it('should be 403 for "multipart/form-data" cross origin', async () => {110+ /*111+ * via http://example.com112+ *113+ * <form action="http://localhost/form" method="POST" enctype="multipart/form-data">114+ * <input name="name" value="hono" />115+ * </form>116+ * or117+ * <script>118+ * fetch('http://localhost/form', {119+ * method: 'POST',120+ * headers: {121+ * 'content-type': 'multipart/form-data',122+ * },123+ * body: 'name=hono',124+ * });125+ * </script>126+ */127+ const res = await app.request(128+ 'http://localhost/form',129+ buildSimplePostRequestData('http://example.com')130+ )131+132+ expect(res.status).toBe(403)133+ expect(simplePostHandler).not.toHaveBeenCalled()134+ })135+136+ it('should be 403 for "text/plain" cross origin', async () => {137+ /*138+ * via http://example.com139+ *140+ * <form action="http://localhost/form" method="POST" enctype="text/plain">141+ * <input name="name" value="hono" />142+ * </form>143+ * or144+ * <script>145+ * fetch('http://localhost/form', {146+ * method: 'POST',147+ * headers: {148+ * 'content-type': 'text/plain',149+ * },150+ * body: 'name=hono',151+ * });152+ * </script>153+ */154+ const res = await app.request(155+ 'http://localhost/form',156+ buildSimplePostRequestData('http://example.com')157+ )158+159+ expect(res.status).toBe(403)160+ expect(simplePostHandler).not.toHaveBeenCalled()161+ })162+163+ it('should be 403 if request has no origin header', async () => {164+ const res = await app.request('http://localhost/form', buildSimplePostRequestData())165+166+ expect(res.status).toBe(403)167+ expect(simplePostHandler).not.toHaveBeenCalled()168+ })169+170+ it('should be 200 for application/json', async () => {171+ /*172+ * via http://example.com173+ * Assume localhost allows cross origin POST174+ *175+ * <script>176+ * fetch('http://localhost/form', {177+ * method: 'POST',178+ * headers: {179+ * 'content-type': 'application/json',180+ * },181+ * body: JSON.stringify({ name: 'hono' }),182+ * });183+ * </script>184+ */185+ const res = await app.request('http://localhost/form', {186+ method: 'POST',187+ headers: {188+ 'content-type': 'application/json',189+ origin: 'http://example.com',190+ },191+ body: JSON.stringify({ name: 'hono' }),192+ })193+194+ expect(res.status).toBe(200)195+ expect(await res.text()).toBe('hono')196+ })197+ })198+199+ describe('with origin option', () => {200+ describe('string', () => {201+ const app = new Hono()202+203+ app.use(204+ '*',205+ csrf({206+ origin: 'https://example.com',207+ })208+ )209+ app.post('/form', simplePostHandler)210+211+ it('should be 200 for allowed origin', async () => {212+ const res = await app.request(213+ 'https://example.com/form',214+ buildSimplePostRequestData('https://example.com')215+ )216+ expect(res.status).toBe(200)217+ })218+219+ it('should be 403 for not allowed origin', async () => {220+ const res = await app.request(221+ 'https://example.jp/form',222+ buildSimplePostRequestData('https://example.jp')223+ )224+ expect(res.status).toBe(403)225+ expect(simplePostHandler).not.toHaveBeenCalled()226+ })227+ })228+229+ describe('string[]', () => {230+ const app = new Hono()231+232+ app.use(233+ '*',234+ csrf({235+ origin: ['https://example.com', 'https://hono.example.com'],236+ })237+ )238+ app.post('/form', simplePostHandler)239+240+ it('should be 200 for allowed origin', async () => {241+ let res = await app.request(242+ 'https://hono.example.com/form',243+ buildSimplePostRequestData('https://hono.example.com')244+ )245+ expect(res.status).toBe(200)246+247+ res = await app.request(248+ 'https://example.com/form',249+ buildSimplePostRequestData('https://example.com')250+ )251+ expect(res.status).toBe(200)252+ })253+254+ it('should be 403 for not allowed origin', async () => {255+ const res = await app.request(256+ 'http://example.jp/form',257+ buildSimplePostRequestData('http://example.jp')258+ )259+ expect(res.status).toBe(403)260+ expect(simplePostHandler).not.toHaveBeenCalled()261+ })262+ })263+264+ describe('IsAllowedOriginHandler', () => {265+ const app = new Hono()266+267+ app.use(268+ '*',269+ csrf({270+ origin: (origin) => /https:\/\/(\w+\.)?example\.com$/.test(origin),271+ })272+ )273+ app.post('/form', simplePostHandler)274+275+ it('should be 200 for allowed origin', async () => {276+ let res = await app.request(277+ 'https://hono.example.com/form',278+ buildSimplePostRequestData('https://hono.example.com')279+ )280+ expect(res.status).toBe(200)281+282+ res = await app.request(283+ 'https://example.com/form',284+ buildSimplePostRequestData('https://example.com')285+ )286+ expect(res.status).toBe(200)287+ })288+289+ it('should be 403 for not allowed origin', async () => {290+ let res = await app.request(291+ 'http://honojs.hono.example.jp/form',292+ buildSimplePostRequestData('http://example.jp')293+ )294+ expect(res.status).toBe(403)295+ expect(simplePostHandler).not.toHaveBeenCalled()296+297+ res = await app.request(298+ 'http://example.jp/form',299+ buildSimplePostRequestData('http://example.jp')300+ )301+ expect(res.status).toBe(403)302+ expect(simplePostHandler).not.toHaveBeenCalled()303+ })304+ })305+ })306+})added:src/middleware/csrf/index.ts+48 added
1+import type { Context } from '../../context'2+import { HTTPException } from '../../http-exception'3+import type { MiddlewareHandler } from '../../types'4+5+type IsAllowedOriginHandler = (origin: string, context: Context) => boolean6+interface CSRFOptions {7+ origin?: string | string[] | IsAllowedOriginHandler8+}9+10+const isSafeMethodRe = /^(GET|HEAD)$/11+const isRequestedByFormElementRe =12+ /^\b(application\/x-www-form-urlencoded|multipart\/form-data|text\/plain)\b/13+14+export const csrf = (options?: CSRFOptions): MiddlewareHandler => {15+ const handler: IsAllowedOriginHandler = ((optsOrigin) => {16+ if (!optsOrigin) {17+ return (origin, c) => origin === new URL(c.req.url).origin18+ } else if (typeof optsOrigin === 'string') {19+ return (origin) => origin === optsOrigin20+ } else if (typeof optsOrigin === 'function') {21+ return optsOrigin22+ } else {23+ return (origin) => optsOrigin.includes(origin)24+ }25+ })(options?.origin)26+ const isAllowedOrigin = (origin: string | undefined, c: Context) => {27+ if (origin === undefined) {28+ // denied always when origin header is not present29+ return false30+ }31+ return handler(origin, c)32+ }33+34+ return async function cors(c, next) {35+ if (36+ !isSafeMethodRe.test(c.req.method) &&37+ isRequestedByFormElementRe.test(c.req.header('content-type') || '') &&38+ !isAllowedOrigin(c.req.header('origin'), c)39+ ) {40+ const res = new Response('Forbidden', {41+ status: 403,42+ })43+ throw new HTTPException(403, { res })44+ }45+46+ await next()47+ }48+}modified:src/utils/html.ts+31 added-7 removed
1-type HtmlEscapedCallbackOpts = { error?: Error; buffer?: [string] }2-export type HtmlEscapedCallback = (opts: HtmlEscapedCallbackOpts) => Promise<string>1+export const HtmlEscapedCallbackPhase = {2+ Stringify: 1,3+ BeforeStream: 2,4+ Stream: 3,5+} as const6+type HtmlEscapedCallbackOpts = {7+ buffer?: [string]8+ phase: typeof HtmlEscapedCallbackPhase[keyof typeof HtmlEscapedCallbackPhase]9+ context: object // An object unique to each JSX tree. This object is used as the WeakMap key.10+}11+export type HtmlEscapedCallback = (opts: HtmlEscapedCallbackOpts) => Promise<string> | undefined12 export type HtmlEscaped = {13 isEscaped: true14 callbacks?: HtmlEscapedCallback[]15 }93 unmodified lines109 110 buffer[0] += str.substring(lastIndex, index)111 }112 104-export const resolveStream = (113+export const resolveCallback = async (114 str: string | HtmlEscapedString,115+ phase: typeof HtmlEscapedCallbackPhase[keyof typeof HtmlEscapedCallbackPhase],116+ preserveCallbacks: boolean,117+ context: object,118 buffer?: [string]119 ): Promise<string> => {108- if (!(str as HtmlEscapedString).callbacks?.length) {120+ const callbacks = (str as HtmlEscapedString).callbacks as HtmlEscapedCallback[]121+ if (!callbacks?.length) {122 return Promise.resolve(str)123 }111- const callbacks = (str as HtmlEscapedString).callbacks as HtmlEscapedCallback[]124 if (buffer) {125 buffer[0] += str126 } else {127 buffer = [str]128 }117- return Promise.all(callbacks.map((c) => c({ buffer }))).then((res) =>118- Promise.all(res.map((str) => resolveStream(str, buffer))).then(() => (buffer as [string])[0])129+130+ const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then((res) =>131+ Promise.all(132+ res133+ // eslint-disable-next-line @typescript-eslint/no-explicit-any134+ .filter<string>(Boolean as any)135+ .map((str) => resolveCallback(str, phase, false, context, buffer))136+ ).then(() => (buffer as [string])[0])137 )138+139+ if (preserveCallbacks) {140+ return raw(await resStr, callbacks)141+ } else {142+ return resStr143+ }144 }modified:src/utils/stream.test.ts+28 added-14 removed
1 unmodified line2 3 describe('StreamingApi', () => {4 it('write(string)', async () => {5 const { readable, writable } = new TransformStream()6- const api = new StreamingApi(writable)7- const reader = readable.getReader()6+ const api = new StreamingApi(writable, readable)7+ const reader = api.responseReadable.getReader()8 api.write('foo')9 expect((await reader.read()).value).toEqual(new TextEncoder().encode('foo'))10 api.write('bar')11 expect((await reader.read()).value).toEqual(new TextEncoder().encode('bar'))12 })13 14 it('write(Uint8Array)', async () => {15 const { readable, writable } = new TransformStream()16- const api = new StreamingApi(writable)17- const reader = readable.getReader()16+ const api = new StreamingApi(writable, readable)17+ const reader = api.responseReadable.getReader()18 api.write(new Uint8Array([1, 2, 3]))19 expect((await reader.read()).value).toEqual(new Uint8Array([1, 2, 3]))20 api.write(new Uint8Array([4, 5, 6]))21 expect((await reader.read()).value).toEqual(new Uint8Array([4, 5, 6]))22 })23 24 it('writeln(string)', async () => {25 const { readable, writable } = new TransformStream()26- const api = new StreamingApi(writable)27- const reader = readable.getReader()26+ const api = new StreamingApi(writable, readable)27+ const reader = api.responseReadable.getReader()28 api.writeln('foo')29 expect((await reader.read()).value).toEqual(new TextEncoder().encode('foo\n'))30 api.writeln('bar')31 expect((await reader.read()).value).toEqual(new TextEncoder().encode('bar\n'))11 unmodified lines43 })()44 45 const { readable: receiverReadable, writable: receiverWritable } = new TransformStream()46 47- const api = new StreamingApi(receiverWritable)47+ const api = new StreamingApi(receiverWritable, receiverReadable)48 49 // pipe readable to api in other scope50 ;(async () => {51 await api.pipe(senderReadable)52 })()53 54 // read data from api55- const reader = receiverReadable.getReader()55+ const reader = api.responseReadable.getReader()56 expect((await reader.read()).value).toEqual(new TextEncoder().encode('foo'))57 expect((await reader.read()).value).toEqual(new TextEncoder().encode('bar'))58 })59 60 it('close()', async () => {61 const { readable, writable } = new TransformStream()62- const api = new StreamingApi(writable)63- const reader = readable.getReader()62+ const api = new StreamingApi(writable, readable)63+ const reader = api.responseReadable.getReader()64 await api.close()65 expect((await reader.read()).done).toBe(true)66 })67 68 it('should not throw an error in write()', async () => {69- const { writable } = new TransformStream()70- const api = new StreamingApi(writable)69+ const { readable, writable } = new TransformStream()70+ const api = new StreamingApi(writable, readable)71 await api.close()72 const write = () => api.write('foo')73 expect(write).not.toThrow()74 })75 76 it('should not throw an error in close()', async () => {77- const { writable } = new TransformStream()78- const api = new StreamingApi(writable)77+ const { readable, writable } = new TransformStream()78+ const api = new StreamingApi(writable, readable)79 const close = async () => {80 await api.close()81 await api.close()82 }83 expect(close).not.toThrow()84 })85+86+ it('onAbort()', async () => {87+ const { readable, writable } = new TransformStream()88+ const handleAbort1 = vi.fn()89+ const handleAbort2 = vi.fn()90+ const api = new StreamingApi(writable, readable)91+ api.onAbort(handleAbort1)92+ api.onAbort(handleAbort2)93+ expect(handleAbort1).not.toBeCalled()94+ expect(handleAbort2).not.toBeCalled()95+ await api.responseReadable.cancel()96+ expect(handleAbort1).toBeCalled()97+ expect(handleAbort2).toBeCalled()98+ })99 })modified:src/utils/stream.ts+23 added-1 removed
1 export class StreamingApi {2 private writer: WritableStreamDefaultWriter<Uint8Array>3 private encoder: TextEncoder4 private writable: WritableStream5+ private abortSubscribers: (() => void | Promise<void>)[] = []6+ responseReadable: ReadableStream7 6- constructor(writable: WritableStream) {8+ constructor(writable: WritableStream, _readable: ReadableStream) {9 this.writable = writable10 this.writer = writable.getWriter()11 this.encoder = new TextEncoder()12+13+ const reader = _readable.getReader()14+15+ this.responseReadable = new ReadableStream({16+ async pull(controller) {17+ const { done, value } = await reader.read()18+ if (done) {19+ controller.close()20+ } else {21+ controller.enqueue(value)22+ }23+ },24+ cancel: () => {25+ this.abortSubscribers.forEach((subscriber) => subscriber())26+ },27+ })28 }29 30 async write(input: Uint8Array | string) {31 try {28 unmodified lines60 this.writer.releaseLock()61 await body.pipeTo(this.writable, { preventClose: true })62 this.writer = this.writable.getWriter()63 }64+65+ async onAbort(listener: () => void | Promise<void>) {66+ this.abortSubscribers.push(listener)67+ }68 }modified:src/context.test.ts+22 added
340 unmodified lines341 const res = await c.render('<h1>content</h1>', { title: 'title' })342 expect(res.headers.get('foo')).toBe('bar')343 expect(await res.text()).toBe('<html><head>title</head><body><h1>content</h1></body></html>')344 })345+346+ it('c.stream() - with aborted during writing', async () => {347+ let aborted = false348+ const res = c.stream(async (stream) => {349+ stream.onAbort(() => {350+ aborted = true351+ })352+ for (let i = 0; i < 3; i++) {353+ await stream.write(new Uint8Array([i]))354+ await stream.sleep(1)355+ }356+ })357+ if (!res.body) {358+ throw new Error('Body is null')359+ }360+ const reader = res.body.getReader()361+ for (let i = 0; i < 2; i++) {362+ await reader.read()363+ await reader.cancel()364+ }365+ expect(aborted).toBe(true)366+ })367 })modified:src/context.ts+12 added-6 removed
1 unmodified line2 import type { HonoRequest } from './request'3 import type { Env, FetchEventLike, NotFoundHandler, Input, TypedResponse } from './types'4 import type { CookieOptions } from './utils/cookie'5 import { serialize } from './utils/cookie'6-import { resolveStream } from './utils/html'6+import { resolveCallback, HtmlEscapedCallbackPhase } from './utils/html'7 import type { StatusCode } from './utils/http-status'8 import { StreamingApi } from './utils/stream'9 import type { JSONValue, InterfaceToType, JSONParsed } from './utils/types'10 71 unmodified lines82 executionCtx?: FetchEventLike | ExecutionContext | undefined83 notFoundHandler?: NotFoundHandler<E>84 }85 86-const TEXT_PLAIN = 'text/plain; charset=UTF-8'86+export const TEXT_PLAIN = 'text/plain; charset=UTF-8'87 88 export class Context<89 // eslint-disable-next-line @typescript-eslint/no-explicit-any90 E extends Env = any,263 unmodified lines354 html = (html as string).toString() // HtmlEscapedString object to string355 }356 if ((html as string | Promise<string>) instanceof Promise) {357 return (html as unknown as Promise<string>)358- .then((html) => resolveStream(html))358+ .then((html) => resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}))359 .then((html) => {360 return typeof arg === 'number'361 ? this.newResponse(html, arg, headers)362 : this.newResponse(html, arg)11 unmodified lines374 this.#headers.set('Location', location)375 return this.newResponse(null, status)376 }377 378+ /** @deprecated379+ * Use `streamText()` in `hono/streaming` instead of `c.streamText()`. The `c.streamText()` will be removed in v4.380+ */381 streamText = (382 cb: (stream: StreamingApi) => Promise<void>,383 arg?: StatusCode | ResponseInit,384 headers?: HeaderRecord4 unmodified lines389 this.header('transfer-encoding', 'chunked')390 return this.stream(cb, arg, headers)391 }392 393+ /** @deprecated394+ * Use `stream()` in `hono/streaming` instead of `c.stream()`. The `c.stream()` will be removed in v4.395+ */396 stream = (397 cb: (stream: StreamingApi) => Promise<void>,398 arg?: StatusCode | ResponseInit,399 headers?: HeaderRecord400 ): Response => {401 const { readable, writable } = new TransformStream()396- const stream = new StreamingApi(writable)402+ const stream = new StreamingApi(writable, readable)403 cb(stream).finally(() => stream.close())404 405 return typeof arg === 'number'400- ? this.newResponse(readable, arg, headers)401- : this.newResponse(readable, arg)406+ ? this.newResponse(stream.responseReadable, arg, headers)407+ : this.newResponse(stream.responseReadable, arg)408 }409 410 /** @deprecated411 * Use Cookie Middleware instead of `c.cookie()`. The `c.cookie()` will be removed in v4.68 unmodified linesmodified:src/helper.ts+1 added
1 // This file is for Deno to import helpers from `hono/helper.ts`.2 export * from './helper/adapter'3 export * from './helper/cookie'4+export * from './helper/css'5 export * from './helper/factory'6 export * from './helper/html'7 export * from './helper/streaming'8 export * from './helper/testing'1 unmodified linemodified:src/hono-base.ts+5 added
241 unmodified lines242 this.addRoute(METHOD_NAME_ALL, mergePath(path, '*'), handler)243 return this244 }245 246+ /**247+ * @deprecated248+ * `app.routerName()` will be removed in v4.249+ * Use `getRouterName()` in `hono/dev` instead of `app.routerName()`.250+ */251 get routerName() {252 this.matchRoute('GET', '/')253 return this.router.name254 }137 unmodified linesmodified:src/middleware.ts+1 added
3 unmodified lines4 export * from './middleware/cache'5 export * from './helper/cookie' // will be moved to helper.ts in v46 export * from './middleware/compress'7 export * from './middleware/cors'8+export * from './middleware/csrf'9 export * from './middleware/etag'10 export * from './helper/html' // will be moved to helper.ts in v411 export * from './jsx'12 export * from './middleware/jsx-renderer'7 unmodified linesmodified:package.json+17 added-1 removed
92 unmodified lines93 "types": "./dist/types/middleware/cors/index.d.ts",94 "import": "./dist/middleware/cors/index.js",95 "require": "./dist/cjs/middleware/cors/index.js"96 },97+ "./csrf": {98+ "types": "./dist/types/middleware/csrf/index.d.ts",99+ "import": "./dist/middleware/csrf/index.js",100+ "require": "./dist/cjs/middleware/csrf/index.js"101+ },102 "./etag": {103 "types": "./dist/types/middleware/etag/index.d.ts",104 "import": "./dist/middleware/etag/index.js",105 "require": "./dist/cjs/middleware/etag/index.js"2 unmodified lines108 "types": "./dist/types/helper/html/index.d.ts",109 "import": "./dist/helper/html/index.js",110 "require": "./dist/cjs/helper/html/index.js"111 },112+ "./css": {113+ "types": "./dist/types/helper/css/index.d.ts",114+ "import": "./dist/helper/css/index.js",115+ "require": "./dist/cjs/helper/css/index.js"116+ },117 "./jsx": {118 "types": "./dist/types/jsx/index.d.ts",119 "import": "./dist/jsx/index.js",120 "require": "./dist/cjs/jsx/index.js"193 unmodified lines314 ],315 "cors": [316 "./dist/types/middleware/cors"317 ],318+ "csrf": [319+ "./dist/types/middleware/csrf"320+ ],321 "etag": [322 "./dist/types/middleware/etag"323 ],324 "html": [325 "./dist/types/helper/html"326 ],327+ "css": [328+ "./dist/types/helper/css"329+ ],330 "jsx": [331 "./dist/types/jsx"332 ],333 "jsx/jsx-runtime": [157 unmodified lines491 },492 "engines": {493 "node": ">=16.0.0"494 }479-}495+}