Skip to content
Myr

Merge pull request #2327 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 4ca5f60, 6eaa696 · Browse files · 68 files+3369 added−1160 removed
This commit

State

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

Diff stats

68 files+3369 added−1160 removed

  • tests:+1336 added−478 removed
  • other:+2033 added−682 removed

68 files+3369 added−1160 removed

modified:deno_dist/adapter/deno/deno.d.ts+5 added
modified:deno_dist/adapter/deno/index.ts+1 added
added:deno_dist/adapter/deno/websocket.ts+30 added
modified:deno_dist/client/client.ts+5 added
modified:deno_dist/client/types.ts+8 added
1import type { UpgradedWebSocketResponseInputJSONType } from '../helper/websocket/index.ts'2import type { Hono } from '../hono.ts'3import type { Schema } from '../types.ts'4import type { HasRequiredKeys } from '../utils/types.ts'5
24 unmodified lines
30 ? { param: P }31 : {}32 : {}33 ) => URL34} & {35 // WebSocket36 $ws: S['$get'] extends { input: { json: UpgradedWebSocketResponseInputJSONType } }37 ? S['$get'] extends { input: infer I }38 ? (args?: Omit<I, 'json'>) => WebSocket39 : never40 : never41}4243// eslint-disable-next-line @typescript-eslint/no-explicit-any44type BlankRecordToNever<T> = T extends any ? (keyof T extends never ? never : T) : never
84 unmodified lines
modified:deno_dist/helper/cookie/index.ts+65 added-9 removed
1import type { Context } from '../../context.ts'2import { parse, parseSigned, serialize, serializeSigned } from '../../utils/cookie.ts'3import type { CookieOptions, Cookie, SignedCookie } from '../../utils/cookie.ts'3import type { CookieOptions, Cookie, SignedCookie, CookiePrefixOptions } from '../../utils/cookie.ts'45interface GetCookie {6 (c: Context, key: string): string | undefined7 (c: Context): Cookie8 (c: Context, key: string, prefixOptions: CookiePrefixOptions): string | undefined9}1011interface GetSignedCookie {12 (c: Context, secret: string | BufferSource, key: string): Promise<string | undefined | false>13 (c: Context, secret: string): Promise<SignedCookie>14 (15 c: Context,16 secret: string | BufferSource,17 key: string,18 prefixOptions: CookiePrefixOptions19 ): Promise<string | undefined | false>20}2115export const getCookie: GetCookie = (c, key?) => {22export const getCookie: GetCookie = (c, key?, prefix?: CookiePrefixOptions) => {23 const cookie = c.req.raw.headers.get('Cookie')24 if (typeof key === 'string') {25 if (!cookie) {26 return undefined27 }28 let finalKey = key29 if (prefix === 'secure') {30 finalKey = '__Secure-' + key31 } else if (prefix === 'host') {32 finalKey = '__Host-' + key33 }21 const obj = parse(cookie, key)22 return obj[key]34 const obj = parse(cookie, finalKey)35 return obj[finalKey]36 }37 if (!cookie) {38 return {}39 }
1 unmodified line
41 // eslint-disable-next-line @typescript-eslint/no-explicit-any42 return obj as any43}4432export const getSignedCookie: GetSignedCookie = async (c, secret, key?) => {45export const getSignedCookie: GetSignedCookie = async (46 c,47 secret,48 key?,49 prefix?: CookiePrefixOptions50) => {51 const cookie = c.req.raw.headers.get('Cookie')52 if (typeof key === 'string') {53 if (!cookie) {54 return undefined55 }56 let finalKey = key57 if (prefix === 'secure') {58 finalKey = '__Secure-' + key59 } else if (prefix === 'host') {60 finalKey = '__Host-' + key61 }38 const obj = await parseSigned(cookie, secret, key)39 return obj[key]62 const obj = await parseSigned(cookie, secret, finalKey)63 return obj[finalKey]64 }65 if (!cookie) {66 return {}67 }
2 unmodified lines
70 return obj as any71}7273export const setCookie = (c: Context, name: string, value: string, opt?: CookieOptions): void => {74 // Cookie names prefixed with __Secure- can be used only if they are set with the secure attribute.75 // Cookie names prefixed with __Host- can be used only if they are set with the secure attribute, must have a path of / (meaning any path at the host)76 // and must not have a Domain attribute.77 // Read more at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie_prefixes'78 let cookie79 if (opt?.prefix === 'secure') {80 cookie = serialize('__Secure-' + name, value, { path: '/', ...opt, secure: true })81 } else if (opt?.prefix === 'host') {82 cookie = serialize('__Host-' + name, value, {83 ...opt,84 path: '/',85 secure: true,86 domain: undefined,87 })88 } else {50 const cookie = serialize(name, value, { path: '/', ...opt })89 cookie = serialize(name, value, { path: '/', ...opt })90 }91 c.header('set-cookie', cookie, { append: true })92}9394export const setSignedCookie = async (
2 unmodified lines
97 value: string,98 secret: string | BufferSource,99 opt?: CookieOptions100): Promise<void> => {101 let cookie102 if (opt?.prefix === 'secure') {103 cookie = await serializeSigned('__Secure-' + name, value, secret, {104 path: '/',105 ...opt,106 secure: true,107 })108 } else if (opt?.prefix === 'host') {109 cookie = await serializeSigned('__Host-' + name, value, secret, {110 ...opt,111 path: '/',112 secure: true,113 domain: undefined,114 })115 } else {61 const cookie = await serializeSigned(name, value, secret, { path: '/', ...opt })116 cookie = await serializeSigned(name, value, secret, { path: '/', ...opt })117 }118 c.header('set-cookie', cookie, { append: true })119}120121export const deleteCookie = (c: Context, name: string, opt?: CookieOptions): void => {
2 unmodified lines
modified:deno_dist/helper/dev/index.ts+2 added-10 removed
1import type { Hono } from '../../hono.ts'2import type { Env, RouterRoute } from '../../types.ts'3import { getColorEnabled } from '../../utils/color.ts'4import { findTargetHandler, isMiddleware } from '../../utils/handler.ts'56interface ShowRoutesOptions {7 verbose?: boolean
23 unmodified lines
31 })32}3334export const showRoutes = <E extends Env>(hono: Hono<E>, opts?: ShowRoutesOptions) => {34 // eslint-disable-next-line @typescript-eslint/no-explicit-any35 const { process, Deno } = globalThis as any36 const isNoColor =37 typeof process !== 'undefined'38 ? // eslint-disable-next-line no-unsafe-optional-chaining39 'NO_COLOR' in process?.env40 : typeof Deno?.noColor === 'boolean'41 ? (Deno.noColor as boolean)42 : false43 const colorEnabled = opts?.colorize ?? !isNoColor35 const colorEnabled = opts?.colorize ?? getColorEnabled()36 const routeData: Record<string, RouteData[]> = {}37 let maxMethodLength = 038 let maxPathLength = 039
35 unmodified lines
modified:deno_dist/helper/ssg/index.ts+2 added-294 removed
1import { replaceUrlParam } from '../../client/utils.ts'2import type { Context } from '../../context.ts'3import type { Hono } from '../../hono.ts'4import type { Env, MiddlewareHandler, Schema } from '../../types.ts'5import { getExtension } from '../../utils/mime.ts'6import { joinPaths, dirname, filterStaticGenerateRoutes } from './utils.ts'78const SSG_CONTEXT = 'HONO_SSG_CONTEXT'9export const SSG_DISABLED_RESPONSE = new Response('SSG is disabled', { status: 404 })1011/**12 * @experimental13 * `FileSystemModule` is an experimental feature.14 * The API might be changed.15 */16export interface FileSystemModule {17 writeFile(path: string, data: string | Uint8Array): Promise<void>18 mkdir(path: string, options: { recursive: boolean }): Promise<void | string>19}2021/**22 * @experimental23 * `ToSSGResult` is an experimental feature.24 * The API might be changed.25 */26export interface ToSSGResult {27 success: boolean28 files: string[]29 error?: Error30}3132const generateFilePath = (routePath: string, outDir: string, mimeType: string) => {33 const extension = determineExtension(mimeType)3435 if (routePath.endsWith(`.${extension}`)) {36 return joinPaths(outDir, routePath)37 }3839 if (routePath === '/') {40 return joinPaths(outDir, `index.${extension}`)41 }42 if (routePath.endsWith('/')) {43 return joinPaths(outDir, routePath, `index.${extension}`)44 }45 return joinPaths(outDir, `${routePath}.${extension}`)46}4748const parseResponseContent = async (response: Response): Promise<string | ArrayBuffer> => {49 const contentType = response.headers.get('Content-Type')5051 try {52 if (contentType?.includes('text') || contentType?.includes('json')) {53 return await response.text()54 } else {55 return await response.arrayBuffer()56 }57 } catch (error) {58 throw new Error(59 `Error processing response: ${error instanceof Error ? error.message : 'Unknown error'}`60 )61 }62}6364const determineExtension = (mimeType: string): string => {65 switch (mimeType) {66 case 'text/html':67 return 'html'68 case 'text/xml':69 case 'application/xml':70 return 'xml'71 default: {72 return getExtension(mimeType) || 'html'73 }74 }75}7677interface SSGParam {78 [key: string]: string79}80type SSGParams = SSGParam[]8182interface SSGParamsMiddleware {83 <E extends Env = Env>(84 generateParams: (c: Context<E>) => SSGParams | Promise<SSGParams>85 ): MiddlewareHandler<E>86 <E extends Env = Env>(params: SSGParams): MiddlewareHandler<E>87}8889type AddedSSGDataRequest = Request & {90 ssgParams?: SSGParams91}92/**93 * Define SSG Route94 */95export const ssgParams: SSGParamsMiddleware = (params) => async (c, next) => {96 ;(c.req.raw as AddedSSGDataRequest).ssgParams = Array.isArray(params) ? params : await params(c)97 await next()98}99100export type BeforeRequestHook = (req: Request) => Request | false101export type AfterResponseHook = (res: Response) => Response | false102export type AfterGenerateHook = (result: ToSSGResult) => void | Promise<void>103104export interface ToSSGOptions {105 dir?: string106 beforeRequestHook?: BeforeRequestHook107 afterResponseHook?: AfterResponseHook108 afterGenerateHook?: AfterGenerateHook109}110111/**112 * @experimental113 * `fetchRoutesContent` is an experimental feature.114 * The API might be changed.115 */116export const fetchRoutesContent = async <117 E extends Env = Env,118 S extends Schema = {},119 BasePath extends string = '/'120>(121 app: Hono<E, S, BasePath>,122 beforeRequestHook?: BeforeRequestHook,123 afterResponseHook?: AfterResponseHook124): Promise<Map<string, { content: string | ArrayBuffer; mimeType: string }>> => {125 const htmlMap = new Map<string, { content: string | ArrayBuffer; mimeType: string }>()126 const baseURL = 'http://localhost'127128 for (const route of filterStaticGenerateRoutes(app)) {129 // GET Route Info130 const thisRouteBaseURL = new URL(route.path, baseURL).toString()131132 let forGetInfoURLRequest = new Request(thisRouteBaseURL) as AddedSSGDataRequest133 if (beforeRequestHook) {134 const maybeRequest = beforeRequestHook(forGetInfoURLRequest)135 if (!maybeRequest) {136 continue137 }138 forGetInfoURLRequest = maybeRequest as unknown as AddedSSGDataRequest139 }140 await app.fetch(forGetInfoURLRequest)141142 if (!forGetInfoURLRequest.ssgParams) {143 if (isDynamicRoute(route.path)) {144 continue145 }146 forGetInfoURLRequest.ssgParams = [{}]147 }148149 const requestInit = {150 method: forGetInfoURLRequest.method,151 headers: forGetInfoURLRequest.headers,152 }153 for (const param of forGetInfoURLRequest.ssgParams) {154 const replacedUrlParam = replaceUrlParam(route.path, param)155 let response = await app.request(replacedUrlParam, requestInit, {156 [SSG_CONTEXT]: true,157 })158 if (response === SSG_DISABLED_RESPONSE) {159 continue160 }161 if (afterResponseHook) {162 const maybeResponse = afterResponseHook(response)163 if (!maybeResponse) {164 continue165 }166 response = maybeResponse167 }168 const mimeType = response.headers.get('Content-Type')?.split(';')[0] || 'text/plain'169 const content = await parseResponseContent(response)170 htmlMap.set(replacedUrlParam, {171 mimeType,172 content,173 })174 }175 }176177 return htmlMap178}179180const isDynamicRoute = (path: string): boolean => {181 return path.split('/').some((segment) => segment.startsWith(':') || segment.includes('*'))182}183184/**185 * @experimental186 * `saveContentToFiles` is an experimental feature.187 * The API might be changed.188 */189export const saveContentToFiles = async (190 htmlMap: Map<string, { content: string | ArrayBuffer; mimeType: string }>,191 fsModule: FileSystemModule,192 outDir: string193): Promise<string[]> => {194 const files: string[] = []195196 for (const [routePath, { content, mimeType }] of htmlMap) {197 const filePath = generateFilePath(routePath, outDir, mimeType)198 const dirPath = dirname(filePath)199200 await fsModule.mkdir(dirPath, { recursive: true })201 if (typeof content === 'string') {202 await fsModule.writeFile(filePath, content)203 } else if (content instanceof ArrayBuffer) {204 await fsModule.writeFile(filePath, new Uint8Array(content))205 }206 files.push(filePath)207 }208209 return files210}211212/**213 * @experimental214 * `ToSSGInterface` is an experimental feature.215 * The API might be changed.216 */217export interface ToSSGInterface {218 (219 // eslint-disable-next-line @typescript-eslint/no-explicit-any220 app: Hono<any, any, any>,221 fsModule: FileSystemModule,222 options?: ToSSGOptions223 ): Promise<ToSSGResult>224}225226/**227 * @experimental228 * `ToSSGAdaptorInterface` is an experimental feature.229 * The API might be changed.230 */231export interface ToSSGAdaptorInterface<232 E extends Env = Env,233 S extends Schema = {},234 BasePath extends string = '/'235> {236 (app: Hono<E, S, BasePath>, options?: ToSSGOptions): Promise<ToSSGResult>237}238239/**240 * @experimental241 * `toSSG` is an experimental feature.242 * The API might be changed.243 */244export const toSSG: ToSSGInterface = async (app, fs, options) => {245 let result: ToSSGResult | undefined = undefined246 try {247 const outputDir = options?.dir ?? './static'248 const maps = await fetchRoutesContent(249 app,250 options?.beforeRequestHook,251 options?.afterResponseHook252 )253 const files = await saveContentToFiles(maps, fs, outputDir)254 result = { success: true, files }255 } catch (error) {256 const errorObj = error instanceof Error ? error : new Error(String(error))257 result = { success: false, files: [], error: errorObj }258 }259 await options?.afterGenerateHook?.(result)260 return result261}262263/**264 * @experimental265 * `isSSGContext` is an experimental feature.266 * The API might be changed.267 */268export const isSSGContext = (c: Context): boolean => !!c.env?.[SSG_CONTEXT]269270/**271 * @experimental272 * `disableSSG` is an experimental feature.273 * The API might be changed.274 */275export const disableSSG = (): MiddlewareHandler =>276 async function disableSSG(c, next) {277 if (isSSGContext(c)) {278 return SSG_DISABLED_RESPONSE279 }280 await next()281 }282283/**284 * @experimental285 * `onlySSG` is an experimental feature.286 * The API might be changed.287 */288export const onlySSG = (): MiddlewareHandler =>289 async function onlySSG(c, next) {290 if (!isSSGContext(c)) {291 return c.notFound()292 }293 await next()294 }1export * from './ssg.ts'2export { SSG_DISABLED_RESPONSE, ssgParams, isSSGContext, disableSSG, onlySSG } from './middleware.ts'
added:deno_dist/helper/ssg/middleware.ts+62 added
1import type { Context } from '../../context.ts'2import type { Env, MiddlewareHandler } from '../../types.ts'34export const SSG_CONTEXT = 'HONO_SSG_CONTEXT'5export const SSG_DISABLED_RESPONSE = new Response('SSG is disabled', { status: 404 })67interface SSGParam {8 [key: string]: string9}10export type SSGParams = SSGParam[]1112interface SSGParamsMiddleware {13 <E extends Env = Env>(14 generateParams: (c: Context<E>) => SSGParams | Promise<SSGParams>15 ): MiddlewareHandler<E>16 <E extends Env = Env>(params: SSGParams): MiddlewareHandler<E>17}1819export type AddedSSGDataRequest = Request & {20 ssgParams?: SSGParams21}2223/**24 * Define SSG Route25 */26export const ssgParams: SSGParamsMiddleware = (params) => async (c, next) => {27 ;(c.req.raw as AddedSSGDataRequest).ssgParams = Array.isArray(params) ? params : await params(c)28 await next()29}3031/**32 * @experimental33 * `isSSGContext` is an experimental feature.34 * The API might be changed.35 */36export const isSSGContext = (c: Context): boolean => !!c.env?.[SSG_CONTEXT]3738/**39 * @experimental40 * `disableSSG` is an experimental feature.41 * The API might be changed.42 */43export const disableSSG = (): MiddlewareHandler =>44 async function disableSSG(c, next) {45 if (isSSGContext(c)) {46 return SSG_DISABLED_RESPONSE47 }48 await next()49 }5051/**52 * @experimental53 * `onlySSG` is an experimental feature.54 * The API might be changed.55 */56export const onlySSG = (): MiddlewareHandler =>57 async function onlySSG(c, next) {58 if (!isSSGContext(c)) {59 return c.notFound()60 }61 await next()62 }
added:deno_dist/helper/ssg/ssg.ts+302 added
1import { replaceUrlParam } from '../../client/utils.ts'2import type { Hono } from '../../hono.ts'3import type { Env, Schema } from '../../types.ts'4import { createPool } from '../../utils/concurrent.ts'5import { getExtension } from '../../utils/mime.ts'6import type { AddedSSGDataRequest, SSGParams } from './middleware.ts'7import { SSG_DISABLED_RESPONSE, SSG_CONTEXT } from './middleware.ts'8import { joinPaths, dirname, filterStaticGenerateRoutes } from './utils.ts'910const DEFAULT_CONCURRENCY = 2 // default concurrency for ssg1112/**13 * @experimental14 * `FileSystemModule` is an experimental feature.15 * The API might be changed.16 */17export interface FileSystemModule {18 writeFile(path: string, data: string | Uint8Array): Promise<void>19 mkdir(path: string, options: { recursive: boolean }): Promise<void | string>20}2122/**23 * @experimental24 * `ToSSGResult` is an experimental feature.25 * The API might be changed.26 */27export interface ToSSGResult {28 success: boolean29 files: string[]30 error?: Error31}3233const generateFilePath = (routePath: string, outDir: string, mimeType: string) => {34 const extension = determineExtension(mimeType)3536 if (routePath.endsWith(`.${extension}`)) {37 return joinPaths(outDir, routePath)38 }3940 if (routePath === '/') {41 return joinPaths(outDir, `index.${extension}`)42 }43 if (routePath.endsWith('/')) {44 return joinPaths(outDir, routePath, `index.${extension}`)45 }46 return joinPaths(outDir, `${routePath}.${extension}`)47}4849const parseResponseContent = async (response: Response): Promise<string | ArrayBuffer> => {50 const contentType = response.headers.get('Content-Type')5152 try {53 if (contentType?.includes('text') || contentType?.includes('json')) {54 return await response.text()55 } else {56 return await response.arrayBuffer()57 }58 } catch (error) {59 throw new Error(60 `Error processing response: ${error instanceof Error ? error.message : 'Unknown error'}`61 )62 }63}6465const determineExtension = (mimeType: string): string => {66 switch (mimeType) {67 case 'text/html':68 return 'html'69 case 'text/xml':70 case 'application/xml':71 return 'xml'72 default: {73 return getExtension(mimeType) || 'html'74 }75 }76}7778export type BeforeRequestHook = (req: Request) => Request | false79export type AfterResponseHook = (res: Response) => Response | false80export type AfterGenerateHook = (result: ToSSGResult) => void | Promise<void>8182export interface ToSSGOptions {83 dir?: string84 beforeRequestHook?: BeforeRequestHook85 afterResponseHook?: AfterResponseHook86 afterGenerateHook?: AfterGenerateHook87 concurrency?: number88}8990/**91 * @experimental92 * `fetchRoutesContent` is an experimental feature.93 * The API might be changed.94 */95export const fetchRoutesContent = function* <96 E extends Env = Env,97 S extends Schema = {},98 BasePath extends string = '/'99>(100 app: Hono<E, S, BasePath>,101 beforeRequestHook?: BeforeRequestHook,102 afterResponseHook?: AfterResponseHook,103 concurrency?: number104): Generator<105 Promise<106 | Generator<107 Promise<{ routePath: string; mimeType: string; content: string | ArrayBuffer } | undefined>108 >109 | undefined110 >111> {112 const baseURL = 'http://localhost'113 const pool = createPool({ concurrency })114115 for (const route of filterStaticGenerateRoutes(app)) {116 // GET Route Info117 const thisRouteBaseURL = new URL(route.path, baseURL).toString()118119 let forGetInfoURLRequest = new Request(thisRouteBaseURL) as AddedSSGDataRequest120 if (beforeRequestHook) {121 const maybeRequest = beforeRequestHook(forGetInfoURLRequest)122 if (!maybeRequest) {123 continue124 }125 forGetInfoURLRequest = maybeRequest as unknown as AddedSSGDataRequest126 }127128 // eslint-disable-next-line no-async-promise-executor129 yield new Promise(async (resolveGetInfo, rejectGetInfo) => {130 try {131 await pool.run(() => app.fetch(forGetInfoURLRequest))132133 if (!forGetInfoURLRequest.ssgParams) {134 if (isDynamicRoute(route.path)) {135 resolveGetInfo(undefined)136 return137 }138 forGetInfoURLRequest.ssgParams = [{}]139 }140141 const requestInit = {142 method: forGetInfoURLRequest.method,143 headers: forGetInfoURLRequest.headers,144 }145146 resolveGetInfo(147 (function* () {148 for (const param of forGetInfoURLRequest.ssgParams as SSGParams) {149 // eslint-disable-next-line no-async-promise-executor150 yield new Promise(async (resolveReq, rejectReq) => {151 try {152 const replacedUrlParam = replaceUrlParam(route.path, param)153 let response = await pool.run(() =>154 app.request(replacedUrlParam, requestInit, {155 [SSG_CONTEXT]: true,156 })157 )158 if (response === SSG_DISABLED_RESPONSE) {159 resolveReq(undefined)160 return161 }162 if (afterResponseHook) {163 const maybeResponse = afterResponseHook(response)164 if (!maybeResponse) {165 resolveReq(undefined)166 return167 }168 response = maybeResponse169 }170 const mimeType =171 response.headers.get('Content-Type')?.split(';')[0] || 'text/plain'172 const content = await parseResponseContent(response)173 resolveReq({174 routePath: replacedUrlParam,175 mimeType,176 content,177 })178 } catch (error) {179 rejectReq(error)180 }181 })182 }183 })()184 )185 } catch (error) {186 rejectGetInfo(error)187 }188 })189 }190}191192const isDynamicRoute = (path: string): boolean => {193 return path.split('/').some((segment) => segment.startsWith(':') || segment.includes('*'))194}195196/**197 * @experimental198 * `saveContentToFile` is an experimental feature.199 * The API might be changed.200 */201const createdDirs: Set<string> = new Set()202export const saveContentToFile = async (203 data: Promise<{ routePath: string; content: string | ArrayBuffer; mimeType: string } | undefined>,204 fsModule: FileSystemModule,205 outDir: string206): Promise<string | undefined> => {207 const awaitedData = await data208 if (!awaitedData) {209 return210 }211 const { routePath, content, mimeType } = awaitedData212 const filePath = generateFilePath(routePath, outDir, mimeType)213 const dirPath = dirname(filePath)214215 if (!createdDirs.has(dirPath)) {216 await fsModule.mkdir(dirPath, { recursive: true })217 createdDirs.add(dirPath)218 }219 if (typeof content === 'string') {220 await fsModule.writeFile(filePath, content)221 } else if (content instanceof ArrayBuffer) {222 await fsModule.writeFile(filePath, new Uint8Array(content))223 }224 return filePath225}226227/**228 * @experimental229 * `ToSSGInterface` is an experimental feature.230 * The API might be changed.231 */232export interface ToSSGInterface {233 (234 // eslint-disable-next-line @typescript-eslint/no-explicit-any235 app: Hono<any, any, any>,236 fsModule: FileSystemModule,237 options?: ToSSGOptions238 ): Promise<ToSSGResult>239}240241/**242 * @experimental243 * `ToSSGAdaptorInterface` is an experimental feature.244 * The API might be changed.245 */246export interface ToSSGAdaptorInterface<247 E extends Env = Env,248 S extends Schema = {},249 BasePath extends string = '/'250> {251 (app: Hono<E, S, BasePath>, options?: ToSSGOptions): Promise<ToSSGResult>252}253254/**255 * @experimental256 * `toSSG` is an experimental feature.257 * The API might be changed.258 */259export const toSSG: ToSSGInterface = async (app, fs, options) => {260 let result: ToSSGResult | undefined = undefined261 const getInfoPromises: Promise<unknown>[] = []262 const savePromises: Promise<string | undefined>[] = []263 try {264 const outputDir = options?.dir ?? './static'265 const concurrency = options?.concurrency ?? DEFAULT_CONCURRENCY266267 const getInfoGen = fetchRoutesContent(268 app,269 options?.beforeRequestHook,270 options?.afterResponseHook,271 concurrency272 )273 for (const getInfo of getInfoGen) {274 getInfoPromises.push(275 getInfo.then((getContentGen) => {276 if (!getContentGen) {277 return278 }279 for (const content of getContentGen) {280 savePromises.push(saveContentToFile(content, fs, outputDir).catch((e) => e))281 }282 })283 )284 }285 await Promise.all(getInfoPromises)286 const files: string[] = []287 for (const savePromise of savePromises) {288 const fileOrError = await savePromise289 if (typeof fileOrError === 'string') {290 files.push(fileOrError)291 } else if (fileOrError) {292 throw fileOrError293 }294 }295 result = { success: true, files }296 } catch (error) {297 const errorObj = error instanceof Error ? error : new Error(String(error))298 result = { success: false, files: [], error: errorObj }299 }300 await options?.afterGenerateHook?.(result)301 return result302}
added:deno_dist/helper/websocket/index.ts+55 added
1/* eslint-disable @typescript-eslint/no-explicit-any */2import type { Context } from '../../context.ts'3import type { MiddlewareHandler } from '../../types.ts'45/**6 * WebSocket Event Listeners type7 */8export interface WSEvents {9 onOpen?: (evt: Event, ws: WSContext) => void10 onMessage?: (evt: MessageEvent<WSMessageReceive>, ws: WSContext) => void11 onClose?: (evt: CloseEvent, ws: WSContext) => void12 onError?: (evt: Event, ws: WSContext) => void13}1415export type UpgradedWebSocketResponseInputJSONType = '__websocket' | undefined1617/**18 * Upgrade WebSocket Type19 */20export type UpgradeWebSocket = (21 createEvents: (c: Context) => WSEvents | Promise<WSEvents>22) => MiddlewareHandler<23 any,24 string,25 {26 in: {27 json: UpgradedWebSocketResponseInputJSONType28 }29 }30>3132export type WSReadyState = 0 | 1 | 2 | 33334export type WSContext = {35 send(36 source: string | ArrayBuffer | Uint8Array,37 options?: {38 compress: boolean39 }40 ): void41 raw?: unknown42 binaryType: BinaryType43 readyState: WSReadyState44 url: URL | null45 protocol: string | null46 close(code?: number, reason?: string): void47}4849export type WSMessageReceive = string | Blob | ArrayBufferLike5051export const createWSMessageEvent = (source: WSMessageReceive): MessageEvent<WSMessageReceive> => {52 return new MessageEvent<WSMessageReceive>('message', {53 data: source,54 })55}
modified:deno_dist/jsx/dom/index.ts+79 added-9 removed
1import type { Props, Child, JSXNode } from '../base.ts'2import { memo, isValidElement } from '../base.ts'3import { useContext } from '../context.ts'1export {4import {5 useState,6 useEffect,7 useRef,8 useCallback,
4 unmodified lines
13 startViewTransition,14 useViewTransition,15 useMemo,16 useLayoutEffect,17 useReducer,18 useDebugValue,19} from '../hooks/index.ts'20import { Suspense, ErrorBoundary } from './components.ts'21import { createContext } from './context.ts'22import { jsx } from './jsx-runtime.ts'2324export { render } from './render.ts'16export { Suspense, ErrorBoundary } from './components.ts'17export { useContext } from '../context.ts'18export type { Context } from '../context.ts'19export { createContext } from './context.ts'20export { memo, isValidElement } from '../base.ts'2522import type { Props, Child, JSXNode } from '../base.ts'23import { jsx } from './jsx-runtime.ts'24export const cloneElement = <T extends JSXNode | JSX.Element>(26const createElement = (27 tag: string | ((props: Props) => JSXNode),28 props: Props,29 ...children: Child[]30): JSXNode => {31 const jsxProps: Props = { ...props, children }32 let key = undefined33 if ('key' in jsxProps) {34 key = jsxProps.key35 delete jsxProps.key36 }37 // eslint-disable-next-line @typescript-eslint/no-explicit-any38 return jsx(tag, jsxProps, key) as any39}4041const cloneElement = <T extends JSXNode | JSX.Element>(42 element: T,43 props: Props,44 ...children: Child[]45): T => {
6 unmodified lines
52 },53 (element as JSXNode).key54 ) as T55}5657export {58 createElement as jsx,59 useState,60 useEffect,61 useRef,62 useCallback,63 use,64 startTransition,65 useTransition,66 useDeferredValue,67 startViewTransition,68 useViewTransition,69 useMemo,70 useLayoutEffect,71 useReducer,72 useDebugValue,73 Suspense,74 ErrorBoundary,75 createContext,76 useContext,77 memo,78 isValidElement,79 createElement,80 cloneElement,81}8283export default {84 useState,85 useEffect,86 useRef,87 useCallback,88 use,89 startTransition,90 useTransition,91 useDeferredValue,92 startViewTransition,93 useViewTransition,94 useMemo,95 useLayoutEffect,96 useReducer,97 useDebugValue,98 Suspense,99 ErrorBoundary,100 createContext,101 useContext,102 memo,103 isValidElement,104 createElement,105 cloneElement,106}107108export type { Context } from '../context.ts'
modified:deno_dist/jsx/hooks/index.ts+18 added
203 unmodified lines
204 },205 ])206}207208export const useReducer = <T, A>(209 reducer: (state: T, action: A) => T,210 initialArg: T,211 init?: (initialState: T) => T212): [T, (action: A) => void] => {213 const [state, setState] = useState(() => (init ? init(initialArg) : initialArg))214 return [215 state,216 (action: A) => {217 setState((state) => reducer(state, action))218 },219 ]220}221222const useEffectCommon = (223 index: number,224 effect: () => void | (() => void),225 deps?: readonly unknown[]
121 unmodified lines
347 memoArray[hookIndex] = [factory(), deps]348 }349 return memoArray[hookIndex][0] as T350}351352// Define to avoid errors. This hook currently does nothing.353// eslint-disable-next-line @typescript-eslint/no-unused-vars354export const useDebugValue = (value: unknown, formatter?: (value: unknown) => string): void => {}
modified:deno_dist/jsx/index.ts+60 added-5 removed
1export { jsx, memo, Fragment, isValidElement, cloneElement } from './base.ts'2export { ErrorBoundary } from './components.ts'3export { Suspense } from './streaming.ts'4export {1import { jsx, memo, Fragment, isValidElement, cloneElement } from './base.ts'2import { ErrorBoundary } from './components.ts'3import { createContext, useContext } from './context.ts'4import {5 useState,6 useEffect,7 useRef,8 useCallback,
4 unmodified lines
13 startViewTransition,14 useViewTransition,15 useMemo,16 useLayoutEffect,17 useReducer,18 useDebugValue,19} from './hooks/index.ts'18export { createContext, useContext } from './context.ts'20import { Suspense } from './streaming.ts'2122export {23 jsx,24 memo,25 Fragment,26 isValidElement,27 jsx as createElement,28 cloneElement,29 ErrorBoundary,30 createContext,31 useContext,32 useState,33 useEffect,34 useRef,35 useCallback,36 useReducer,37 useDebugValue,38 use,39 startTransition,40 useTransition,41 useDeferredValue,42 startViewTransition,43 useViewTransition,44 useMemo,45 useLayoutEffect,46 Suspense,47}4849export default {50 memo,51 Fragment,52 isValidElement,53 createElement: jsx,54 cloneElement,55 ErrorBoundary,56 createContext,57 useContext,58 useState,59 useEffect,60 useRef,61 useCallback,62 useReducer,63 useDebugValue,64 use,65 startTransition,66 useTransition,67 useDeferredValue,68 startViewTransition,69 useViewTransition,70 useMemo,71 useLayoutEffect,72 Suspense,73}7475// TODO: change to `export type *` after denoify bug is fixed76// https://github.com/garronej/denoify/issues/12477export * from './types.ts'
added:deno_dist/middleware/body-limit/index.ts+96 added
1import type { Context } from '../../context.ts'2import { HTTPException } from '../../http-exception.ts'3import type { MiddlewareHandler } from '../../types.ts'45const ERROR_MESSAGE = 'Payload Too Large'67type OnError = (c: Context) => Response | Promise<Response>8type BodyLimitOptions = {9 maxSize: number10 onError?: OnError11}1213class BodyLimitError extends Error {14 constructor(message: string) {15 super(message)16 this.name = 'BodyLimitError'17 }18}1920/**21 * Body Limit Middleware22 *23 * @example24 * ```ts25 * app.post(26 * '/hello',27 * bodyLimit({28 * maxSize: 100 * 1024, // 100kb29 * onError: (c) => {30 * return c.text('overflow :(', 413)31 * }32 * }),33 * (c) => {34 * return c.text('pass :)')35 * }36 * )37 * ```38 */39export const bodyLimit = (options: BodyLimitOptions): MiddlewareHandler => {40 const onError: OnError =41 options.onError ||42 (() => {43 const res = new Response(ERROR_MESSAGE, {44 status: 413,45 })46 throw new HTTPException(413, { res })47 })48 const maxSize = options.maxSize4950 return async function bodyLimit(c, next) {51 if (!c.req.raw.body) {52 // maybe GET or HEAD request53 return next()54 }5556 if (c.req.raw.headers.has('content-length')) {57 // we can trust content-length header because it's already validated by server58 const contentLength = parseInt(c.req.raw.headers.get('content-length') || '0', 10)59 return contentLength > maxSize ? onError(c) : next()60 }6162 // maybe chunked transfer encoding6364 let size = 065 const rawReader = c.req.raw.body.getReader()66 const reader = new ReadableStream({67 async start(controller) {68 try {69 for (;;) {70 const { done, value } = await rawReader.read()71 if (done) {72 break73 }74 size += value.length75 if (size > maxSize) {76 controller.error(new BodyLimitError(ERROR_MESSAGE))77 break78 }7980 controller.enqueue(value)81 }82 } finally {83 controller.close()84 }85 },86 })8788 c.req.raw = new Request(c.req.raw, { body: reader })8990 await next()9192 if (c.error instanceof BodyLimitError) {93 c.res = await onError(c)94 }95 }96}
modified:deno_dist/middleware/logger/index.ts+9 added-7 removed
1import type { MiddlewareHandler } from '../../types.ts'2import { getColorEnabled } from '../../utils/color.ts'3import { getPath } from '../../utils/url.ts'45enum LogPrefix {6 Outgoing = '-->',
14 unmodified lines
21 return humanize([delta < 1000 ? delta + 'ms' : Math.round(delta / 1000) + 's'])22}2324const colorStatus = (status: number) => {25 const colorEnabled = getColorEnabled()26 const out: { [key: string]: string } = {25 7: `\x1b[35m${status}\x1b[0m`,26 5: `\x1b[31m${status}\x1b[0m`,27 4: `\x1b[33m${status}\x1b[0m`,28 3: `\x1b[36m${status}\x1b[0m`,29 2: `\x1b[32m${status}\x1b[0m`,30 1: `\x1b[32m${status}\x1b[0m`,31 0: `\x1b[33m${status}\x1b[0m`,27 7: colorEnabled ? `\x1b[35m${status}\x1b[0m` : `${status}`,28 5: colorEnabled ? `\x1b[31m${status}\x1b[0m` : `${status}`,29 4: colorEnabled ? `\x1b[33m${status}\x1b[0m` : `${status}`,30 3: colorEnabled ? `\x1b[36m${status}\x1b[0m` : `${status}`,31 2: colorEnabled ? `\x1b[32m${status}\x1b[0m` : `${status}`,32 1: colorEnabled ? `\x1b[32m${status}\x1b[0m` : `${status}`,33 0: colorEnabled ? `\x1b[33m${status}\x1b[0m` : `${status}`,34 }3536 const calculateStatus = (status / 100) | 037
35 unmodified lines
added:deno_dist/utils/color.ts+12 added
1export function getColorEnabled() {2 // eslint-disable-next-line @typescript-eslint/no-explicit-any3 const { process, Deno } = globalThis as any4 const isNoColor =5 typeof process !== 'undefined'6 ? // eslint-disable-next-line no-unsafe-optional-chaining7 'NO_COLOR' in process?.env8 : typeof Deno?.noColor === 'boolean'9 ? (Deno.noColor as boolean)10 : false11 return !isNoColor12}
added:deno_dist/utils/concurrent.ts+50 added
1const DEFAULT_CONCURRENCY = 102423export interface Pool {4 run<T>(fn: () => T): Promise<T>5}67export const createPool = ({8 concurrency,9 interval,10}: {11 concurrency?: number12 interval?: number13} = {}): Pool => {14 concurrency ||= DEFAULT_CONCURRENCY1516 if (concurrency === Infinity) {17 // unlimited18 return {19 run: async (fn) => fn(),20 }21 }2223 const pool: Set<{}> = new Set()24 const run = async <T>(25 fn: () => T,26 promise?: Promise<T>,27 resolve?: (result: T) => void28 ): Promise<T> => {29 if (pool.size >= (concurrency as number)) {30 promise ||= new Promise<T>((r) => (resolve = r))31 setTimeout(() => run(fn, promise, resolve))32 return promise33 }34 const marker = {}35 pool.add(marker)36 const result = await fn()37 if (interval) {38 setTimeout(() => pool.delete(marker), interval)39 } else {40 pool.delete(marker)41 }42 if (resolve) {43 resolve(result)44 return promise as Promise<T>45 } else {46 return result47 }48 }49 return { run }50}
modified:deno_dist/utils/cookie.ts+44 added-1 removed
10 unmodified lines
11 secure?: boolean12 signingSecret?: string13 sameSite?: 'Strict' | 'Lax' | 'None'14 partitioned?: boolean15 prefix?: CookiePrefixOptions16}17export type CookiePrefixOptions = 'host' | 'secure'1819const algorithm = { name: 'HMAC', hash: 'SHA-256' }2021const getCryptoKey = async (secret: string | BufferSource): Promise<CryptoKey> => {
91 unmodified lines
113114const _serialize = (name: string, value: string, opt: CookieOptions = {}): string => {115 let cookie = `${name}=${value}`116117 if (name.startsWith('__Secure-') && !opt.secure) {118 // FIXME: replace link to RFC119 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.3.1120 throw new Error('__Secure- Cookie must have Secure attributes')121 }122123 if (name.startsWith('__Host-')) {124 // FIXME: replace link to RFC125 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.3.2126 if (!opt.secure) {127 throw new Error('__Host- Cookie must have Secure attributes')128 }129130 if (opt.path !== '/') {131 throw new Error('__Host- Cookie must have Path attributes with "/"')132 }133134 if (opt.domain) {135 throw new Error('__Host- Cookie must not have Domain attributes')136 }137 }138139 if (opt && typeof opt.maxAge === 'number' && opt.maxAge >= 0) {140 if (opt.maxAge > 34560000) {141 // FIXME: replace link to RFC142 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.2.2143 throw new Error(144 'Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.'145 )146 }147 cookie += `; Max-Age=${Math.floor(opt.maxAge)}`148 }149119 if (opt.domain) {150 if (opt.domain && opt.prefix !== 'host') {151 cookie += `; Domain=${opt.domain}`152 }153154 if (opt.path) {155 cookie += `; Path=${opt.path}`156 }157158 if (opt.expires) {159 if (opt.expires.getTime() - Date.now() > 34560000_000) {160 // FIXME: replace link to RFC161 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.2.1162 throw new Error(163 'Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.'164 )165 }166 cookie += `; Expires=${opt.expires.toUTCString()}`167 }168169 if (opt.httpOnly) {
8 unmodified lines
178 cookie += `; SameSite=${opt.sameSite}`179 }180181 if (opt.partitioned) {182 // FIXME: replace link to RFC183 // https://www.ietf.org/archive/id/draft-cutler-httpbis-partitioned-cookies-01.html#section-2.3184 if (!opt.secure) {185 throw new Error('Partitioned Cookie must have Secure attributes')186 }187 cookie += '; Partitioned'188 }189190 return cookie
18 unmodified lines
modified:deno_dist/helper.ts+1 added
7 unmodified lines
8export * from './helper/streaming/index.ts'9export * from './helper/testing/index.ts'10export * from './helper/dev/index.ts'11export * from './adapter/deno/ssg.ts'12export * from './adapter/deno/websocket.ts'
modified:deno_dist/http-exception.ts+4 added-1 removed
1 unmodified line
23type HTTPExceptionOptions = {4 res?: Response5 message?: string6 cause?: unknown7}89/**10 * `HTTPException` must be used when a fatal error such as authentication failure occurs.
15 unmodified lines
26 */27export class HTTPException extends Error {28 readonly res?: Response29 readonly status: StatusCode3031 constructor(status: StatusCode = 500, options?: HTTPExceptionOptions) {30 super(options?.message)32 super(options?.message, { cause: options?.cause })33 this.res = options?.res34 this.status = status35 }3637 getResponse(): Response {38 if (this.res) {39 return this.res40 }
5 unmodified lines
modified:deno_dist/middleware.ts+1 added
1// This file is for Deno to import middleware from `hono/middleware.ts`.2export * from './middleware/basic-auth/index.ts'3export * from './middleware/bearer-auth/index.ts'4export * from './middleware/body-limit/index.ts'5export * from './middleware/cache/index.ts'6export * from './middleware/compress/index.ts'7export * from './middleware/cors/index.ts'8export * from './middleware/csrf/index.ts'
10 unmodified lines
modified:runtime_tests/bun/index.test.tsx+38 added
1import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest'2import { serveStatic, toSSG } from '../../src/adapter/bun'3import { createBunWebSocket, type BunWebSocketData } from '../../src/adapter/bun/websocket'4import { Context } from '../../src/context'5import { env, getRuntimeKey } from '../../src/helper/adapter'6import type { WSMessageReceive } from '../../src/helper/websocket'7import { Hono } from '../../src/index'8// eslint-disable-next-line @typescript-eslint/no-unused-vars9import { jsx } from '../../src/jsx'10import { basicAuth } from '../../src/middleware/basic-auth'
248 unmodified lines
259 })260 })261})262263describe('WebSockets Helper', () => {264 const app = new Hono()265 const { websocket, upgradeWebSocket } = createBunWebSocket()266267 it('Should websockets is working', async () => {268 const receivedMessagePromise = new Promise<WSMessageReceive>((resolve) =>269 app.get(270 '/ws',271 upgradeWebSocket(() => ({272 onMessage(evt) {273 resolve(evt.data)274 },275 }))276 )277 )278 const upgradedData = await new Promise<BunWebSocketData>((resolve) =>279 app.fetch(new Request('http://localhost/ws'), {280 upgrade: (_req: Request, data: { data: BunWebSocketData }) => {281 resolve(data.data)282 },283 })284 )285 const message = Math.random().toString()286 websocket.message(287 {288 close: () => undefined,289 readyState: 3,290 data: upgradedData,291 send: () => undefined,292 },293 message294 )295 const receivedMessage = await receivedMessagePromise296 expect(receivedMessage).toBe(message)297 })298})299const fs = require('fs').promises300const path = require('path')301302async function deleteDirectory(dirPath) {
15 unmodified lines
modified:src/adapter/bun/index.ts+1 added
1// @denoify-ignore2export { serveStatic } from './serve-static'3export { bunFileSystemModule, toSSG } from './ssg'4export { createBunWebSocket } from './websocket'
added:src/adapter/bun/websocket.ts+115 added
1// @denoify-ignore2import {3 createWSMessageEvent,4 type UpgradeWebSocket,5 type WSContext,6 type WSEvents,7 type WSMessageReceive,8} from '../../helper/websocket'910interface BunServerWebSocket<T> {11 send(data: string | ArrayBufferLike, compress?: boolean): void12 close(code?: number, reason?: string): void13 data: T14 readyState: 0 | 1 | 2 | 315}16interface BunServer {17 upgrade<T>(18 req: Request,19 options?: {20 data: T21 }22 ): boolean23}24interface BunWebSocketHandler<T> {25 open(ws: BunServerWebSocket<T>): void26 close(ws: BunServerWebSocket<T>, code?: number, reason?: string): void27 message(ws: BunServerWebSocket<T>, message: string | Buffer): void28}29interface CreateWebSocket {30 (): {31 upgradeWebSocket: UpgradeWebSocket32 websocket: BunWebSocketHandler<BunWebSocketData>33 }34}35export interface BunWebSocketData {36 connId: number37 url: URL38 protocol: string39}4041const createWSContext = (ws: BunServerWebSocket<BunWebSocketData>): WSContext => {42 return {43 send: (source, options) => {44 const sendingData =45 typeof source === 'string' ? source : source instanceof Uint8Array ? source.buffer : source46 ws.send(sendingData, options?.compress)47 },48 raw: ws,49 binaryType: 'arraybuffer',50 readyState: ws.readyState,51 url: ws.data.url,52 protocol: ws.data.protocol,53 close(code, reason) {54 ws.close(code, reason)55 },56 }57}5859export const createBunWebSocket: CreateWebSocket = () => {60 const websocketConns: WSEvents[] = []6162 const upgradeWebSocket: UpgradeWebSocket = (createEvents) => {63 return async (c, next) => {64 const server = c.env as BunServer65 const connId = websocketConns.push(await createEvents(c)) - 166 const upgradeResult = server.upgrade<BunWebSocketData>(c.req.raw, {67 data: {68 connId,69 url: new URL(c.req.url),70 protocol: c.req.url,71 },72 })73 if (upgradeResult) {74 return new Response(null)75 }76 await next() // Failed77 }78 }79 const websocket: BunWebSocketHandler<BunWebSocketData> = {80 open(ws) {81 const websocketListeners = websocketConns[ws.data.connId]82 if (websocketListeners.onOpen) {83 websocketListeners.onOpen(new Event('open'), createWSContext(ws))84 }85 },86 close(ws, code, reason) {87 const websocketListeners = websocketConns[ws.data.connId]88 if (websocketListeners.onClose) {89 websocketListeners.onClose(90 new CloseEvent('close', {91 code,92 reason,93 }),94 createWSContext(ws)95 )96 }97 },98 message(ws, message) {99 const websocketListeners = websocketConns[ws.data.connId]100 if (websocketListeners.onMessage) {101 const normalizedReceiveData =102 typeof message === 'string' ? message : (message.buffer satisfies WSMessageReceive)103104 websocketListeners.onMessage(105 createWSMessageEvent(normalizedReceiveData),106 createWSContext(ws)107 )108 }109 },110 }111 return {112 upgradeWebSocket,113 websocket,114 }115}
modified:src/adapter/cloudflare-workers/index.ts+1 added
1// @denoify-ignore2export { serveStatic } from './serve-static-module'3export { upgradeWebSocket } from './websocket'
added:src/adapter/cloudflare-workers/websocket.test.ts+45 added
1import { Hono } from '../..'2import { upgradeWebSocket } from '.'34describe('upgradeWebSocket middleware', () => {5 const server = new EventTarget()67 // @ts-expect-error Cloudflare API8 globalThis.WebSocketPair = class {9 0: WebSocket // client10 1: WebSocket // server11 constructor() {12 this[0] = {} as WebSocket13 this[1] = server as WebSocket14 }15 }1617 const app = new Hono()1819 const wsPromise = new Promise((resolve) =>20 app.get(21 '/ws',22 upgradeWebSocket(() => ({23 onMessage(evt, ws) {24 console.log('evt')25 resolve(evt.data)26 },27 }))28 )29 )30 it('Should receive message is valid', async () => {31 const sendingData = Math.random().toString()32 await app.request('/ws', {33 headers: {34 Upgrade: 'websocket',35 },36 })37 server.dispatchEvent(38 new MessageEvent('message', {39 data: sendingData,40 })41 )4243 expect(sendingData).toBe(await wsPromise)44 })45})
added:src/adapter/cloudflare-workers/websocket.ts+68 added
1// @denoify-ignore2/* eslint-disable @typescript-eslint/ban-ts-comment */3import type { WebSocketPair } from '@cloudflare/workers-types'4import type { UpgradeWebSocket, WSContext, WSReadyState } from '../../helper/websocket'56// Based on https://github.com/honojs/hono/issues/1153#issuecomment-17673213327export const upgradeWebSocket: UpgradeWebSocket = (createEvents) => async (c, next) => {8 const CFWebSocketPair = (9 globalThis as unknown as {10 WebSocketPair: typeof WebSocketPair11 }12 ).WebSocketPair1314 const events = await createEvents(c)1516 const upgradeHeader = c.req.header('Upgrade')17 if (upgradeHeader !== 'websocket') {18 return await next()19 }2021 const webSocketPair = new CFWebSocketPair()22 const client = webSocketPair[0]23 const server = webSocketPair[1]2425 const wsContext: WSContext = {26 binaryType: 'arraybuffer',27 close: (code, reason) => server.close(code, reason),28 get protocol() {29 return server.protocol30 },31 raw: server,32 get readyState() {33 return server.readyState as WSReadyState34 },35 url: server.url ? new URL(server.url) : null,36 send: (source) => server.send(source),37 }38 if (events.onOpen) {39 server.addEventListener(40 'open',41 (evt) => events.onOpen && events.onOpen(evt as Event, wsContext)42 )43 }44 if (events.onClose) {45 server.addEventListener(46 'close',47 (evt) => events.onClose && events.onClose(evt as CloseEvent, wsContext)48 )49 }50 if (events.onMessage) {51 server.addEventListener(52 'message',53 (evt) => events.onMessage && events.onMessage(evt as MessageEvent, wsContext)54 )55 }56 if (events.onError) {57 server.addEventListener(58 'error',59 (evt) => events.onError && events.onError(evt as ErrorEvent as Event, wsContext)60 )61 }62 server.accept()63 return new Response(null, {64 status: 101,65 // @ts-expect-error Cloudflare Workers API66 webSocket: client,67 })68}
modified:src/adapter/deno/deno.d.ts+5 added
14 unmodified lines
15 * @param data The data to write to the file.16 * @returns A promise that resolves when the file is written.17 */18 export function writeFile(path: string, data: Uint8Array): Promise<void>1920 export function upgradeWebSocket(req: Request): {21 response: Response22 socket: WebSocket23 }24}
modified:src/adapter/deno/index.ts+1 added
1export { serveStatic } from './serve-static'2export { toSSG, denoFileSystemModule } from './ssg'3export { upgradeWebSocket } from './websocket'
added:src/adapter/deno/websocket.test.ts+42 added
1import { Hono } from '../..'2import { upgradeWebSocket } from './websocket'34globalThis.Deno = {} as typeof Deno56describe('WebSockets', () => {7 let app: Hono8 beforeEach(() => {9 app = new Hono()10 })1112 it('Should receive data is valid', async () => {13 const messagePromise = new Promise((resolve) =>14 app.get(15 '/ws',16 upgradeWebSocket(() => ({17 onMessage: (evt) => resolve(evt.data),18 }))19 )20 )21 const socket = new EventTarget() as WebSocket22 Deno.upgradeWebSocket = () => {23 return {24 response: new Response(),25 socket,26 }27 }28 await app.request('/ws', {29 headers: {30 upgrade: 'websocket',31 },32 })33 const data = Math.random().toString()34 socket.onmessage &&35 socket.onmessage(36 new MessageEvent('message', {37 data,38 })39 )40 expect(await messagePromise).toBe(data)41 })42})
added:src/adapter/deno/websocket.ts+30 added
1import type { UpgradeWebSocket, WSContext, WSReadyState } from '../../helper/websocket'23export const upgradeWebSocket: UpgradeWebSocket = (createEvents) => async (c, next) => {4 if (c.req.header('upgrade') !== 'websocket') {5 return await next()6 }7 const { response, socket } = Deno.upgradeWebSocket(c.req.raw)89 const events = await createEvents(c)1011 const wsContext: WSContext = {12 binaryType: 'arraybuffer',13 close: (code, reason) => socket.close(code, reason),14 get protocol() {15 return socket.protocol16 },17 raw: socket,18 get readyState() {19 return socket.readyState as WSReadyState20 },21 url: socket.url ? new URL(socket.url) : null,22 send: (source) => socket.send(source),23 }24 socket.onopen = (evt) => events.onOpen && events.onOpen(evt, wsContext)25 socket.onmessage = (evt) => events.onMessage && events.onMessage(evt, wsContext)26 socket.onclose = (evt) => events.onClose && events.onClose(evt, wsContext)27 socket.onerror = (evt) => events.onError && events.onError(evt, wsContext)2829 return response30}
modified:src/client/client.ts+5 added
140 unmodified lines
141 return new URL(replaceUrlParam(url, opts.args[0].param))142 }143 return new URL(url)144 }145 if (method === 'ws') {146 const targetUrl =147 opts.args[0] && opts.args[0].param ? replaceUrlParam(url, opts.args[0].param) : url148 return new WebSocket(targetUrl)149 }150151 const req = new ClientRequestImpl(url, method)152 if (method) {153 options ??= {}
5 unmodified lines
modified:src/client/types.ts+8 added
1import type { UpgradedWebSocketResponseInputJSONType } from '../helper/websocket'2import type { Hono } from '../hono'3import type { Schema } from '../types'4import type { HasRequiredKeys } from '../utils/types'5
24 unmodified lines
30 ? { param: P }31 : {}32 : {}33 ) => URL34} & {35 // WebSocket36 $ws: S['$get'] extends { input: { json: UpgradedWebSocketResponseInputJSONType } }37 ? S['$get'] extends { input: infer I }38 ? (args?: Omit<I, 'json'>) => WebSocket39 : never40 : never41}4243// eslint-disable-next-line @typescript-eslint/no-explicit-any44type BlankRecordToNever<T> = T extends any ? (keyof T extends never ? never : T) : never
84 unmodified lines
modified:src/helper/cookie/index.test.ts+117 added
193 unmodified lines
194 'delicious_cookie=macha.diubJPY8O7hI1pLa42QSfkPiyDWQ0I4DnlACH%2FN2HaA%3D; Path=/a'195 )196 })197198 app.get('/get-secure-prefix-cookie', async (c) => {199 const cookie = getCookie(c, 'delicious_cookie', 'secure')200 if (cookie) {201 return c.text(cookie)202 } else {203 return c.notFound()204 }205 })206207 app.get('/get-host-prefix-cookie', async (c) => {208 const cookie = getCookie(c, 'delicious_cookie', 'host')209 if (cookie) {210 return c.text(cookie)211 } else {212 return c.notFound()213 }214 })215216 app.get('/set-secure-prefix-cookie', (c) => {217 setCookie(c, 'delicious_cookie', 'macha', {218 prefix: 'secure',219 secure: false, // this will be ignore220 })221 return c.text('Set secure prefix cookie')222 })223224 it('Set cookie with secure prefix', async () => {225 const res = await app.request('http://localhost/set-secure-prefix-cookie')226 expect(res.status).toBe(200)227 const header = res.headers.get('Set-Cookie')228 expect(header).toBe('__Secure-delicious_cookie=macha; Path=/; Secure')229 })230231 it('Get cookie with secure prefix', async () => {232 const setCookie = await app.request('http://localhost/set-secure-prefix-cookie')233 const header = setCookie.headers.get('Set-Cookie')234 if (!header) {235 assert.fail('invalid header')236 }237 const res = await app.request('http://localhost/get-secure-prefix-cookie', {238 headers: {239 Cookie: header,240 },241 })242 const response = await res.text()243 expect(res.status).toBe(200)244 expect(response).toBe('macha')245 })246247 app.get('/set-host-prefix-cookie', (c) => {248 setCookie(c, 'delicious_cookie', 'macha', {249 prefix: 'host',250 path: '/foo', // this will be ignored251 domain: 'example.com', // this will be ignored252 secure: false, // this will be ignored253 })254 return c.text('Set host prefix cookie')255 })256257 it('Set cookie with host prefix', async () => {258 const res = await app.request('http://localhost/set-host-prefix-cookie')259 expect(res.status).toBe(200)260 const header = res.headers.get('Set-Cookie')261 expect(header).toBe('__Host-delicious_cookie=macha; Path=/; Secure')262 })263264 it('Get cookie with host prefix', async () => {265 const setCookie = await app.request('http://localhost/set-host-prefix-cookie')266 const header = setCookie.headers.get('Set-Cookie')267 if (!header) {268 assert.fail('invalid header')269 }270 const res = await app.request('http://localhost/get-host-prefix-cookie', {271 headers: {272 Cookie: header,273 },274 })275 const response = await res.text()276 expect(res.status).toBe(200)277 expect(response).toBe('macha')278 })279280 app.get('/set-signed-secure-prefix-cookie', async (c) => {281 await setSignedCookie(c, 'delicious_cookie', 'macha', 'secret choco chips', {282 prefix: 'secure',283 })284 return c.text('Set secure prefix cookie')285 })286287 it('Set signed cookie with secure prefix', async () => {288 const res = await app.request('http://localhost/set-signed-secure-prefix-cookie')289 expect(res.status).toBe(200)290 const header = res.headers.get('Set-Cookie')291 expect(header).toBe(292 '__Secure-delicious_cookie=macha.i225faTyCrJUY8TvpTuJHI20HBWbQ89B4GV7lT4E%2FB0%3D; Path=/; Secure'293 )294 })295296 app.get('/set-signed-host-prefix-cookie', async (c) => {297 await setSignedCookie(c, 'delicious_cookie', 'macha', 'secret choco chips', {298 prefix: 'host',299 domain: 'example.com', // this will be ignored300 path: 'example.com', // thi will be ignored301 secure: false, // this will be ignored302 })303 return c.text('Set host prefix cookie')304 })305306 it('Set signed cookie with host prefix', async () => {307 const res = await app.request('http://localhost/set-signed-host-prefix-cookie')308 expect(res.status).toBe(200)309 const header = res.headers.get('Set-Cookie')310 expect(header).toBe(311 '__Host-delicious_cookie=macha.i225faTyCrJUY8TvpTuJHI20HBWbQ89B4GV7lT4E%2FB0%3D; Path=/; Secure'312 )313 })314315 app.get('/set-cookie-complex', (c) => {316 setCookie(c, 'great_cookie', 'banana', {317 path: '/',318 secure: true,
102 unmodified lines
modified:src/helper/cookie/index.ts+65 added-9 removed
1import type { Context } from '../../context'2import { parse, parseSigned, serialize, serializeSigned } from '../../utils/cookie'3import type { CookieOptions, Cookie, SignedCookie } from '../../utils/cookie'3import type { CookieOptions, Cookie, SignedCookie, CookiePrefixOptions } from '../../utils/cookie'45interface GetCookie {6 (c: Context, key: string): string | undefined7 (c: Context): Cookie8 (c: Context, key: string, prefixOptions: CookiePrefixOptions): string | undefined9}1011interface GetSignedCookie {12 (c: Context, secret: string | BufferSource, key: string): Promise<string | undefined | false>13 (c: Context, secret: string): Promise<SignedCookie>14 (15 c: Context,16 secret: string | BufferSource,17 key: string,18 prefixOptions: CookiePrefixOptions19 ): Promise<string | undefined | false>20}2115export const getCookie: GetCookie = (c, key?) => {22export const getCookie: GetCookie = (c, key?, prefix?: CookiePrefixOptions) => {23 const cookie = c.req.raw.headers.get('Cookie')24 if (typeof key === 'string') {25 if (!cookie) {26 return undefined27 }28 let finalKey = key29 if (prefix === 'secure') {30 finalKey = '__Secure-' + key31 } else if (prefix === 'host') {32 finalKey = '__Host-' + key33 }21 const obj = parse(cookie, key)22 return obj[key]34 const obj = parse(cookie, finalKey)35 return obj[finalKey]36 }37 if (!cookie) {38 return {}39 }
1 unmodified line
41 // eslint-disable-next-line @typescript-eslint/no-explicit-any42 return obj as any43}4432export const getSignedCookie: GetSignedCookie = async (c, secret, key?) => {45export const getSignedCookie: GetSignedCookie = async (46 c,47 secret,48 key?,49 prefix?: CookiePrefixOptions50) => {51 const cookie = c.req.raw.headers.get('Cookie')52 if (typeof key === 'string') {53 if (!cookie) {54 return undefined55 }56 let finalKey = key57 if (prefix === 'secure') {58 finalKey = '__Secure-' + key59 } else if (prefix === 'host') {60 finalKey = '__Host-' + key61 }38 const obj = await parseSigned(cookie, secret, key)39 return obj[key]62 const obj = await parseSigned(cookie, secret, finalKey)63 return obj[finalKey]64 }65 if (!cookie) {66 return {}67 }
2 unmodified lines
70 return obj as any71}7273export const setCookie = (c: Context, name: string, value: string, opt?: CookieOptions): void => {74 // Cookie names prefixed with __Secure- can be used only if they are set with the secure attribute.75 // Cookie names prefixed with __Host- can be used only if they are set with the secure attribute, must have a path of / (meaning any path at the host)76 // and must not have a Domain attribute.77 // Read more at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie_prefixes'78 let cookie79 if (opt?.prefix === 'secure') {80 cookie = serialize('__Secure-' + name, value, { path: '/', ...opt, secure: true })81 } else if (opt?.prefix === 'host') {82 cookie = serialize('__Host-' + name, value, {83 ...opt,84 path: '/',85 secure: true,86 domain: undefined,87 })88 } else {50 const cookie = serialize(name, value, { path: '/', ...opt })89 cookie = serialize(name, value, { path: '/', ...opt })90 }91 c.header('set-cookie', cookie, { append: true })92}9394export const setSignedCookie = async (
2 unmodified lines
97 value: string,98 secret: string | BufferSource,99 opt?: CookieOptions100): Promise<void> => {101 let cookie102 if (opt?.prefix === 'secure') {103 cookie = await serializeSigned('__Secure-' + name, value, secret, {104 path: '/',105 ...opt,106 secure: true,107 })108 } else if (opt?.prefix === 'host') {109 cookie = await serializeSigned('__Host-' + name, value, secret, {110 ...opt,111 path: '/',112 secure: true,113 domain: undefined,114 })115 } else {61 const cookie = await serializeSigned(name, value, secret, { path: '/', ...opt })116 cookie = await serializeSigned(name, value, secret, { path: '/', ...opt })117 }118 c.header('set-cookie', cookie, { append: true })119}120121export const deleteCookie = (c: Context, name: string, opt?: CookieOptions): void => {
2 unmodified lines
modified:src/helper/dev/index.ts+2 added-10 removed
1import type { Hono } from '../../hono'2import type { Env, RouterRoute } from '../../types'3import { getColorEnabled } from '../../utils/color'4import { findTargetHandler, isMiddleware } from '../../utils/handler'56interface ShowRoutesOptions {7 verbose?: boolean
23 unmodified lines
31 })32}3334export const showRoutes = <E extends Env>(hono: Hono<E>, opts?: ShowRoutesOptions) => {34 // eslint-disable-next-line @typescript-eslint/no-explicit-any35 const { process, Deno } = globalThis as any36 const isNoColor =37 typeof process !== 'undefined'38 ? // eslint-disable-next-line no-unsafe-optional-chaining39 'NO_COLOR' in process?.env40 : typeof Deno?.noColor === 'boolean'41 ? (Deno.noColor as boolean)42 : false43 const colorEnabled = opts?.colorize ?? !isNoColor35 const colorEnabled = opts?.colorize ?? getColorEnabled()36 const routeData: Record<string, RouteData[]> = {}37 let maxMethodLength = 038 let maxPathLength = 039
35 unmodified lines
deleted:src/helper/ssg/index.test.tsx-470 removed
1import { beforeEach, describe, expect, it } from 'vitest'2import { Hono } from '../../hono'3// eslint-disable-next-line @typescript-eslint/no-unused-vars4import { jsx } from '../../jsx'5import { poweredBy } from '../../middleware/powered-by'6import {7 SSG_DISABLED_RESPONSE,8 fetchRoutesContent,9 saveContentToFiles,10 ssgParams,11 toSSG,12 isSSGContext,13 disableSSG,14 onlySSG,15} from './index'16import type {17 BeforeRequestHook,18 AfterResponseHook,19 AfterGenerateHook,20 FileSystemModule,21} from './index'2223describe('toSSG function', () => {24 let app: Hono2526 const postParams = [{ post: '1' }, { post: '2' }]2728 beforeEach(() => {29 app = new Hono()30 app.all('/', (c) => c.html('Hello, World!'))31 app.get('/about', (c) => c.html('About Page'))32 app.get('/about/some', (c) => c.text('About Page 2tier'))33 app.post('/about/some/thing', (c) => c.text('About Page 3tier'))34 app.get('/bravo', (c) => c.html('Bravo Page'))35 app.get('/Charlie', async (c, next) => {36 c.setRenderer((content, head) => {37 return c.html(38 <html>39 <head>40 <title>{head.title || ''}</title>41 </head>42 <body>43 <p>{content}</p>44 </body>45 </html>46 )47 })48 await next()49 })50 app.get('/Charlie', (c) => {51 return c.render('Hello!', { title: 'Charlies Page' })52 })5354 // Included params55 app.get(56 '/post/:post',57 ssgParams(() => postParams),58 (c) => c.html(<h1>{c.req.param('post')}</h1>)59 )6061 app.get(62 '/user/:user_id',63 ssgParams([{ user_id: '1' }, { user_id: '2' }, { user_id: '3' }]),64 (c) => c.html(<h1>{c.req.param('user_id')}</h1>)65 )6667 type Env = {68 Bindings: {69 FOO_DB: string70 }71 Variables: {72 FOO_VAR: string73 }74 }7576 app.get(77 '/env-type-check',78 ssgParams<Env>((c) => {79 expectTypeOf<typeof c.env.FOO_DB>().toBeString()80 expectTypeOf<typeof c.var.FOO_VAR>().toBeString()81 return []82 })83 )84 })85 it('Should correctly generate static HTML files for Hono routes', async () => {86 const fsMock: FileSystemModule = {87 writeFile: vi.fn(() => Promise.resolve()),88 mkdir: vi.fn(() => Promise.resolve()),89 }9091 const htmlMap = await fetchRoutesContent(app)9293 for (const postParam of postParams) {94 const html = htmlMap.get(`/post/${postParam.post}`)95 expect(html?.content).toBe(`<h1>${postParam.post}</h1>`)96 }9798 for (let i = 1; i <= 3; i++) {99 const html = htmlMap.get(`/user/${i}`)100 expect(html?.content).toBe(`<h1>${i}</h1>`)101 }102103 const files = await saveContentToFiles(htmlMap, fsMock, './static')104105 expect(files.length).toBeGreaterThan(0)106 expect(fsMock.mkdir).toHaveBeenCalledWith(expect.any(String), {107 recursive: true,108 })109 expect(fsMock.writeFile).toHaveBeenCalled()110 })111112 it('Should handle file system errors correctly in saveContentToFiles', async () => {113 const fsMock: FileSystemModule = {114 writeFile: vi.fn(() => Promise.reject(new Error('Write error'))),115 mkdir: vi.fn(() => Promise.resolve()),116 }117118 try {119 const htmlMap = await fetchRoutesContent(app)120 await saveContentToFiles(htmlMap, fsMock, './static')121 expect(true).toBe(false) // This should not be reached122 } catch (error) {123 if (error instanceof Error) {124 expect(error.message).toBe('Write error')125 } else {126 throw error127 }128 }129 })130131 it('Should handle overall process errors correctly in toSSG', async () => {132 const fsMock: FileSystemModule = {133 writeFile: vi.fn(() => Promise.reject(new Error('Write error'))),134 mkdir: vi.fn(() => Promise.resolve()),135 }136137 const result = await toSSG(app, fsMock, { dir: './static' })138139 expect(result.success).toBe(false)140 expect(result.error).toBeDefined()141 expect(result.files).toStrictEqual([])142 })143144 it('Should correctly generate files with the expected paths', async () => {145 const fsMock: FileSystemModule = {146 writeFile: vi.fn(() => Promise.resolve()),147 mkdir: vi.fn(() => Promise.resolve()),148 }149150 const htmlMap = await fetchRoutesContent(app)151 await saveContentToFiles(htmlMap, fsMock, './static')152153 expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', expect.any(String))154 expect(fsMock.writeFile).toHaveBeenCalledWith('static/about.html', expect.any(String))155 expect(fsMock.writeFile).toHaveBeenCalledWith('static/about/some.txt', expect.any(String))156 expect(fsMock.writeFile).not.toHaveBeenCalledWith(157 'static/about/some/thing.txt',158 expect.any(String)159 )160 expect(fsMock.writeFile).toHaveBeenCalledWith('static/about.html', expect.any(String))161 expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo.html', expect.any(String))162 expect(fsMock.writeFile).toHaveBeenCalledWith('static/Charlie.html', expect.any(String))163 })164165 it('should modify the request if the hook is provided', async () => {166 const fsMock: FileSystemModule = {167 writeFile: vi.fn(() => Promise.resolve()),168 mkdir: vi.fn(() => Promise.resolve()),169 }170 const beforeRequestHook: BeforeRequestHook = (req) => {171 if (req.method === 'GET') {172 return req173 }174 return false175 }176 const result = await toSSG(app, fsMock, { beforeRequestHook })177 expect(result.files).toHaveLength(10)178 })179180 it('should skip the route if the request hook returns false', async () => {181 const beforeRequest: BeforeRequestHook = () => false182 const htmlMap = await fetchRoutesContent(app, beforeRequest)183 expect(htmlMap.size).toBe(0)184 })185186 it('should modify the response if the hook is provided', async () => {187 const afterResponseHook: AfterResponseHook = (res) => {188 if (res.status === 200 || res.status === 500) {189 return res190 }191 return false192 }193 const fsMock: FileSystemModule = {194 writeFile: vi.fn(() => Promise.resolve()),195 mkdir: vi.fn(() => Promise.resolve()),196 }197 const result = await toSSG(app, fsMock, { afterResponseHook })198 expect(result.files).toHaveLength(10)199 })200201 it('should skip the route if the response hook returns false', async () => {202 const afterResponse: AfterResponseHook = () => false203 const htmlMap = await fetchRoutesContent(app, undefined, afterResponse)204 expect(htmlMap.size).toBe(0)205 })206207 it('should execute additional processing using afterGenerateHook', async () => {208 const fsMock: FileSystemModule = {209 writeFile: vi.fn(() => Promise.resolve()),210 mkdir: vi.fn(() => Promise.resolve()),211 }212 const afterGenerateHookMock: AfterGenerateHook = vi.fn((result) => {213 if (result.files) {214 result.files.forEach((file) => console.log(file))215 }216 })217218 await toSSG(app, fsMock, { dir: './static', afterGenerateHook: afterGenerateHookMock })219220 expect(afterGenerateHookMock).toHaveBeenCalled()221 expect(afterGenerateHookMock).toHaveBeenCalledWith(expect.anything())222 })223224 it('should avoid memory leak from `req.signal.addEventListener()`', async () => {225 const fsMock: FileSystemModule = {226 writeFile: vi.fn(() => Promise.resolve()),227 mkdir: vi.fn(() => Promise.resolve()),228 }229230 const signalAddEventListener = vi.fn(() => {})231 const app = new Hono()232 app.get('/post/:post', ssgParams([{ post: '1' }, { post: '2' }]), (c) =>233 c.html(<h1>{c.req.param('post')}</h1>)234 )235 await toSSG(app, fsMock, {236 beforeRequestHook: (req) => {237 req.signal.addEventListener = signalAddEventListener238 return req239 },240 })241242 expect(signalAddEventListener).not.toHaveBeenCalled()243 })244})245246describe('fetchRoutesContent function', () => {247 let app: Hono248249 beforeEach(() => {250 app = new Hono()251 app.get('/text', (c) => c.text('Text Response'))252 app.get('/html', (c) => c.html('<p>HTML Response</p>'))253 app.get('/json', (c) => c.json({ message: 'JSON Response' }))254 app.use('*', poweredBy())255 })256257 it('should fetch the correct content and MIME type for each route', async () => {258 const htmlMap = await fetchRoutesContent(app)259 expect(htmlMap.get('/text')).toEqual({260 content: 'Text Response',261 mimeType: 'text/plain',262 })263 expect(htmlMap.get('/html')).toEqual({264 content: '<p>HTML Response</p>',265 mimeType: 'text/html',266 })267 expect(htmlMap.get('/json')).toEqual({268 content: '{"message":"JSON Response"}',269 mimeType: 'application/json',270 })271 })272273 it('should skip middleware routes', async () => {274 const htmlMap = await fetchRoutesContent(app)275 expect(htmlMap.has('*')).toBeFalsy()276 })277278 it('should handle errors correctly', async () => {279 vi.spyOn(app, 'fetch').mockRejectedValue(new Error('Network error'))280 await expect(fetchRoutesContent(app)).rejects.toThrow('Network error')281 vi.restoreAllMocks()282 })283})284285describe('saveContentToFiles function', () => {286 let fsMock: FileSystemModule287 let htmlMap: Map<string, { content: string | ArrayBuffer; mimeType: string }>288 // tar.gz, testdir/test.txt289 const gzFileBuffer = Buffer.from(290 'H4sIAAAAAAAAA+3SQQrCMBSE4aw9RU6gSc3LO0/FLgqukgj29qZgsQgqCEHE/9vMIoEMTMqQy3FMO9OQq1RkTq/i1rkwPkiMUXWvnXG+U/XGSstSi3MufbLWHIZ0mvLYP7v37vxHldv+c27LpbR4Yx44hvBi/3DfX3zdP0j9Eta1KPPoz/ef+mnz7Q4AAAAAAAAAAAAAAAAAPnMFqt1/BQAoAAA=',291 'base64'292 )293 const gzFileArrayBuffer = gzFileBuffer.buffer.slice(294 gzFileBuffer.byteOffset,295 gzFileBuffer.byteLength + gzFileBuffer.byteOffset296 )297 // PNG, red dot (1x1)298 const pngFileBuffer = Buffer.from(299 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCCAAAALw',300 'base64'301 )302 const pngFileArrayBuffer = pngFileBuffer.buffer.slice(303 pngFileBuffer.byteOffset,304 pngFileBuffer.byteLength + pngFileBuffer.byteOffset305 )306307 beforeEach(() => {308 fsMock = {309 writeFile: vi.fn(() => Promise.resolve()),310 mkdir: vi.fn(() => Promise.resolve()),311 }312 htmlMap = new Map([313 ['/', { content: 'Home Page', mimeType: 'text/html' }],314 ['/index.html', { content: 'Home Page2', mimeType: 'text/html' }],315 ['/about', { content: 'About Page', mimeType: 'text/html' }],316 ['/about/', { content: 'About Page', mimeType: 'text/html' }],317 ['/bravo/index.html', { content: 'About Page', mimeType: 'text/html' }],318 ['/bravo/release-4.0.0', { content: 'Release 4.0.0', mimeType: 'text/html' }],319 ['/bravo/2024.02.18-sweet-memories', { content: 'Sweet Memories', mimeType: 'text/html' }],320 ['/bravo/deep.dive.to.html', { content: 'Deep Dive To HTML', mimeType: 'text/html' }],321 ['/bravo/alert.js', { content: 'alert("evil content")', mimeType: 'text/html' }],322 [323 '/bravo/index.tar.gz',324 {325 content: gzFileArrayBuffer,326 mimeType: 'application/gzip',327 },328 ],329 [330 '/bravo/dot.png',331 {332 content: pngFileArrayBuffer,333 mimeType: 'image/png',334 },335 ],336 ['/bravo.text/index.html', { content: 'About Page', mimeType: 'text/html' }],337 ['/bravo.text/', { content: 'Bravo Page', mimeType: 'text/html' }],338 ])339 })340341 it('should correctly create files with the right content and paths', async () => {342 await saveContentToFiles(htmlMap, fsMock, './static')343344 expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', 'Home Page')345 expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', 'Home Page2')346 expect(fsMock.writeFile).toHaveBeenCalledWith('static/about.html', 'About Page')347 expect(fsMock.writeFile).toHaveBeenCalledWith('static/about/index.html', 'About Page')348 expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo/index.html', 'About Page')349 expect(fsMock.writeFile).toHaveBeenCalledWith(350 'static/bravo/release-4.0.0.html',351 'Release 4.0.0'352 )353 expect(fsMock.writeFile).toHaveBeenCalledWith(354 'static/bravo/deep.dive.to.html',355 'Deep Dive To HTML'356 )357 expect(fsMock.writeFile).toHaveBeenCalledWith(358 'static/bravo/2024.02.18-sweet-memories.html',359 'Sweet Memories'360 )361 expect(fsMock.writeFile).toHaveBeenCalledWith(362 'static/bravo/alert.js.html',363 'alert("evil content")'364 )365 expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo.text/index.html', 'About Page')366 expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo.text/index.html', 'Bravo Page')367368 // binary files369 expect(fsMock.writeFile).toHaveBeenCalledWith(370 'static/bravo/index.tar.gz',371 new Uint8Array(gzFileArrayBuffer)372 )373 expect(fsMock.writeFile).toHaveBeenCalledWith(374 'static/bravo/dot.png',375 new Uint8Array(pngFileArrayBuffer)376 )377 })378379 it('should correctly create directories if they do not exist', async () => {380 await saveContentToFiles(htmlMap, fsMock, './static')381382 expect(fsMock.mkdir).toHaveBeenCalledWith('static', { recursive: true })383 })384385 it('should handle file writing or directory creation errors', async () => {386 const fsMock: FileSystemModule = {387 writeFile: vi.fn(() => Promise.resolve()),388 mkdir: vi.fn(() => Promise.reject(new Error('File write error'))),389 }390391 await expect(saveContentToFiles(htmlMap, fsMock, './static')).rejects.toThrow(392 'File write error'393 )394 })395 it('check extensions', async () => {396 await saveContentToFiles(htmlMap, fsMock, './static')397398 expect(fsMock.mkdir).toHaveBeenCalledWith('static', { recursive: true })399 })400})401402describe('Dynamic route handling', () => {403 let app: Hono404 beforeEach(() => {405 app = new Hono()406 app.get('/shops/:id', (c) => c.html('Shop Page'))407 app.get('/shops/:id/:comments([0-9]+)', (c) => c.html('Comments Page'))408 app.get('/foo/*', (c) => c.html('Foo Page'))409 app.get('/foo:bar', (c) => c.html('Foo Bar Page'))410 })411412 it('should skip /shops/:id dynamic route', async () => {413 const htmlMap = await fetchRoutesContent(app)414 expect(htmlMap.has('/shops/:id')).toBeFalsy()415 })416417 it('should skip /shops/:id/:comments([0-9]+) dynamic route', async () => {418 const htmlMap = await fetchRoutesContent(app)419 expect(htmlMap.has('/shops/:id/:comments([0-9]+)')).toBeFalsy()420 })421422 it('should skip /foo/* dynamic route', async () => {423 const htmlMap = await fetchRoutesContent(app)424 expect(htmlMap.has('/foo/*')).toBeFalsy()425 })426427 it('should not skip /foo:bar dynamic route', async () => {428 const htmlMap = await fetchRoutesContent(app)429 expect(htmlMap.has('/foo:bar')).toBeTruthy()430 })431})432433describe('isSSGContext()', () => {434 const app = new Hono()435 app.get('/', (c) => c.html(<h1>{isSSGContext(c) ? 'SSG' : 'noSSG'}</h1>))436437 it('Should not generate the page if disableSSG is set', async () => {438 const htmlMap = await fetchRoutesContent(app)439 expect(await htmlMap.get('/')).toEqual({440 content: '<h1>SSG</h1>',441 mimeType: 'text/html',442 })443 })444445 it('Should return 404 response if onlySSG() is set', async () => {446 const res = await app.request('/')447 expect(await res.text()).toBe('<h1>noSSG</h1>')448 })449})450451describe('disableSSG/onlySSG middlewares', () => {452 const app = new Hono()453 app.get('/', (c) => c.html(<h1>Hello</h1>))454 app.get('/api', disableSSG(), (c) => c.text('an-api'))455 app.get('/disable-by-response', () => SSG_DISABLED_RESPONSE)456 app.get('/static-page', onlySSG(), (c) => c.html(<h1>Welcome to my site</h1>))457458 it('Should not generate the page if disableSSG is set', async () => {459 const htmlMap = await fetchRoutesContent(app)460 expect(htmlMap.has('/')).toBe(true)461 expect(htmlMap.has('/static-page')).toBe(true)462 expect(htmlMap.has('/api')).toBe(false)463 expect(htmlMap.has('/disable-by-response')).toBe(false)464 })465466 it('Should return 404 response if onlySSG() is set', async () => {467 const res = await app.request('/static-page')468 expect(res.status).toBe(404)469 })470})
modified:src/helper/ssg/index.ts+2 added-294 removed
1import { replaceUrlParam } from '../../client/utils'2import type { Context } from '../../context'3import type { Hono } from '../../hono'4import type { Env, MiddlewareHandler, Schema } from '../../types'5import { getExtension } from '../../utils/mime'6import { joinPaths, dirname, filterStaticGenerateRoutes } from './utils'78const SSG_CONTEXT = 'HONO_SSG_CONTEXT'9export const SSG_DISABLED_RESPONSE = new Response('SSG is disabled', { status: 404 })1011/**12 * @experimental13 * `FileSystemModule` is an experimental feature.14 * The API might be changed.15 */16export interface FileSystemModule {17 writeFile(path: string, data: string | Uint8Array): Promise<void>18 mkdir(path: string, options: { recursive: boolean }): Promise<void | string>19}2021/**22 * @experimental23 * `ToSSGResult` is an experimental feature.24 * The API might be changed.25 */26export interface ToSSGResult {27 success: boolean28 files: string[]29 error?: Error30}3132const generateFilePath = (routePath: string, outDir: string, mimeType: string) => {33 const extension = determineExtension(mimeType)3435 if (routePath.endsWith(`.${extension}`)) {36 return joinPaths(outDir, routePath)37 }3839 if (routePath === '/') {40 return joinPaths(outDir, `index.${extension}`)41 }42 if (routePath.endsWith('/')) {43 return joinPaths(outDir, routePath, `index.${extension}`)44 }45 return joinPaths(outDir, `${routePath}.${extension}`)46}4748const parseResponseContent = async (response: Response): Promise<string | ArrayBuffer> => {49 const contentType = response.headers.get('Content-Type')5051 try {52 if (contentType?.includes('text') || contentType?.includes('json')) {53 return await response.text()54 } else {55 return await response.arrayBuffer()56 }57 } catch (error) {58 throw new Error(59 `Error processing response: ${error instanceof Error ? error.message : 'Unknown error'}`60 )61 }62}6364const determineExtension = (mimeType: string): string => {65 switch (mimeType) {66 case 'text/html':67 return 'html'68 case 'text/xml':69 case 'application/xml':70 return 'xml'71 default: {72 return getExtension(mimeType) || 'html'73 }74 }75}7677interface SSGParam {78 [key: string]: string79}80type SSGParams = SSGParam[]8182interface SSGParamsMiddleware {83 <E extends Env = Env>(84 generateParams: (c: Context<E>) => SSGParams | Promise<SSGParams>85 ): MiddlewareHandler<E>86 <E extends Env = Env>(params: SSGParams): MiddlewareHandler<E>87}8889type AddedSSGDataRequest = Request & {90 ssgParams?: SSGParams91}92/**93 * Define SSG Route94 */95export const ssgParams: SSGParamsMiddleware = (params) => async (c, next) => {96 ;(c.req.raw as AddedSSGDataRequest).ssgParams = Array.isArray(params) ? params : await params(c)97 await next()98}99100export type BeforeRequestHook = (req: Request) => Request | false101export type AfterResponseHook = (res: Response) => Response | false102export type AfterGenerateHook = (result: ToSSGResult) => void | Promise<void>103104export interface ToSSGOptions {105 dir?: string106 beforeRequestHook?: BeforeRequestHook107 afterResponseHook?: AfterResponseHook108 afterGenerateHook?: AfterGenerateHook109}110111/**112 * @experimental113 * `fetchRoutesContent` is an experimental feature.114 * The API might be changed.115 */116export const fetchRoutesContent = async <117 E extends Env = Env,118 S extends Schema = {},119 BasePath extends string = '/'120>(121 app: Hono<E, S, BasePath>,122 beforeRequestHook?: BeforeRequestHook,123 afterResponseHook?: AfterResponseHook124): Promise<Map<string, { content: string | ArrayBuffer; mimeType: string }>> => {125 const htmlMap = new Map<string, { content: string | ArrayBuffer; mimeType: string }>()126 const baseURL = 'http://localhost'127128 for (const route of filterStaticGenerateRoutes(app)) {129 // GET Route Info130 const thisRouteBaseURL = new URL(route.path, baseURL).toString()131132 let forGetInfoURLRequest = new Request(thisRouteBaseURL) as AddedSSGDataRequest133 if (beforeRequestHook) {134 const maybeRequest = beforeRequestHook(forGetInfoURLRequest)135 if (!maybeRequest) {136 continue137 }138 forGetInfoURLRequest = maybeRequest as unknown as AddedSSGDataRequest139 }140 await app.fetch(forGetInfoURLRequest)141142 if (!forGetInfoURLRequest.ssgParams) {143 if (isDynamicRoute(route.path)) {144 continue145 }146 forGetInfoURLRequest.ssgParams = [{}]147 }148149 const requestInit = {150 method: forGetInfoURLRequest.method,151 headers: forGetInfoURLRequest.headers,152 }153 for (const param of forGetInfoURLRequest.ssgParams) {154 const replacedUrlParam = replaceUrlParam(route.path, param)155 let response = await app.request(replacedUrlParam, requestInit, {156 [SSG_CONTEXT]: true,157 })158 if (response === SSG_DISABLED_RESPONSE) {159 continue160 }161 if (afterResponseHook) {162 const maybeResponse = afterResponseHook(response)163 if (!maybeResponse) {164 continue165 }166 response = maybeResponse167 }168 const mimeType = response.headers.get('Content-Type')?.split(';')[0] || 'text/plain'169 const content = await parseResponseContent(response)170 htmlMap.set(replacedUrlParam, {171 mimeType,172 content,173 })174 }175 }176177 return htmlMap178}179180const isDynamicRoute = (path: string): boolean => {181 return path.split('/').some((segment) => segment.startsWith(':') || segment.includes('*'))182}183184/**185 * @experimental186 * `saveContentToFiles` is an experimental feature.187 * The API might be changed.188 */189export const saveContentToFiles = async (190 htmlMap: Map<string, { content: string | ArrayBuffer; mimeType: string }>,191 fsModule: FileSystemModule,192 outDir: string193): Promise<string[]> => {194 const files: string[] = []195196 for (const [routePath, { content, mimeType }] of htmlMap) {197 const filePath = generateFilePath(routePath, outDir, mimeType)198 const dirPath = dirname(filePath)199200 await fsModule.mkdir(dirPath, { recursive: true })201 if (typeof content === 'string') {202 await fsModule.writeFile(filePath, content)203 } else if (content instanceof ArrayBuffer) {204 await fsModule.writeFile(filePath, new Uint8Array(content))205 }206 files.push(filePath)207 }208209 return files210}211212/**213 * @experimental214 * `ToSSGInterface` is an experimental feature.215 * The API might be changed.216 */217export interface ToSSGInterface {218 (219 // eslint-disable-next-line @typescript-eslint/no-explicit-any220 app: Hono<any, any, any>,221 fsModule: FileSystemModule,222 options?: ToSSGOptions223 ): Promise<ToSSGResult>224}225226/**227 * @experimental228 * `ToSSGAdaptorInterface` is an experimental feature.229 * The API might be changed.230 */231export interface ToSSGAdaptorInterface<232 E extends Env = Env,233 S extends Schema = {},234 BasePath extends string = '/'235> {236 (app: Hono<E, S, BasePath>, options?: ToSSGOptions): Promise<ToSSGResult>237}238239/**240 * @experimental241 * `toSSG` is an experimental feature.242 * The API might be changed.243 */244export const toSSG: ToSSGInterface = async (app, fs, options) => {245 let result: ToSSGResult | undefined = undefined246 try {247 const outputDir = options?.dir ?? './static'248 const maps = await fetchRoutesContent(249 app,250 options?.beforeRequestHook,251 options?.afterResponseHook252 )253 const files = await saveContentToFiles(maps, fs, outputDir)254 result = { success: true, files }255 } catch (error) {256 const errorObj = error instanceof Error ? error : new Error(String(error))257 result = { success: false, files: [], error: errorObj }258 }259 await options?.afterGenerateHook?.(result)260 return result261}262263/**264 * @experimental265 * `isSSGContext` is an experimental feature.266 * The API might be changed.267 */268export const isSSGContext = (c: Context): boolean => !!c.env?.[SSG_CONTEXT]269270/**271 * @experimental272 * `disableSSG` is an experimental feature.273 * The API might be changed.274 */275export const disableSSG = (): MiddlewareHandler =>276 async function disableSSG(c, next) {277 if (isSSGContext(c)) {278 return SSG_DISABLED_RESPONSE279 }280 await next()281 }282283/**284 * @experimental285 * `onlySSG` is an experimental feature.286 * The API might be changed.287 */288export const onlySSG = (): MiddlewareHandler =>289 async function onlySSG(c, next) {290 if (!isSSGContext(c)) {291 return c.notFound()292 }293 await next()294 }1export * from './ssg'2export { SSG_DISABLED_RESPONSE, ssgParams, isSSGContext, disableSSG, onlySSG } from './middleware'
added:src/helper/ssg/middleware.ts+62 added
1import type { Context } from '../../context'2import type { Env, MiddlewareHandler } from '../../types'34export const SSG_CONTEXT = 'HONO_SSG_CONTEXT'5export const SSG_DISABLED_RESPONSE = new Response('SSG is disabled', { status: 404 })67interface SSGParam {8 [key: string]: string9}10export type SSGParams = SSGParam[]1112interface SSGParamsMiddleware {13 <E extends Env = Env>(14 generateParams: (c: Context<E>) => SSGParams | Promise<SSGParams>15 ): MiddlewareHandler<E>16 <E extends Env = Env>(params: SSGParams): MiddlewareHandler<E>17}1819export type AddedSSGDataRequest = Request & {20 ssgParams?: SSGParams21}2223/**24 * Define SSG Route25 */26export const ssgParams: SSGParamsMiddleware = (params) => async (c, next) => {27 ;(c.req.raw as AddedSSGDataRequest).ssgParams = Array.isArray(params) ? params : await params(c)28 await next()29}3031/**32 * @experimental33 * `isSSGContext` is an experimental feature.34 * The API might be changed.35 */36export const isSSGContext = (c: Context): boolean => !!c.env?.[SSG_CONTEXT]3738/**39 * @experimental40 * `disableSSG` is an experimental feature.41 * The API might be changed.42 */43export const disableSSG = (): MiddlewareHandler =>44 async function disableSSG(c, next) {45 if (isSSGContext(c)) {46 return SSG_DISABLED_RESPONSE47 }48 await next()49 }5051/**52 * @experimental53 * `onlySSG` is an experimental feature.54 * The API might be changed.55 */56export const onlySSG = (): MiddlewareHandler =>57 async function onlySSG(c, next) {58 if (!isSSGContext(c)) {59 return c.notFound()60 }61 await next()62 }
added:src/helper/ssg/ssg.test.tsx+500 added
1import { beforeEach, describe, expect, it } from 'vitest'2import { Hono } from '../../hono'3// eslint-disable-next-line @typescript-eslint/no-unused-vars4import { jsx } from '../../jsx'5import { poweredBy } from '../../middleware/powered-by'6import { SSG_DISABLED_RESPONSE, ssgParams, isSSGContext, disableSSG, onlySSG } from './middleware'7import { fetchRoutesContent, saveContentToFile, toSSG } from './ssg'8import type {9 BeforeRequestHook,10 AfterResponseHook,11 AfterGenerateHook,12 FileSystemModule,13} from './ssg'1415const resolveRoutesContent = async (res: ReturnType<typeof fetchRoutesContent>) => {16 const htmlMap = new Map<string, { content: string | ArrayBuffer; mimeType: string }>()17 for (const getInfoPromise of res) {18 const getInfo = await getInfoPromise19 if (!getInfo) {20 continue21 }22 for (const dataPromise of getInfo) {23 const data = await dataPromise24 if (!data) {25 continue26 }27 htmlMap.set(data.routePath, {28 content: data.content,29 mimeType: data.mimeType,30 })31 }32 }33 return htmlMap34}3536describe('toSSG function', () => {37 let app: Hono38 let fsMock: FileSystemModule3940 const postParams = [{ post: '1' }, { post: '2' }]4142 beforeEach(() => {43 app = new Hono()44 app.all('/', (c) => c.html('Hello, World!'))45 app.get('/about', (c) => c.html('About Page'))46 app.get('/about/some', (c) => c.text('About Page 2tier'))47 app.post('/about/some/thing', (c) => c.text('About Page 3tier'))48 app.get('/bravo', (c) => c.html('Bravo Page'))49 app.get('/Charlie', async (c, next) => {50 c.setRenderer((content, head) => {51 return c.html(52 <html>53 <head>54 <title>{head.title || ''}</title>55 </head>56 <body>57 <p>{content}</p>58 </body>59 </html>60 )61 })62 await next()63 })64 app.get('/Charlie', (c) => {65 return c.render('Hello!', { title: 'Charlies Page' })66 })6768 // Included params69 app.get(70 '/post/:post',71 ssgParams(() => postParams),72 (c) => c.html(<h1>{c.req.param('post')}</h1>)73 )7475 app.get(76 '/user/:user_id',77 ssgParams([{ user_id: '1' }, { user_id: '2' }, { user_id: '3' }]),78 (c) => c.html(<h1>{c.req.param('user_id')}</h1>)79 )8081 type Env = {82 Bindings: {83 FOO_DB: string84 }85 Variables: {86 FOO_VAR: string87 }88 }8990 app.get(91 '/env-type-check',92 ssgParams<Env>((c) => {93 expectTypeOf<typeof c.env.FOO_DB>().toBeString()94 expectTypeOf<typeof c.var.FOO_VAR>().toBeString()95 return []96 })97 )9899 fsMock = {100 writeFile: vi.fn(() => Promise.resolve()),101 mkdir: vi.fn(() => Promise.resolve()),102 }103 })104 it('Should correctly generate static HTML files for Hono routes', async () => {105 const writtenFiles: Record<string, string> = {}106 const fsMock: FileSystemModule = {107 writeFile: (path, data) => {108 writtenFiles[path] = typeof data === 'string' ? data : data.toString()109 return Promise.resolve()110 },111 mkdir: vi.fn(() => Promise.resolve()),112 }113114 const result = await toSSG(app, fsMock, { dir: './static' })115116 for (const postParam of postParams) {117 const html = writtenFiles[`static/post/${postParam.post}.html`]118 expect(html).toBe(`<h1>${postParam.post}</h1>`)119 }120121 for (let i = 1; i <= 3; i++) {122 const html = writtenFiles[`static/user/${i}.html`]123 expect(html).toBe(`<h1>${i}</h1>`)124 }125126 expect(result.files.length).toBe(10)127 expect(fsMock.mkdir).toHaveBeenCalledWith(expect.any(String), {128 recursive: true,129 })130 })131132 it('Should handle file system errors correctly in saveContentToFiles', async () => {133 const fsMock: FileSystemModule = {134 writeFile: vi.fn(() => Promise.reject(new Error('Write error'))),135 mkdir: vi.fn(() => Promise.resolve()),136 }137138 const result = await toSSG(app, fsMock, { dir: './static' })139 expect(result.success).toBe(false)140 expect(result.files).toStrictEqual([])141 expect(result.error?.message).toBe('Write error')142 })143144 it('Should handle overall process errors correctly in toSSG', async () => {145 const fsMock: FileSystemModule = {146 writeFile: vi.fn(() => Promise.reject(new Error('Write error'))),147 mkdir: vi.fn(() => Promise.resolve()),148 }149150 const result = await toSSG(app, fsMock, { dir: './static' })151152 expect(result.success).toBe(false)153 expect(result.error).toBeDefined()154 expect(result.files).toStrictEqual([])155 })156157 it('Should correctly generate files with the expected paths', async () => {158 await toSSG(app, fsMock, { dir: './static' })159160 expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', expect.any(String))161 expect(fsMock.writeFile).toHaveBeenCalledWith('static/about.html', expect.any(String))162 expect(fsMock.writeFile).toHaveBeenCalledWith('static/about/some.txt', expect.any(String))163 expect(fsMock.writeFile).not.toHaveBeenCalledWith(164 'static/about/some/thing.txt',165 expect.any(String)166 )167 expect(fsMock.writeFile).toHaveBeenCalledWith('static/about.html', expect.any(String))168 expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo.html', expect.any(String))169 expect(fsMock.writeFile).toHaveBeenCalledWith('static/Charlie.html', expect.any(String))170 })171172 it('should modify the request if the hook is provided', async () => {173 const beforeRequestHook: BeforeRequestHook = (req) => {174 if (req.method === 'GET') {175 return req176 }177 return false178 }179 const result = await toSSG(app, fsMock, { beforeRequestHook })180 expect(result.files).toHaveLength(10)181 })182183 it('should skip the route if the request hook returns false', async () => {184 const beforeRequest: BeforeRequestHook = () => false185 const result = await toSSG(app, fsMock, { beforeRequestHook: beforeRequest })186 expect(result.success).toBe(true)187 expect(result.files).toStrictEqual([])188 })189190 it('should modify the response if the hook is provided', async () => {191 const afterResponseHook: AfterResponseHook = (res) => {192 if (res.status === 200 || res.status === 500) {193 return res194 }195 return false196 }197 const result = await toSSG(app, fsMock, { afterResponseHook })198 expect(result.files).toHaveLength(10)199 })200201 it('should skip the route if the response hook returns false', async () => {202 const afterResponse: AfterResponseHook = () => false203 const result = await toSSG(app, fsMock, { afterResponseHook: afterResponse })204 expect(result.success).toBe(true)205 expect(result.files).toStrictEqual([])206 })207208 it('should execute additional processing using afterGenerateHook', async () => {209 const fsMock: FileSystemModule = {210 writeFile: vi.fn(() => Promise.resolve()),211 mkdir: vi.fn(() => Promise.resolve()),212 }213 const afterGenerateHookMock: AfterGenerateHook = vi.fn((result) => {214 if (result.files) {215 result.files.forEach((file) => console.log(file))216 }217 })218219 await toSSG(app, fsMock, { dir: './static', afterGenerateHook: afterGenerateHookMock })220221 expect(afterGenerateHookMock).toHaveBeenCalled()222 expect(afterGenerateHookMock).toHaveBeenCalledWith(expect.anything())223 })224225 it('should avoid memory leak from `req.signal.addEventListener()`', async () => {226 const fsMock: FileSystemModule = {227 writeFile: vi.fn(() => Promise.resolve()),228 mkdir: vi.fn(() => Promise.resolve()),229 }230231 const signalAddEventListener = vi.fn(() => {})232 const app = new Hono()233 app.get('/post/:post', ssgParams([{ post: '1' }, { post: '2' }]), (c) =>234 c.html(<h1>{c.req.param('post')}</h1>)235 )236 await toSSG(app, fsMock, {237 beforeRequestHook: (req) => {238 req.signal.addEventListener = signalAddEventListener239 return req240 },241 })242243 expect(signalAddEventListener).not.toHaveBeenCalled()244 })245})246247describe('fetchRoutesContent function', () => {248 let app: Hono249250 beforeEach(() => {251 app = new Hono()252 app.get('/text', (c) => c.text('Text Response'))253 app.get('/html', (c) => c.html('<p>HTML Response</p>'))254 app.get('/json', (c) => c.json({ message: 'JSON Response' }))255 app.use('*', poweredBy())256 })257258 it('should fetch the correct content and MIME type for each route', async () => {259 const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))260261 expect(htmlMap.get('/text')).toEqual({262 content: 'Text Response',263 mimeType: 'text/plain',264 })265 expect(htmlMap.get('/html')).toEqual({266 content: '<p>HTML Response</p>',267 mimeType: 'text/html',268 })269 expect(htmlMap.get('/json')).toEqual({270 content: '{"message":"JSON Response"}',271 mimeType: 'application/json',272 })273 })274275 it('should skip middleware routes', async () => {276 const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))277 expect(htmlMap.has('*')).toBeFalsy()278 })279280 it('should handle errors correctly', async () => {281 vi.spyOn(app, 'fetch').mockRejectedValue(new Error('Network error'))282 await expect(resolveRoutesContent(fetchRoutesContent(app))).rejects.toThrow('Network error')283 vi.restoreAllMocks()284 })285})286287describe('saveContentToFile function', () => {288 // tar.gz, testdir/test.txt289 const gzFileBuffer = Buffer.from(290 'H4sIAAAAAAAAA+3SQQrCMBSE4aw9RU6gSc3LO0/FLgqukgj29qZgsQgqCEHE/9vMIoEMTMqQy3FMO9OQq1RkTq/i1rkwPkiMUXWvnXG+U/XGSstSi3MufbLWHIZ0mvLYP7v37vxHldv+c27LpbR4Yx44hvBi/3DfX3zdP0j9Eta1KPPoz/ef+mnz7Q4AAAAAAAAAAAAAAAAAPnMFqt1/BQAoAAA=',291 'base64'292 )293 const gzFileArrayBuffer = gzFileBuffer.buffer.slice(294 gzFileBuffer.byteOffset,295 gzFileBuffer.byteLength + gzFileBuffer.byteOffset296 )297 // PNG, red dot (1x1)298 const pngFileBuffer = Buffer.from(299 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCCAAAALw',300 'base64'301 )302 const pngFileArrayBuffer = pngFileBuffer.buffer.slice(303 pngFileBuffer.byteOffset,304 pngFileBuffer.byteLength + pngFileBuffer.byteOffset305 )306307 const fileData = [308 { routePath: '/', content: 'Home Page', mimeType: 'text/html' },309 { routePath: '/index.html', content: 'Home Page2', mimeType: 'text/html' },310 { routePath: '/about', content: 'About Page', mimeType: 'text/html' },311 { routePath: '/about/', content: 'About Page', mimeType: 'text/html' },312 { routePath: '/bravo/index.html', content: 'About Page', mimeType: 'text/html' },313 { routePath: '/bravo/release-4.0.0', content: 'Release 4.0.0', mimeType: 'text/html' },314 {315 routePath: '/bravo/2024.02.18-sweet-memories',316 content: 'Sweet Memories',317 mimeType: 'text/html',318 },319 { routePath: '/bravo/deep.dive.to.html', content: 'Deep Dive To HTML', mimeType: 'text/html' },320 { routePath: '/bravo/alert.js', content: 'alert("evil content")', mimeType: 'text/html' },321 { routePath: '/bravo.text/index.html', content: 'About Page', mimeType: 'text/html' },322 { routePath: '/bravo.text/', content: 'Bravo Page', mimeType: 'text/html' },323 {324 routePath: '/bravo/index.tar.gz',325 content: gzFileArrayBuffer,326 mimeType: 'application/gzip',327 },328 {329 routePath: '/bravo/dot.png',330 content: pngFileArrayBuffer,331 mimeType: 'image/png',332 },333 ]334335 let fsMock: FileSystemModule336337 beforeEach(() => {338 fsMock = {339 writeFile: vi.fn(() => Promise.resolve()),340 mkdir: vi.fn(() => Promise.resolve()),341 }342 })343344 it('should correctly create files with the right content and paths', async () => {345 for (const data of fileData) {346 await saveContentToFile(Promise.resolve(data), fsMock, './static')347 }348349 expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', 'Home Page')350 expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', 'Home Page2')351 expect(fsMock.writeFile).toHaveBeenCalledWith('static/about.html', 'About Page')352 expect(fsMock.writeFile).toHaveBeenCalledWith('static/about/index.html', 'About Page')353 expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo/index.html', 'About Page')354 expect(fsMock.writeFile).toHaveBeenCalledWith(355 'static/bravo/release-4.0.0.html',356 'Release 4.0.0'357 )358 expect(fsMock.writeFile).toHaveBeenCalledWith(359 'static/bravo/deep.dive.to.html',360 'Deep Dive To HTML'361 )362 expect(fsMock.writeFile).toHaveBeenCalledWith(363 'static/bravo/2024.02.18-sweet-memories.html',364 'Sweet Memories'365 )366 expect(fsMock.writeFile).toHaveBeenCalledWith(367 'static/bravo/alert.js.html',368 'alert("evil content")'369 )370 expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo.text/index.html', 'About Page')371 expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo.text/index.html', 'Bravo Page')372 // binary files373 expect(fsMock.writeFile).toHaveBeenCalledWith(374 'static/bravo/index.tar.gz',375 new Uint8Array(gzFileArrayBuffer)376 )377 expect(fsMock.writeFile).toHaveBeenCalledWith(378 'static/bravo/dot.png',379 new Uint8Array(pngFileArrayBuffer)380 )381 })382383 it('should correctly create directories if they do not exist', async () => {384 await saveContentToFile(385 Promise.resolve({386 routePath: '/new-dir/index.html',387 content: 'New Page',388 mimeType: 'text/html',389 }),390 fsMock,391 './static'392 )393 expect(fsMock.mkdir).toHaveBeenCalledWith('static/new-dir', { recursive: true })394 })395396 it('should handle file writing or directory creation errors', async () => {397 const fsMock: FileSystemModule = {398 writeFile: vi.fn(() => Promise.resolve()),399 mkdir: vi.fn(() => Promise.reject(new Error('File write error'))),400 }401402 await expect(403 saveContentToFile(404 Promise.resolve({405 routePath: '/error-dir/index.html',406 content: 'New Page',407 mimeType: 'text/html',408 }),409 fsMock,410 './static'411 )412 ).rejects.toThrow('File write error')413 })414 it('check extensions', async () => {415 for (const data of fileData) {416 await saveContentToFile(Promise.resolve(data), fsMock, './static-check-extensions')417 }418 expect(fsMock.mkdir).toHaveBeenCalledWith('static-check-extensions', { recursive: true })419 })420})421422describe('Dynamic route handling', () => {423 let app: Hono424 beforeEach(() => {425 app = new Hono()426 app.get('/shops/:id', (c) => c.html('Shop Page'))427 app.get('/shops/:id/:comments([0-9]+)', (c) => c.html('Comments Page'))428 app.get('/foo/*', (c) => c.html('Foo Page'))429 app.get('/foo:bar', (c) => c.html('Foo Bar Page'))430 })431432 it('should skip /shops/:id dynamic route', async () => {433 const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))434 expect(htmlMap.has('/shops/:id')).toBeFalsy()435 })436437 it('should skip /shops/:id/:comments([0-9]+) dynamic route', async () => {438 const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))439 expect(htmlMap.has('/shops/:id/:comments([0-9]+)')).toBeFalsy()440 })441442 it('should skip /foo/* dynamic route', async () => {443 const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))444 expect(htmlMap.has('/foo/*')).toBeFalsy()445 })446447 it('should not skip /foo:bar dynamic route', async () => {448 const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))449 expect(htmlMap.has('/foo:bar')).toBeTruthy()450 })451})452453describe('isSSGContext()', () => {454 const app = new Hono()455 app.get('/', (c) => c.html(<h1>{isSSGContext(c) ? 'SSG' : 'noSSG'}</h1>))456457 const fsMock: FileSystemModule = {458 writeFile: vi.fn(() => Promise.resolve()),459 mkdir: vi.fn(() => Promise.resolve()),460 }461462 it('Should not generate the page if disableSSG is set', async () => {463 await toSSG(app, fsMock, { dir: './static' })464 expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', '<h1>SSG</h1>')465 })466467 it('Should return 404 response if onlySSG() is set', async () => {468 const res = await app.request('/')469 expect(await res.text()).toBe('<h1>noSSG</h1>')470 })471})472473describe('disableSSG/onlySSG middlewares', () => {474 const app = new Hono()475 app.get('/', (c) => c.html(<h1>Hello</h1>))476 app.get('/api', disableSSG(), (c) => c.text('an-api'))477 app.get('/disable-by-response', () => SSG_DISABLED_RESPONSE)478 app.get('/static-page', onlySSG(), (c) => c.html(<h1>Welcome to my site</h1>))479480 const fsMock: FileSystemModule = {481 writeFile: vi.fn(() => Promise.resolve()),482 mkdir: vi.fn(() => Promise.resolve()),483 }484485 it('Should not generate the page if disableSSG is set', async () => {486 await toSSG(app, fsMock, { dir: './static' })487 expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', expect.any(String))488 expect(fsMock.writeFile).toHaveBeenCalledWith('static/static-page.html', expect.any(String))489 expect(fsMock.writeFile).not.toHaveBeenCalledWith('static/api.html', expect.any(String))490 expect(fsMock.writeFile).not.toHaveBeenCalledWith(491 'static/disable-by-response.html',492 expect.any(String)493 )494 })495496 it('Should return 404 response if onlySSG() is set', async () => {497 const res = await app.request('/static-page')498 expect(res.status).toBe(404)499 })500})
added:src/helper/ssg/ssg.ts+302 added
1import { replaceUrlParam } from '../../client/utils'2import type { Hono } from '../../hono'3import type { Env, Schema } from '../../types'4import { createPool } from '../../utils/concurrent'5import { getExtension } from '../../utils/mime'6import type { AddedSSGDataRequest, SSGParams } from './middleware'7import { SSG_DISABLED_RESPONSE, SSG_CONTEXT } from './middleware'8import { joinPaths, dirname, filterStaticGenerateRoutes } from './utils'910const DEFAULT_CONCURRENCY = 2 // default concurrency for ssg1112/**13 * @experimental14 * `FileSystemModule` is an experimental feature.15 * The API might be changed.16 */17export interface FileSystemModule {18 writeFile(path: string, data: string | Uint8Array): Promise<void>19 mkdir(path: string, options: { recursive: boolean }): Promise<void | string>20}2122/**23 * @experimental24 * `ToSSGResult` is an experimental feature.25 * The API might be changed.26 */27export interface ToSSGResult {28 success: boolean29 files: string[]30 error?: Error31}3233const generateFilePath = (routePath: string, outDir: string, mimeType: string) => {34 const extension = determineExtension(mimeType)3536 if (routePath.endsWith(`.${extension}`)) {37 return joinPaths(outDir, routePath)38 }3940 if (routePath === '/') {41 return joinPaths(outDir, `index.${extension}`)42 }43 if (routePath.endsWith('/')) {44 return joinPaths(outDir, routePath, `index.${extension}`)45 }46 return joinPaths(outDir, `${routePath}.${extension}`)47}4849const parseResponseContent = async (response: Response): Promise<string | ArrayBuffer> => {50 const contentType = response.headers.get('Content-Type')5152 try {53 if (contentType?.includes('text') || contentType?.includes('json')) {54 return await response.text()55 } else {56 return await response.arrayBuffer()57 }58 } catch (error) {59 throw new Error(60 `Error processing response: ${error instanceof Error ? error.message : 'Unknown error'}`61 )62 }63}6465const determineExtension = (mimeType: string): string => {66 switch (mimeType) {67 case 'text/html':68 return 'html'69 case 'text/xml':70 case 'application/xml':71 return 'xml'72 default: {73 return getExtension(mimeType) || 'html'74 }75 }76}7778export type BeforeRequestHook = (req: Request) => Request | false79export type AfterResponseHook = (res: Response) => Response | false80export type AfterGenerateHook = (result: ToSSGResult) => void | Promise<void>8182export interface ToSSGOptions {83 dir?: string84 beforeRequestHook?: BeforeRequestHook85 afterResponseHook?: AfterResponseHook86 afterGenerateHook?: AfterGenerateHook87 concurrency?: number88}8990/**91 * @experimental92 * `fetchRoutesContent` is an experimental feature.93 * The API might be changed.94 */95export const fetchRoutesContent = function* <96 E extends Env = Env,97 S extends Schema = {},98 BasePath extends string = '/'99>(100 app: Hono<E, S, BasePath>,101 beforeRequestHook?: BeforeRequestHook,102 afterResponseHook?: AfterResponseHook,103 concurrency?: number104): Generator<105 Promise<106 | Generator<107 Promise<{ routePath: string; mimeType: string; content: string | ArrayBuffer } | undefined>108 >109 | undefined110 >111> {112 const baseURL = 'http://localhost'113 const pool = createPool({ concurrency })114115 for (const route of filterStaticGenerateRoutes(app)) {116 // GET Route Info117 const thisRouteBaseURL = new URL(route.path, baseURL).toString()118119 let forGetInfoURLRequest = new Request(thisRouteBaseURL) as AddedSSGDataRequest120 if (beforeRequestHook) {121 const maybeRequest = beforeRequestHook(forGetInfoURLRequest)122 if (!maybeRequest) {123 continue124 }125 forGetInfoURLRequest = maybeRequest as unknown as AddedSSGDataRequest126 }127128 // eslint-disable-next-line no-async-promise-executor129 yield new Promise(async (resolveGetInfo, rejectGetInfo) => {130 try {131 await pool.run(() => app.fetch(forGetInfoURLRequest))132133 if (!forGetInfoURLRequest.ssgParams) {134 if (isDynamicRoute(route.path)) {135 resolveGetInfo(undefined)136 return137 }138 forGetInfoURLRequest.ssgParams = [{}]139 }140141 const requestInit = {142 method: forGetInfoURLRequest.method,143 headers: forGetInfoURLRequest.headers,144 }145146 resolveGetInfo(147 (function* () {148 for (const param of forGetInfoURLRequest.ssgParams as SSGParams) {149 // eslint-disable-next-line no-async-promise-executor150 yield new Promise(async (resolveReq, rejectReq) => {151 try {152 const replacedUrlParam = replaceUrlParam(route.path, param)153 let response = await pool.run(() =>154 app.request(replacedUrlParam, requestInit, {155 [SSG_CONTEXT]: true,156 })157 )158 if (response === SSG_DISABLED_RESPONSE) {159 resolveReq(undefined)160 return161 }162 if (afterResponseHook) {163 const maybeResponse = afterResponseHook(response)164 if (!maybeResponse) {165 resolveReq(undefined)166 return167 }168 response = maybeResponse169 }170 const mimeType =171 response.headers.get('Content-Type')?.split(';')[0] || 'text/plain'172 const content = await parseResponseContent(response)173 resolveReq({174 routePath: replacedUrlParam,175 mimeType,176 content,177 })178 } catch (error) {179 rejectReq(error)180 }181 })182 }183 })()184 )185 } catch (error) {186 rejectGetInfo(error)187 }188 })189 }190}191192const isDynamicRoute = (path: string): boolean => {193 return path.split('/').some((segment) => segment.startsWith(':') || segment.includes('*'))194}195196/**197 * @experimental198 * `saveContentToFile` is an experimental feature.199 * The API might be changed.200 */201const createdDirs: Set<string> = new Set()202export const saveContentToFile = async (203 data: Promise<{ routePath: string; content: string | ArrayBuffer; mimeType: string } | undefined>,204 fsModule: FileSystemModule,205 outDir: string206): Promise<string | undefined> => {207 const awaitedData = await data208 if (!awaitedData) {209 return210 }211 const { routePath, content, mimeType } = awaitedData212 const filePath = generateFilePath(routePath, outDir, mimeType)213 const dirPath = dirname(filePath)214215 if (!createdDirs.has(dirPath)) {216 await fsModule.mkdir(dirPath, { recursive: true })217 createdDirs.add(dirPath)218 }219 if (typeof content === 'string') {220 await fsModule.writeFile(filePath, content)221 } else if (content instanceof ArrayBuffer) {222 await fsModule.writeFile(filePath, new Uint8Array(content))223 }224 return filePath225}226227/**228 * @experimental229 * `ToSSGInterface` is an experimental feature.230 * The API might be changed.231 */232export interface ToSSGInterface {233 (234 // eslint-disable-next-line @typescript-eslint/no-explicit-any235 app: Hono<any, any, any>,236 fsModule: FileSystemModule,237 options?: ToSSGOptions238 ): Promise<ToSSGResult>239}240241/**242 * @experimental243 * `ToSSGAdaptorInterface` is an experimental feature.244 * The API might be changed.245 */246export interface ToSSGAdaptorInterface<247 E extends Env = Env,248 S extends Schema = {},249 BasePath extends string = '/'250> {251 (app: Hono<E, S, BasePath>, options?: ToSSGOptions): Promise<ToSSGResult>252}253254/**255 * @experimental256 * `toSSG` is an experimental feature.257 * The API might be changed.258 */259export const toSSG: ToSSGInterface = async (app, fs, options) => {260 let result: ToSSGResult | undefined = undefined261 const getInfoPromises: Promise<unknown>[] = []262 const savePromises: Promise<string | undefined>[] = []263 try {264 const outputDir = options?.dir ?? './static'265 const concurrency = options?.concurrency ?? DEFAULT_CONCURRENCY266267 const getInfoGen = fetchRoutesContent(268 app,269 options?.beforeRequestHook,270 options?.afterResponseHook,271 concurrency272 )273 for (const getInfo of getInfoGen) {274 getInfoPromises.push(275 getInfo.then((getContentGen) => {276 if (!getContentGen) {277 return278 }279 for (const content of getContentGen) {280 savePromises.push(saveContentToFile(content, fs, outputDir).catch((e) => e))281 }282 })283 )284 }285 await Promise.all(getInfoPromises)286 const files: string[] = []287 for (const savePromise of savePromises) {288 const fileOrError = await savePromise289 if (typeof fileOrError === 'string') {290 files.push(fileOrError)291 } else if (fileOrError) {292 throw fileOrError293 }294 }295 result = { success: true, files }296 } catch (error) {297 const errorObj = error instanceof Error ? error : new Error(String(error))298 result = { success: false, files: [], error: errorObj }299 }300 await options?.afterGenerateHook?.(result)301 return result302}
added:src/helper/websocket/index.test.ts+14 added
1import { createWSMessageEvent } from '.'23describe('`createWSMessageEvent`', () => {4 it('Should `createWSMessageEvent` is working for string', () => {5 const randomString = Math.random().toString()6 const event = createWSMessageEvent(randomString)78 expect(event.data).toBe(randomString)9 })10 it('Should `createWSMessageEvent` type is `message`', () => {11 const event = createWSMessageEvent('')12 expect(event.type).toBe('message')13 })14})
added:src/helper/websocket/index.ts+55 added
1/* eslint-disable @typescript-eslint/no-explicit-any */2import type { Context } from '../../context'3import type { MiddlewareHandler } from '../../types'45/**6 * WebSocket Event Listeners type7 */8export interface WSEvents {9 onOpen?: (evt: Event, ws: WSContext) => void10 onMessage?: (evt: MessageEvent<WSMessageReceive>, ws: WSContext) => void11 onClose?: (evt: CloseEvent, ws: WSContext) => void12 onError?: (evt: Event, ws: WSContext) => void13}1415export type UpgradedWebSocketResponseInputJSONType = '__websocket' | undefined1617/**18 * Upgrade WebSocket Type19 */20export type UpgradeWebSocket = (21 createEvents: (c: Context) => WSEvents | Promise<WSEvents>22) => MiddlewareHandler<23 any,24 string,25 {26 in: {27 json: UpgradedWebSocketResponseInputJSONType28 }29 }30>3132export type WSReadyState = 0 | 1 | 2 | 33334export type WSContext = {35 send(36 source: string | ArrayBuffer | Uint8Array,37 options?: {38 compress: boolean39 }40 ): void41 raw?: unknown42 binaryType: BinaryType43 readyState: WSReadyState44 url: URL | null45 protocol: string | null46 close(code?: number, reason?: string): void47}4849export type WSMessageReceive = string | Blob | ArrayBufferLike5051export const createWSMessageEvent = (source: WSMessageReceive): MessageEvent<WSMessageReceive> => {52 return new MessageEvent<WSMessageReceive>('message', {53 data: source,54 })55}
modified:src/jsx/dom/index.test.tsx+75 added-2 removed
1 unmodified line
2import type { FC } from '..'3// run tests by old style jsx default4// hono/jsx/jsx-runtime and hono/jsx/dom/jsx-runtime are tested in their respective settings5// eslint-disable-next-line @typescript-eslint/no-unused-vars6import { jsx, Fragment } from '..'6import { jsx, Fragment, createElement } from '..'7import DefaultExport from '..'8import type { RefObject } from '../hooks'9import { useState, useEffect, useLayoutEffect, useCallback, useRef, useMemo } from '../hooks'10import { memo, isValidElement, cloneElement } from '.'10import { render, cloneElement as cloneElementForDom } from '.'11import { render, createElement as createElementForDom, cloneElement as cloneElementForDom } from '.'1213describe('DOM', () => {14 beforeAll(() => {15 global.requestAnimationFrame = (cb) => setTimeout(cb)
1285 unmodified lines
1301 expect(isValidElement({})).toBe(false)1302 })1303 })13041305 describe('createElement', () => {1306 it('simple', async () => {1307 const App = () => {1308 const [count, setCount] = useState(0)1309 return (1310 <div>{createElement('p', { onClick: () => setCount(count + 1) }, String(count))}</div>1311 )1312 }1313 const app = <App />1314 render(app, root)1315 expect(root.innerHTML).toBe('<div><p>0</p></div>')1316 root.querySelector('p')?.click()1317 await Promise.resolve()1318 expect(root.innerHTML).toBe('<div><p>1</p></div>')1319 })1320 })13211322 describe('dom-specific createElement', () => {1323 it('simple', async () => {1324 const App = () => {1325 const [count, setCount] = useState(0)1326 return <div>{createElementForDom('p', { onClick: () => setCount(count + 1) }, count)}</div>1327 }1328 const app = <App />1329 render(app, root)1330 expect(root.innerHTML).toBe('<div><p>0</p></div>')1331 root.querySelector('p')?.click()1332 await Promise.resolve()1333 expect(root.innerHTML).toBe('<div><p>1</p></div>')1334 })1335 })13361337 describe('cloneElement', () => {1338 it('simple', async () => {1339 const App = () => {1340 const [count, setCount] = useState(0)
82 unmodified lines
1423 expect(createElementNSSpy).toHaveBeenCalledWith('http://www.w3.org/1998/Math/MathML', 'mrow')1424 })1425 })1426})14271428describe('jsx', () => {1429 it('exported as an alias of createElement', () => {1430 expect(jsx).toBeDefined()1431 expect(jsx('div', {}, 'Hello')).toBeInstanceOf(Object)1432 })1433})14341435describe('default export', () => {1436 ;[1437 'memo',1438 'Fragment',1439 'isValidElement',1440 'createElement',1441 'cloneElement',1442 'ErrorBoundary',1443 'createContext',1444 'useContext',1445 'useState',1446 'useEffect',1447 'useRef',1448 'useCallback',1449 'useReducer',1450 'useDebugValue',1451 'use',1452 'startTransition',1453 'useTransition',1454 'useDeferredValue',1455 'startViewTransition',1456 'useViewTransition',1457 'useMemo',1458 'useLayoutEffect',1459 'Suspense',1460 ].forEach((key) => {1461 it(key, () => {1462 // eslint-disable-next-line @typescript-eslint/no-explicit-any1463 expect((DefaultExport as any)[key]).toBeDefined()1464 })1465 })1466})
modified:src/jsx/dom/index.ts+79 added-9 removed
1import type { Props, Child, JSXNode } from '../base'2import { memo, isValidElement } from '../base'3import { useContext } from '../context'1export {4import {5 useState,6 useEffect,7 useRef,8 useCallback,
4 unmodified lines
13 startViewTransition,14 useViewTransition,15 useMemo,16 useLayoutEffect,17 useReducer,18 useDebugValue,19} from '../hooks'20import { Suspense, ErrorBoundary } from './components'21import { createContext } from './context'22import { jsx } from './jsx-runtime'2324export { render } from './render'16export { Suspense, ErrorBoundary } from './components'17export { useContext } from '../context'18export type { Context } from '../context'19export { createContext } from './context'20export { memo, isValidElement } from '../base'2522import type { Props, Child, JSXNode } from '../base'23import { jsx } from './jsx-runtime'24export const cloneElement = <T extends JSXNode | JSX.Element>(26const createElement = (27 tag: string | ((props: Props) => JSXNode),28 props: Props,29 ...children: Child[]30): JSXNode => {31 const jsxProps: Props = { ...props, children }32 let key = undefined33 if ('key' in jsxProps) {34 key = jsxProps.key35 delete jsxProps.key36 }37 // eslint-disable-next-line @typescript-eslint/no-explicit-any38 return jsx(tag, jsxProps, key) as any39}4041const cloneElement = <T extends JSXNode | JSX.Element>(42 element: T,43 props: Props,44 ...children: Child[]45): T => {
6 unmodified lines
52 },53 (element as JSXNode).key54 ) as T55}5657export {58 createElement as jsx,59 useState,60 useEffect,61 useRef,62 useCallback,63 use,64 startTransition,65 useTransition,66 useDeferredValue,67 startViewTransition,68 useViewTransition,69 useMemo,70 useLayoutEffect,71 useReducer,72 useDebugValue,73 Suspense,74 ErrorBoundary,75 createContext,76 useContext,77 memo,78 isValidElement,79 createElement,80 cloneElement,81}8283export default {84 useState,85 useEffect,86 useRef,87 useCallback,88 use,89 startTransition,90 useTransition,91 useDeferredValue,92 startViewTransition,93 useViewTransition,94 useMemo,95 useLayoutEffect,96 useReducer,97 useDebugValue,98 Suspense,99 ErrorBoundary,100 createContext,101 useContext,102 memo,103 isValidElement,104 createElement,105 cloneElement,106}107108export type { Context } from '../context'
modified:src/jsx/hooks/dom.test.tsx+61 added
5 unmodified lines
6import { Suspense } from '../dom'7import { render } from '../dom'8import {9 useState,10 useReducer,11 use,12 startTransition,13 useTransition,14 useDeferredValue,15 startViewTransition,16 useViewTransition,17 useDebugValue,18} from '.'1920describe('useReducer()', () => {21 beforeAll(() => {22 global.requestAnimationFrame = (cb) => setTimeout(cb)23 })2425 let dom: JSDOM26 let root: HTMLElement27 beforeEach(() => {28 dom = new JSDOM('<html><body><div id="root"></div></body></html>', {29 runScripts: 'dangerously',30 })31 global.document = dom.window.document32 global.HTMLElement = dom.window.HTMLElement33 global.Text = dom.window.Text34 root = document.getElementById('root') as HTMLElement35 })3637 it('simple', async () => {38 const App = () => {39 const [state, dispatch] = useReducer((state: number, action: number) => state + action, 0)40 return (41 <div>42 <button onClick={() => dispatch(1)}>{state}</button>43 </div>44 )45 }46 render(<App />, root)47 expect(root.innerHTML).toBe('<div><button>0</button></div>')48 root.querySelector('button')?.click()49 await Promise.resolve()50 expect(root.innerHTML).toBe('<div><button>1</button></div>')51 })52})5354describe('startTransition()', () => {55 beforeAll(() => {56 global.requestAnimationFrame = (cb) => setTimeout(cb)57 })
421 unmodified lines
479 expect(root.innerHTML).toBe('<div><button>1</button></div>')480 expect(called).toBe(3)481 })482})483484describe('useDebugValue()', () => {485 let dom: JSDOM486 let root: HTMLElement487 beforeEach(() => {488 dom = new JSDOM('<html><body><div id="root"></div></body></html>', {489 runScripts: 'dangerously',490 })491 global.document = dom.window.document492 global.HTMLElement = dom.window.HTMLElement493 global.Text = dom.window.Text494 root = document.getElementById('root') as HTMLElement495 })496497 it('simple', () => {498 const spy = vi.fn()499 const App = () => {500 useDebugValue('hello', spy)501 return <div />502 }503 render(<App />, root)504 expect(root.innerHTML).toBe('<div></div>')505 expect(spy).not.toBeCalled()506 })507})
modified:src/jsx/hooks/index.ts+18 added
203 unmodified lines
204 },205 ])206}207208export const useReducer = <T, A>(209 reducer: (state: T, action: A) => T,210 initialArg: T,211 init?: (initialState: T) => T212): [T, (action: A) => void] => {213 const [state, setState] = useState(() => (init ? init(initialArg) : initialArg))214 return [215 state,216 (action: A) => {217 setState((state) => reducer(state, action))218 },219 ]220}221222const useEffectCommon = (223 index: number,224 effect: () => void | (() => void),225 deps?: readonly unknown[]
121 unmodified lines
347 memoArray[hookIndex] = [factory(), deps]348 }349 return memoArray[hookIndex][0] as T350}351352// Define to avoid errors. This hook currently does nothing.353// eslint-disable-next-line @typescript-eslint/no-unused-vars354export const useDebugValue = (value: unknown, formatter?: (value: unknown) => string): void => {}
modified:src/jsx/index.test.tsx+34 added-1 removed
2 unmodified lines
3import { html } from '../helper/html'4import { Hono } from '../hono'5import { Suspense, renderToReadableStream } from './streaming'6// eslint-disable-next-line @typescript-eslint/no-unused-vars7import { jsx, memo, Fragment, createContext, useContext } from '.'7import DefaultExport, { jsx, memo, Fragment, createContext, useContext } from '.'8import type { Context, FC, PropsWithChildren } from '.'910interface SiteData {11 title: string
707 unmodified lines
719 expect(nextRequest.toString()).toBe('<span>light</span>')720 })721 })722})723724describe('default export', () => {725 ;[726 'memo',727 'Fragment',728 'isValidElement',729 'createElement',730 'cloneElement',731 'ErrorBoundary',732 'createContext',733 'useContext',734 'useState',735 'useEffect',736 'useRef',737 'useCallback',738 'useReducer',739 'useDebugValue',740 'use',741 'startTransition',742 'useTransition',743 'useDeferredValue',744 'startViewTransition',745 'useViewTransition',746 'useMemo',747 'useLayoutEffect',748 'Suspense',749 ].forEach((key) => {750 it(key, () => {751 // eslint-disable-next-line @typescript-eslint/no-explicit-any752 expect((DefaultExport as any)[key]).toBeDefined()753 })754 })755})
modified:src/jsx/index.ts+60 added-5 removed
1export { jsx, memo, Fragment, isValidElement, cloneElement } from './base'2export { ErrorBoundary } from './components'3export { Suspense } from './streaming'4export {1import { jsx, memo, Fragment, isValidElement, cloneElement } from './base'2import { ErrorBoundary } from './components'3import { createContext, useContext } from './context'4import {5 useState,6 useEffect,7 useRef,8 useCallback,
4 unmodified lines
13 startViewTransition,14 useViewTransition,15 useMemo,16 useLayoutEffect,17 useReducer,18 useDebugValue,19} from './hooks'18export { createContext, useContext } from './context'20import { Suspense } from './streaming'2122export {23 jsx,24 memo,25 Fragment,26 isValidElement,27 jsx as createElement,28 cloneElement,29 ErrorBoundary,30 createContext,31 useContext,32 useState,33 useEffect,34 useRef,35 useCallback,36 useReducer,37 useDebugValue,38 use,39 startTransition,40 useTransition,41 useDeferredValue,42 startViewTransition,43 useViewTransition,44 useMemo,45 useLayoutEffect,46 Suspense,47}4849export default {50 memo,51 Fragment,52 isValidElement,53 createElement: jsx,54 cloneElement,55 ErrorBoundary,56 createContext,57 useContext,58 useState,59 useEffect,60 useRef,61 useCallback,62 useReducer,63 useDebugValue,64 use,65 startTransition,66 useTransition,67 useDeferredValue,68 startViewTransition,69 useViewTransition,70 useMemo,71 useLayoutEffect,72 Suspense,73}7475// TODO: change to `export type *` after denoify bug is fixed76// https://github.com/garronej/denoify/issues/12477export * from './types'
added:src/middleware/body-limit/index.test.ts+143 added
1import { Hono } from '../../hono'2import { bodyLimit } from '.'34const GlobalRequest = globalThis.Request5globalThis.Request = class Request extends GlobalRequest {6 constructor(input: Request | string, init: RequestInit) {7 if (init) {8 // eslint-disable-next-line @typescript-eslint/no-explicit-any9 ;(init as any).duplex ??= 'half'10 }11 super(input, init)12 }13} as typeof GlobalRequest1415const buildRequestInit = (init: RequestInit = {}): RequestInit => {16 const headers: Record<string, string> = {17 'Content-Type': 'text/plain',18 }19 if (typeof init.body === 'string') {20 headers['Content-Length'] = init.body.length.toString()21 }22 return {23 method: 'POST',24 headers,25 body: null,26 ...init,27 }28}2930describe('Body Limit Middleware', () => {31 let app: Hono3233 const exampleText = 'hono is so cool' // 15byte34 const exampleText2 = 'hono is so cool and cute' // 24byte3536 beforeEach(() => {37 app = new Hono()38 app.use('*', bodyLimit({ maxSize: 15 }))39 app.get('/', (c) => c.text('index'))40 app.post('/body-limit-15byte', async (c) => {41 return c.text(await c.req.raw.text())42 })43 })4445 describe('GET request', () => {46 it('should return 200 response', async () => {47 const res = await app.request('/')48 expect(res).not.toBeNull()49 expect(res.status).toBe(200)50 expect(await res.text()).toBe('index')51 })52 })5354 describe('POST request', () => {55 describe('string body', () => {56 it('should return 200 response', async () => {57 const res = await app.request('/body-limit-15byte', buildRequestInit({ body: exampleText }))5859 expect(res).not.toBeNull()60 expect(res.status).toBe(200)61 expect(await res.text()).toBe(exampleText)62 })6364 it('should return 413 response', async () => {65 const res = await app.request(66 '/body-limit-15byte',67 buildRequestInit({ body: exampleText2 })68 )6970 expect(res).not.toBeNull()71 expect(res.status).toBe(413)72 expect(await res.text()).toBe('Payload Too Large')73 })74 })7576 describe('ReadableStream body', () => {77 it('should return 200 response', async () => {78 const contents = ['a', 'b', 'c']79 const stream = new ReadableStream({80 start(controller) {81 while (contents.length) {82 controller.enqueue(new TextEncoder().encode(contents.shift() as string))83 }84 controller.close()85 },86 })87 const res = await app.request('/body-limit-15byte', buildRequestInit({ body: stream }))8889 expect(res).not.toBeNull()90 expect(res.status).toBe(200)91 expect(await res.text()).toBe('abc')92 })9394 it('should return 413 response', async () => {95 const readSpy = vi.fn().mockImplementation(() => {96 return {97 done: false,98 value: new TextEncoder().encode(exampleText),99 }100 })101 const stream = new ReadableStream()102 vi.spyOn(stream, 'getReader').mockReturnValue({103 read: readSpy,104 } as unknown as ReadableStreamDefaultReader)105 const res = await app.request('/body-limit-15byte', buildRequestInit({ body: stream }))106107 expect(res).not.toBeNull()108 expect(res.status).toBe(413)109 expect(readSpy).toHaveBeenCalledTimes(2)110 expect(await res.text()).toBe('Payload Too Large')111 })112 })113 })114115 describe('custom error handler', () => {116 beforeEach(() => {117 app = new Hono()118 app.post(119 '/text-limit-15byte-custom',120 bodyLimit({121 maxSize: 15,122 onError: (c) => {123 return c.text('no', 413)124 },125 }),126 (c) => {127 return c.text('yes')128 }129 )130 })131132 it('should return the custom error handler', async () => {133 const res = await app.request(134 '/text-limit-15byte-custom',135 buildRequestInit({ body: exampleText2 })136 )137138 expect(res).not.toBeNull()139 expect(res.status).toBe(413)140 expect(await res.text()).toBe('no')141 })142 })143})
added:src/middleware/body-limit/index.ts+96 added
1import type { Context } from '../../context'2import { HTTPException } from '../../http-exception'3import type { MiddlewareHandler } from '../../types'45const ERROR_MESSAGE = 'Payload Too Large'67type OnError = (c: Context) => Response | Promise<Response>8type BodyLimitOptions = {9 maxSize: number10 onError?: OnError11}1213class BodyLimitError extends Error {14 constructor(message: string) {15 super(message)16 this.name = 'BodyLimitError'17 }18}1920/**21 * Body Limit Middleware22 *23 * @example24 * ```ts25 * app.post(26 * '/hello',27 * bodyLimit({28 * maxSize: 100 * 1024, // 100kb29 * onError: (c) => {30 * return c.text('overflow :(', 413)31 * }32 * }),33 * (c) => {34 * return c.text('pass :)')35 * }36 * )37 * ```38 */39export const bodyLimit = (options: BodyLimitOptions): MiddlewareHandler => {40 const onError: OnError =41 options.onError ||42 (() => {43 const res = new Response(ERROR_MESSAGE, {44 status: 413,45 })46 throw new HTTPException(413, { res })47 })48 const maxSize = options.maxSize4950 return async function bodyLimit(c, next) {51 if (!c.req.raw.body) {52 // maybe GET or HEAD request53 return next()54 }5556 if (c.req.raw.headers.has('content-length')) {57 // we can trust content-length header because it's already validated by server58 const contentLength = parseInt(c.req.raw.headers.get('content-length') || '0', 10)59 return contentLength > maxSize ? onError(c) : next()60 }6162 // maybe chunked transfer encoding6364 let size = 065 const rawReader = c.req.raw.body.getReader()66 const reader = new ReadableStream({67 async start(controller) {68 try {69 for (;;) {70 const { done, value } = await rawReader.read()71 if (done) {72 break73 }74 size += value.length75 if (size > maxSize) {76 controller.error(new BodyLimitError(ERROR_MESSAGE))77 break78 }7980 controller.enqueue(value)81 }82 } finally {83 controller.close()84 }85 },86 })8788 c.req.raw = new Request(c.req.raw, { body: reader })8990 await next()9192 if (c.error instanceof BodyLimitError) {93 c.res = await onError(c)94 }95 }96}
modified:src/middleware/logger/index.test.ts+77 added
72 unmodified lines
73 expect(log.startsWith(' --> GET /notfound \x1b[33m404\x1b[0m')).toBe(true)74 expect(log).toMatch(/m?s$/)75 })76})7778describe('Logger by Middleware in NO_COLOR', () => {79 let app: Hono80 let log: string8182 beforeEach(() => {83 vi.stubEnv('NO_COLOR', '1')84 function sleep(time: number) {85 return new Promise((resolve) => setTimeout(resolve, time))86 }8788 app = new Hono()8990 const logFn = (str: string) => {91 log = str92 }9394 const shortRandomString = 'hono'95 const longRandomString = 'hono'.repeat(1000)9697 app.use('*', logger(logFn))98 app.get('/short', (c) => c.text(shortRandomString))99 app.get('/long', (c) => c.text(longRandomString))100 app.get('/seconds', async (c) => {101 await sleep(1000)102103 return c.text(longRandomString)104 })105 app.get('/empty', (c) => c.text(''))106 })107 afterAll(() => {108 vi.unstubAllEnvs()109 })110 it('Log status 200 with empty body', async () => {111 const res = await app.request('http://localhost/empty')112 expect(res).not.toBeNull()113 expect(res.status).toBe(200)114 expect(log.startsWith(' --> GET /empty 200')).toBe(true)115 expect(log).toMatch(/m?s$/)116 })117118 it('Log status 200 with small body', async () => {119 const res = await app.request('http://localhost/short')120 expect(res).not.toBeNull()121 expect(res.status).toBe(200)122 expect(log.startsWith(' --> GET /short 200')).toBe(true)123 expect(log).toMatch(/m?s$/)124 })125126 it('Log status 200 with big body', async () => {127 const res = await app.request('http://localhost/long')128 expect(res).not.toBeNull()129 expect(res.status).toBe(200)130 expect(log.startsWith(' --> GET /long 200')).toBe(true)131 expect(log).toMatch(/m?s$/)132 })133134 it('Time in seconds', async () => {135 const res = await app.request('http://localhost/seconds')136 expect(res).not.toBeNull()137 expect(res.status).toBe(200)138 expect(log.startsWith(' --> GET /seconds 200')).toBe(true)139 expect(log).toMatch(/1s/)140 })141142 it('Log status 404', async () => {143 const msg = 'Default 404 Not Found'144 app.all('*', (c) => {145 return c.text(msg, 404)146 })147 const res = await app.request('http://localhost/notfound')148 expect(res).not.toBeNull()149 expect(res.status).toBe(404)150 expect(log.startsWith(' --> GET /notfound 404')).toBe(true)151 expect(log).toMatch(/m?s$/)152 })153})
modified:src/middleware/logger/index.ts+9 added-7 removed
1import type { MiddlewareHandler } from '../../types'2import { getColorEnabled } from '../../utils/color'3import { getPath } from '../../utils/url'45enum LogPrefix {6 Outgoing = '-->',
14 unmodified lines
21 return humanize([delta < 1000 ? delta + 'ms' : Math.round(delta / 1000) + 's'])22}2324const colorStatus = (status: number) => {25 const colorEnabled = getColorEnabled()26 const out: { [key: string]: string } = {25 7: `\x1b[35m${status}\x1b[0m`,26 5: `\x1b[31m${status}\x1b[0m`,27 4: `\x1b[33m${status}\x1b[0m`,28 3: `\x1b[36m${status}\x1b[0m`,29 2: `\x1b[32m${status}\x1b[0m`,30 1: `\x1b[32m${status}\x1b[0m`,31 0: `\x1b[33m${status}\x1b[0m`,27 7: colorEnabled ? `\x1b[35m${status}\x1b[0m` : `${status}`,28 5: colorEnabled ? `\x1b[31m${status}\x1b[0m` : `${status}`,29 4: colorEnabled ? `\x1b[33m${status}\x1b[0m` : `${status}`,30 3: colorEnabled ? `\x1b[36m${status}\x1b[0m` : `${status}`,31 2: colorEnabled ? `\x1b[32m${status}\x1b[0m` : `${status}`,32 1: colorEnabled ? `\x1b[32m${status}\x1b[0m` : `${status}`,33 0: colorEnabled ? `\x1b[33m${status}\x1b[0m` : `${status}`,34 }3536 const calculateStatus = (status / 100) | 037
35 unmodified lines
added:src/utils/color.test.ts+18 added
1import { getColorEnabled } from './color'23describe('getColorEnabled()', () => {4 it('getColorEnabled() is true', async () => {5 expect(getColorEnabled()).toBe(true)6 })7})8describe('getColorEnabled() in NO_COLOR', () => {9 beforeAll(() => {10 vi.stubEnv('NO_COLOR', '1')11 })12 afterAll(() => {13 vi.unstubAllEnvs()14 })15 it('getColorEnabled() is false', async () => {16 expect(getColorEnabled()).toBe(false)17 })18})
added:src/utils/color.ts+12 added
1export function getColorEnabled() {2 // eslint-disable-next-line @typescript-eslint/no-explicit-any3 const { process, Deno } = globalThis as any4 const isNoColor =5 typeof process !== 'undefined'6 ? // eslint-disable-next-line no-unsafe-optional-chaining7 'NO_COLOR' in process?.env8 : typeof Deno?.noColor === 'boolean'9 ? (Deno.noColor as boolean)10 : false11 return !isNoColor12}
added:src/utils/concurrent.test.ts+69 added
1import { createPool } from './concurrent'23describe('concurrent execution', () => {4 test.each`5 concurrency | count6 ${1} | ${10}7 ${10} | ${10}8 ${100} | ${10}9 ${Infinity} | ${2000}10 `('concurrency $concurrency, count $count', async ({ concurrency, count }) => {11 const running = new Set()1213 const pool = createPool({ concurrency })14 let resolve: (() => void) | undefined15 const promise = new Promise<void>((r) => {16 resolve = r17 })18 const fn = async (i: number) => {19 if (running.size > concurrency) {20 throw new Error('concurrency exceeded')21 }2223 running.add(i)24 await promise25 running.delete(i)26 return i27 }2829 const jobs = new Array(count).fill(0).map((_, i) => () => fn(i))30 const expectedResults = new Array(count).fill(0).map((_, i) => i)31 const resultPromises = jobs.map((job) => pool.run(job))3233 expect(running.size).toBe(Math.min(concurrency, count))34 resolve?.()35 const results = await Promise.all(resultPromises)36 expect(running.size).toBe(0)37 expect(results).toEqual(expectedResults)38 })3940 describe('with interval', () => {41 test.each`42 concurrency | interval43 ${1} | ${10}44 ${2} | ${10}45 `('concurrency $concurrency, interval $interval', async ({ concurrency, interval }) => {46 const workingTimeQueue: number[] = []47 const pool = createPool({ concurrency, interval })48 const fn = async (i: number) => {49 const now = Date.now()50 if (workingTimeQueue.length >= concurrency) {51 const last = workingTimeQueue.shift()52 // Not so accurate, -1 ms is acceptable53 if (last && now - last < interval - 1) {54 throw new Error('interval violated')55 }56 }57 workingTimeQueue.push(now)58 return i59 }6061 const jobs = new Array(10).fill(0).map((_, i) => () => fn(i))62 const expectedResults = new Array(10).fill(0).map((_, i) => i)63 const resultPromises = jobs.map((job) => pool.run(job))6465 const results = await Promise.all(resultPromises)66 expect(results).toEqual(expectedResults)67 })68 })69})
added:src/utils/concurrent.ts+50 added
1const DEFAULT_CONCURRENCY = 102423export interface Pool {4 run<T>(fn: () => T): Promise<T>5}67export const createPool = ({8 concurrency,9 interval,10}: {11 concurrency?: number12 interval?: number13} = {}): Pool => {14 concurrency ||= DEFAULT_CONCURRENCY1516 if (concurrency === Infinity) {17 // unlimited18 return {19 run: async (fn) => fn(),20 }21 }2223 const pool: Set<{}> = new Set()24 const run = async <T>(25 fn: () => T,26 promise?: Promise<T>,27 resolve?: (result: T) => void28 ): Promise<T> => {29 if (pool.size >= (concurrency as number)) {30 promise ||= new Promise<T>((r) => (resolve = r))31 setTimeout(() => run(fn, promise, resolve))32 return promise33 }34 const marker = {}35 pool.add(marker)36 const result = await fn()37 if (interval) {38 setTimeout(() => pool.delete(marker), interval)39 } else {40 pool.delete(marker)41 }42 if (resolve) {43 resolve(result)44 return promise as Promise<T>45 } else {46 return result47 }48 }49 return { run }50}
modified:src/utils/cookie.test.ts+81 added-2 removed
152 unmodified lines
153 expect(serialized).toBe('delicious_cookie=macha')154 })155156 it('Should serialize cookie with all options', () => {157 const serialized = serialize('great_cookie', 'banana', {157 const serialized = serialize('__Secure-great_cookie', 'banana', {158 path: '/',159 secure: true,160 domain: 'example.com',161 httpOnly: true,
2 unmodified lines
164 sameSite: 'Strict',165 partitioned: true,166 })167 expect(serialized).toBe(168 'great_cookie=banana; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict; Partitioned'168 '__Secure-great_cookie=banana; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict; Partitioned'169 )170 })171172 it('Should serialize __Host- cookie with all valid options', () => {173 const serialized = serialize('__Host-great_cookie', 'banana', {174 path: '/',175 secure: true,176 httpOnly: true,177 maxAge: 1000,178 expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)),179 sameSite: 'Strict',180 partitioned: true,181 })182 expect(serialized).toBe(183 '__Host-great_cookie=banana; Max-Age=1000; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict; Partitioned'184 )185 })186187 it('Should serialize a signed cookie', async () => {188 const secret = 'secret chocolate chips'189 const serialized = await serializeSigned('delicious_cookie', 'macha', secret)190 expect(serialized).toBe(
30 unmodified lines
221 maxAge: -1,222 })223 expect(serialized).toBe('great_cookie=banana')224 })225226 it('Should throw Error cookie with maxAge grater than 400days', () => {227 expect(() => {228 serialize('great_cookie', 'banana', {229 maxAge: 3600 * 24 * 401,230 })231 }).toThrowError(232 'Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.'233 )234 })235236 it('Should throw Error cookie with expires grater than 400days', () => {237 const now = Date.now()238 const day401 = new Date(now + 1000 * 3600 * 24 * 401)239 expect(() => {240 serialize('great_cookie', 'banana', {241 expires: day401,242 })243 }).toThrowError(244 'Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.'245 )246 })247248 it('Should throw Error __Secure- cookie without Secure attributes', () => {249 expect(() => {250 serialize('__Secure-great_cookie', 'banana', {})251 }).toThrowError('__Secure- Cookie must have Secure attributes')252 })253254 it('Should throw Error __Host- cookie without Secure attributes', () => {255 expect(() => {256 serialize('__Host-great_cookie', 'banana', {257 secure: false,258 path: '/',259 })260 }).toThrowError('__Host- Cookie must have Secure attributes')261 })262263 it('Should throw Error __Host- cookie without Path attributes with "/"', () => {264 expect(() => {265 serialize('__Host-great_cookie', 'banana', {266 secure: true,267 path: '/admin',268 })269 }).toThrowError('__Host- Cookie must have Path attributes with "/"')270 })271272 it('Should throw Error __Host- cookie with Domain attributes', () => {273 expect(() => {274 serialize('__Host-great_cookie', 'banana', {275 secure: true,276 path: '/',277 domain: 'site.example',278 })279 }).toThrowError('__Host- Cookie must not have Domain attributes')280 })281282 it('Should throw Error Partitioned cookie without Secure attributes', () => {283 expect(() => {284 serialize('great_cookie', 'banana', {285 partitioned: true,286 })287 }).toThrowError('Partitioned Cookie must have Secure attributes')288 })289})
modified:src/utils/cookie.ts+44 added-1 removed
10 unmodified lines
11 secure?: boolean12 signingSecret?: string13 sameSite?: 'Strict' | 'Lax' | 'None'14 partitioned?: boolean15 prefix?: CookiePrefixOptions16}17export type CookiePrefixOptions = 'host' | 'secure'1819const algorithm = { name: 'HMAC', hash: 'SHA-256' }2021const getCryptoKey = async (secret: string | BufferSource): Promise<CryptoKey> => {
91 unmodified lines
113114const _serialize = (name: string, value: string, opt: CookieOptions = {}): string => {115 let cookie = `${name}=${value}`116117 if (name.startsWith('__Secure-') && !opt.secure) {118 // FIXME: replace link to RFC119 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.3.1120 throw new Error('__Secure- Cookie must have Secure attributes')121 }122123 if (name.startsWith('__Host-')) {124 // FIXME: replace link to RFC125 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.3.2126 if (!opt.secure) {127 throw new Error('__Host- Cookie must have Secure attributes')128 }129130 if (opt.path !== '/') {131 throw new Error('__Host- Cookie must have Path attributes with "/"')132 }133134 if (opt.domain) {135 throw new Error('__Host- Cookie must not have Domain attributes')136 }137 }138139 if (opt && typeof opt.maxAge === 'number' && opt.maxAge >= 0) {140 if (opt.maxAge > 34560000) {141 // FIXME: replace link to RFC142 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.2.2143 throw new Error(144 'Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.'145 )146 }147 cookie += `; Max-Age=${Math.floor(opt.maxAge)}`148 }149119 if (opt.domain) {150 if (opt.domain && opt.prefix !== 'host') {151 cookie += `; Domain=${opt.domain}`152 }153154 if (opt.path) {155 cookie += `; Path=${opt.path}`156 }157158 if (opt.expires) {159 if (opt.expires.getTime() - Date.now() > 34560000_000) {160 // FIXME: replace link to RFC161 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.2.1162 throw new Error(163 'Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.'164 )165 }166 cookie += `; Expires=${opt.expires.toUTCString()}`167 }168169 if (opt.httpOnly) {
8 unmodified lines
178 cookie += `; SameSite=${opt.sameSite}`179 }180181 if (opt.partitioned) {182 // FIXME: replace link to RFC183 // https://www.ietf.org/archive/id/draft-cutler-httpbis-partitioned-cookies-01.html#section-2.3184 if (!opt.secure) {185 throw new Error('Partitioned Cookie must have Secure attributes')186 }187 cookie += '; Partitioned'188 }189190 return cookie
18 unmodified lines
modified:src/helper.ts+1 added
7 unmodified lines
8export * from './helper/streaming'9export * from './helper/testing'10export * from './helper/dev'11export * from './adapter/deno/ssg'12export * from './adapter/deno/websocket'
modified:src/http-exception.test.ts+22 added-3 removed
1import { HTTPException } from './http-exception'23describe('HTTPFatalError', () => {4 it('Should be 401 HTTP exception object', () => {3describe('HTTPException', () => {4 it('Should be 401 HTTP exception object', async () => {5 // We should throw an exception if is not authorized6 // because next handlers should not be fired.7 const exception = new HTTPException(401, {8 message: 'Unauthorized',9 })10 const res = exception.getResponse()1112 expect(res.status).toBe(401)13 expect(await res.text()).toBe('Unauthorized')14 expect(exception.status).toBe(401)15 expect(exception.message).toBe('Unauthorized')16 })1718 it('Should be accessible to the object causing the exception', async () => {19 // We should pass the cause of the error to the cause option20 // because it makes debugging easier.21 const error = new Error('Server Error')22 const exception = new HTTPException(500, {23 message: 'Internal Server Error',24 cause: error,25 })26 const res = exception.getResponse()2713 expect(res.status).toBe(401)28 expect(res.status).toBe(500)29 expect(await res.text()).toBe('Internal Server Error')30 expect(exception.status).toBe(500)31 expect(exception.message).toBe('Internal Server Error')32 expect(exception.cause).toBe(error)33 })34})
modified:src/http-exception.ts+4 added-1 removed
1 unmodified line
23type HTTPExceptionOptions = {4 res?: Response5 message?: string6 cause?: unknown7}89/**10 * `HTTPException` must be used when a fatal error such as authentication failure occurs.
15 unmodified lines
26 */27export class HTTPException extends Error {28 readonly res?: Response29 readonly status: StatusCode3031 constructor(status: StatusCode = 500, options?: HTTPExceptionOptions) {30 super(options?.message)32 super(options?.message, { cause: options?.cause })33 this.res = options?.res34 this.status = status35 }3637 getResponse(): Response {38 if (this.res) {39 return this.res40 }
5 unmodified lines
modified:src/middleware.ts+1 added
1// This file is for Deno to import middleware from `hono/middleware.ts`.2export * from './middleware/basic-auth'3export * from './middleware/bearer-auth'4export * from './middleware/body-limit'5export * from './middleware/cache'6export * from './middleware/compress'7export * from './middleware/cors'8export * from './middleware/csrf'
10 unmodified lines
modified:bun.lockbbinary

A binary file, modified.

modified:package.json+19 added-3 removed
1{2 "name": "hono",3 "version": "4.0.10",3 "version": "4.1.0-rc.1",4 "description": "Ultrafast web framework for the Edges",5 "main": "dist/cjs/index.js",6 "type": "module",7 "module": "dist/index.js",
65 unmodified lines
73 "types": "./dist/types/middleware/bearer-auth/index.d.ts",74 "import": "./dist/middleware/bearer-auth/index.js",75 "require": "./dist/cjs/middleware/bearer-auth/index.js"76 },77 "./body-limit": {78 "types": "./dist/types/middleware/body-limit/index.d.ts",79 "import": "./dist/middleware/body-limit/index.js",80 "require": "./dist/cjs/middleware/body-limit/index.js"81 },82 "./cache": {83 "types": "./dist/types/middleware/cache/index.d.ts",84 "import": "./dist/middleware/cache/index.js",85 "require": "./dist/cjs/middleware/cache/index.js"
231 unmodified lines
317 "./dev": {318 "types": "./dist/types/helper/dev/index.d.ts",319 "import": "./dist/helper/dev/index.js",320 "require": "./dist/cjs/helper/dev/index.js"321 },322 "./ws": {323 "types": "./dist/types/helper/websocket/index.d.ts",324 "import": "./dist/helper/websocket/index.js",325 "require": "./dist/cjs/helper/websocket/index.js"326 }327 },328 "typesVersions": {329 "*": {
17 unmodified lines
347 ],348 "bearer-auth": [349 "./dist/types/middleware/bearer-auth"350 ],351 "body-limit": [352 "./dist/types/middleware/body-limit"353 ],354 "cache": [355 "./dist/types/middleware/cache"356 ],357 "cookie": [
129 unmodified lines
487 "./dist/types/helper/testing"488 ],489 "dev": [490 "./dist/types/helper/dev"491 ],492 "ws": [493 "./dist/types/helper/websocket"494 ]495 }496 },497 "author": "Yusuke Wada <yusuke@kamawada.com> (https://github.com/yusukebe)",
25 unmodified lines
523 ],524 "devDependencies": {525 "@cloudflare/workers-types": "^4.20231121.0",526 "@hono/eslint-config": "^0.0.4",511 "@hono/node-server": "^1.3.3",527 "@hono/node-server": "^1.8.2",528 "@types/crypto-js": "^4.1.1",529 "@types/glob": "^8.0.0",530 "@types/jsdom": "^21.1.4",531 "@types/node": "20.11.4",
21 unmodified lines
553 },554 "engines": {555 "node": ">=16.0.0"556 }541}557}
modified:tsconfig.json+2 added-2 removed
1{2 "compilerOptions": {3 "target": "ES2020",3 "target": "ES2022",4 "declaration": true,5 "moduleResolution": "Bundler",6 "outDir": "./dist",7 "esModuleInterop": true,
16 unmodified lines
24 "src/**/*.mts",25 "src/**/*.test.ts",26 "src/**/*.test.tsx"27 ],28}28}
modified:yarn.lock+5 added-5 removed
1# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.2# yarn lockfile v13# bun ./bun.lockb --hash: 71DE5A52207AB6DA-7e1bfe1f417d1f54-AEA1FB1F9EC7B654-4b7f874b4eade45b3# bun ./bun.lockb --hash: 03E95F4C55D78A53-2aac63394bface86-D16648EEBEA28A46-92573638c505f925456"@aashutoshrathi/word-wrap@^1.2.3":7 version "1.2.6"
466 unmodified lines
474 eslint-import-resolver-typescript "^3.6.1"475 eslint-plugin-import "^2.29.0"476 eslint-plugin-node "^11.1.0"477478"@hono/node-server@^1.3.3":479 version "1.5.0"480 resolved "https://registry.npmjs.org/@hono/node-server/-/node-server-1.5.0.tgz"481 integrity sha512-xMZW2tuHLdUtx5B28E5bsLazJe9NVU2z4QW/Xefgvg41U84r4L1mTxNutTMNwt6BrRujy7hs1aKyUpIuSqcXtQ==478"@hono/node-server@^1.8.2":479 version "1.8.2"480 resolved "https://registry.npmjs.org/@hono/node-server/-/node-server-1.8.2.tgz"481 integrity sha512-h8l2TBLCPHZBUrrkosZ6L5CpBLj6zdESyF4B+zngiCDF7aZFQJ0alVbLx7jn8PCVi9EyoFf8a4hOZFi1tD95EA==482483"@humanwhocodes/config-array@^0.11.13":484 version "0.11.14"485 resolved "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.14.tgz"
6013 unmodified lines