Skip to content
Myr

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

62 files+2338 added−332 removed

modified:deno_dist/adapter/deno/serve-static.ts+10 added-7 removed
modified:deno_dist/client/client.ts+3 added
140 unmodified lines
141142 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 }150151 const req = new ClientRequestImpl(url, method)
7 unmodified lines
modified:deno_dist/client/types.ts+7 added-1 removed
added:deno_dist/helper/css/index.ts+306 added
1import { raw } from '../../helper/html/index.ts'2import type { HtmlEscapedCallback, HtmlEscapedString } from '../../utils/html.ts'34const IS_CSS_CLASS_NAME = Symbol('IS_CSS_CLASS_NAME')5const STYLE_STRING = Symbol('STYLE_STRING')6const SELECTORS = Symbol('SELECTORS')7const EXTERNAL_CLASS_NAMES = Symbol('EXTERNAL_CLASS_NAMES')8type 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}1516type CssEscaped = {17 isCssEscaped: true18}19type CssEscapedString = string & CssEscaped2021/**22 * @experimental23 * `rawCssString` is an experimental feature.24 * The API might be changed.25 */26export const rawCssString = (value: string): CssEscapedString => {27 const escapedString = new String(value) as CssEscapedString28 escapedString.isCssEscaped = true29 return escapedString30}3132const DEFAULT_STYLE_ID = 'hono-css'3334/**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 */39const 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}4748const cssStringReStr = [49 '"(?:(?:\\\\[\\s\\S]|[^"\\\\])*)"', // double quoted string50 // eslint-disable-next-line quotes51 "'(?:(?:\\\\[\\s\\S]|[^'\\\\])*)'", // single quoted string52].join('|')53const minifyCssRe = new RegExp(54 [55 '(' + cssStringReStr + ')', // $1: quoted string5657 '(?:' +58 [59 '^\\s+', // head whitespace60 '\\/\\*.*?\\*\\/\\s*', // multi-line comment61 '\\/\\/.*\\n\\s*', // single-line comment62 '\\s+$', // tail whitespace63 ].join('|') +64 ')',6566 ';\\s*(}|$)\\s*', // $2: trailing semicolon67 '\\s*([{};:,])\\s*', // $3: whitespace around { } : , ;68 '(\\s)\\s+', // $4: 2+ spaces69 ].join('|'),70 'g'71)7273const minify = (css: string): string => {74 return css.replace(minifyCssRe, (_, $1, $2, $3, $4) => $1 || $2 || $3 || $4 || '')75}7677type usedClassNameData = [78 Record<string, string>, // class name to add79 Record<string, true> // class name already added80]81// eslint-disable-next-line @typescript-eslint/ban-types82type CssVariableBasicType = string | String | number | boolean | null | undefined83type CssVariableAsyncType = Promise<CssVariableBasicType>84type CssVariableArrayType = (CssVariableBasicType | CssVariableAsyncType)[]85type CssVariableType = CssVariableBasicType | CssVariableAsyncType | CssVariableArrayType8687const 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 }101102 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 }138139 return minify(styleString)140}141142/**143 * @experimental144 * `createCssContext` is an experimental feature.145 * The API might be changed.146 */147export const createCssContext = ({ id }: { id: Readonly<string> }) => {148 const contextMap: WeakMap<object, usedClassNameData> = new WeakMap()149150 const replaceStyleRe = new RegExp(`(<style id="${id}">.*?)(</style>)`)151152 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 CssClassName162163 const appendStyle: HtmlEscapedCallback = ({ buffer, context }): Promise<string> | undefined => {164 const [toAdd, added] = contextMap.get(context) as usedClassNameData165 const names = Object.keys(toAdd)166167 if (!names.length) {168 return169 }170171 let stylesStr = ''172 names.forEach((className) => {173 added[className] = true174 stylesStr += `${className[0] === '@' ? '' : '.'}${className}{${toAdd[className]}}`175 })176 contextMap.set(context, [{}, added])177178 if (buffer && replaceStyleRe.test(buffer[0])) {179 buffer[0] = buffer[0].replace(replaceStyleRe, (_, pre, post) => `${pre}${stylesStr}${post}`)180 return181 }182183 const appendStyleScript = `<script>document.querySelector('#${id}').textContent+=${JSON.stringify(184 stylesStr185 )}</script>`186 if (buffer) {187 buffer[0] = `${appendStyleScript}${buffer[0]}`188 return189 }190191 return Promise.resolve(appendStyleScript)192 }193194 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 }213214 return Promise.resolve(raw('', [appendStyle]))215 }216217 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 })225226 return className as string227 }228229 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 }246247 // eslint-disable-next-line @typescript-eslint/no-explicit-any248 return css(Array(resolvedArgs.length).fill('') as any, ...resolvedArgs)249 }250251 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 }267268 const Style = () => raw(`<style id="${id}"></style>`)269270 return {271 css,272 cx,273 keyframes,274 Style,275 }276}277278const defaultContext = createCssContext({ id: DEFAULT_STYLE_ID })279280/**281 * @experimental282 * `css` is an experimental feature.283 * The API might be changed.284 */285export const css = defaultContext.css286287/**288 * @experimental289 * `cx` is an experimental feature.290 * The API might be changed.291 */292export const cx = defaultContext.cx293294/**295 * @experimental296 * `keyframes` is an experimental feature.297 * The API might be changed.298 */299export const keyframes = defaultContext.keyframes300301/**302 * @experimental303 * `Style` is an experimental feature.304 * The API might be changed.305 */306export const Style = defaultContext.Style
modified:deno_dist/helper/dev/index.ts+8 added-1 removed
2 unmodified lines
3import type { Env, RouterRoute } from '../../types.ts'45interface ShowRoutesOptions {6 verbose?: boolean7 colorize?: boolean8}910interface RouteData {11 path: string
48 unmodified lines
60 return61 }62 const { method, path, routes } = data6364 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}`)6667 if (!opts?.verbose) {68 return69 }
2 unmodified lines
72 console.log(`${' '.repeat(maxMethodLength + 3)} ${name}`)73 })74 })75}7677export 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
1import type { Context } from '../../context.ts'2import { StreamingApi } from '../../utils/stream.ts'34interface SSEMessage {5 data: string6 event?: string7 id?: string8}910class SSEStreamingApi extends StreamingApi {11 constructor(writable: WritableStream) {12 super(writable)13 }1415 async writeSSE(message: SSEMessage) {16 const data = message.data17 .split('\n')18 .map((line) => {19 return `data: ${line}`20 })21 .join('\n')2223 const sseData =24 [message.event && `event: ${message.event}`, data, message.id && `id: ${message.id}`]25 .filter(Boolean)26 .join('\n') + '\n\n'2728 await this.write(sseData)29 }30}3132const 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}3839export 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)4344 originalStream.pipe(readable).catch((err) => {45 console.error('Error in stream piping: ', err)46 stream.close()47 })4849 setSSEHeaders(c)5051 try {52 await cb(stream)53 } catch (err) {54 console.error('Error during streaming: ', err)55 } finally {56 await stream.close()57 }58 })59}1export { stream } from './stream.ts'2export type { SSEMessage } from './sse.ts'3export { streamSSE, SSEStreamingApi } from './sse.ts'4export { streamText } from './text.ts'
added:deno_dist/helper/streaming/sse.ts+60 added
1import type { Context } from '../../context.ts'2import { StreamingApi } from '../../utils/stream.ts'3import { stream } from './index.ts'45export interface SSEMessage {6 data: string7 event?: string8 id?: string9}1011export class SSEStreamingApi extends StreamingApi {12 constructor(writable: WritableStream, readable: ReadableStream) {13 super(writable, readable)14 }1516 async writeSSE(message: SSEMessage) {17 const data = message.data18 .split('\n')19 .map((line) => {20 return `data: ${line}`21 })22 .join('\n')2324 const sseData =25 [message.event && `event: ${message.event}`, data, message.id && `id: ${message.id}`]26 .filter(Boolean)27 .join('\n') + '\n\n'2829 await this.write(sseData)30 }31}3233const 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}3940export 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)4445 originalStream.pipe(stream.responseReadable).catch((err) => {46 console.error('Error in stream piping: ', err)47 stream.close()48 })4950 setSSEHeaders(c)5152 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
added:deno_dist/helper/streaming/text.ts+11 added
modified:deno_dist/jsx/components.ts+29 added-9 removed
1import { raw } from '../helper/html/index.ts'2import type { HtmlEscapedString } from '../utils/html.ts'2import {3 HtmlEscapedCallbackPhase,4 resolveCallback,5 type HtmlEscapedString,6 type HtmlEscapedCallback,7} from '../utils/html.ts'8import type { FC, Child } from './index.ts'910let errorBoundaryCounter = 011
30 unmodified lines
42 if (!Array.isArray(children)) {43 children = [children]44 }4546 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 lines
62 }63 }6465 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 lines
88})(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) => {104c=d.currentScript.previousSibling
20 unmodified lines
125 const callbacks = htmlArray126 .map((html) => (html as HtmlEscapedString).callbacks || [])127 .flat()128129 if (phase === HtmlEscapedCallbackPhase.Stream) {130 html = await resolveCallback(131 html,132 HtmlEscapedCallbackPhase.BeforeStream,133 true,134 context135 )136 }137138 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++145146 if (buffer) {147 if (resolvedCount === callbacks.length) {
36 unmodified lines
modified:deno_dist/jsx/index.ts+3 added
143 unmodified lines
144 throw 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'145 }146147 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 lines
modified:deno_dist/jsx/intrinsic-elements.ts+1 added-1 removed
21 unmodified lines
2223 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 | undefined
576 unmodified lines
modified:deno_dist/jsx/streaming.ts+40 added-16 removed
1import { raw } from '../helper/html/index.ts'2import { HtmlEscapedCallbackPhase, resolveCallback } from '../utils/html.ts'3import type { HtmlEscapedString } from '../utils/html.ts'4import { childrenToString } from './components.ts'5import type { FC, Child } from './index.ts'6
27 unmodified lines
34 }3536 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) => {58c=d.currentScript.previousSibling
2 unmodified lines
61do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')62d.replaceWith(c.content)63})(document)64</script>`59 if (htmlArray.every((html) => !(html as HtmlEscapedString).callbacks?.length)) {6566 const callbacks = htmlArray67 .map((html) => (html as HtmlEscapedString).callbacks || [])68 .flat()69 if (!callbacks.length) {70 return html71 }7263 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 }7677 return raw(html, callbacks)78 })79 },80 ])81 } else {
11 unmodified lines
93 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))106107 let resolvedCount = 0108 const callbacks: Promise<void>[] = []
3 unmodified lines
112 .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 lines
added:deno_dist/middleware/csrf/index.ts+48 added
1import type { Context } from '../../context.ts'2import { HTTPException } from '../../http-exception.ts'3import type { MiddlewareHandler } from '../../types.ts'45type IsAllowedOriginHandler = (origin: string, context: Context) => boolean6interface CSRFOptions {7 origin?: string | string[] | IsAllowedOriginHandler8}910const isSafeMethodRe = /^(GET|HEAD)$/11const isRequestedByFormElementRe =12 /^\b(application\/x-www-form-urlencoded|multipart\/form-data|text\/plain)\b/1314export 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 }3334 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 }4546 await next()47 }48}
modified:deno_dist/utils/html.ts+31 added-7 removed
1type HtmlEscapedCallbackOpts = { error?: Error; buffer?: [string] }2export type HtmlEscapedCallback = (opts: HtmlEscapedCallbackOpts) => Promise<string>1export const HtmlEscapedCallbackPhase = {2 Stringify: 1,3 BeforeStream: 2,4 Stream: 3,5} as const6type 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}11export type HtmlEscapedCallback = (opts: HtmlEscapedCallbackOpts) => Promise<string> | undefined12export type HtmlEscaped = {13 isEscaped: true14 callbacks?: HtmlEscapedCallback[]15}
93 unmodified lines
109110 buffer[0] += str.substring(lastIndex, index)111}112104export const resolveStream = (113export 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])129130 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 )138139 if (preserveCallbacks) {140 return raw(await resStr, callbacks)141 } else {142 return resStr143 }144}
modified:deno_dist/utils/stream.ts+23 added-1 removed
1export class StreamingApi {2 private writer: WritableStreamDefaultWriter<Uint8Array>3 private encoder: TextEncoder4 private writable: WritableStream5 private abortSubscribers: (() => void | Promise<void>)[] = []6 responseReadable: ReadableStream76 constructor(writable: WritableStream) {8 constructor(writable: WritableStream, _readable: ReadableStream) {9 this.writable = writable10 this.writer = writable.getWriter()11 this.encoder = new TextEncoder()1213 const reader = _readable.getReader()1415 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 }2930 async write(input: Uint8Array | string) {31 try {
28 unmodified lines
60 this.writer.releaseLock()61 await body.pipeTo(this.writable, { preventClose: true })62 this.writer = this.writable.getWriter()63 }6465 async onAbort(listener: () => void | Promise<void>) {66 this.abortSubscribers.push(listener)67 }68}
modified:deno_dist/context.ts+12 added-6 removed
1 unmodified line
2import type { HonoRequest } from './request.ts'3import type { Env, FetchEventLike, NotFoundHandler, Input, TypedResponse } from './types.ts'4import type { CookieOptions } from './utils/cookie.ts'5import { serialize } from './utils/cookie.ts'6import { resolveStream } from './utils/html.ts'6import { resolveCallback, HtmlEscapedCallbackPhase } from './utils/html.ts'7import type { StatusCode } from './utils/http-status.ts'8import { StreamingApi } from './utils/stream.ts'9import type { JSONValue, InterfaceToType, JSONParsed } from './utils/types.ts'10
71 unmodified lines
82 executionCtx?: FetchEventLike | ExecutionContext | undefined83 notFoundHandler?: NotFoundHandler<E>84}8586const TEXT_PLAIN = 'text/plain; charset=UTF-8'86export const TEXT_PLAIN = 'text/plain; charset=UTF-8'8788export class Context<89 // eslint-disable-next-line @typescript-eslint/no-explicit-any90 E extends Env = any,
263 unmodified lines
354 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 lines
374 this.#headers.set('Location', location)375 return this.newResponse(null, status)376 }377378 /** @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?: HeaderRecord
4 unmodified lines
389 this.header('transfer-encoding', 'chunked')390 return this.stream(cb, arg, headers)391 }392393 /** @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())404405 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 }409410 /** @deprecated411 * Use Cookie Middleware instead of `c.cookie()`. The `c.cookie()` will be removed in v4.
68 unmodified lines
modified:deno_dist/helper.ts+1 added
1// This file is for Deno to import helpers from `hono/helper.ts`.2export * from './helper/adapter/index.ts'3export * from './helper/cookie/index.ts'4export * from './helper/css/index.ts'5export * from './helper/factory/index.ts'6export * from './helper/html/index.ts'7export * from './helper/streaming/index.ts'8export * from './helper/testing/index.ts'
1 unmodified line
modified:deno_dist/hono-base.ts+5 added
241 unmodified lines
242 this.addRoute(METHOD_NAME_ALL, mergePath(path, '*'), handler)243 return this244 }245246 /**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 lines
modified:deno_dist/middleware.ts+1 added
3 unmodified lines
4export * from './middleware/cache/index.ts'5export * from './helper/cookie/index.ts' // will be moved to helper.ts in v46export * from './middleware/compress/index.ts'7export * from './middleware/cors/index.ts'8export * from './middleware/csrf/index.ts'9export * from './middleware/etag/index.ts'10export * from './helper/html/index.ts' // will be moved to helper.ts in v411export * from './jsx/index.ts'12export * from './middleware/jsx-renderer/index.ts'
7 unmodified lines
modified:runtime_tests/bun/index.test.tsx+11 added-2 removed
1import { describe, expect, it } from 'bun:test'1import { describe, expect, it, mock, beforeEach } from 'bun:test'2import { serveStatic } from '../../src/adapter/bun'3import { Context } from '../../src/context'4import { env, getRuntimeKey } from '../../src/helper/adapter'5import { Hono } from '../../src/index'
69 unmodified lines
75})7677describe('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 line
89 app.get(90 '/static/*',91 serveStatic({92 root: './runtime_tests/bun/',93 onNotFound,94 })95 )96 app.get(97 '/dot-static/*',
2 unmodified lines
100 rewriteRequestPath: (path) => path.replace(/^\/dot-static/, './.static'),101 })102 )103104 beforeEach(() => onNotFound.mockClear())105106 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 lines
113 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 })122123 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 })129130 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 lines
modified:runtime_tests/deno/deps.ts+1 added
1export { assert, assertEquals, assertMatch } from 'https://deno.land/std@0.147.0/testing/asserts.ts'2export { 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 */3import { basicAuth, jsx, Fragment, serveStatic, jwt } from '../../deno_dist/middleware.ts'4import { Hono } from '../../deno_dist/mod.ts'5import { assertEquals, assertMatch } from './deps.ts'5import { assertEquals, assertMatch, assertSpyCall, assertSpyCalls, spy } from './deps.ts'67// Test just only minimal patterns.8// Because others are already tested well in Cloudflare Workers environment.9
55 unmodified lines
65})6667Deno.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 lines
80 app.get(81 '/static/*',82 serveStatic({83 root: './runtime_tests/deno',84 onNotFound,85 })86 )8788 app.get(
12 unmodified lines
101 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)106107 res = await app.request('http://localhost/static/plain.txt')108 assertEquals(res.status, 200)109 assertEquals(await res.text(), 'Deno!')110111 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})116117Deno.test('JWT Authentication middleware', async () => {118 const app = new Hono<{ Variables: { 'x-foo': string } }>()
25 unmodified lines
modified:src/adapter/bun/serve-static.ts+8 added-5 removed
1// @denoify-ignore2/* eslint-disable @typescript-eslint/ban-ts-comment */3import { existsSync } from 'fs'4import type { Context } from '../../context'5import type { Next } from '../../types'5import type { Env, MiddlewareHandler } from '../../types'6import { getFilePath } from '../../utils/filepath'7import { getMimeType } from '../../utils/mime'89// @ts-ignore10const { file } = Bun1112export type ServeStaticOptions = {12export 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}1819const DEFAULT_DOCUMENT = 'index.html'2020export const serveStatic = (options: ServeStaticOptions = { root: '' }) => {21 return async (c: Context, next: Next) => {21export 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 return
22 unmodified lines
51 return c.body(content)52 }53 }5452 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-ignore2export { serveStatic } from './server-static-module'2export { 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 mode5import manifest from '__STATIC_CONTENT_MANIFEST'6import type { Env } from '../../types'7import type { ServeStaticOptions } from './serve-static'8import { serveStatic } from './serve-static'910const module = <E extends Env = Env>(11 options: Omit<ServeStaticOptions<E>, 'namespace'> = { root: '' }12) => {13 options.manifest ??= manifest14 return serveStatic<E>(options)15}1617export { module as serveStatic }
modified:src/adapter/cloudflare-workers/serve-static.test.ts+27 added-1 removed
29 unmodified lines
30})3132describe('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 line
41 rewriteRequestPath: (path) => path.replace(/^\/dot-static/, '/.static'),42 })43 )4445 beforeEach(() => onNotFound.mockClear())4647 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 })5455 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 })6263 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 })6869 it('Should return plan.txt', async () => {70 const res = await app.request('http://localhost/static-no-root/plain.txt')
83 unmodified lines
154 expect(res.status).toBe(200)155 expect(await res.text()).toBe('bar')156 })157})158159describe('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-ignore2import type { KVNamespace } from '@cloudflare/workers-types'3import type { Context } from '../../context'3import type { MiddlewareHandler } from '../../types'4import type { Env, MiddlewareHandler } from '../../types'5import { getFilePath } from '../../utils/filepath'6import { getMimeType } from '../../utils/mime'7import { getContentFromKVAsset } from './utils'88export type ServeStaticOptions = {9export 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}1718const DEFAULT_DOCUMENT = 'index.html'1920// This middleware is available only on Cloudflare Workers.19export const serveStatic = (options: ServeStaticOptions = { root: '' }): MiddlewareHandler => {21export 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 lines
43 // eslint-disable-next-line @typescript-eslint/ban-ts-comment44 // @ts-ignore45 namespace: options.namespace ? options.namespace : c.env ? c.env.__STATIC_CONTENT : undefined,46 })4748 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 }5657 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 mode5import manifest from '__STATIC_CONTENT_MANIFEST'6import type { ServeStaticOptions } from './serve-static'7import { serveStatic } from './serve-static'89const 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}1718export { module as serveStatic }
modified:src/adapter/deno/serve-static.ts+10 added-7 removed
1import type { Context } from '../../context'2import type { Next } from '../../types'2import type { Env, MiddlewareHandler } from '../../types'3import { getFilePath } from '../../utils/filepath'4import { getMimeType } from '../../utils/mime'56// eslint-disable-next-line @typescript-eslint/ban-ts-comment7// @ts-ignore8const { open } = Deno910export type ServeStaticOptions = {10export 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}1617const DEFAULT_DOCUMENT = 'index.html'1818export const serveStatic = (options: ServeStaticOptions = { root: '' }) => {19 return async (c: Context, next: Next) => {19export 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 return
25 unmodified lines
52 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 }5758 await options.onNotFound?.(path, c)59 await next()60 return61 }62}
modified:src/client/client.test.ts+20 added
603 unmodified lines
604 const json = await res.json()605 expectTypeOf(json).toEqualTypeOf<{ data: string } | { message: string }>()606 })607})608609describe('$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')613614 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 })622623 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 lines
141142 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 }150151 const req = new ClientRequestImpl(url, method)
7 unmodified lines
modified:src/client/types.ts+7 added-1 removed
21 unmodified lines
22 : (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}3435// eslint-disable-next-line @typescript-eslint/no-explicit-any36type BlankRecordToNever<T> = T extends any ? (keyof T extends never ? never : T) : never
84 unmodified lines
added:src/helper/css/index.test.tsx+473 added
1import { Hono } from '../../'2import { html } from '../../helper/html'3import { jsx, Fragment, JSXNode } from '../../jsx'4import { Suspense, renderToReadableStream } from '../../jsx/streaming'5import type { HtmlEscapedString } from '../../utils/html'6import { HtmlEscapedCallbackPhase, resolveCallback } from '../../utils/html'7import { css, cx, keyframes, rawCssString, Style, createCssContext } from './index'89async 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}1617async 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}2425describe('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 })4142 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 })5354 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 })7778 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 })9697 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 })112113 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 })128129 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 })144145 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 })160161 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 })179180 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 })195196 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 })223224 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 })240241 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 })258259 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 })281282 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 `291292 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 })302303 it('Should render CSS with cx() includes external class name', async () => {304 const btn = css`305 border-radius: 4px;306 `307308 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 })318319 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 })340341 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 })391392 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 })415416 describe('with application', () => {417 const app = new Hono()418419 const headerClass = css`420 background-color: blue;421 `422423 app.get('/sync', (c) =>424 c.html(425 <>426 <Style />427 <h1 class={headerClass}>Hello!</h1>428 </>429 )430 )431432 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 })448449 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 })456457 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) => {463c=d.currentScript.previousSibling464d=d.getElementById('H:0')465if(!d)return466do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')467d.replaceWith(c.content)468})(document)469</script>`470 )471 })472 })473})
added:src/helper/css/index.ts+306 added
1import { raw } from '../../helper/html'2import type { HtmlEscapedCallback, HtmlEscapedString } from '../../utils/html'34const IS_CSS_CLASS_NAME = Symbol('IS_CSS_CLASS_NAME')5const STYLE_STRING = Symbol('STYLE_STRING')6const SELECTORS = Symbol('SELECTORS')7const EXTERNAL_CLASS_NAMES = Symbol('EXTERNAL_CLASS_NAMES')8type 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}1516type CssEscaped = {17 isCssEscaped: true18}19type CssEscapedString = string & CssEscaped2021/**22 * @experimental23 * `rawCssString` is an experimental feature.24 * The API might be changed.25 */26export const rawCssString = (value: string): CssEscapedString => {27 const escapedString = new String(value) as CssEscapedString28 escapedString.isCssEscaped = true29 return escapedString30}3132const DEFAULT_STYLE_ID = 'hono-css'3334/**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 */39const 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}4748const cssStringReStr = [49 '"(?:(?:\\\\[\\s\\S]|[^"\\\\])*)"', // double quoted string50 // eslint-disable-next-line quotes51 "'(?:(?:\\\\[\\s\\S]|[^'\\\\])*)'", // single quoted string52].join('|')53const minifyCssRe = new RegExp(54 [55 '(' + cssStringReStr + ')', // $1: quoted string5657 '(?:' +58 [59 '^\\s+', // head whitespace60 '\\/\\*.*?\\*\\/\\s*', // multi-line comment61 '\\/\\/.*\\n\\s*', // single-line comment62 '\\s+$', // tail whitespace63 ].join('|') +64 ')',6566 ';\\s*(}|$)\\s*', // $2: trailing semicolon67 '\\s*([{};:,])\\s*', // $3: whitespace around { } : , ;68 '(\\s)\\s+', // $4: 2+ spaces69 ].join('|'),70 'g'71)7273const minify = (css: string): string => {74 return css.replace(minifyCssRe, (_, $1, $2, $3, $4) => $1 || $2 || $3 || $4 || '')75}7677type usedClassNameData = [78 Record<string, string>, // class name to add79 Record<string, true> // class name already added80]81// eslint-disable-next-line @typescript-eslint/ban-types82type CssVariableBasicType = string | String | number | boolean | null | undefined83type CssVariableAsyncType = Promise<CssVariableBasicType>84type CssVariableArrayType = (CssVariableBasicType | CssVariableAsyncType)[]85type CssVariableType = CssVariableBasicType | CssVariableAsyncType | CssVariableArrayType8687const 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 }101102 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 }138139 return minify(styleString)140}141142/**143 * @experimental144 * `createCssContext` is an experimental feature.145 * The API might be changed.146 */147export const createCssContext = ({ id }: { id: Readonly<string> }) => {148 const contextMap: WeakMap<object, usedClassNameData> = new WeakMap()149150 const replaceStyleRe = new RegExp(`(<style id="${id}">.*?)(</style>)`)151152 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 CssClassName162163 const appendStyle: HtmlEscapedCallback = ({ buffer, context }): Promise<string> | undefined => {164 const [toAdd, added] = contextMap.get(context) as usedClassNameData165 const names = Object.keys(toAdd)166167 if (!names.length) {168 return169 }170171 let stylesStr = ''172 names.forEach((className) => {173 added[className] = true174 stylesStr += `${className[0] === '@' ? '' : '.'}${className}{${toAdd[className]}}`175 })176 contextMap.set(context, [{}, added])177178 if (buffer && replaceStyleRe.test(buffer[0])) {179 buffer[0] = buffer[0].replace(replaceStyleRe, (_, pre, post) => `${pre}${stylesStr}${post}`)180 return181 }182183 const appendStyleScript = `<script>document.querySelector('#${id}').textContent+=${JSON.stringify(184 stylesStr185 )}</script>`186 if (buffer) {187 buffer[0] = `${appendStyleScript}${buffer[0]}`188 return189 }190191 return Promise.resolve(appendStyleScript)192 }193194 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 }213214 return Promise.resolve(raw('', [appendStyle]))215 }216217 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 })225226 return className as string227 }228229 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 }246247 // eslint-disable-next-line @typescript-eslint/no-explicit-any248 return css(Array(resolvedArgs.length).fill('') as any, ...resolvedArgs)249 }250251 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 }267268 const Style = () => raw(`<style id="${id}"></style>`)269270 return {271 css,272 cx,273 keyframes,274 Style,275 }276}277278const defaultContext = createCssContext({ id: DEFAULT_STYLE_ID })279280/**281 * @experimental282 * `css` is an experimental feature.283 * The API might be changed.284 */285export const css = defaultContext.css286287/**288 * @experimental289 * `cx` is an experimental feature.290 * The API might be changed.291 */292export const cx = defaultContext.cx293294/**295 * @experimental296 * `keyframes` is an experimental feature.297 * The API might be changed.298 */299export const keyframes = defaultContext.keyframes300301/**302 * @experimental303 * `Style` is an experimental feature.304 * The API might be changed.305 */306export const Style = defaultContext.Style
modified:src/helper/dev/index.test.ts+25 added-1 removed
1import { Hono } from '../../hono'2import { RegExpRouter } from '../../router/reg-exp-router'3import type { Handler, MiddlewareHandler } from '../../types'3import { inspectRoutes, showRoutes } from '.'4import { inspectRoutes, showRoutes, getRouterName } from '.'56const namedMiddleware: MiddlewareHandler = (_, next) => next()7const namedHandler: Handler = (c) => c.text('hi')8const app = new Hono()
100 unmodified lines
109 '\x1b[32mGET\x1b[0m /static',110 ' [handler]',111 ])112 })113114 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})128129describe('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 lines
3import type { Env, RouterRoute } from '../../types'45interface ShowRoutesOptions {6 verbose?: boolean7 colorize?: boolean8}910interface RouteData {11 path: string
48 unmodified lines
60 return61 }62 const { method, path, routes } = data6364 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}`)6667 if (!opts?.verbose) {68 return69 }
2 unmodified lines
72 console.log(`${' '.repeat(maxMethodLength + 3)} ${name}`)73 })74 })75}7677export 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
1import { Hono } from '../../hono'2import { streamSSE } from '.'34describe('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 = 51112 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 })1920 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')2728 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)3637 // 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
1import type { Context } from '../../context'2import { StreamingApi } from '../../utils/stream'34interface SSEMessage {5 data: string6 event?: string7 id?: string8}910class SSEStreamingApi extends StreamingApi {11 constructor(writable: WritableStream) {12 super(writable)13 }1415 async writeSSE(message: SSEMessage) {16 const data = message.data17 .split('\n')18 .map((line) => {19 return `data: ${line}`20 })21 .join('\n')2223 const sseData =24 [message.event && `event: ${message.event}`, data, message.id && `id: ${message.id}`]25 .filter(Boolean)26 .join('\n') + '\n\n'2728 await this.write(sseData)29 }30}3132const 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}3839export 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)4344 originalStream.pipe(readable).catch((err) => {45 console.error('Error in stream piping: ', err)46 stream.close()47 })4849 setSSEHeaders(c)5051 try {52 await cb(stream)53 } catch (err) {54 console.error('Error during streaming: ', err)55 } finally {56 await stream.close()57 }58 })59}1export { stream } from './stream'2export type { SSEMessage } from './sse'3export { streamSSE, SSEStreamingApi } from './sse'4export { streamText } from './text'
added:src/helper/streaming/sse.test.ts+48 added
1import { Context } from '../../context'2import { HonoRequest } from '../../request'3import { streamSSE } from '.'45describe('SSE Streaming helper', () => {6 const req = new HonoRequest(new Request('http://localhost/'))7 let c: Context8 beforeEach(() => {9 c = new Context(req)10 })1112 it('Check streamSSE Response', async () => {13 const res = streamSSE(c, async (stream) => {14 let id = 015 const maxIterations = 51617 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 })2324 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')3031 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)3940 // 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
1import type { Context } from '../../context'2import { StreamingApi } from '../../utils/stream'3import { stream } from '.'45export interface SSEMessage {6 data: string7 event?: string8 id?: string9}1011export class SSEStreamingApi extends StreamingApi {12 constructor(writable: WritableStream, readable: ReadableStream) {13 super(writable, readable)14 }1516 async writeSSE(message: SSEMessage) {17 const data = message.data18 .split('\n')19 .map((line) => {20 return `data: ${line}`21 })22 .join('\n')2324 const sseData =25 [message.event && `event: ${message.event}`, data, message.id && `id: ${message.id}`]26 .filter(Boolean)27 .join('\n') + '\n\n'2829 await this.write(sseData)30 }31}3233const 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}3940export 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)4445 originalStream.pipe(stream.responseReadable).catch((err) => {46 console.error('Error in stream piping: ', err)47 stream.close()48 })4950 setSSEHeaders(c)5152 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
1import { Context } from '../../context'2import { HonoRequest } from '../../request'3import { stream } from '.'45describe('Basic Streaming Helper', () => {6 const req = new HonoRequest(new Request('http://localhost/'))7 let c: Context8 beforeEach(() => {9 c = new Context(req)10 })1112 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
1import type { Context } from '../../context'2import { StreamingApi } from '../../utils/stream'34export 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
1import { Context } from '../../context'2import { HonoRequest } from '../../request'3import { streamText } from '.'45describe('Text Streaming Helper', () => {6 const req = new HonoRequest(new Request('http://localhost/'))7 let c: Context8 beforeEach(() => {9 c = new Context(req)10 })1112 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 })1920 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')2425 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
1import type { Context } from '../../context'2import { TEXT_PLAIN } from '../../context'3import type { StreamingApi } from '../../utils/stream'4import { stream } from '.'56export 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
1import { JSDOM } from 'jsdom'2import { resolveStream } from '../utils/html'2import type { HtmlEscapedString } from '../utils/html'3import { HtmlEscapedCallbackPhase, resolveCallback as rawResolveCallback } from '../utils/html'4import { ErrorBoundary } from './components'5import { Suspense, renderToReadableStream } from './streaming'6// eslint-disable-next-line @typescript-eslint/no-unused-vars6import { jsx, Fragment } from './index'7import { jsx } from './index'89function resolveCallback(template: string | HtmlEscapedString) {10 return rawResolveCallback(template, HtmlEscapedCallbackPhase.Stream, false, {})11}1213function 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.innerHTML
23 unmodified lines
40 <Component />41 </ErrorBoundary>42 )4339 expect((await resolveStream(await html.toString())).toString()).toEqual('<div>Hello</div>')44 expect((await resolveCallback(await html.toString())).toString()).toEqual('<div>Hello</div>')4546 errorBoundaryCounter--47 suspenseCounter--48 })
4 unmodified lines
53 <Component error={true} />54 </ErrorBoundary>55 )5652 expect((await resolveStream(await html.toString())).toString()).toEqual(57 expect((await resolveCallback(await html.toString())).toString()).toEqual(58 '<div>Out Of Service</div>'59 )6061 suspenseCounter--
15 unmodified lines
77 <Component />78 </ErrorBoundary>79 )8076 expect((await resolveStream(await html.toString())).toString()).toEqual('<div>Hello</div>')81 expect((await resolveCallback(await html.toString())).toString()).toEqual('<div>Hello</div>')8283 errorBoundaryCounter--84 suspenseCounter--85 })
4 unmodified lines
90 <Component error={true} />91 </ErrorBoundary>92 )9389 expect((await resolveStream(await html.toString())).toString()).toEqual(94 expect((await resolveCallback(await html.toString())).toString()).toEqual(95 '<div>Out Of Service</div>'96 )9798 suspenseCounter--
18 unmodified lines
117 ).toString()118119 Object.values(handlers).forEach(({ resolve }) => resolve(undefined))120116 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>')122123 errorBoundaryCounter++124 suspenseCounter--125 })
10 unmodified lines
136137 handlers[2].resolve(undefined)138 handlers[1].reject()139135 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>')141142 errorBoundaryCounter++143 suspenseCounter--144 })
10 unmodified lines
155156 handlers[1].resolve(undefined)157 handlers[2].reject()158154 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 )162163 errorBoundaryCounter++
65 unmodified lines
229 <Component error={true} />230 </ErrorBoundary>231 )232228 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 lines
408 <Component />409 </ErrorBoundary>410 )411407 expect((await resolveStream(await html.toString())).toString()).toEqual('<div>Hello</div>')412 expect((await resolveCallback(await html.toString())).toString()).toEqual('<div>Hello</div>')413414 errorBoundaryCounter--415 suspenseCounter--416
7 unmodified lines
424 <Component error={true} />425 </ErrorBoundary>426 )427423 expect((await resolveStream(await html.toString())).toString()).toEqual(428 expect((await resolveCallback(await html.toString())).toString()).toEqual(429 '<div>Out Of Service</div>'430 )431432 suspenseCounter--
18 unmodified lines
451 <Component />452 </ErrorBoundary>453 )454450 expect((await resolveStream(await html.toString())).toString()).toEqual('<div>Hello</div>')455 expect((await resolveCallback(await html.toString())).toString()).toEqual('<div>Hello</div>')456457 errorBoundaryCounter--458 suspenseCounter--459
6 unmodified lines
466 <Component error={true} />467 </ErrorBoundary>468 )469465 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 )473474 suspenseCounter--
3 unmodified lines
modified:src/jsx/components.ts+29 added-9 removed
1import { raw } from '../helper/html'2import type { HtmlEscapedString } from '../utils/html'2import {3 HtmlEscapedCallbackPhase,4 resolveCallback,5 type HtmlEscapedString,6 type HtmlEscapedCallback,7} from '../utils/html'8import type { FC, Child } from './index'910let errorBoundaryCounter = 011
30 unmodified lines
42 if (!Array.isArray(children)) {43 children = [children]44 }4546 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 lines
62 }63 }6465 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 lines
88})(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) => {104c=d.currentScript.previousSibling
20 unmodified lines
125 const callbacks = htmlArray126 .map((html) => (html as HtmlEscapedString).callbacks || [])127 .flat()128129 if (phase === HtmlEscapedCallbackPhase.Stream) {130 html = await resolveCallback(131 html,132 HtmlEscapedCallbackPhase.BeforeStream,133 true,134 context135 )136 }137138 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++145146 if (buffer) {147 if (resolvedCount === callbacks.length) {
36 unmodified lines
modified:src/jsx/index.ts+3 added
143 unmodified lines
144 throw 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'145 }146147 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 lines
modified:src/jsx/intrinsic-elements.ts+1 added-1 removed
21 unmodified lines
2223 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 | undefined
576 unmodified lines
modified:src/jsx/streaming.test.tsx+11 added-6 removed
1import { JSDOM } from 'jsdom'2import { raw } from '../helper/html'3import { resolveStream } from '../utils/html'3import { HtmlEscapedCallbackPhase, resolveCallback } from '../utils/html'4import type { HtmlEscapedString } from '../utils/html'5import { Suspense, renderToReadableStream } from './streaming'6// eslint-disable-next-line @typescript-eslint/no-unused-vars7import { jsx, Fragment } from './index'
510 unmodified lines
518 )519 return content520 }521522 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 )532533 expect(str).toEqual('<h1>Hello</h1>')534 expect(contentEvaluatedCount).toEqual(1)535 })
26 unmodified lines
modified:src/jsx/streaming.ts+40 added-16 removed
1import { raw } from '../helper/html'2import { HtmlEscapedCallbackPhase, resolveCallback } from '../utils/html'3import type { HtmlEscapedString } from '../utils/html'4import { childrenToString } from './components'5import type { FC, Child } from './index'6
27 unmodified lines
34 }3536 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) => {58c=d.currentScript.previousSibling
2 unmodified lines
61do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')62d.replaceWith(c.content)63})(document)64</script>`59 if (htmlArray.every((html) => !(html as HtmlEscapedString).callbacks?.length)) {6566 const callbacks = htmlArray67 .map((html) => (html as HtmlEscapedString).callbacks || [])68 .flat()69 if (!callbacks.length) {70 return html71 }7263 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 }7677 return raw(html, callbacks)78 })79 },80 ])81 } else {
11 unmodified lines
93 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))106107 let resolvedCount = 0108 const callbacks: Promise<void>[] = []
3 unmodified lines
112 .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 lines
added:src/middleware/csrf/index.test.ts+306 added
1import type { Context } from '../../context'2import { Hono } from '../../hono'3import { csrf } from '../../middleware/csrf'45const 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})1314const 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})2425describe('CSRF by Middleware', () => {26 beforeEach(() => {27 simplePostHandler.mockClear()28 })2930 describe('simple usage', () => {31 const app = new Hono()3233 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'))3940 describe('GET /form', async () => {41 it('should be 200 for any request', async () => {42 const res = await app.request('http://localhost/form')4344 expect(res.status).toBe(200)45 expect(await res.text()).toBe('<form></form>')46 })47 })4849 describe('HEAD /form', async () => {50 it('should be 200 for any request', async () => {51 const res = await app.request('http://localhost/form', { method: 'HEAD' })5253 expect(res.status).toBe(200)54 })55 })5657 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 )7677 expect(res.status).toBe(200)78 expect(await res.text()).toBe('hono')79 })8081 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 )103104 expect(res.status).toBe(403)105 expect(simplePostHandler).not.toHaveBeenCalled()106 })107 })108109 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 )131132 expect(res.status).toBe(403)133 expect(simplePostHandler).not.toHaveBeenCalled()134 })135136 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 )158159 expect(res.status).toBe(403)160 expect(simplePostHandler).not.toHaveBeenCalled()161 })162163 it('should be 403 if request has no origin header', async () => {164 const res = await app.request('http://localhost/form', buildSimplePostRequestData())165166 expect(res.status).toBe(403)167 expect(simplePostHandler).not.toHaveBeenCalled()168 })169170 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 })193194 expect(res.status).toBe(200)195 expect(await res.text()).toBe('hono')196 })197 })198199 describe('with origin option', () => {200 describe('string', () => {201 const app = new Hono()202203 app.use(204 '*',205 csrf({206 origin: 'https://example.com',207 })208 )209 app.post('/form', simplePostHandler)210211 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 })218219 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 })228229 describe('string[]', () => {230 const app = new Hono()231232 app.use(233 '*',234 csrf({235 origin: ['https://example.com', 'https://hono.example.com'],236 })237 )238 app.post('/form', simplePostHandler)239240 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)246247 res = await app.request(248 'https://example.com/form',249 buildSimplePostRequestData('https://example.com')250 )251 expect(res.status).toBe(200)252 })253254 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 })263264 describe('IsAllowedOriginHandler', () => {265 const app = new Hono()266267 app.use(268 '*',269 csrf({270 origin: (origin) => /https:\/\/(\w+\.)?example\.com$/.test(origin),271 })272 )273 app.post('/form', simplePostHandler)274275 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)281282 res = await app.request(283 'https://example.com/form',284 buildSimplePostRequestData('https://example.com')285 )286 expect(res.status).toBe(200)287 })288289 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()296297 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
1import type { Context } from '../../context'2import { HTTPException } from '../../http-exception'3import type { MiddlewareHandler } from '../../types'45type IsAllowedOriginHandler = (origin: string, context: Context) => boolean6interface CSRFOptions {7 origin?: string | string[] | IsAllowedOriginHandler8}910const isSafeMethodRe = /^(GET|HEAD)$/11const isRequestedByFormElementRe =12 /^\b(application\/x-www-form-urlencoded|multipart\/form-data|text\/plain)\b/1314export 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 }3334 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 }4546 await next()47 }48}
modified:src/utils/html.ts+31 added-7 removed
1type HtmlEscapedCallbackOpts = { error?: Error; buffer?: [string] }2export type HtmlEscapedCallback = (opts: HtmlEscapedCallbackOpts) => Promise<string>1export const HtmlEscapedCallbackPhase = {2 Stringify: 1,3 BeforeStream: 2,4 Stream: 3,5} as const6type 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}11export type HtmlEscapedCallback = (opts: HtmlEscapedCallbackOpts) => Promise<string> | undefined12export type HtmlEscaped = {13 isEscaped: true14 callbacks?: HtmlEscapedCallback[]15}
93 unmodified lines
109110 buffer[0] += str.substring(lastIndex, index)111}112104export const resolveStream = (113export 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])129130 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 )138139 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 line
23describe('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 })1314 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 })2324 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 lines
43 })()4445 const { readable: receiverReadable, writable: receiverWritable } = new TransformStream()4647 const api = new StreamingApi(receiverWritable)47 const api = new StreamingApi(receiverWritable, receiverReadable)4849 // pipe readable to api in other scope50 ;(async () => {51 await api.pipe(senderReadable)52 })()5354 // 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 })5960 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 })6768 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 })7576 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 })8586 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
1export class StreamingApi {2 private writer: WritableStreamDefaultWriter<Uint8Array>3 private encoder: TextEncoder4 private writable: WritableStream5 private abortSubscribers: (() => void | Promise<void>)[] = []6 responseReadable: ReadableStream76 constructor(writable: WritableStream) {8 constructor(writable: WritableStream, _readable: ReadableStream) {9 this.writable = writable10 this.writer = writable.getWriter()11 this.encoder = new TextEncoder()1213 const reader = _readable.getReader()1415 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 }2930 async write(input: Uint8Array | string) {31 try {
28 unmodified lines
60 this.writer.releaseLock()61 await body.pipeTo(this.writable, { preventClose: true })62 this.writer = this.writable.getWriter()63 }6465 async onAbort(listener: () => void | Promise<void>) {66 this.abortSubscribers.push(listener)67 }68}
modified:src/context.test.ts+22 added
340 unmodified lines
341 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 })345346 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 line
2import type { HonoRequest } from './request'3import type { Env, FetchEventLike, NotFoundHandler, Input, TypedResponse } from './types'4import type { CookieOptions } from './utils/cookie'5import { serialize } from './utils/cookie'6import { resolveStream } from './utils/html'6import { resolveCallback, HtmlEscapedCallbackPhase } from './utils/html'7import type { StatusCode } from './utils/http-status'8import { StreamingApi } from './utils/stream'9import type { JSONValue, InterfaceToType, JSONParsed } from './utils/types'10
71 unmodified lines
82 executionCtx?: FetchEventLike | ExecutionContext | undefined83 notFoundHandler?: NotFoundHandler<E>84}8586const TEXT_PLAIN = 'text/plain; charset=UTF-8'86export const TEXT_PLAIN = 'text/plain; charset=UTF-8'8788export class Context<89 // eslint-disable-next-line @typescript-eslint/no-explicit-any90 E extends Env = any,
263 unmodified lines
354 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 lines
374 this.#headers.set('Location', location)375 return this.newResponse(null, status)376 }377378 /** @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?: HeaderRecord
4 unmodified lines
389 this.header('transfer-encoding', 'chunked')390 return this.stream(cb, arg, headers)391 }392393 /** @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())404405 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 }409410 /** @deprecated411 * Use Cookie Middleware instead of `c.cookie()`. The `c.cookie()` will be removed in v4.
68 unmodified lines
modified:src/helper.ts+1 added
1// This file is for Deno to import helpers from `hono/helper.ts`.2export * from './helper/adapter'3export * from './helper/cookie'4export * from './helper/css'5export * from './helper/factory'6export * from './helper/html'7export * from './helper/streaming'8export * from './helper/testing'
1 unmodified line
modified:src/hono-base.ts+5 added
241 unmodified lines
242 this.addRoute(METHOD_NAME_ALL, mergePath(path, '*'), handler)243 return this244 }245246 /**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 lines
modified:src/middleware.ts+1 added
3 unmodified lines
4export * from './middleware/cache'5export * from './helper/cookie' // will be moved to helper.ts in v46export * from './middleware/compress'7export * from './middleware/cors'8export * from './middleware/csrf'9export * from './middleware/etag'10export * from './helper/html' // will be moved to helper.ts in v411export * from './jsx'12export * from './middleware/jsx-renderer'
7 unmodified lines
modified:package.json+17 added-1 removed
92 unmodified lines
93 "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 lines
108 "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 lines
314 ],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 lines
491 },492 "engines": {493 "node": ">=16.0.0"494 }479}495}