Merge pull request #2167 from honojs/v4
Before adoption: this commit came in with the history the project adopted, so no landing records it.
v4
authored by Yusuke Wada · committed by GitHub · parents a3dfe0f, 88a82ba · Browse files · 177 files·+10554 added−3411 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
177 files+10554 added−3411 removed
- tests:+3912 added−912 removed
- other:+6642 added−2499 removed
Provenance
- Commit
2c44ad7- Tree
1bd6f4d- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent 1
a3dfe0f- Parent 2
88a82ba
177 files changed+10554 added−3411 removed
This commit is too large to show whole: its files are listed by path, without their changes.
modified:.devcontainer/Dockerfile-3 removed
6 unmodified lines7 # Install Bun8 ENV BUN_INSTALL=/usr/local9 RUN curl -fsSL https://bun.sh/install | bash10 11-# Install Lagon12-RUN yarn global add @lagon/cli esbuild13-11 WORKDIR /honomodified:.github/workflows/ci.yml+34 added-54 removed
1 name: ci2 on:3 push:4- branches: [main, next]4+ branches: [main, next, v4]5 pull_request:6 branches: ['*']7 8 jobs:1 unmodified line10 name: 'Main'11 runs-on: ubuntu-latest12 steps:13 - uses: actions/checkout@v414- - uses: actions/setup-node@v414+ - uses: oven-sh/setup-bun@v115 with:16- node-version: 20.x17- - run: yarn install --frozen-lockfile18- - run: npm run format19- - run: npm run lint20- - run: npm run build21- - run: NODE_OPTIONS="--no-warnings" npm test16+ bun-version: '1.0.25'17+ - run: bun install18+ - run: bun run format19+ - run: bun run lint20+ - run: bun run build21+ - run: bun run test22 23 denoify:24 name: "Checking if you've done denoify"25 runs-on: ubuntu-latest2 unmodified lines28 steps:29 - uses: actions/checkout@v430 - uses: actions/setup-node@v431 with:32- node-version: 18.x33- - run: yarn install --frozen-lockfile34- - run: npm run build32+ node-version: '18.x'33+ - uses: oven-sh/setup-bun@v134+ - run: bun install35 - run: |36- npm run denoify36+ bun run denoify37 if [[ `git status --porcelain` ]]; then38 exit 139 fi40 4 unmodified lines45 - uses: actions/checkout@v446 - uses: denoland/setup-deno@v147 with:48 deno-version: v1.x49- - run: env NAME=Deno deno test --allow-read --allow-env runtime_tests/deno49+ - run: env NAME=Deno deno test --allow-read --allow-env --allow-write -c runtime_tests/deno/deno.json runtime_tests/deno50 - run: deno test -c runtime_tests/deno-jsx/deno.precompile.json runtime_tests/deno-jsx51 - run: deno test -c runtime_tests/deno-jsx/deno.react-jsx.json runtime_tests/deno-jsx52 53 bun:2 unmodified lines56 steps:57 - uses: actions/checkout@v458 - uses: oven-sh/setup-bun@v159 with:60- bun-version: '1.0.18'60+ bun-version: '1.0.25'61 - run: bun run test:bun62 63 fastly:64 name: 'Fastly Compute'65 runs-on: ubuntu-latest66 steps:67 - uses: actions/checkout@v468- - uses: actions/setup-node@v469- with:70- node-version: 18.x71- - run: yarn install --frozen-lockfile72- - run: npm run build73- - run: npm run test:fastly68+ - uses: oven-sh/setup-bun@v169+ - run: bun install70+ - run: bun run build71+ - run: bun run test:fastly72 75- lagon:76- name: 'Lagon'77- runs-on: ubuntu-latest78- steps:79- - uses: actions/checkout@v480- - uses: actions/setup-node@v481- with:82- node-version: 18.x83- - run: yarn install --frozen-lockfile84- - run: npm run build85- - run: npm i -g @lagon/cli@latest esbuild@latest86- - run: npm run test:lagon87-73 node:74 name: 'Node.js v${{ matrix.node }}'75 runs-on: ubuntu-latest76 strategy:3 unmodified lines80 - uses: actions/checkout@v481 - uses: actions/setup-node@v482 with:83 node-version: ${{ matrix.node }}99- - run: yarn install --frozen-lockfile100- - run: npm run build101- - run: npm run test:node84+ - uses: oven-sh/setup-bun@v185+ - run: bun install86+ - run: bun run build87+ - run: bun run test:node88 89 wrangler:90 name: 'Cloudflare Workers'91 runs-on: ubuntu-latest92 steps:93 - uses: actions/checkout@v4108- - uses: actions/setup-node@v4109- with:110- node-version: 18.x111- - run: yarn install --frozen-lockfile112- - run: npm run build113- - run: npm run test:wrangler94+ - uses: oven-sh/setup-bun@v195+ - run: bun install96+ - run: bun run build97+ - run: bun run test:wrangler98 99 lambda:100 name: 'AWS Lambda'101 runs-on: ubuntu-latest102 steps:103 - uses: actions/checkout@v4120- - uses: actions/setup-node@v4121- with:122- node-version: 18.x123- - run: yarn install --frozen-lockfile124- - run: npm run build125- - run: npm run test:lambda104+ - uses: oven-sh/setup-bun@v1105+ - run: bun install106+ - run: bun run build107+ - run: bun run test:lambda108 109 lambda-edge:110 name: 'Lambda@Edge'111 runs-on: ubuntu-latest112 steps:113 - uses: actions/checkout@v4132- - uses: actions/setup-node@v4133- with:134- node-version: 18.x135- - run: yarn install --frozen-lockfile136- - run: npm run build137- - run: npm run test:lambda-edge114+ - uses: oven-sh/setup-bun@v1115+ - run: bun install --frozen-lockfile116+ - run: bun run build117+ - run: bun run test:lambda-edgeadded:.vitest.config/jsx-runtime-default.ts+12 added
1+import config from '../vitest.config'2+config.esbuild = {3+ jsx: 'automatic',4+ jsxImportSource: __dirname + '/../src/jsx',5+}6+if (config.test) {7+ config.test.include = [8+ '**/src/jsx/dom/**/(*.)+(spec|test).+(ts|tsx|js)',9+ 'src/jsx/hooks/dom.test.tsx',10+ ]11+}12+export default configadded:.vitest.config/jsx-runtime-dom.ts+12 added
1+import config from '../vitest.config'2+config.esbuild = {3+ jsx: 'automatic',4+ jsxImportSource: __dirname + '/../src/jsx/dom',5+}6+if (config.test) {7+ config.test.include = [8+ '**/src/jsx/dom/**/(*.)+(spec|test).+(ts|tsx|js)',9+ 'src/jsx/hooks/dom.test.tsx',10+ ]11+}12+export default configadded:benchmarks/query-param/bun.lockbbinary
A binary file, added.
added:deno_dist/adapter/deno/deno.d.ts+19 added
1+declare namespace Deno {2+ /**3+ * Creates a new directory with the specified path.4+ *5+ * @param path The path to create a directory.6+ * @param options Options for creating a directory.7+ * @returns A promise that resolves when the directory is created.8+ */9+ export function mkdir(path: string, options?: { recursive?: boolean }): Promise<void>10+11+ /**12+ * Write a new file, with the specified path and data.13+ *14+ * @param path The path to the file to write.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>19+}modified:deno_dist/adapter/deno/index.ts+1 added
1 export { serveStatic } from './serve-static.ts'2+export { toSSG, denoFileSystemModule } from './ssg.ts'modified:deno_dist/adapter/deno/serve-static.ts+1 added
8 unmodified lines9 10 export type ServeStaticOptions<E extends Env = Env> = {11 root?: string12 path?: string13+ mimes?: Record<string, string>14 rewriteRequestPath?: (path: string) => string15 onNotFound?: (path: string, c: Context<E>) => void | Promise<void>16 }17 48 unmodified linesadded:deno_dist/adapter/deno/ssg.ts+27 added
1+import { toSSG as baseToSSG } from '../../helper/ssg/index.ts'2+import type { FileSystemModule, ToSSGAdaptorInterface } from '../../helper/ssg/index.ts'3+4+/**5+ * @experimental6+ * `denoFileSystemModule` is an experimental feature.7+ * The API might be changed.8+ */9+export const denoFileSystemModule: FileSystemModule = {10+ writeFile: async (path, data) => {11+ const uint8Data =12+ typeof data === 'string' ? new TextEncoder().encode(data) : new Uint8Array(data)13+ await Deno.writeFile(path, uint8Data)14+ },15+ mkdir: async (path, options) => {16+ return Deno.mkdir(path, { recursive: options?.recursive ?? false })17+ },18+}19+20+/**21+ * @experimental22+ * `toSSG` is an experimental feature.23+ * The API might be changed.24+ */25+export const toSSG: ToSSGAdaptorInterface = async (app, options) => {26+ return baseToSSG(app, denoFileSystemModule, options)27+}modified:deno_dist/client/client.ts-9 removed
57 unmodified lines58 }59 }60 }61 62- if (args.queries) {63- for (const [k, v] of Object.entries(args.queries)) {64- for (const v2 of v) {65- this.queryParams ||= new URLSearchParams()66- this.queryParams.append(k, v2)67- }68- }69- }70-62 if (args.form) {63 const form = new FormData()64 for (const [k, v] of Object.entries(args.form)) {65 form.append(k, v)88 unmodified linesmodified:deno_dist/client/types.ts+1 added-1 removed
1 import type { Hono } from '../hono.ts'2 import type { Schema } from '../types.ts'3 import type { HasRequiredKeys } from '../utils/types.ts'4 5-type HonoRequest = typeof Hono.prototype['request']5+type HonoRequest = (typeof Hono.prototype)['request']6 7 export type ClientRequestOptions<T = unknown> = keyof T extends never8 ? {9 headers?: Record<string, string>111 unmodified linesadded:deno_dist/helper/accepts/accepts.ts+73 added
1+import type { Context } from '../../context.ts'2+3+export type AcceptHeader =4+ | 'Accept'5+ | 'Accept-Charset'6+ | 'Accept-Encoding'7+ | 'Accept-Language'8+ | 'Accept-Patch'9+ | 'Accept-Post'10+ | 'Accept-Ranges'11+12+export interface Accept {13+ type: string14+ params: Record<string, string>15+ q: number16+}17+18+export interface acceptsConfig {19+ header: AcceptHeader20+ supports: string[]21+ default: string22+}23+24+export interface acceptsOptions extends acceptsConfig {25+ match?: (accepts: Accept[], config: acceptsConfig) => string26+}27+28+export const parseAccept = (acceptHeader: string) => {29+ // Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.830+ const accepts = acceptHeader.split(',') // ['text/html', 'application/xhtml+xml', 'application/xml;q=0.9', 'image/webp', '*/*;q=0.8']31+ return accepts.map((accept) => {32+ const [type, ...params] = accept.trim().split(';') // ['application/xml', 'q=0.9']33+ const q = params.find((param) => param.startsWith('q=')) // 'q=0.9'34+ return {35+ type,36+ params: params.reduce((acc, param) => {37+ const [key, value] = param.split('=')38+ return { ...acc, [key.trim()]: value.trim() }39+ }, {}),40+ q: q ? parseFloat(q.split('=')[1]) : 1,41+ }42+ })43+}44+45+export const defaultMatch = (accepts: Accept[], config: acceptsConfig) => {46+ const { supports, default: defaultSupport } = config47+ const accept = accepts.sort((a, b) => b.q - a.q).find((accept) => supports.includes(accept.type))48+ return accept ? accept.type : defaultSupport49+}50+51+/**52+ * Match the accept header with the given options.53+ * @example54+ * ```ts55+ * app.get('/users', (c) => {56+ * const lang = accepts(c, {57+ * header: 'Accept-Language',58+ * supports: ['en', 'zh'],59+ * default: 'en',60+ * })61+ * })62+ * ```63+ */64+export const accepts = (c: Context, options: acceptsOptions) => {65+ const acceptHeader = c.req.header(options.header)66+ if (!acceptHeader) {67+ return options.default68+ }69+ const accepts = parseAccept(acceptHeader)70+ const match = options.match || defaultMatch71+72+ return match(accepts, options)73+}added:deno_dist/helper/accepts/index.ts+1 added
1+export { accepts } from './accepts.ts'modified:deno_dist/helper/adapter/index.ts+1 added-13 removed
1 import type { Context } from '../../context.ts'2 3-export type Runtime =4- | 'node'5- | 'deno'6- | 'bun'7- | 'workerd'8- | 'fastly'9- | 'edge-light'10- | 'lagon'11- | 'other'3+export type Runtime = 'node' | 'deno' | 'bun' | 'workerd' | 'fastly' | 'edge-light' | 'other'4 5 export const env = <T extends Record<string, unknown>, C extends Context = Context<{}>>(6 c: C,7 runtime?: Runtime7 unmodified lines15 const runtimeEnvHandlers: Record<string, () => T> = {16 bun: () => globalEnv,17 node: () => globalEnv,18 'edge-light': () => globalEnv,27- lagon: () => globalEnv,19 deno: () => {20 // eslint-disable-next-line @typescript-eslint/ban-ts-comment21 // @ts-ignore22 return Deno.env.toObject() as T25 unmodified lines48 }49 if (global?.fastly !== undefined) {50 return 'fastly'51 }61- if (global?.__lagon__ !== undefined) {62- return 'lagon'63- }52 if (global?.process?.release?.name === 'node') {53 return 'node'54 }55 2 unmodified linesadded:deno_dist/helper/css/common.ts+243 added
1+// provide utility functions for css helper both on server and client2+export const PSEUDO_GLOBAL_SELECTOR = ':-hono-global'3+export const isPseudoGlobalSelectorRe = new RegExp(`^${PSEUDO_GLOBAL_SELECTOR}{(.*)}$`)4+export const DEFAULT_STYLE_ID = 'hono-css'5+6+export const SELECTOR = Symbol()7+export const CLASS_NAME = Symbol()8+export const STYLE_STRING = Symbol()9+export const SELECTORS = Symbol()10+export const EXTERNAL_CLASS_NAMES = Symbol()11+const CSS_ESCAPED = Symbol()12+13+export interface CssClassName {14+ [SELECTOR]: string15+ [CLASS_NAME]: string16+ [STYLE_STRING]: string17+ [SELECTORS]: CssClassName[]18+ [EXTERNAL_CLASS_NAMES]: string[]19+}20+21+export const IS_CSS_ESCAPED = Symbol()22+23+interface CssEscapedString {24+ [CSS_ESCAPED]: string25+}26+27+/**28+ * @experimental29+ * `rawCssString` is an experimental feature.30+ * The API might be changed.31+ */32+export const rawCssString = (value: string): CssEscapedString => {33+ return {34+ [CSS_ESCAPED]: value,35+ }36+}37+38+/**39+ * Used the goober'code as a reference:40+ * https://github.com/cristianbote/goober/blob/master/src/core/to-hash.js41+ * MIT License, Copyright (c) 2019 Cristian Bote42+ */43+const toHash = (str: string): string => {44+ let i = 0,45+ out = 1146+ while (i < str.length) {47+ out = (101 * out + str.charCodeAt(i++)) >>> 048+ }49+ return 'css-' + out50+}51+52+const cssStringReStr = [53+ '"(?:(?:\\\\[\\s\\S]|[^"\\\\])*)"', // double quoted string54+ // eslint-disable-next-line quotes55+ "'(?:(?:\\\\[\\s\\S]|[^'\\\\])*)'", // single quoted string56+].join('|')57+const minifyCssRe = new RegExp(58+ [59+ '(' + cssStringReStr + ')', // $1: quoted string60+61+ '(?:' +62+ [63+ '^\\s+', // head whitespace64+ '\\/\\*.*?\\*\\/\\s*', // multi-line comment65+ '\\/\\/.*\\n\\s*', // single-line comment66+ '\\s+$', // tail whitespace67+ ].join('|') +68+ ')',69+70+ '\\s*;\\s*(}|$)\\s*', // $2: trailing semicolon71+ '\\s*([{};:,])\\s*', // $3: whitespace around { } : , ;72+ '(\\s)\\s+', // $4: 2+ spaces73+ ].join('|'),74+ 'g'75+)76+77+export const minify = (css: string): string => {78+ return css.replace(minifyCssRe, (_, $1, $2, $3, $4) => $1 || $2 || $3 || $4 || '')79+}80+81+type CssVariableBasicType =82+ | CssClassName83+ | CssEscapedString84+ | string85+ | number86+ | boolean87+ | null88+ | undefined89+type CssVariableAsyncType = Promise<CssVariableBasicType>90+type CssVariableArrayType = (CssVariableBasicType | CssVariableAsyncType)[]91+export type CssVariableType = CssVariableBasicType | CssVariableAsyncType | CssVariableArrayType92+93+export const buildStyleString = (94+ strings: TemplateStringsArray,95+ values: CssVariableType[]96+): [string, string, CssClassName[], string[]] => {97+ const selectors: CssClassName[] = []98+ const externalClassNames: string[] = []99+100+ const label = strings[0].match(/^\s*\/\*(.*?)\*\//)?.[1] || ''101+ let styleString = ''102+ for (let i = 0, len = strings.length; i < len; i++) {103+ styleString += strings[i]104+ let vArray = values[i]105+ if (typeof vArray === 'boolean' || vArray === null || vArray === undefined) {106+ continue107+ }108+109+ if (!Array.isArray(vArray)) {110+ vArray = [vArray]111+ }112+ for (let j = 0, len = vArray.length; j < len; j++) {113+ let value = vArray[j]114+ if (typeof value === 'boolean' || value === null || value === undefined) {115+ continue116+ }117+ if (typeof value === 'string') {118+ if (/([\\"'\/])/.test(value)) {119+ styleString += value.replace(/([\\"']|(?<=<)\/)/g, '\\$1')120+ } else {121+ styleString += value122+ }123+ } else if (typeof value === 'number') {124+ styleString += value125+ } else if ((value as CssEscapedString)[CSS_ESCAPED]) {126+ styleString += (value as CssEscapedString)[CSS_ESCAPED]127+ } else if ((value as CssClassName)[CLASS_NAME].startsWith('@keyframes ')) {128+ selectors.push(value as CssClassName)129+ styleString += ` ${(value as CssClassName)[CLASS_NAME].substring(11)} `130+ } else {131+ if (strings[i + 1]?.match(/^\s*{/)) {132+ // assume this value is a class name133+ selectors.push(value as CssClassName)134+ value = `.${(value as CssClassName)[CLASS_NAME]}`135+ } else {136+ selectors.push(...(value as CssClassName)[SELECTORS])137+ externalClassNames.push(...(value as CssClassName)[EXTERNAL_CLASS_NAMES])138+ value = (value as CssClassName)[STYLE_STRING]139+ const valueLen = value.length140+ if (valueLen > 0) {141+ const lastChar = value[valueLen - 1]142+ if (lastChar !== ';' && lastChar !== '}') {143+ value += ';'144+ }145+ }146+ }147+ styleString += `${value || ''}`148+ }149+ }150+ }151+152+ return [label, minify(styleString), selectors, externalClassNames]153+}154+155+export const cssCommon = (156+ strings: TemplateStringsArray,157+ values: CssVariableType[]158+): CssClassName => {159+ let [label, thisStyleString, selectors, externalClassNames] = buildStyleString(strings, values)160+ const isPseudoGlobal = isPseudoGlobalSelectorRe.exec(thisStyleString)161+ if (isPseudoGlobal) {162+ thisStyleString = isPseudoGlobal[1]163+ }164+ const selector = (isPseudoGlobal ? PSEUDO_GLOBAL_SELECTOR : '') + toHash(label + thisStyleString)165+ const className = (166+ isPseudoGlobal ? selectors.map((s) => s[CLASS_NAME]) : [selector, ...externalClassNames]167+ ).join(' ')168+169+ return {170+ [SELECTOR]: selector,171+ [CLASS_NAME]: className,172+ [STYLE_STRING]: thisStyleString,173+ [SELECTORS]: selectors,174+ [EXTERNAL_CLASS_NAMES]: externalClassNames,175+ }176+}177+178+export const cxCommon = (179+ args: (string | boolean | null | undefined | CssClassName)[]180+): (string | boolean | null | undefined | CssClassName)[] => {181+ for (let i = 0, len = args.length; i < len; i++) {182+ const arg = args[i]183+ if (typeof arg === 'string') {184+ args[i] = {185+ [SELECTOR]: '',186+ [CLASS_NAME]: '',187+ [STYLE_STRING]: '',188+ [SELECTORS]: [],189+ [EXTERNAL_CLASS_NAMES]: [arg],190+ }191+ }192+ }193+194+ return args195+}196+197+export const keyframesCommon = (198+ strings: TemplateStringsArray,199+ ...values: CssVariableType[]200+): CssClassName => {201+ const [label, styleString] = buildStyleString(strings, values)202+ return {203+ [SELECTOR]: '',204+ [CLASS_NAME]: `@keyframes ${toHash(label + styleString)}`,205+ [STYLE_STRING]: styleString,206+ [SELECTORS]: [],207+ [EXTERNAL_CLASS_NAMES]: [],208+ }209+}210+211+type ViewTransitionType = {212+ (strings: TemplateStringsArray, values: CssVariableType[]): CssClassName213+ (content: CssClassName): CssClassName214+ (): CssClassName215+}216+217+let viewTransitionNameIndex = 0218+export const viewTransitionCommon: ViewTransitionType = ((219+ strings: TemplateStringsArray | CssClassName | undefined,220+ values: CssVariableType[]221+): CssClassName => {222+ if (!strings) {223+ // eslint-disable-next-line @typescript-eslint/no-explicit-any224+ strings = [`/* h-v-t ${viewTransitionNameIndex++} */`] as any225+ }226+ const content = Array.isArray(strings)227+ ? cssCommon(strings as TemplateStringsArray, values)228+ : (strings as CssClassName)229+230+ const transitionName = content[CLASS_NAME]231+ // eslint-disable-next-line @typescript-eslint/no-explicit-any232+ const res = cssCommon(['view-transition-name:', ''] as any, [transitionName])233+234+ content[CLASS_NAME] = PSEUDO_GLOBAL_SELECTOR + content[CLASS_NAME]235+ content[STYLE_STRING] = content[STYLE_STRING].replace(236+ /(?<=::view-transition(?:[a-z-]*)\()(?=\))/g,237+ transitionName238+ )239+ res[CLASS_NAME] = res[SELECTOR] = transitionName240+ res[SELECTORS] = [...content[SELECTORS], content]241+242+ return res243+}) as ViewTransitionTypemodified:deno_dist/helper/css/index.ts+75 added-194 removed
1 import { raw } from '../../helper/html/index.ts'2+import { DOM_RENDERER } from '../../jsx/constants.ts'3+import { createCssJsxDomObjects } from '../../jsx/dom/css.ts'4 import type { HtmlEscapedCallback, HtmlEscapedString } from '../../utils/html.ts'5+import type { CssClassName as CssClassNameCommon, CssVariableType } from './common.ts'6+import {7+ SELECTOR,8+ CLASS_NAME,9+ STYLE_STRING,10+ SELECTORS,11+ PSEUDO_GLOBAL_SELECTOR,12+ DEFAULT_STYLE_ID,13+ cssCommon,14+ cxCommon,15+ keyframesCommon,16+ viewTransitionCommon,17+} from './common.ts'18+export { rawCssString } from './common.ts'19 4-const IS_CSS_CLASS_NAME = Symbol('IS_CSS_CLASS_NAME')5-const STYLE_STRING = Symbol('STYLE_STRING')6-const SELECTORS = Symbol('SELECTORS')7-const EXTERNAL_CLASS_NAMES = Symbol('EXTERNAL_CLASS_NAMES')8-type CssClassName = HtmlEscapedString & {20+type CssClassName = HtmlEscapedString & CssClassNameCommon9- [IS_CSS_CLASS_NAME]: true10- [STYLE_STRING]: string11- // eslint-disable-next-line @typescript-eslint/ban-types12- [SELECTORS]: String[]13- [EXTERNAL_CLASS_NAMES]: string[]14-}21 16-type CssEscaped = {17- isCssEscaped: true18-}19-type CssEscapedString = string & CssEscaped20-21-/**22- * @experimental23- * `rawCssString` is an experimental feature.24- * The API might be changed.25- */26-export const rawCssString = (value: string): CssEscapedString => {27- const escapedString = new String(value) as CssEscapedString28- escapedString.isCssEscaped = true29- return escapedString30-}31-32-const DEFAULT_STYLE_ID = 'hono-css'33-34-/**35- * Used the goober'code as a reference:36- * https://github.com/cristianbote/goober/blob/master/src/core/to-hash.js37- * MIT License, Copyright (c) 2019 Cristian Bote38- */39-const toHash = (str: string): string => {40- let i = 0,41- out = 1142- while (i < str.length) {43- out = (101 * out + str.charCodeAt(i++)) >>> 044- }45- return 'css-' + out46-}47-48-const cssStringReStr = [49- '"(?:(?:\\\\[\\s\\S]|[^"\\\\])*)"', // double quoted string50- // eslint-disable-next-line quotes51- "'(?:(?:\\\\[\\s\\S]|[^'\\\\])*)'", // single quoted string52-].join('|')53-const minifyCssRe = new RegExp(54- [55- '(' + cssStringReStr + ')', // $1: quoted string56-57- '(?:' +58- [59- '^\\s+', // head whitespace60- '\\/\\*.*?\\*\\/\\s*', // multi-line comment61- '\\/\\/.*\\n\\s*', // single-line comment62- '\\s+$', // tail whitespace63- ].join('|') +64- ')',65-66- ';\\s*(}|$)\\s*', // $2: trailing semicolon67- '\\s*([{};:,])\\s*', // $3: whitespace around { } : , ;68- '(\\s)\\s+', // $4: 2+ spaces69- ].join('|'),70- 'g'71-)72-73-const minify = (css: string): string => {74- return css.replace(minifyCssRe, (_, $1, $2, $3, $4) => $1 || $2 || $3 || $4 || '')75-}76-22 type usedClassNameData = [23 Record<string, string>, // class name to add24 Record<string, true> // class name already added25 ]81-// eslint-disable-next-line @typescript-eslint/ban-types82-type CssVariableBasicType = string | String | number | boolean | null | undefined83-type CssVariableAsyncType = Promise<CssVariableBasicType>84-type CssVariableArrayType = (CssVariableBasicType | CssVariableAsyncType)[]85-type CssVariableType = CssVariableBasicType | CssVariableAsyncType | CssVariableArrayType26 87-const buildStyleString = async (88- strings: TemplateStringsArray,89- values: CssVariableType[],90- // eslint-disable-next-line @typescript-eslint/ban-types91- selectors: String[],92- externalClassNames: string[]93-): Promise<string> => {94- let styleString = ''95- for (let i = 0; i < strings.length; i++) {96- styleString += strings[i]97- let vArray = values[i]98- if (typeof vArray === 'boolean' || vArray === null || vArray === undefined) {99- continue100- }101-102- if (!Array.isArray(vArray)) {103- vArray = [vArray] as CssVariableArrayType104- }105- for (let j = 0; j < vArray.length; j++) {106- let value = (107- vArray[j] instanceof Promise ? await vArray[j] : vArray[j]108- ) as CssVariableBasicType109- if (typeof value === 'boolean' || value === null || value === undefined) {110- continue111- }112- if (typeof value === 'number') {113- styleString += value114- } else if (value.startsWith('@keyframes ')) {115- selectors.push(value)116- styleString += ` ${value.substring(11)} `117- } else {118- if ((value as CssClassName)[IS_CSS_CLASS_NAME]) {119- selectors.push(...(value as CssClassName)[SELECTORS])120- externalClassNames.push(...(value as CssClassName)[EXTERNAL_CLASS_NAMES])121- value = (value as CssClassName)[STYLE_STRING]122- if (value.length > 0) {123- const lastChar = value[value.length - 1]124- if (lastChar !== ';' && lastChar !== '}') {125- value += ';'126- }127- }128- } else if (129- !(value as CssEscapedString).isCssEscaped &&130- /([\\"'\/])/.test(value as string)131- ) {132- value = value.replace(/([\\"']|(?<=<)\/)/g, '\\$1')133- }134- styleString += `${value || ''}`135- }136- }137- }138-139- return minify(styleString)140-}141-27 /**28 * @experimental29 * `createCssContext` is an experimental feature.30 * The API might be changed.31 */32 export const createCssContext = ({ id }: { id: Readonly<string> }) => {33+ const [cssJsxDomObject, StyleRenderToDom] = createCssJsxDomObjects({ id })34+35 const contextMap: WeakMap<object, usedClassNameData> = new WeakMap()36 37 const replaceStyleRe = new RegExp(`(<style id="${id}">.*?)(</style>)`)38 152- const css = async (153- strings: TemplateStringsArray,154- ...values: CssVariableType[]155- ): Promise<string> => {156- // eslint-disable-next-line @typescript-eslint/ban-types157- const selectors: String[] = []158- const externalClassNames: string[] = []159- const thisStyleString = await buildStyleString(strings, values, selectors, externalClassNames)160- const thisSelector = toHash(thisStyleString)161- const className = new String([thisSelector, ...externalClassNames].join(' ')) as CssClassName162-39+ const newCssClassNameObject = (cssClassName: CssClassNameCommon): Promise<string> => {40 const appendStyle: HtmlEscapedCallback = ({ buffer, context }): Promise<string> | undefined => {41 const [toAdd, added] = contextMap.get(context) as usedClassNameData42 const names = Object.keys(toAdd)43 3 unmodified lines47 48 let stylesStr = ''49 names.forEach((className) => {50 added[className] = true51+ stylesStr += className.startsWith(PSEUDO_GLOBAL_SELECTOR)52+ ? toAdd[className]174- stylesStr += `${className[0] === '@' ? '' : '.'}${className}{${toAdd[className]}}`53+ : `${className[0] === '@' ? '' : '.'}${className}{${toAdd[className]}}`54 })55 contextMap.set(context, [{}, added])56 57 if (buffer && replaceStyleRe.test(buffer[0])) {17 unmodified lines75 contextMap.set(context, [{}, {}])76 }77 const [toAdd, added] = contextMap.get(context) as usedClassNameData78 let allAdded = true200- if (!added[thisSelector]) {79+ if (!added[cssClassName[SELECTOR]]) {80 allAdded = false202- toAdd[thisSelector] = thisStyleString81+ toAdd[cssClassName[SELECTOR]] = cssClassName[STYLE_STRING]82 }204- selectors.forEach((className) => {205- if (!added[`${className}`]) {206- allAdded = false207- toAdd[`${className}`] = (className as CssClassName)[STYLE_STRING]83+ cssClassName[SELECTORS].forEach(84+ ({ [CLASS_NAME]: className, [STYLE_STRING]: styleString }) => {85+ if (!added[className]) {86+ allAdded = false87+ toAdd[className] = styleString88+ }89 }209- })90+ )91 if (allAdded) {92 return93 }94 95 return Promise.resolve(raw('', [appendStyle]))96 }97 217- Object.assign(className, {218- isEscaped: true,219- callbacks: [addClassNameToContext],220- [IS_CSS_CLASS_NAME]: true,221- [STYLE_STRING]: thisStyleString,222- [SELECTORS]: selectors,223- [EXTERNAL_CLASS_NAMES]: externalClassNames,224- })98+ const className = new String(cssClassName[CLASS_NAME]) as CssClassName99+ Object.assign(className, cssClassName)100+ ;(className as HtmlEscapedString).isEscaped = true101+ ;(className as HtmlEscapedString).callbacks = [addClassNameToContext]102+ const promise = Promise.resolve(className)103+ Object.assign(promise, cssClassName)104+ promise.toString = cssJsxDomObject.toString105+ return promise106+ }107 226- return className as string108+ const css = (strings: TemplateStringsArray, ...values: CssVariableType[]): Promise<string> => {109+ return newCssClassNameObject(cssCommon(strings, values))110 }111 229- const cx = async (230- ...args: (string | boolean | null | undefined | Promise<string | boolean | null | undefined>)[]112+ const cx = (113+ ...args: (CssClassName | Promise<string> | string | boolean | null | undefined)[]114 ): Promise<string> => {232- const resolvedArgs = await Promise.all(args)233- for (let i = 0; i < resolvedArgs.length; i++) {234- const arg = resolvedArgs[i]235- if (typeof arg === 'string' && !(arg as CssClassName)[IS_CSS_CLASS_NAME]) {236- const externalClassName = new String(arg) as CssClassName237- resolvedArgs[i] = Object.assign(externalClassName, {238- isEscaped: true,239- [IS_CSS_CLASS_NAME]: true,240- [STYLE_STRING]: '',241- [SELECTORS]: [],242- [EXTERNAL_CLASS_NAMES]: [arg],243- })244- }245- }246-115 // eslint-disable-next-line @typescript-eslint/no-explicit-any248- return css(Array(resolvedArgs.length).fill('') as any, ...resolvedArgs)116+ args = cxCommon(args as any) as any117+ // eslint-disable-next-line @typescript-eslint/no-explicit-any118+ return css(Array(args.length).fill('') as any, ...args)119 }120 251- const keyframes = async (252- strings: TemplateStringsArray,253- ...values: CssVariableType[]254- ): // eslint-disable-next-line @typescript-eslint/ban-types255- Promise<String> => {256- const styleString = await buildStyleString(strings, values, [], [])257- const className = new String(`@keyframes ${toHash(styleString)}`)258- Object.assign(className as CssClassName, {259- isEscaped: true,260- [IS_CSS_CLASS_NAME]: true,261- [STYLE_STRING]: styleString,262- [SELECTORS]: [],263- [EXTERNAL_CLASS_NAMES]: [],264- })265- return className121+ const keyframes = keyframesCommon122+123+ type ViewTransitionType = {124+ (strings: TemplateStringsArray, ...values: CssVariableType[]): Promise<string>125+ (content: Promise<string>): Promise<string>126+ (): Promise<string>127 }128+ const viewTransition: ViewTransitionType = ((129+ strings: TemplateStringsArray | Promise<string> | undefined,130+ ...values: CssVariableType[]131+ ): Promise<string> => {132+ // eslint-disable-next-line @typescript-eslint/no-explicit-any133+ return newCssClassNameObject(viewTransitionCommon(strings as any, values))134+ }) as ViewTransitionType135 268- const Style = () => raw(`<style id="${id}"></style>`)136+ const Style = ({ children }: { children?: Promise<string> } = {}) =>137+ children138+ ? raw(`<style id="${id}">${(children as unknown as CssClassName)[STYLE_STRING]}</style>`)139+ : raw(`<style id="${id}"></style>`)140+ // eslint-disable-next-line @typescript-eslint/no-explicit-any141+ ;(Style as any)[DOM_RENDERER] = StyleRenderToDom142 143 return {144 css,145 cx,146 keyframes,147+ viewTransition: viewTransition as ViewTransitionType,148 Style,149 }150 }151 21 unmodified lines173 export const keyframes = defaultContext.keyframes174 175 /**176 * @experimental177+ * `viewTransition` is an experimental feature.178+ * The API might be changed.179+ */180+export const viewTransition = defaultContext.viewTransition181+182+/**183+ * @experimental184 * `Style` is an experimental feature.185 * The API might be changed.186 */187 export const Style = defaultContext.Stylemodified:deno_dist/helper/factory/index.ts-60 removed
1 /* eslint-disable @typescript-eslint/no-explicit-any */2 import type { Env, Input, MiddlewareHandler, H, HandlerResponse } from '../../types.ts'3 4-/**5- * @experimental6- * `Factory` class is an experimental feature.7- * The API might be changed.8- */4 export class Factory<E extends Env = any, P extends string = any> {5 createMiddleware = <I extends Input = {}>(middleware: MiddlewareHandler<E, P, I>) => middleware6 12- /**13- * @experimental14- * `createHandlers` is an experimental feature.15- * The API might be changed.16- */7 createHandlers<I extends Input = {}>(handler1: H<E, P, I>): [H<E, P, I>]8 9 // handler x220- /**21- * @experimental22- * `createHandlers` is an experimental feature.23- * The API might be changed.24- */10 createHandlers<I extends Input = {}, I2 extends Input = I, R extends HandlerResponse<any> = any>(11 handler1: H<E, P, I, R>,12 handler2: H<E, P, I2, R>13 ): [H<E, P, I, R>, H<E, P, I2, R>]14 15 // handler x331- /**32- * @experimental33- * `createHandlers` is an experimental feature.34- * The API might be changed.35- */16 createHandlers<17 I extends Input = {},18 I2 extends Input = I,19 I3 extends Input = I & I2,4 unmodified lines24 handler3: H<E, P, I3, R>25 ): [H<E, P, I, R>, H<E, P, I2, R>, H<E, P, I3, R>]26 27 // handler x448- /**49- * @experimental50- * `createHandlers` is an experimental feature.51- * The API might be changed.52- */28 createHandlers<29 I extends Input = {},30 I2 extends Input = I,31 I3 extends Input = I & I2,6 unmodified lines38 handler4: H<E, P, I4, R>39 ): [H<E, P, I, R>, H<E, P, I2, R>, H<E, P, I3, R>, H<E, P, I4, R>]40 41 // handler x567- /**68- * @experimental69- * `createHandlers` is an experimental feature.70- * The API might be changed.71- */42 createHandlers<43 I extends Input = {},44 I2 extends Input = I,45 I3 extends Input = I & I2,8 unmodified lines54 handler5: H<E, P, I5, R>55 ): [H<E, P, I, R>, H<E, P, I2, R>, H<E, P, I3, R>, H<E, P, I4, R>, H<E, P, I5, R>]56 57 // handler x688- /**89- * @experimental90- * `createHandlers` is an experimental feature.91- * The API might be changed.92- */58 createHandlers<59 I extends Input = {},60 I2 extends Input = I,61 I3 extends Input = I & I2,10 unmodified lines72 handler6: H<E, P, I6, R>73 ): [H<E, P, I, R>, H<E, P, I2, R>, H<E, P, I3, R>, H<E, P, I4, R>, H<E, P, I5, R>, H<E, P, I6, R>]74 75 // handler x7111- /**112- * @experimental113- * `createHandlers` is an experimental feature.114- * The API might be changed.115- */76 createHandlers<77 I extends Input = {},78 I2 extends Input = I,79 I3 extends Input = I & I2,20 unmodified lines100 H<E, P, I7, R>101 ]102 103 // handler x8144- /**145- * @experimental146- * `createHandlers` is an experimental feature.147- * The API might be changed.148- */104 createHandlers<105 I extends Input = {},106 I2 extends Input = I,107 I3 extends Input = I & I2,23 unmodified lines131 H<E, P, I8, R>132 ]133 134 // handler x9180- /**181- * @experimental182- * `createHandlers` is an experimental feature.183- * The API might be changed.184- */135 createHandlers<136 I extends Input = {},137 I2 extends Input = I,138 I3 extends Input = I & I2,26 unmodified lines165 H<E, P, I9, R>166 ]167 168 // handler x10219- /**220- * @experimental221- * `createHandlers` is an experimental feature.222- * The API might be changed.223- */169 createHandlers<170 I extends Input = {},171 I2 extends Input = I,172 I3 extends Input = I & I2,33 unmodified lines206 return handlers.filter((handler) => handler !== undefined)207 }208 }209 265-/**266- * @experimental267- * `createFactory` is an experimental feature.268- * The API might be changed.269- */210 export const createFactory = <E extends Env = any, P extends string = any>() => new Factory<E, P>()211 212 export const createMiddleware = <E extends Env = any, P extends string = any, I extends Input = {}>(213 middleware: MiddlewareHandler<E, P, I>1 unmodified lineadded:deno_dist/helper/ssg/index.ts+286 added
1+import { replaceUrlParam } from '../../client/utils.ts'2+import type { Context } from '../../context.ts'3+import { inspectRoutes } from '../../helper/dev/index.ts'4+import type { Hono } from '../../hono.ts'5+import type { Env, MiddlewareHandler, Schema } from '../../types.ts'6+import { bufferToString } from '../../utils/buffer.ts'7+import { getExtension } from '../../utils/mime.ts'8+import { joinPaths, dirname } from './utils.ts'9+10+export const X_HONO_SSG_HEADER_KEY = 'x-hono-ssg'11+export const X_HONO_DISABLE_SSG_HEADER_KEY = 'x-hono-disable-ssg'12+13+/**14+ * @experimental15+ * `FileSystemModule` is an experimental feature.16+ * The API might be changed.17+ */18+export interface FileSystemModule {19+ writeFile(path: string, data: string | Uint8Array): Promise<void>20+ mkdir(path: string, options: { recursive: boolean }): Promise<void | string>21+}22+23+/**24+ * @experimental25+ * `ToSSGResult` is an experimental feature.26+ * The API might be changed.27+ */28+export interface ToSSGResult {29+ success: boolean30+ files: string[]31+ error?: Error32+}33+34+const generateFilePath = (routePath: string, outDir: string, mimeType: string) => {35+ const extension = determineExtension(mimeType)36+ if (routePath === '/') {37+ return joinPaths(outDir, `index.${extension}`)38+ }39+ if (routePath.endsWith('/')) {40+ return joinPaths(outDir, routePath, `index.${extension}`)41+ }42+ return joinPaths(outDir, `${routePath}.${extension}`)43+}44+45+const parseResponseContent = async (response: Response): Promise<string | ArrayBuffer> => {46+ const contentType = response.headers.get('Content-Type')47+48+ try {49+ if (contentType?.includes('text') || contentType?.includes('json')) {50+ return await response.text()51+ } else {52+ return await response.arrayBuffer()53+ }54+ } catch (error) {55+ throw new Error(56+ `Error processing response: ${error instanceof Error ? error.message : 'Unknown error'}`57+ )58+ }59+}60+61+const determineExtension = (mimeType: string): string => {62+ switch (mimeType) {63+ case 'text/html':64+ return 'html'65+ case 'text/xml':66+ case 'application/xml':67+ return 'xml'68+ default: {69+ return getExtension(mimeType) || 'html'70+ }71+ }72+}73+74+interface SSGParam {75+ [key: string]: string76+}77+type SSGParams = SSGParam[]78+79+interface SSGParamsMiddleware {80+ <E extends Env = Env>(81+ generateParams: (c: Context<E>) => SSGParams | Promise<SSGParams>82+ ): MiddlewareHandler<E>83+ <E extends Env = Env>(params: SSGParams): MiddlewareHandler<E>84+}85+86+type AddedSSGDataRequest = Request & {87+ ssgParams?: SSGParams88+}89+/**90+ * Define SSG Route91+ */92+export const ssgParams: SSGParamsMiddleware = (params) => async (c, next) => {93+ ;(c.req.raw as AddedSSGDataRequest).ssgParams = Array.isArray(params) ? params : await params(c)94+ await next()95+}96+97+export type BeforeRequestHook = (req: Request) => Request | false98+export type AfterResponseHook = (res: Response) => Response | false99+export type AfterGenerateHook = (result: ToSSGResult) => void | Promise<void>100+101+export interface ToSSGOptions {102+ dir?: string103+ beforeRequestHook?: BeforeRequestHook104+ afterResponseHook?: AfterResponseHook105+ afterGenerateHook?: AfterGenerateHook106+}107+108+/**109+ * @experimental110+ * `fetchRoutesContent` is an experimental feature.111+ * The API might be changed.112+ */113+export const fetchRoutesContent = async <114+ E extends Env = Env,115+ S extends Schema = {},116+ BasePath extends string = '/'117+>(118+ app: Hono<E, S, BasePath>,119+ beforeRequestHook?: BeforeRequestHook,120+ afterResponseHook?: AfterResponseHook121+): Promise<Map<string, { content: string | ArrayBuffer; mimeType: string }>> => {122+ const htmlMap = new Map<string, { content: string | ArrayBuffer; mimeType: string }>()123+ const baseURL = 'http://localhost'124+125+ for (const route of inspectRoutes(app)) {126+ if (route.isMiddleware) {127+ continue128+ }129+130+ // GET Route Info131+ const thisRouteBaseURL = new URL(route.path, baseURL).toString()132+133+ let forGetInfoURLRequest = new Request(thisRouteBaseURL) as AddedSSGDataRequest134+ forGetInfoURLRequest.headers.set(X_HONO_SSG_HEADER_KEY, 'true')135+ if (beforeRequestHook) {136+ const maybeRequest = beforeRequestHook(forGetInfoURLRequest)137+ if (!maybeRequest) {138+ continue139+ }140+ forGetInfoURLRequest = maybeRequest as unknown as AddedSSGDataRequest141+ }142+ await app.fetch(forGetInfoURLRequest)143+144+ if (!forGetInfoURLRequest.ssgParams) {145+ if (isDynamicRoute(route.path)) {146+ continue147+ }148+ forGetInfoURLRequest.ssgParams = [{}]149+ }150+151+ for (const param of forGetInfoURLRequest.ssgParams) {152+ const replacedUrlParam = replaceUrlParam(route.path, param)153+ let response = await app.request(replacedUrlParam, forGetInfoURLRequest)154+ if (response.headers.get(X_HONO_DISABLE_SSG_HEADER_KEY)) {155+ continue156+ }157+ if (afterResponseHook) {158+ const maybeResponse = afterResponseHook(response)159+ if (!maybeResponse) {160+ continue161+ }162+ response = maybeResponse163+ }164+ const mimeType = response.headers.get('Content-Type')?.split(';')[0] || 'text/plain'165+ const content = await parseResponseContent(response)166+ htmlMap.set(replacedUrlParam, {167+ mimeType,168+ content,169+ })170+ }171+ }172+173+ return htmlMap174+}175+176+const isDynamicRoute = (path: string): boolean => {177+ return path.split('/').some((segment) => segment.startsWith(':') || segment.includes('*'))178+}179+180+/**181+ * @experimental182+ * `saveContentToFiles` is an experimental feature.183+ * The API might be changed.184+ */185+export const saveContentToFiles = async (186+ htmlMap: Map<string, { content: string | ArrayBuffer; mimeType: string }>,187+ fsModule: FileSystemModule,188+ outDir: string189+): Promise<string[]> => {190+ const files: string[] = []191+192+ for (const [routePath, { content, mimeType }] of htmlMap) {193+ const filePath = generateFilePath(routePath, outDir, mimeType)194+ const dirPath = dirname(filePath)195+196+ await fsModule.mkdir(dirPath, { recursive: true })197+ if (typeof content === 'string') {198+ await fsModule.writeFile(filePath, content)199+ } else if (content instanceof ArrayBuffer) {200+ await fsModule.writeFile(filePath, bufferToString(content))201+ }202+ files.push(filePath)203+ }204+205+ return files206+}207+208+/**209+ * @experimental210+ * `ToSSGInterface` is an experimental feature.211+ * The API might be changed.212+ */213+export interface ToSSGInterface<214+ E extends Env = Env,215+ S extends Schema = {},216+ BasePath extends string = '/'217+> {218+ (219+ app: Hono<E, S, BasePath>,220+ fsModule: FileSystemModule,221+ options?: ToSSGOptions222+ ): Promise<ToSSGResult>223+}224+225+/**226+ * @experimental227+ * `ToSSGAdaptorInterface` is an experimental feature.228+ * The API might be changed.229+ */230+export interface ToSSGAdaptorInterface<231+ E extends Env = Env,232+ S extends Schema = {},233+ BasePath extends string = '/'234+> {235+ (app: Hono<E, S, BasePath>, options?: ToSSGOptions): Promise<ToSSGResult>236+}237+238+/**239+ * @experimental240+ * `toSSG` is an experimental feature.241+ * The API might be changed.242+ */243+export const toSSG: ToSSGInterface = async (app, fs, options) => {244+ let result: ToSSGResult | undefined = undefined245+ try {246+ const outputDir = options?.dir ?? './static'247+ const maps = await fetchRoutesContent(248+ app,249+ options?.beforeRequestHook,250+ options?.afterResponseHook251+ )252+ const files = await saveContentToFiles(maps, fs, outputDir)253+ result = { success: true, files }254+ } catch (error) {255+ const errorObj = error instanceof Error ? error : new Error(String(error))256+ result = { success: false, files: [], error: errorObj }257+ }258+ await options?.afterGenerateHook?.(result)259+ return result260+}261+262+/**263+ * @experimental264+ * `disableSSG` is an experimental feature.265+ * The API might be changed.266+ */267+268+export const disableSSG = (): MiddlewareHandler =>269+ async function disableSSG(c, next) {270+ await next()271+ c.header(X_HONO_DISABLE_SSG_HEADER_KEY, 'true')272+ }273+274+/**275+ * @experimental276+ * `onlySSG` is an experimental feature.277+ * The API might be changed.278+ */279+export const onlySSG = (): MiddlewareHandler =>280+ async function onlySSG(c, next) {281+ const headerValue = c.req.raw.headers.get(X_HONO_SSG_HEADER_KEY)282+ if (headerValue) {283+ await next()284+ }285+ return c.notFound()286+ }added:deno_dist/helper/ssg/utils.ts+47 added
1+/**2+ * Get dirname3+ * @param path File Path4+ * @returns Parent dir path5+ */6+export const dirname = (path: string) => {7+ const splitedPath = path.split(/[\/\\]/)8+ return splitedPath.slice(0, -1).join('/') // Windows supports slash path9+}10+11+const normalizePath = (path: string) => {12+ return path.replace(/(\\)/g, '/').replace(/\/$/g, '')13+}14+15+const handleDotDot = (resultPaths: string[]) => {16+ if (resultPaths.length === 0) {17+ resultPaths.push('..')18+ } else {19+ resultPaths.pop()20+ }21+}22+23+const handleNonDot = (path: string, resultPaths: string[]) => {24+ path = path.replace(/^\.(?!.)/, '')25+ if (path !== '') {26+ resultPaths.push(path)27+ }28+}29+30+const handleSegments = (paths: string[], resultPaths: string[]) => {31+ for (const path of paths) {32+ // Handle `..` or `../`33+ if (path === '..') {34+ handleDotDot(resultPaths)35+ } else {36+ // Handle `.` or `./`37+ handleNonDot(path, resultPaths)38+ }39+ }40+}41+42+export const joinPaths = (...paths: string[]) => {43+ paths = paths.map(normalizePath)44+ const resultPaths: string[] = []45+ handleSegments(paths.join('/').split('/'), resultPaths)46+ return (paths[0][0] === '/' ? '/' : '') + resultPaths.join('/')47+}added:deno_dist/jsx/dom/components.ts+39 added
1+import type { FC, PropsWithChildren, Child } from '../index.ts'2+import type { FallbackRender, ErrorHandler } from '../components.ts'3+import { DOM_ERROR_HANDLER } from '../constants.ts'4+import { Fragment } from './jsx-runtime.ts'5+6+/* eslint-disable @typescript-eslint/no-explicit-any */7+export const ErrorBoundary: FC<8+ PropsWithChildren<{9+ fallback?: Child10+ fallbackRender?: FallbackRender11+ onError?: ErrorHandler12+ }>13+> = (({ children, fallback, fallbackRender, onError }: any) => {14+ const res = Fragment({ children })15+ ;(res as any)[DOM_ERROR_HANDLER] = (err: any) => {16+ if (err instanceof Promise) {17+ throw err18+ }19+ onError?.(err)20+ return fallbackRender?.(err) || fallback21+ }22+ return res23+}) as any24+25+export const Suspense: FC<PropsWithChildren<{ fallback: any }>> = (({26+ children,27+ fallback,28+}: any) => {29+ const res = Fragment({ children })30+ ;(res as any)[DOM_ERROR_HANDLER] = (err: any, retry: () => void) => {31+ if (!(err instanceof Promise)) {32+ throw err33+ }34+ err.finally(retry)35+ return fallback36+ }37+ return res38+}) as any39+/* eslint-enable @typescript-eslint/no-explicit-any */added:deno_dist/jsx/dom/context.ts+42 added
1+import type { Child } from '../base.ts'2+import { DOM_ERROR_HANDLER } from '../constants.ts'3+import type { Context } from '../context.ts'4+import { globalContexts } from '../context.ts'5+import { Fragment } from './jsx-runtime.ts'6+7+export const createContextProviderFunction =8+ <T>(values: T[]) =>9+ ({ value, children }: { value: T; children: Child[] }) => {10+ const res = Fragment({11+ children: [12+ {13+ tag: () => {14+ values.push(value)15+ },16+ },17+ ...(children as Child[]),18+ {19+ tag: () => {20+ values.pop()21+ },22+ },23+ ],24+ })25+ // eslint-disable-next-line @typescript-eslint/no-explicit-any26+ ;(res as any)[DOM_ERROR_HANDLER] = (err: unknown) => {27+ values.pop()28+ throw err29+ }30+ return res31+ }32+33+export const createContext = <T>(defaultValue: T): Context<T> => {34+ const values = [defaultValue]35+ const context = {36+ values,37+ // eslint-disable-next-line @typescript-eslint/no-explicit-any38+ Provider: createContextProviderFunction(values) as any,39+ }40+ globalContexts.push(context)41+ return context42+}added:deno_dist/jsx/dom/css.ts+206 added
1+import type { FC, PropsWithChildren } from '../index.ts'2+import type { CssClassName, CssVariableType } from '../../helper/css/common.ts'3+import {4+ SELECTOR,5+ CLASS_NAME,6+ STYLE_STRING,7+ SELECTORS,8+ PSEUDO_GLOBAL_SELECTOR,9+ DEFAULT_STYLE_ID,10+ cssCommon,11+ cxCommon,12+ keyframesCommon,13+ viewTransitionCommon,14+} from '../../helper/css/common.ts'15+export { rawCssString } from '../../helper/css/common.ts'16+17+const splitRule = (rule: string): string[] => {18+ const result: string[] = []19+ let startPos = 020+ let depth = 021+ for (let i = 0, len = rule.length; i < len; i++) {22+ const char = rule[i]23+24+ // consume quote25+ // eslint-disable-next-line quotes26+ if (char === "'" || char === '"') {27+ const quote = char28+ i++29+ for (; i < len; i++) {30+ if (rule[i] === '\\') {31+ i++32+ continue33+ }34+ if (rule[i] === quote) {35+ break36+ }37+ }38+ continue39+ }40+41+ // comments are removed from the rule in advance42+43+ if (char === '{') {44+ depth++45+ continue46+ }47+ if (char === '}') {48+ depth--49+ if (depth === 0) {50+ result.push(rule.slice(startPos, i + 1))51+ startPos = i + 152+ }53+ continue54+ }55+ }56+ return result57+}58+59+export const createCssJsxDomObjects = ({ id }: { id: Readonly<string> }) => {60+ let styleSheet: CSSStyleSheet | null | undefined = undefined61+ const findStyleSheet = (): [CSSStyleSheet, Set<string>] | [] => {62+ if (!styleSheet) {63+ styleSheet = document.querySelector<HTMLStyleElement>(`style#${id}`)64+ ?.sheet as CSSStyleSheet | null65+ if (styleSheet) {66+ // eslint-disable-next-line @typescript-eslint/no-explicit-any67+ ;(styleSheet as any).addedStyles = new Set<string>()68+ }69+ }70+ // eslint-disable-next-line @typescript-eslint/no-explicit-any71+ return styleSheet ? [styleSheet, (styleSheet as any).addedStyles] : []72+ }73+74+ const insertRule = (className: string, styleString: string) => {75+ const [sheet, addedStyles] = findStyleSheet()76+ if (!sheet || !addedStyles) {77+ Promise.resolve().then(() => {78+ if (!findStyleSheet()[0]) {79+ throw new Error('style sheet not found')80+ }81+ insertRule(className, styleString)82+ })83+ return84+ }85+86+ if (!addedStyles.has(className)) {87+ addedStyles.add(className)88+ ;(className.startsWith(PSEUDO_GLOBAL_SELECTOR)89+ ? splitRule(styleString)90+ : [`${className[0] === '@' ? '' : '.'}${className}{${styleString}}`]91+ ).forEach((rule) => {92+ sheet.insertRule(rule, sheet.cssRules.length)93+ })94+ }95+ }96+97+ const cssObject = {98+ toString(this: CssClassName): string {99+ const selector = this[SELECTOR]100+ insertRule(selector, this[STYLE_STRING])101+ this[SELECTORS].forEach(({ [CLASS_NAME]: className, [STYLE_STRING]: styleString }) => {102+ insertRule(className, styleString)103+ })104+105+ return this[CLASS_NAME]106+ },107+ }108+109+ // eslint-disable-next-line @typescript-eslint/no-explicit-any110+ const Style: FC<PropsWithChildren<void>> = ({ children }) =>111+ ({112+ tag: 'style',113+ children: (Array.isArray(children) ? children : [children]).map(114+ (c) => (c as unknown as CssClassName)[STYLE_STRING]115+ ),116+ props: { id },117+ // eslint-disable-next-line @typescript-eslint/no-explicit-any118+ } as any)119+120+ return [cssObject, Style] as const121+}122+123+/**124+ * @experimental125+ * `createCssContext` is an experimental feature.126+ * The API might be changed.127+ */128+export const createCssContext = ({ id }: { id: Readonly<string> }) => {129+ const [cssObject, Style] = createCssJsxDomObjects({ id })130+131+ const newCssClassNameObject = (cssClassName: CssClassName): string => {132+ cssClassName.toString = cssObject.toString133+ return cssClassName as unknown as string134+ }135+136+ const css = (strings: TemplateStringsArray, ...values: CssVariableType[]): string => {137+ return newCssClassNameObject(cssCommon(strings, values))138+ }139+140+ const cx = (...args: (string | boolean | null | undefined)[]): string => {141+ // eslint-disable-next-line @typescript-eslint/no-explicit-any142+ args = cxCommon(args as any) as any143+ // eslint-disable-next-line @typescript-eslint/no-explicit-any144+ return css(Array(args.length).fill('') as any, ...args)145+ }146+147+ const keyframes = keyframesCommon148+149+ type ViewTransitionType = {150+ (strings: TemplateStringsArray, ...values: CssVariableType[]): string151+ (content: string): string152+ (): string153+ }154+ const viewTransition: ViewTransitionType = ((155+ strings: TemplateStringsArray | string | undefined,156+ ...values: CssVariableType[]157+ ) => {158+ // eslint-disable-next-line @typescript-eslint/no-explicit-any159+ return newCssClassNameObject(viewTransitionCommon(strings as any, values))160+ }) as ViewTransitionType161+162+ return {163+ css,164+ cx,165+ keyframes,166+ viewTransition,167+ Style,168+ }169+}170+171+const defaultContext = createCssContext({ id: DEFAULT_STYLE_ID })172+173+/**174+ * @experimental175+ * `css` is an experimental feature.176+ * The API might be changed.177+ */178+export const css = defaultContext.css179+180+/**181+ * @experimental182+ * `cx` is an experimental feature.183+ * The API might be changed.184+ */185+export const cx = defaultContext.cx186+187+/**188+ * @experimental189+ * `keyframes` is an experimental feature.190+ * The API might be changed.191+ */192+export const keyframes = defaultContext.keyframes193+194+/**195+ * @experimental196+ * `viewTransition` is an experimental feature.197+ * The API might be changed.198+ */199+export const viewTransition = defaultContext.viewTransition200+201+/**202+ * @experimental203+ * `Style` is an experimental feature.204+ * The API might be changed.205+ */206+export const Style = defaultContext.Styleadded:deno_dist/jsx/dom/index.ts+38 added
1+export {2+ useState,3+ useEffect,4+ useRef,5+ useCallback,6+ use,7+ startTransition,8+ useTransition,9+ useDeferredValue,10+ startViewTransition,11+ useViewTransition,12+ useMemo,13+ useLayoutEffect,14+} from '../hooks/index.ts'15+export { render } from './render.ts'16+export { Suspense, ErrorBoundary } from './components.ts'17+export { useContext } from '../context.ts'18+export type { Context } from '../context.ts'19+export { createContext } from './context.ts'20+export { memo, isValidElement } from '../base.ts'21+22+import type { Props, Child, JSXNode } from '../base.ts'23+import { jsx } from './jsx-runtime.ts'24+export const cloneElement = <T extends JSXNode | JSX.Element>(25+ element: T,26+ props: Props,27+ ...children: Child[]28+): T => {29+ return jsx(30+ (element as JSXNode).tag,31+ {32+ ...(element as JSXNode).props,33+ ...props,34+ children: children.length ? children : (element as JSXNode).children,35+ },36+ (element as JSXNode).key37+ ) as T38+}added:deno_dist/jsx/dom/jsx-dev-runtime.ts+23 added
1+import type { Props } from '../base.ts'2+import { normalizeIntrinsicElementProps } from '../utils.ts'3+4+export const jsxDEV = (tag: string | Function, props: Props, key?: string) => {5+ if (typeof tag === 'string') {6+ normalizeIntrinsicElementProps(props)7+ }8+ let children9+ if (props && 'children' in props) {10+ children = props.children11+ delete props['children']12+ } else {13+ children = []14+ }15+ return {16+ tag,17+ props,18+ key,19+ children: Array.isArray(children) ? children : [children],20+ }21+}22+23+export const Fragment = (props: Record<string, unknown>) => jsxDEV('', props, undefined)added:deno_dist/jsx/dom/jsx-runtime.ts+2 added
1+export { jsxDEV as jsx, Fragment } from './jsx-dev-runtime.ts'2+export { jsxDEV as jsxs } from './jsx-dev-runtime.ts'added:deno_dist/jsx/dom/render.ts+450 added
1+import type { JSXNode } from '../base.ts'2+import type { FC, Child, Props } from '../base.ts'3+import { DOM_RENDERER, DOM_ERROR_HANDLER, DOM_STASH } from '../constants.ts'4+import type { Context as JSXContext } from '../context.ts'5+import { globalContexts as globalJSXContexts } from '../context.ts'6+import type { EffectData } from '../hooks/index.ts'7+import { STASH_EFFECT } from '../hooks/index.ts'8+9+const eventAliasMap: Record<string, string> = {10+ Change: 'Input',11+ DoubleClick: 'DblClick',12+}13+14+// eslint-disable-next-line @typescript-eslint/no-explicit-any15+export type HasRenderToDom = FC<any> & { [DOM_RENDERER]: FC<any> }16+// eslint-disable-next-line @typescript-eslint/no-explicit-any17+export type ErrorHandler = (error: any, retry: () => void) => Child | undefined18+19+type Container = HTMLElement | DocumentFragment20+type LocalJSXContexts = [JSXContext<unknown>, unknown][] | undefined21+22+export type NodeObject = {23+ pP: Props | undefined // previous props24+ nN: Node | undefined // next node25+ vC: Node[] // virtual dom children26+ vR: Node[] // virtual dom children to remove27+ s?: Node[] // shadow virtual dom children28+ c: Container | undefined // container29+ e: HTMLElement | Text | undefined // rendered element30+ [DOM_STASH]:31+ | [32+ number, // current hook index33+ // eslint-disable-next-line @typescript-eslint/no-explicit-any34+ any[][], // stash for hooks35+ LocalJSXContexts // context36+ ]37+ | [38+ number,39+ // eslint-disable-next-line @typescript-eslint/no-explicit-any40+ any[][]41+ ]42+} & JSXNode43+type NodeString = [string] & {44+ e?: Text45+ // like a NodeObject46+ vC: undefined47+ nN: undefined48+ // from JSXNode49+ key: undefined50+ tag: undefined51+}52+export type Node = NodeString | NodeObject53+54+export type PendingType =55+ | 0 // no pending56+ | 1 // global57+ | 2 // hook58+export type UpdateHook = (59+ context: Context,60+ node: Node,61+ cb: (context: Context) => void62+) => Promise<void>63+export type Context =64+ | [65+ PendingType, // PendingType66+ boolean, // got an error67+ UpdateHook, // update hook68+ boolean // is in view transition69+ ]70+ | [PendingType, boolean, UpdateHook]71+ | [PendingType, boolean]72+ | [PendingType]73+ | []74+75+export const buildDataStack: [Context, Node][] = []76+77+const isNodeString = (node: Node): node is NodeString => Array.isArray(node)78+79+const getEventSpec = (key: string): [string, boolean] | undefined => {80+ const match = key.match(/^on([A-Z][a-zA-Z]+?)((?<!Pointer)Capture)?$/)81+ if (match) {82+ const [, eventName, capture] = match83+ return [(eventAliasMap[eventName] || eventName).toLowerCase(), !!capture]84+ }85+ return undefined86+}87+88+const applyProps = (container: HTMLElement, attributes: Props, oldAttributes?: Props) => {89+ attributes ||= {}90+ for (const [key, value] of Object.entries(attributes)) {91+ if (!oldAttributes || oldAttributes[key] !== value) {92+ const eventSpec = getEventSpec(key)93+ if (eventSpec) {94+ if (typeof value !== 'function') {95+ throw new Error(`Event handler for "${key}" is not a function`)96+ }97+98+ if (oldAttributes) {99+ container.removeEventListener(eventSpec[0], oldAttributes[key], eventSpec[1])100+ }101+ container.addEventListener(eventSpec[0], value, eventSpec[1])102+ } else if (key === 'dangerouslySetInnerHTML' && value) {103+ container.innerHTML = value.__html104+ } else if (key === 'ref') {105+ if (typeof value === 'function') {106+ value(container)107+ } else if ('current' in value) {108+ value.current = container109+ }110+ } else if (key === 'style') {111+ if (typeof value === 'string') {112+ container.style.cssText = value113+ } else {114+ container.style.cssText = ''115+ Object.assign(container.style, value)116+ }117+ } else {118+ if (value === null || value === undefined || value === false) {119+ container.removeAttribute(key)120+ } else if (value === true) {121+ container.setAttribute(key, '')122+ } else if (typeof value === 'string' || typeof value === 'number') {123+ container.setAttribute(key, value as string)124+ } else {125+ container.setAttribute(key, value.toString())126+ }127+ }128+ }129+ }130+ if (oldAttributes) {131+ for (const [key, value] of Object.entries(oldAttributes)) {132+ if (!(key in attributes)) {133+ const eventSpec = getEventSpec(key)134+ if (eventSpec) {135+ container.removeEventListener(eventSpec[0], value, eventSpec[1])136+ } else if (key === 'ref') {137+ if (typeof value === 'function') {138+ value(null)139+ } else {140+ value.current = null141+ }142+ } else {143+ container.removeAttribute(key)144+ }145+ }146+ }147+ }148+}149+150+const invokeTag = (context: Context, node: NodeObject): Child[] => {151+ if (node.s) {152+ const res = node.s153+ node.s = undefined154+ return res155+ }156+157+ node[DOM_STASH][0] = 0158+ buildDataStack.push([context, node])159+ const func = (node.tag as HasRenderToDom)[DOM_RENDERER] || node.tag160+ try {161+ return [162+ func.call(null, {163+ ...node.props,164+ children: node.children,165+ }),166+ ]167+ } finally {168+ buildDataStack.pop()169+ }170+}171+172+const getNextChildren = (173+ node: NodeObject,174+ container: Container,175+ nextChildren: Node[],176+ childrenToRemove: Node[],177+ callbacks: EffectData[]178+) => {179+ childrenToRemove.push(...node.vR)180+ if (typeof node.tag === 'function') {181+ node[DOM_STASH][1][STASH_EFFECT]?.forEach((data: EffectData) => callbacks.push(data))182+ }183+ node.vC.forEach((child) => {184+ if (isNodeString(child)) {185+ nextChildren.push(child)186+ } else {187+ if (typeof child.tag === 'function' || child.tag === '') {188+ child.c = container189+ getNextChildren(child, container, nextChildren, childrenToRemove, callbacks)190+ } else {191+ nextChildren.push(child)192+ childrenToRemove.push(...child.vR)193+ }194+ }195+ })196+}197+198+const findInsertBefore = (node: Node | undefined): ChildNode | null => {199+ if (!node) {200+ return null201+ } else if (node.e) {202+ return node.e203+ }204+205+ if (node.vC) {206+ for (let i = 0, len = node.vC.length; i < len; i++) {207+ const e = findInsertBefore(node.vC[i])208+ if (e) {209+ return e210+ }211+ }212+ }213+214+ return findInsertBefore(node.nN)215+}216+217+const removeNode = (node: Node) => {218+ if (!isNodeString(node)) {219+ node[DOM_STASH]?.[1][STASH_EFFECT]?.forEach((data: EffectData) => data[2]?.())220+ node.vC?.forEach(removeNode)221+ }222+ node.e?.remove()223+ node.tag = undefined224+}225+226+const apply = (node: NodeObject, container: Container) => {227+ if (node.tag === undefined) {228+ return229+ }230+231+ node.c = container232+ applyNodeObject(node, container)233+}234+235+const applyNode = (node: Node, container: Container) => {236+ if (isNodeString(node)) {237+ container.textContent = node[0]238+ } else {239+ applyNodeObject(node, container)240+ }241+}242+243+const applyNodeObject = (node: NodeObject, container: Container) => {244+ const next: Node[] = []245+ const remove: Node[] = []246+ const callbacks: EffectData[] = []247+ getNextChildren(node, container, next, remove, callbacks)248+ let offset = container.childNodes.length249+ const insertBefore = findInsertBefore(node.nN) || next.find((n) => n.e)?.e250+ if (insertBefore) {251+ for (let i = 0; i < offset; i++) {252+ if (container.childNodes[i] === insertBefore) {253+ offset = i254+ break255+ }256+ }257+ }258+259+ for (let i = 0, len = next.length; i < len; i++, offset++) {260+ const child = next[i]261+262+ let el: HTMLElement | Text263+ if (isNodeString(child)) {264+ if (child.e) {265+ child.e.textContent = child[0]266+ }267+ el = child.e ||= document.createTextNode(child[0])268+ } else {269+ el = child.e ||= document.createElement(child.tag as string)270+ applyProps(el as HTMLElement, child.props, child.pP)271+ applyNode(child, el as HTMLElement)272+ }273+ if (container.childNodes[offset] !== el) {274+ container.insertBefore(el, container.childNodes[offset] || null)275+ }276+ }277+ remove.forEach(removeNode)278+ callbacks.forEach(([, cb]) => cb?.())279+ requestAnimationFrame(() => {280+ callbacks.forEach(([, , , cb]) => cb?.())281+ })282+}283+284+export const build = (285+ context: Context,286+ node: NodeObject,287+ topLevelErrorHandlerNode: NodeObject | undefined,288+ children?: Child[]289+): void => {290+ if (node.tag === undefined) {291+ return292+ }293+294+ let errorHandler: ErrorHandler | undefined295+ children ||= typeof node.tag == 'function' ? invokeTag(context, node) : node.children296+ if ((children[0] as JSXNode)?.tag === '') {297+ // eslint-disable-next-line @typescript-eslint/no-explicit-any298+ errorHandler = (children[0] as any)[DOM_ERROR_HANDLER] as ErrorHandler299+ topLevelErrorHandlerNode ||= node300+ }301+ const oldVChildren: Node[] = node.vC ? [...node.vC] : []302+ const vChildren: Node[] = []303+ const vChildrenToRemove: Node[] = []304+ let prevNode: Node | undefined305+ try {306+ children.flat().forEach((c: Child) => {307+ let child = buildNode(c)308+ if (child) {309+ if (prevNode) {310+ prevNode.nN = child311+ }312+ prevNode = child313+314+ if (typeof child.tag === 'function' && globalJSXContexts.length > 0) {315+ child[DOM_STASH][2] = globalJSXContexts.map((c) => [c, c.values.at(-1)])316+ }317+318+ let oldChild: Node | undefined319+ const i = oldVChildren.findIndex((c) => c.key === (child as Node).key)320+ if (i !== -1) {321+ oldChild = oldVChildren[i]322+ oldVChildren.splice(i, 1)323+ }324+325+ if (oldChild) {326+ if (isNodeString(child)) {327+ if (!isNodeString(oldChild)) {328+ vChildrenToRemove.push(oldChild)329+ } else {330+ oldChild[0] = child[0] // update text content331+ child = oldChild332+ }333+ } else if (oldChild.tag !== child.tag) {334+ vChildrenToRemove.push(oldChild)335+ } else {336+ oldChild.pP = oldChild.props337+ oldChild.props = child.props338+ oldChild.children = child.children339+ child = oldChild340+ }341+ }342+343+ if (!isNodeString(child)) {344+ build(context, child, topLevelErrorHandlerNode)345+ }346+ vChildren.push(child)347+ }348+ })349+ node.vC = vChildren350+ vChildrenToRemove.push(...oldVChildren)351+ node.vR = vChildrenToRemove352+ } catch (e) {353+ if (errorHandler) {354+ const fallback = errorHandler(e, () =>355+ update([0, false, context[2] as UpdateHook], topLevelErrorHandlerNode as NodeObject)356+ )357+ if (fallback) {358+ if (context[0] === 1) {359+ context[1] = true360+ } else {361+ build(context, node, topLevelErrorHandlerNode, [fallback])362+ }363+ return364+ }365+ }366+ throw e367+ }368+}369+370+const buildNode = (node: Child): Node | undefined => {371+ if (node === undefined || node === null || typeof node === 'boolean') {372+ return undefined373+ } else if (typeof node === 'string' || typeof node === 'number') {374+ return [node.toString()] as NodeString375+ } else {376+ if (typeof (node as JSXNode).tag === 'function') {377+ ;(node as NodeObject)[DOM_STASH] = [0, []]378+ }379+ return node as NodeObject380+ }381+}382+383+const replaceContainer = (node: NodeObject, from: DocumentFragment, to: Container) => {384+ if (node.c === from) {385+ node.c = to386+ node.vC.forEach((child) => replaceContainer(child as NodeObject, from, to))387+ }388+}389+390+const updateSync = (context: Context, node: NodeObject) => {391+ node[DOM_STASH][2]?.forEach(([c, v]) => {392+ c.values.push(v)393+ })394+ build(context, node, undefined)395+ node[DOM_STASH][2]?.forEach(([c]) => {396+ c.values.pop()397+ })398+ if (context[0] !== 1 || !context[1]) {399+ apply(node, node.c as Container)400+ }401+}402+403+type UpdateMapResolve = (node: NodeObject | undefined) => void404+const updateMap = new WeakMap<NodeObject, [UpdateMapResolve, Function]>()405+export const update = async (406+ context: Context,407+ node: NodeObject408+): Promise<NodeObject | undefined> => {409+ const existing = updateMap.get(node)410+ if (existing) {411+ // execute only the last update() call, so the previous update will be canceled.412+ existing[0](undefined)413+ }414+415+ let resolve: UpdateMapResolve | undefined416+ const promise = new Promise<NodeObject | undefined>((r) => (resolve = r))417+ updateMap.set(node, [418+ resolve as UpdateMapResolve,419+ () => {420+ if (context[2]) {421+ context[2](context, node, (context) => {422+ updateSync(context, node)423+ }).then(() => (resolve as UpdateMapResolve)(node))424+ } else {425+ updateSync(context, node)426+ ;(resolve as UpdateMapResolve)(node)427+ }428+ },429+ ])430+431+ await Promise.resolve()432+433+ const latest = updateMap.get(node)434+ if (latest) {435+ updateMap.delete(node)436+ latest[1]()437+ }438+439+ return promise440+}441+442+export const render = (jsxNode: unknown, container: Container) => {443+ const node = buildNode({ tag: '', children: [jsxNode] } as JSXNode) as NodeObject444+ build([], node, undefined)445+446+ const fragment = document.createDocumentFragment()447+ apply(node, fragment)448+ replaceContainer(node, fragment, container)449+ container.replaceChildren(fragment)450+}added:deno_dist/jsx/hooks/index.ts+324 added
1+import { DOM_STASH } from '../constants.ts'2+import { buildDataStack, update, build } from '../dom/render.ts'3+import type { Node, NodeObject, Context, PendingType, UpdateHook } from '../dom/render.ts'4+5+type UpdateStateFunction<T> = (newState: T | ((currentState: T) => T)) => void6+7+const STASH_SATE = 08+export const STASH_EFFECT = 19+const STASH_CALLBACK = 210+const STASH_USE = 311+const STASH_MEMO = 412+13+export type EffectData = [14+ readonly unknown[] | undefined, // deps15+ (() => void | (() => void)) | undefined, // layout effect16+ (() => void) | undefined, // cleanup17+ (() => void) | undefined // effect18+]19+20+const resolvedPromiseValueMap = new WeakMap<Promise<unknown>, unknown>()21+22+const isDepsChanged = (23+ prevDeps: readonly unknown[] | undefined,24+ deps: readonly unknown[] | undefined25+): boolean =>26+ !prevDeps ||27+ !deps ||28+ prevDeps.length !== deps.length ||29+ deps.some((dep, i) => dep !== prevDeps[i])30+31+let viewTransitionState:32+ | [33+ boolean, // isUpdating34+ boolean // useViewTransition() is called35+ ]36+ | undefined = undefined37+38+const documentStartViewTransition: (cb: () => void) => { finished: Promise<void> } = (cb) => {39+ // eslint-disable-next-line @typescript-eslint/no-explicit-any40+ if ((document as any)?.startViewTransition) {41+ // eslint-disable-next-line @typescript-eslint/no-explicit-any42+ return (document as any).startViewTransition(cb)43+ } else {44+ cb()45+ return { finished: Promise.resolve() }46+ }47+}48+49+let updateHook: UpdateHook | undefined = undefined50+const viewTransitionHook = (51+ context: Context,52+ node: Node,53+ cb: (context: Context) => void54+): Promise<void> => {55+ const state: [boolean, boolean] = [true, false]56+ let lastVC = node.vC57+ return documentStartViewTransition(() => {58+ if (lastVC === node.vC) {59+ viewTransitionState = state60+ cb(context)61+ viewTransitionState = undefined62+ lastVC = node.vC63+ }64+ }).finished.then(() => {65+ if (state[1] && lastVC === node.vC) {66+ state[0] = false67+ viewTransitionState = state68+ cb(context)69+ viewTransitionState = undefined70+ }71+ })72+}73+74+export const startViewTransition = (callback: () => void): void => {75+ updateHook = viewTransitionHook76+77+ try {78+ callback()79+ } finally {80+ updateHook = undefined81+ }82+}83+84+export const useViewTransition = (): [boolean, (callback: () => void) => void] => {85+ const buildData = buildDataStack.at(-1) as [Context, NodeObject]86+ if (!buildData) {87+ return [false, () => {}]88+ }89+90+ if (viewTransitionState) {91+ viewTransitionState[1] = true92+ }93+ return [!!viewTransitionState?.[0], startViewTransition]94+}95+96+const pendingStack: PendingType[] = []97+const runCallback = (type: PendingType, callback: Function): void => {98+ pendingStack.push(type)99+ try {100+ callback()101+ } finally {102+ pendingStack.pop()103+ }104+}105+106+export const startTransition = (callback: () => void): void => {107+ runCallback(1, callback)108+}109+const startTransitionHook = (callback: () => void): void => {110+ runCallback(2, callback)111+}112+113+export const useTransition = (): [boolean, (callback: () => void) => void] => {114+ const buildData = buildDataStack.at(-1) as [Context, NodeObject]115+ if (!buildData) {116+ return [false, () => {}]117+ }118+ const [context] = buildData119+ return [context[0] === 2, startTransitionHook]120+}121+122+export const useDeferredValue = <T>(value: T): T => {123+ const buildData = buildDataStack.at(-1) as [Context, NodeObject]124+ if (buildData) {125+ buildData[0][0] = 1126+ }127+ return value128+}129+130+const setShadow = (node: Node) => {131+ if (node.vC) {132+ node.s = node.vC133+ // eslint-disable-next-line @typescript-eslint/no-explicit-any134+ ;(node as any).vC = undefined135+ }136+ // eslint-disable-next-line @typescript-eslint/no-explicit-any137+ ;(node as any).s?.forEach(setShadow)138+}139+140+export const useState = <T>(initialState: T | (() => T)): [T, UpdateStateFunction<T>] => {141+ const resolveInitialState = () =>142+ typeof initialState === 'function' ? (initialState as () => T)() : initialState143+144+ const buildData = buildDataStack.at(-1) as [unknown, NodeObject]145+ if (!buildData) {146+ return [resolveInitialState(), () => {}]147+ }148+ const [, node] = buildData149+150+ const stateArray = (node[DOM_STASH][1][STASH_SATE] ||= [])151+ const hookIndex = node[DOM_STASH][0]++152+153+ return (stateArray[hookIndex] ||= [154+ resolveInitialState(),155+ (newState: T | ((currentState: T) => T)) => {156+ const localUpdateHook = updateHook157+ const stateData = stateArray[hookIndex]158+ if (typeof newState === 'function') {159+ newState = (newState as (currentState: T) => T)(stateData[0])160+ }161+162+ if (newState !== stateData[0]) {163+ stateData[0] = newState164+ if (pendingStack.length) {165+ const pendingType = pendingStack.at(-1) as PendingType166+ update([pendingType, false, localUpdateHook as UpdateHook], node).then((node) => {167+ if (!node || pendingType !== 2) {168+ return169+ }170+171+ const lastVC = node.vC172+173+ const addUpdateTask = () => {174+ setTimeout(() => {175+ // `node` is not rerendered after current transition176+ if (lastVC !== node.vC) {177+ return178+ }179+180+ const shadowNode = Object.assign({}, node) as NodeObject181+182+ // eslint-disable-next-line @typescript-eslint/no-explicit-any183+ ;(shadowNode as any).vC = undefined // delete the prev build data and build with clean state184+ build([], shadowNode, undefined)185+ setShadow(shadowNode) // save the `shadowNode.vC` of the virtual DOM of the build result as a result of shadow virtual DOM `shadowNode.s`186+187+ node.s = shadowNode.s188+ update([0, false, localUpdateHook as UpdateHook], node)189+ })190+ }191+192+ if (localUpdateHook) {193+ // wait for next animation frame, then invoke `update()`194+ requestAnimationFrame(addUpdateTask)195+ } else {196+ addUpdateTask()197+ }198+ })199+ } else {200+ update([0, false, localUpdateHook as UpdateHook], node)201+ }202+ }203+ },204+ ])205+}206+207+const useEffectCommon = (208+ index: number,209+ effect: () => void | (() => void),210+ deps?: readonly unknown[]211+): void => {212+ const buildData = buildDataStack.at(-1) as [unknown, NodeObject]213+ if (!buildData) {214+ return215+ }216+ const [, node] = buildData217+218+ const effectDepsArray = (node[DOM_STASH][1][STASH_EFFECT] ||= [])219+ const hookIndex = node[DOM_STASH][0]++220+221+ const [prevDeps, , prevCleanup] = (effectDepsArray[hookIndex] ||= [])222+ if (isDepsChanged(prevDeps, deps)) {223+ if (prevCleanup) {224+ prevCleanup()225+ }226+ const runner = () => {227+ data[index] = undefined // clear this effect in order to avoid calling effect twice228+ data[2] = effect() as (() => void) | undefined229+ }230+ const data: EffectData = [deps, undefined, undefined, undefined]231+ data[index] = runner232+ effectDepsArray[hookIndex] = data233+ }234+}235+export const useEffect = (effect: () => void | (() => void), deps?: readonly unknown[]): void =>236+ useEffectCommon(3, effect, deps)237+export const useLayoutEffect = (238+ effect: () => void | (() => void),239+ deps?: readonly unknown[]240+): void => useEffectCommon(1, effect, deps)241+242+export const useCallback = <T extends (...args: unknown[]) => unknown>(243+ callback: T,244+ deps: readonly unknown[]245+): T => {246+ const buildData = buildDataStack.at(-1) as [unknown, NodeObject]247+ if (!buildData) {248+ return callback249+ }250+ const [, node] = buildData251+252+ const callbackArray = (node[DOM_STASH][1][STASH_CALLBACK] ||= [])253+ const hookIndex = node[DOM_STASH][0]++254+255+ const prevDeps = callbackArray[hookIndex]256+ if (isDepsChanged(prevDeps?.[1], deps)) {257+ callbackArray[hookIndex] = [callback, deps]258+ } else {259+ callback = callbackArray[hookIndex][0] as T260+ }261+ return callback262+}263+264+export type RefObject<T> = { current: T | null }265+export const useRef = <T>(initialValue: T | null): RefObject<T> => {266+ return { current: initialValue }267+}268+269+export const use = <T>(promise: Promise<T>): T => {270+ const cachedRes = resolvedPromiseValueMap.get(promise) as [T] | [undefined, unknown] | undefined271+ if (cachedRes) {272+ if (cachedRes.length === 2) {273+ throw cachedRes[1]274+ }275+ return cachedRes[0] as T276+ }277+ promise278+ .then((res) => resolvedPromiseValueMap.set(promise, [res]))279+ .catch((e) => resolvedPromiseValueMap.set(promise, [undefined, e]))280+281+ const buildData = buildDataStack.at(-1) as [unknown, NodeObject]282+ if (!buildData) {283+ throw promise284+ }285+ const [, node] = buildData286+287+ const promiseArray = (node[DOM_STASH][1][STASH_USE] ||= [])288+ const hookIndex = node[DOM_STASH][0]++289+290+ promise291+ .then((res) => {292+ promiseArray[hookIndex] = [res]293+ })294+ .catch((e) => {295+ promiseArray[hookIndex] = [undefined, e]296+ })297+298+ const res = promiseArray[hookIndex]299+ if (res) {300+ if (res.length === 2) {301+ throw res[1]302+ }303+ return res[0] as T304+ }305+306+ throw promise307+}308+309+export const useMemo = <T>(factory: () => T, deps: readonly unknown[]): T => {310+ const buildData = buildDataStack.at(-1) as [unknown, NodeObject]311+ if (!buildData) {312+ return factory()313+ }314+ const [, node] = buildData315+316+ const memoArray = (node[DOM_STASH][1][STASH_MEMO] ||= [])317+ const hookIndex = node[DOM_STASH][0]++318+319+ const prevDeps = memoArray[hookIndex]320+ if (isDepsChanged(prevDeps?.[1], deps)) {321+ memoArray[hookIndex] = [factory(), deps]322+ }323+ return memoArray[hookIndex][0] as T324+}added:deno_dist/jsx/base.ts+336 added
1+import { raw } from '../helper/html/index.ts'2+import { escapeToBuffer, stringBufferToString } from '../utils/html.ts'3+import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../utils/html.ts'4+import type { Context } from './context.ts'5+import { globalContexts } from './context.ts'6+import type { IntrinsicElements as IntrinsicElementsDefined } from './intrinsic-elements.ts'7+import { normalizeIntrinsicElementProps } from './utils.ts'8+9+// eslint-disable-next-line @typescript-eslint/no-explicit-any10+export type Props = Record<string, any>11+export type FC<T = Props> = (props: T) => HtmlEscapedString | Promise<HtmlEscapedString>12+13+declare global {14+ // eslint-disable-next-line @typescript-eslint/no-namespace15+ namespace JSX {16+ type Element = HtmlEscapedString | Promise<HtmlEscapedString>17+ interface ElementChildrenAttribute {18+ children: Child19+ }20+ interface IntrinsicElements extends IntrinsicElementsDefined {21+ [tagName: string]: Props22+ }23+ }24+}25+26+const emptyTags = [27+ 'area',28+ 'base',29+ 'br',30+ 'col',31+ 'embed',32+ 'hr',33+ 'img',34+ 'input',35+ 'keygen',36+ 'link',37+ 'meta',38+ 'param',39+ 'source',40+ 'track',41+ 'wbr',42+]43+const booleanAttributes = [44+ 'allowfullscreen',45+ 'async',46+ 'autofocus',47+ 'autoplay',48+ 'checked',49+ 'controls',50+ 'default',51+ 'defer',52+ 'disabled',53+ 'formnovalidate',54+ 'hidden',55+ 'inert',56+ 'ismap',57+ 'itemscope',58+ 'loop',59+ 'multiple',60+ 'muted',61+ 'nomodule',62+ 'novalidate',63+ 'open',64+ 'playsinline',65+ 'readonly',66+ 'required',67+ 'reversed',68+ 'selected',69+]70+71+const childrenToStringToBuffer = (children: Child[], buffer: StringBuffer): void => {72+ for (let i = 0, len = children.length; i < len; i++) {73+ const child = children[i]74+ if (typeof child === 'string') {75+ escapeToBuffer(child, buffer)76+ } else if (typeof child === 'boolean' || child === null || child === undefined) {77+ continue78+ } else if (child instanceof JSXNode) {79+ child.toStringToBuffer(buffer)80+ } else if (81+ typeof child === 'number' ||82+ (child as unknown as { isEscaped: boolean }).isEscaped83+ ) {84+ ;(buffer[0] as string) += child85+ } else if (child instanceof Promise) {86+ buffer.unshift('', child)87+ } else {88+ // `child` type is `Child[]`, so stringify recursively89+ childrenToStringToBuffer(child, buffer)90+ }91+ }92+}93+94+type LocalContexts = [Context<unknown>, unknown][]95+export type Child = string | Promise<string> | number | JSXNode | Child[]96+export class JSXNode implements HtmlEscaped {97+ tag: string | Function98+ props: Props99+ key?: string100+ children: Child[]101+ isEscaped: true = true as const102+ localContexts?: LocalContexts103+ constructor(tag: string | Function, props: Props, children: Child[]) {104+ this.tag = tag105+ this.props = props106+ this.children = children107+ }108+109+ toString(): string | Promise<string> {110+ const buffer: StringBuffer = ['']111+ this.localContexts?.forEach(([context, value]) => {112+ context.values.push(value)113+ })114+ try {115+ this.toStringToBuffer(buffer)116+ } finally {117+ this.localContexts?.forEach(([context]) => {118+ context.values.pop()119+ })120+ }121+ return buffer.length === 1 ? buffer[0] : stringBufferToString(buffer)122+ }123+124+ toStringToBuffer(buffer: StringBuffer): void {125+ const tag = this.tag as string126+ const props = this.props127+ let { children } = this128+129+ buffer[0] += `<${tag}`130+131+ const propsKeys = Object.keys(props || {})132+133+ for (let i = 0, len = propsKeys.length; i < len; i++) {134+ const key = propsKeys[i]135+ const v = props[key]136+ // object to style strings137+ if (key === 'style' && typeof v === 'object') {138+ const styles = Object.keys(v)139+ .map((k) => {140+ const property = k.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`)141+ return `${property}:${v[k]}`142+ })143+ .join(';')144+ buffer[0] += ` style="${styles}"`145+ } else if (typeof v === 'string') {146+ buffer[0] += ` ${key}="`147+ escapeToBuffer(v, buffer)148+ buffer[0] += '"'149+ } else if (v === null || v === undefined) {150+ // Do nothing151+ } else if (typeof v === 'number' || (v as HtmlEscaped).isEscaped) {152+ buffer[0] += ` ${key}="${v}"`153+ } else if (typeof v === 'boolean' && booleanAttributes.includes(key)) {154+ if (v) {155+ buffer[0] += ` ${key}=""`156+ }157+ } else if (key === 'dangerouslySetInnerHTML') {158+ if (children.length > 0) {159+ throw 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'160+ }161+162+ children = [raw(v.__html)]163+ } else if (v instanceof Promise) {164+ buffer[0] += ` ${key}="`165+ buffer.unshift('"', v)166+ } else if (typeof v === 'function') {167+ if (!key.startsWith('on')) {168+ throw `Invalid prop '${key}' of type 'function' supplied to '${tag}'.`169+ }170+ // maybe event handler for client components, just ignore in server components171+ } else {172+ buffer[0] += ` ${key}="`173+ escapeToBuffer(v.toString(), buffer)174+ buffer[0] += '"'175+ }176+ }177+178+ if (emptyTags.includes(tag as string)) {179+ buffer[0] += '/>'180+ return181+ }182+183+ buffer[0] += '>'184+185+ childrenToStringToBuffer(children, buffer)186+187+ buffer[0] += `</${tag}>`188+ }189+}190+191+class JSXFunctionNode extends JSXNode {192+ toStringToBuffer(buffer: StringBuffer): void {193+ const { children } = this194+195+ const res = (this.tag as Function).call(null, {196+ ...this.props,197+ children: children.length <= 1 ? children[0] : children,198+ })199+200+ if (res instanceof Promise) {201+ if (globalContexts.length === 0) {202+ buffer.unshift('', res)203+ } else {204+ // save current contexts for resuming205+ const currentContexts: LocalContexts = globalContexts.map((c) => [c, c.values.at(-1)])206+ buffer.unshift(207+ '',208+ res.then((childRes) => {209+ if (childRes instanceof JSXNode) {210+ childRes.localContexts = currentContexts211+ }212+ return childRes213+ })214+ )215+ }216+ } else if (res instanceof JSXNode) {217+ res.toStringToBuffer(buffer)218+ } else if (typeof res === 'number' || (res as HtmlEscaped).isEscaped) {219+ buffer[0] += res220+ } else {221+ escapeToBuffer(res, buffer)222+ }223+ }224+}225+226+export class JSXFragmentNode extends JSXNode {227+ toStringToBuffer(buffer: StringBuffer): void {228+ childrenToStringToBuffer(this.children, buffer)229+ }230+}231+232+export const jsx = (233+ tag: string | Function,234+ props: Props,235+ ...children: (string | HtmlEscapedString)[]236+): JSXNode => {237+ let key238+ if (props) {239+ key = props?.key240+ delete props['key']241+ }242+ const node = jsxFn(tag, props, children)243+ node.key = key244+ return node245+}246+247+export const jsxFn = (248+ tag: string | Function,249+ props: Props,250+ children: (string | HtmlEscapedString)[]251+): JSXNode => {252+ if (typeof tag === 'function') {253+ return new JSXFunctionNode(tag, props, children)254+ } else {255+ normalizeIntrinsicElementProps(props)256+ return new JSXNode(tag, props, children)257+ }258+}259+260+const shallowEqual = (a: Props, b: Props): boolean => {261+ if (a === b) {262+ return true263+ }264+265+ const aKeys = Object.keys(a).sort()266+ const bKeys = Object.keys(b).sort()267+ if (aKeys.length !== bKeys.length) {268+ return false269+ }270+271+ for (let i = 0, len = aKeys.length; i < len; i++) {272+ if (273+ aKeys[i] === 'children' &&274+ bKeys[i] === 'children' &&275+ !a.children?.length &&276+ !b.children?.length277+ ) {278+ continue279+ } else if (a[aKeys[i]] !== b[aKeys[i]]) {280+ return false281+ }282+ }283+284+ return true285+}286+287+export const memo = <T>(288+ component: FC<T>,289+ propsAreEqual: (prevProps: Readonly<T>, nextProps: Readonly<T>) => boolean = shallowEqual290+): FC<T> => {291+ let computed: HtmlEscapedString | Promise<HtmlEscapedString> | undefined = undefined292+ let prevProps: T | undefined = undefined293+ return ((props: T & { children?: Child }): HtmlEscapedString | Promise<HtmlEscapedString> => {294+ if (prevProps && !propsAreEqual(prevProps, props)) {295+ computed = undefined296+ }297+ prevProps = props298+ return (computed ||= component(props))299+ }) as FC<T>300+}301+302+export const Fragment = ({303+ children,304+}: {305+ key?: string306+ children?: Child | HtmlEscapedString307+}): HtmlEscapedString => {308+ return new JSXFragmentNode(309+ '',310+ {},311+ Array.isArray(children) ? children : children ? [children] : []312+ ) as never313+}314+315+export const isValidElement = (element: unknown): element is JSXNode => {316+ return !!(317+ element &&318+ typeof element === 'object' &&319+ 'tag' in element &&320+ 'props' in element &&321+ 'children' in element322+ )323+}324+325+export const cloneElement = <T extends JSXNode | JSX.Element>(326+ element: T,327+ props: Partial<Props>,328+ ...children: Child[]329+): T => {330+ return jsxFn(331+ (element as JSXNode).tag,332+ { ...(element as JSXNode).props, ...props },333+ // eslint-disable-next-line @typescript-eslint/no-explicit-any334+ children.length ? children : ((element as JSXNode).children as any) || []335+ ) as T336+}modified:deno_dist/jsx/components.ts+16 added-14 removed
1 import { raw } from '../helper/html/index.ts'2-import {3- HtmlEscapedCallbackPhase,4- resolveCallback,5- type HtmlEscapedString,6- type HtmlEscapedCallback,7-} from '../utils/html.ts'8-import type { FC, Child } from './index.ts'2+import type { HtmlEscapedString, HtmlEscapedCallback } from '../utils/html.ts'3+import { HtmlEscapedCallbackPhase, resolveCallback } from '../utils/html.ts'4+import { DOM_RENDERER } from './constants.ts'5+import { ErrorBoundary as ErrorBoundaryDomRenderer } from './dom/components.ts'6+import type { HasRenderToDom } from './dom/render.ts'7+import type { FC, PropsWithChildren, Child } from './index.ts'8 9 let errorBoundaryCounter = 010 11 export const childrenToString = async (children: Child[]): Promise<HtmlEscapedString[]> => {8 unmodified lines20 }21 }22 }23 25-type ErrorHandler = (error: Error) => void26-type FallbackRender = (error: Error) => Child24+export type ErrorHandler = (error: Error) => void25+export type FallbackRender = (error: Error) => Child26 27 /**28 * @experimental29 * `ErrorBoundary` is an experimental feature.30 * The API might be changed.31 */33-export const ErrorBoundary: FC<{34- fallback?: Child35- fallbackRender?: FallbackRender36- onError?: ErrorHandler37-}> = async ({ children, fallback, fallbackRender, onError }) => {32+export const ErrorBoundary: FC<33+ PropsWithChildren<{34+ fallback?: Child35+ fallbackRender?: FallbackRender36+ onError?: ErrorHandler37+ }>38+> = async ({ children, fallback, fallbackRender, onError }) => {39 if (!children) {40 return raw('')41 }42 138 unmodified lines181 } else {182 return raw(resArray.join(''))183 }184 }185+;(ErrorBoundary as HasRenderToDom)[DOM_RENDERER] = ErrorBoundaryDomRendereradded:deno_dist/jsx/constants.ts+3 added
1+export const DOM_RENDERER = Symbol('RENDERER')2+export const DOM_ERROR_HANDLER = Symbol('ERROR_HANDLER')3+export const DOM_STASH = Symbol('STASH')added:deno_dist/jsx/context.ts+52 added
1+import { raw } from '../helper/html/index.ts'2+import type { HtmlEscapedString } from '../utils/html.ts'3+import { JSXFragmentNode } from './base.ts'4+import { DOM_RENDERER } from './constants.ts'5+import { createContextProviderFunction } from './dom/context.ts'6+import type { FC, PropsWithChildren } from './index.ts'7+8+export interface Context<T> {9+ values: T[]10+ Provider: FC<PropsWithChildren<{ value: T }>>11+}12+13+export const globalContexts: Context<unknown>[] = []14+15+export const createContext = <T>(defaultValue: T): Context<T> => {16+ const values = [defaultValue]17+ const context: Context<T> = {18+ values,19+ Provider(props): HtmlEscapedString | Promise<HtmlEscapedString> {20+ values.push(props.value)21+ let string22+ try {23+ string = props.children24+ ? (Array.isArray(props.children)25+ ? new JSXFragmentNode('', {}, props.children)26+ : props.children27+ ).toString()28+ : ''29+ } finally {30+ values.pop()31+ }32+33+ if (string instanceof Promise) {34+ return string.then((resString) =>35+ raw(resString, (resString as HtmlEscapedString).callbacks)36+ )37+ } else {38+ return raw(string)39+ }40+ },41+ }42+ // eslint-disable-next-line @typescript-eslint/no-explicit-any43+ ;(context.Provider as any)[DOM_RENDERER] = createContextProviderFunction(values)44+45+ globalContexts.push(context as Context<unknown>)46+47+ return context48+}49+50+export const useContext = <T>(context: Context<T>): T => {51+ return context.values.at(-1) as T52+}modified:deno_dist/jsx/index.ts+20 added-323 removed
1-import { raw } from '../helper/html/index.ts'2-import { escapeToBuffer, stringBufferToString } from '../utils/html.ts'3-import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../utils/html.ts'4-import type { IntrinsicElements as IntrinsicElementsDefined } from './intrinsic-elements.ts'1+export { jsx, memo, Fragment, isValidElement, cloneElement } from './base.ts'2 export { ErrorBoundary } from './components.ts'3+export { Suspense } from './streaming.ts'4+export {5+ useState,6+ useEffect,7+ useRef,8+ useCallback,9+ use,10+ startTransition,11+ useTransition,12+ useDeferredValue,13+ startViewTransition,14+ useViewTransition,15+ useMemo,16+ useLayoutEffect,17+} from './hooks/index.ts'18+export { createContext, useContext } from './context.ts'19 7-// eslint-disable-next-line @typescript-eslint/no-explicit-any8-type Props = Record<string, any>9-10-declare global {11- // eslint-disable-next-line @typescript-eslint/no-namespace12- namespace JSX {13- type Element = HtmlEscapedString | Promise<HtmlEscapedString>14- interface ElementChildrenAttribute {15- children: Child16- }17- interface IntrinsicElements extends IntrinsicElementsDefined {18- [tagName: string]: Props19- }20- }21-}22-23-const emptyTags = [24- 'area',25- 'base',26- 'br',27- 'col',28- 'embed',29- 'hr',30- 'img',31- 'input',32- 'keygen',33- 'link',34- 'meta',35- 'param',36- 'source',37- 'track',38- 'wbr',39-]40-const booleanAttributes = [41- 'allowfullscreen',42- 'async',43- 'autofocus',44- 'autoplay',45- 'checked',46- 'controls',47- 'default',48- 'defer',49- 'disabled',50- 'formnovalidate',51- 'hidden',52- 'inert',53- 'ismap',54- 'itemscope',55- 'loop',56- 'multiple',57- 'muted',58- 'nomodule',59- 'novalidate',60- 'open',61- 'playsinline',62- 'readonly',63- 'required',64- 'reversed',65- 'selected',66-]67-68-const childrenToStringToBuffer = (children: Child[], buffer: StringBuffer): void => {69- for (let i = 0, len = children.length; i < len; i++) {70- const child = children[i]71- if (typeof child === 'string') {72- escapeToBuffer(child, buffer)73- } else if (typeof child === 'boolean' || child === null || child === undefined) {74- continue75- } else if (child instanceof JSXNode) {76- child.toStringToBuffer(buffer)77- } else if (78- typeof child === 'number' ||79- (child as unknown as { isEscaped: boolean }).isEscaped80- ) {81- ;(buffer[0] as string) += child82- } else if (child instanceof Promise) {83- buffer.unshift('', child)84- } else {85- // `child` type is `Child[]`, so stringify recursively86- childrenToStringToBuffer(child, buffer)87- }88- }89-}90-91-type LocalContexts = [Context<unknown>, unknown][]92-export type Child = string | Promise<string> | number | JSXNode | Child[]93-export class JSXNode implements HtmlEscaped {94- tag: string | Function95- props: Props96- children: Child[]97- isEscaped: true = true as const98- localContexts?: LocalContexts99- constructor(tag: string | Function, props: Props, children: Child[]) {100- this.tag = tag101- this.props = props102- this.children = children103- }104-105- toString(): string | Promise<string> {106- const buffer: StringBuffer = ['']107- this.localContexts?.forEach(([context, value]) => {108- context.values.push(value)109- })110- try {111- this.toStringToBuffer(buffer)112- } finally {113- this.localContexts?.forEach(([context]) => {114- context.values.pop()115- })116- }117- return buffer.length === 1 ? buffer[0] : stringBufferToString(buffer)118- }119-120- toStringToBuffer(buffer: StringBuffer): void {121- const tag = this.tag as string122- const props = this.props123- let { children } = this124-125- buffer[0] += `<${tag}`126-127- const propsKeys = Object.keys(props || {})128-129- for (let i = 0, len = propsKeys.length; i < len; i++) {130- const key = propsKeys[i]131- const v = props[key]132- // object to style strings133- if (key === 'style' && typeof v === 'object') {134- const styles = Object.keys(v)135- .map((k) => {136- const property = k.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`)137- return `${property}:${v[k]}`138- })139- .join(';')140- buffer[0] += ` style="${styles}"`141- } else if (typeof v === 'string') {142- buffer[0] += ` ${key}="`143- escapeToBuffer(v, buffer)144- buffer[0] += '"'145- } else if (v === null || v === undefined) {146- // Do nothing147- } else if (typeof v === 'number' || (v as HtmlEscaped).isEscaped) {148- buffer[0] += ` ${key}="${v}"`149- } else if (typeof v === 'boolean' && booleanAttributes.includes(key)) {150- if (v) {151- buffer[0] += ` ${key}=""`152- }153- } else if (key === 'dangerouslySetInnerHTML') {154- if (children.length > 0) {155- throw 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'156- }157-158- children = [raw(v.__html)]159- } else if (v instanceof Promise) {160- buffer[0] += ` ${key}="`161- buffer.unshift('"', v)162- } else {163- buffer[0] += ` ${key}="`164- escapeToBuffer(v.toString(), buffer)165- buffer[0] += '"'166- }167- }168-169- if (emptyTags.includes(tag as string)) {170- buffer[0] += '/>'171- return172- }173-174- buffer[0] += '>'175-176- childrenToStringToBuffer(children, buffer)177-178- buffer[0] += `</${tag}>`179- }180-}181-182-class JSXFunctionNode extends JSXNode {183- toStringToBuffer(buffer: StringBuffer): void {184- const { children } = this185-186- const res = (this.tag as Function).call(null, {187- ...this.props,188- children: children.length <= 1 ? children[0] : children,189- })190-191- if (res instanceof Promise) {192- if (globalContexts.length === 0) {193- buffer.unshift('', res)194- } else {195- // save current contexts for resuming196- const currentContexts: LocalContexts = globalContexts.map((c) => [197- c,198- c.values[c.values.length - 1],199- ])200- buffer.unshift(201- '',202- res.then((childRes) => {203- if (childRes instanceof JSXNode) {204- childRes.localContexts = currentContexts205- }206- return childRes207- })208- )209- }210- } else if (res instanceof JSXNode) {211- res.toStringToBuffer(buffer)212- } else if (typeof res === 'number' || (res as HtmlEscaped).isEscaped) {213- buffer[0] += res214- } else {215- escapeToBuffer(res, buffer)216- }217- }218-}219-220-class JSXFragmentNode extends JSXNode {221- toStringToBuffer(buffer: StringBuffer): void {222- childrenToStringToBuffer(this.children, buffer)223- }224-}225-226-export { jsxFn as jsx }227-const jsxFn = (228- tag: string | Function,229- props: Props,230- ...children: (string | HtmlEscapedString)[]231-): JSXNode => {232- if (typeof tag === 'function') {233- return new JSXFunctionNode(tag, props, children)234- } else {235- return new JSXNode(tag, props, children)236- }237-}238-239-export type FC<T = Props> = (240- props: T & { children?: Child }241-) => HtmlEscapedString | Promise<HtmlEscapedString>242-243-const shallowEqual = (a: Props, b: Props): boolean => {244- if (a === b) {245- return true246- }247-248- const aKeys = Object.keys(a)249- const bKeys = Object.keys(b)250- if (aKeys.length !== bKeys.length) {251- return false252- }253-254- for (let i = 0, len = aKeys.length; i < len; i++) {255- if (a[aKeys[i]] !== b[aKeys[i]]) {256- return false257- }258- }259-260- return true261-}262-263-export const memo = <T>(264- component: FC<T>,265- propsAreEqual: (prevProps: Readonly<T>, nextProps: Readonly<T>) => boolean = shallowEqual266-): FC<T> => {267- let computed = undefined268- let prevProps: T | undefined = undefined269- return ((props: T & { children?: Child }): HtmlEscapedString => {270- if (prevProps && !propsAreEqual(prevProps, props)) {271- computed = undefined272- }273- prevProps = props274- return (computed ||= component(props))275- }) as FC<T>276-}277-278-export const Fragment = (props: {279- key?: string280- children?: Child | HtmlEscapedString281-}): HtmlEscapedString => {282- return new JSXFragmentNode('', {}, props.children ? [props.children] : []) as never283-}284-285-export interface Context<T> {286- values: T[]287- Provider: FC<{ value: T }>288-}289-290-const globalContexts: Context<unknown>[] = []291-292-export const createContext = <T>(defaultValue: T): Context<T> => {293- const values = [defaultValue]294- const context: Context<T> = {295- values,296- Provider(props): HtmlEscapedString | Promise<HtmlEscapedString> {297- values.push(props.value)298- let string299- try {300- string = props.children301- ? (Array.isArray(props.children)302- ? new JSXFragmentNode('', {}, props.children)303- : props.children304- ).toString()305- : ''306- } finally {307- values.pop()308- }309-310- if (string instanceof Promise) {311- return string.then((resString) =>312- raw(resString, (resString as HtmlEscapedString).callbacks)313- )314- } else {315- return raw(string)316- }317- },318- }319- globalContexts.push(context as Context<unknown>)320- return context321-}322-323-export const useContext = <T>(context: Context<T>): T => {324- return context.values[context.values.length - 1]325-}20+// TODO: change to `export type *` after denoify bug is fixed21+// https://github.com/garronej/denoify/issues/12422+export * from './types.ts'modified:deno_dist/jsx/intrinsic-elements.ts+126 added-1 removed
18 unmodified lines19 __html: string20 }21 }22 23- interface HTMLAttributes extends JSXAttributes, AnyAttributes {23+ interface EventAttributes {24+ onScroll?: (event: Event) => void25+ onScrollCapture?: (event: Event) => void26+ onScrollEnd?: (event: Event) => void27+ onScrollEndCapture?: (event: Event) => void28+ onWheel?: (event: WheelEvent) => void29+ onWheelCapture?: (event: WheelEvent) => void30+ onAnimationCancel?: (event: AnimationEvent) => void31+ onAnimationCancelCapture?: (event: AnimationEvent) => void32+ onAnimationEnd?: (event: AnimationEvent) => void33+ onAnimationEndCapture?: (event: AnimationEvent) => void34+ onAnimationIteration?: (event: AnimationEvent) => void35+ onAnimationIterationCapture?: (event: AnimationEvent) => void36+ onAnimationStart?: (event: AnimationEvent) => void37+ onAnimationStartCapture?: (event: AnimationEvent) => void38+ onCopy?: (event: ClipboardEvent) => void39+ onCopyCapture?: (event: ClipboardEvent) => void40+ onCut?: (event: ClipboardEvent) => void41+ onCutCapture?: (event: ClipboardEvent) => void42+ onPaste?: (event: ClipboardEvent) => void43+ onPasteCapture?: (event: ClipboardEvent) => void44+ onCompositionEnd?: (event: CompositionEvent) => void45+ onCompositionEndCapture?: (event: CompositionEvent) => void46+ onCompositionStart?: (event: CompositionEvent) => void47+ onCompositionStartCapture?: (event: CompositionEvent) => void48+ onCompositionUpdate?: (event: CompositionEvent) => void49+ onCompositionUpdateCapture?: (event: CompositionEvent) => void50+ onBlur?: (event: FocusEvent) => void51+ onBlurCapture?: (event: FocusEvent) => void52+ onFocus?: (event: FocusEvent) => void53+ onFocusCapture?: (event: FocusEvent) => void54+ onFocusIn?: (event: FocusEvent) => void55+ onFocusInCapture?: (event: FocusEvent) => void56+ onFocusOut?: (event: FocusEvent) => void57+ onFocusOutCapture?: (event: FocusEvent) => void58+ onFullscreenChange?: (event: Event) => void59+ onFullscreenChangeCapture?: (event: Event) => void60+ onFullscreenError?: (event: Event) => void61+ onFullscreenErrorCapture?: (event: Event) => void62+ onKeyDown?: (event: KeyboardEvent) => void63+ onKeyDownCapture?: (event: KeyboardEvent) => void64+ onKeyPress?: (event: KeyboardEvent) => void65+ onKeyPressCapture?: (event: KeyboardEvent) => void66+ onKeyUp?: (event: KeyboardEvent) => void67+ onKeyUpCapture?: (event: KeyboardEvent) => void68+ onAuxClick?: (event: MouseEvent) => void69+ onAuxClickCapture?: (event: MouseEvent) => void70+ onClick?: (event: MouseEvent) => void71+ onClickCapture?: (event: MouseEvent) => void72+ onContextMenu?: (event: MouseEvent) => void73+ onContextMenuCapture?: (event: MouseEvent) => void74+ onDoubleClick?: (event: MouseEvent) => void75+ onDoubleClickCapture?: (event: MouseEvent) => void76+ onMouseDown?: (event: MouseEvent) => void77+ onMouseDownCapture?: (event: MouseEvent) => void78+ onMouseEnter?: (event: MouseEvent) => void79+ onMouseEnterCapture?: (event: MouseEvent) => void80+ onMouseLeave?: (event: MouseEvent) => void81+ onMouseLeaveCapture?: (event: MouseEvent) => void82+ onMouseMove?: (event: MouseEvent) => void83+ onMouseMoveCapture?: (event: MouseEvent) => void84+ onMouseOut?: (event: MouseEvent) => void85+ onMouseOutCapture?: (event: MouseEvent) => void86+ onMouseOver?: (event: MouseEvent) => void87+ onMouseOverCapture?: (event: MouseEvent) => void88+ onMouseUp?: (event: MouseEvent) => void89+ onMouseUpCapture?: (event: MouseEvent) => void90+ onMouseWheel?: (event: WheelEvent) => void91+ onMouseWheelCapture?: (event: WheelEvent) => void92+ onGotPointerCapture?: (event: PointerEvent) => void93+ onGotPointerCaptureCapture?: (event: PointerEvent) => void94+ onLostPointerCapture?: (event: PointerEvent) => void95+ onLostPointerCaptureCapture?: (event: PointerEvent) => void96+ onPointerCancel?: (event: PointerEvent) => void97+ onPointerCancelCapture?: (event: PointerEvent) => void98+ onPointerDown?: (event: PointerEvent) => void99+ onPointerDownCapture?: (event: PointerEvent) => void100+ onPointerEnter?: (event: PointerEvent) => void101+ onPointerEnterCapture?: (event: PointerEvent) => void102+ onPointerLeave?: (event: PointerEvent) => void103+ onPointerLeaveCapture?: (event: PointerEvent) => void104+ onPointerMove?: (event: PointerEvent) => void105+ onPointerMoveCapture?: (event: PointerEvent) => void106+ onPointerOut?: (event: PointerEvent) => void107+ onPointerOutCapture?: (event: PointerEvent) => void108+ onPointerOver?: (event: PointerEvent) => void109+ onPointerOverCapture?: (event: PointerEvent) => void110+ onPointerUp?: (event: PointerEvent) => void111+ onPointerUpCapture?: (event: PointerEvent) => void112+ onTouchCancel?: (event: TouchEvent) => void113+ onTouchCancelCapture?: (event: TouchEvent) => void114+ onTouchEnd?: (event: TouchEvent) => void115+ onTouchEndCapture?: (event: TouchEvent) => void116+ onTouchMove?: (event: TouchEvent) => void117+ onTouchMoveCapture?: (event: TouchEvent) => void118+ onTouchStart?: (event: TouchEvent) => void119+ onTouchStartCapture?: (event: TouchEvent) => void120+ onTransitionCancel?: (event: TransitionEvent) => void121+ onTransitionCancelCapture?: (event: TransitionEvent) => void122+ onTransitionEnd?: (event: TransitionEvent) => void123+ onTransitionEndCapture?: (event: TransitionEvent) => void124+ onTransitionRun?: (event: TransitionEvent) => void125+ onTransitionRunCapture?: (event: TransitionEvent) => void126+ onTransitionStart?: (event: TransitionEvent) => void127+ onTransitionStartCapture?: (event: TransitionEvent) => void128+ onFormData?: (event: FormDataEvent) => void129+ onFormDataCapture?: (event: FormDataEvent) => void130+ onReset?: (event: Event) => void131+ onResetCapture?: (event: Event) => void132+ onSubmit?: (event: Event) => void133+ onSubmitCapture?: (event: Event) => void134+ onInvalid?: (event: Event) => void135+ onInvalidCapture?: (event: Event) => void136+ onSelect?: (event: Event) => void137+ onSelectCapture?: (event: Event) => void138+ onSelectChange?: (event: Event) => void139+ onSelectChangeCapture?: (event: Event) => void140+ onInput?: (event: InputEvent) => void141+ onInputCapture?: (event: InputEvent) => void142+ onBeforeInput?: (event: InputEvent) => void143+ onBeforeInputCapture?: (event: InputEvent) => void144+ onChange?: (event: Event) => void145+ onChangeCapture?: (event: Event) => void146+ }147+148+ interface HTMLAttributes extends JSXAttributes, EventAttributes, AnyAttributes {149 accesskey?: string | undefined150 autofocus?: boolean | undefined151 class?: string | Promise<string> | undefined152 contenteditable?: boolean | 'inherit' | undefined579 unmodified linesmodified:deno_dist/jsx/jsx-dev-runtime.ts+16 added-8 removed
1 import type { HtmlEscapedString } from '../utils/html.ts'2-import { jsx } from './index.ts'3-import type { JSXNode } from './index.ts'4-export { Fragment } from './index.ts'2+import { jsxFn } from './base.ts'3+import type { JSXNode } from './base.ts'4+export { Fragment } from './base.ts'5 6-export function jsxDEV(tag: string | Function, props: Record<string, unknown>): JSXNode {6+export function jsxDEV(7+ tag: string | Function,8+ props: Record<string, unknown>,9+ key?: string10+): JSXNode {11+ let node: JSXNode12 if (!props || !('children' in props)) {8- return jsx(tag, props)13+ node = jsxFn(tag, props, [])14+ } else {15+ const children = props.children as string | HtmlEscapedString16+ delete props['children']17+ node = Array.isArray(children) ? jsxFn(tag, props, children) : jsxFn(tag, props, [children])18 }10- const children = props.children as string | HtmlEscapedString11- delete props['children']12- return Array.isArray(children) ? jsx(tag, props, ...children) : jsx(tag, props, children)19+ node.key = key20+ return node21 }modified:deno_dist/jsx/streaming.ts+29 added-5 removed
1 import { raw } from '../helper/html/index.ts'2 import { HtmlEscapedCallbackPhase, resolveCallback } from '../utils/html.ts'3 import type { HtmlEscapedString } from '../utils/html.ts'4 import { childrenToString } from './components.ts'5-import type { FC, Child } from './index.ts'5+import { DOM_RENDERER, DOM_STASH } from './constants.ts'6+import { Suspense as SuspenseDomRenderer } from './dom/components.ts'7+import { buildDataStack } from './dom/render.ts'8+import type { HasRenderToDom, NodeObject } from './dom/render.ts'9+import type { FC, PropsWithChildren, Child } from './index.ts'10 11 let suspenseCounter = 012 13 /**1 unmodified line15 * `Suspense` is an experimental feature.16 * The API might be changed.17 */18 // eslint-disable-next-line @typescript-eslint/no-explicit-any15-export const Suspense: FC<{ fallback: any }> = async ({ children, fallback }) => {19+export const Suspense: FC<PropsWithChildren<{ fallback: any }>> = async ({20+ children,21+ fallback,22+}) => {23 if (!children) {24 return fallback.toString()25 }26 if (!Array.isArray(children)) {27 children = [children]28 }29 30 let resArray: HtmlEscapedString[] | Promise<HtmlEscapedString[]>[] = []31+32+ // for use() hook33+ const stackNode = { [DOM_STASH]: [0, []] } as unknown as NodeObject34+ const popNodeStack = (value?: unknown) => {35+ buildDataStack.pop()36+ return value37+ }38+39 try {40+ stackNode[DOM_STASH][0] = 041+ buildDataStack.push([[], stackNode])42 resArray = children.map((c) => c.toString()) as HtmlEscapedString[]43 } catch (e) {44 if (e instanceof Promise) {28- resArray = [e.then(() => childrenToString(children as Child[]))] as Promise<29- HtmlEscapedString[]30- >[]45+ resArray = [46+ e.then(() => {47+ stackNode[DOM_STASH][0] = 048+ buildDataStack.push([[], stackNode])49+ return childrenToString(children as Child[]).then(popNodeStack)50+ }),51+ ] as Promise<HtmlEscapedString[]>[]52 } else {53 throw e54 }55+ } finally {56+ popNodeStack()57 }58 59 if (resArray.some((res) => (res as {}) instanceof Promise)) {60 const index = suspenseCounter++43 unmodified lines104 } else {105 return raw(resArray.join(''))106 }107 }108+;(Suspense as HasRenderToDom)[DOM_RENDERER] = SuspenseDomRenderer109 110 const textEncoder = new TextEncoder()111 /**112 * @experimental53 unmodified linesadded:deno_dist/jsx/types.ts+11 added
1+/**2+ * All types exported from "hono/jsx" are in this file.3+ */4+import type { Child } from './base.ts'5+6+export type { Child, JSXNode, FC } from './base.ts'7+export type { RefObject } from './hooks/index.ts'8+export type { Context } from './context.ts'9+10+export type PropsWithChildren<P = unknown> = P & { children?: Child | undefined }11+export type CSSProperties = Hono.CSSPropertiesadded:deno_dist/jsx/utils.ts+6 added
1+export const normalizeIntrinsicElementProps = (props: Record<string, unknown>): void => {2+ if (props && 'className' in props) {3+ props['class'] = props['className']4+ delete props['className']5+ }6+}modified:deno_dist/middleware/basic-auth/index.ts+1 added-1 removed
6 unmodified lines7 const CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/8 const USER_PASS_REGEXP = /^([^:]*):(.*)$/9 const utf8Decoder = new TextDecoder()10 const auth = (req: HonoRequest) => {11- const match = CREDENTIALS_REGEXP.exec(req.headers.get('Authorization') || '')11+ const match = CREDENTIALS_REGEXP.exec(req.header('Authorization') || '')12 if (!match) {13 return undefined14 }15 49 unmodified linesmodified:deno_dist/middleware/compress/index.ts+2 added-2 removed
1 unmodified line2 3 const ENCODING_TYPES = ['gzip', 'deflate'] as const4 5 interface CompressionOptions {6- encoding?: typeof ENCODING_TYPES[number]6+ encoding?: (typeof ENCODING_TYPES)[number]7 }8 9 export const compress = (options?: CompressionOptions): MiddlewareHandler => {10 return async function compress(ctx, next) {11 await next()12- const accepted = ctx.req.headers.get('Accept-Encoding')12+ const accepted = ctx.req.header('Accept-Encoding')13 const encoding =14 options?.encoding ?? ENCODING_TYPES.find((encoding) => accepted?.includes(encoding))15 if (!encoding || !ctx.res.body) {16 return9 unmodified linesmodified:deno_dist/middleware/jsx-renderer/index.ts+32 added-13 removed
1+/* eslint-disable @typescript-eslint/no-explicit-any */2 import type { Context, Renderer } from '../../context.ts'2-// eslint-disable-next-line @typescript-eslint/no-unused-vars3 import { html, raw } from '../../helper/html/index.ts'4-import { jsx, createContext, useContext } from '../../jsx/index.ts'5-import type { FC, JSXNode } from '../../jsx/index.ts'4+import { jsx, createContext, useContext, Fragment } from '../../jsx/index.ts'5+import type { FC, PropsWithChildren, JSXNode } from '../../jsx/index.ts'6 import { renderToReadableStream } from '../../jsx/streaming.ts'7 import type { Env, Input, MiddlewareHandler } from '../../types.ts'8 9 export const RequestContext = createContext<Context | null>(null)10 11-type PropsForRenderer = [...Required<Parameters<Renderer>>] extends [unknown, infer Props]11+export type PropsForRenderer = [...Required<Parameters<Renderer>>] extends [unknown, infer Props]12 ? Props13 : unknown14 15 type RendererOptions = {1 unmodified line17 stream?: boolean | Record<string, string>18 }19 20 const createRenderer =21- (c: Context, component?: FC<PropsForRenderer>, options?: RendererOptions) =>21+ (22+ c: Context,23+ Layout: FC,24+ component?: FC<PropsForRenderer & { Layout: FC }>,25+ options?: RendererOptions26+ ) =>27 (children: JSXNode, props: PropsForRenderer) => {28 const docType =29 typeof options?.docType === 'string'30 ? options.docType26- : options?.docType === true27- ? '<!DOCTYPE html>'28- : ''29- /* eslint-disable @typescript-eslint/no-explicit-any */31+ : options?.docType === false32+ ? ''33+ : '<!DOCTYPE html>'34+35+ const currentLayout = component36+ ? component({37+ children,38+ // eslint-disable-next-line @typescript-eslint/no-explicit-any39+ ...{ Layout, ...(props as any) },40+ })41+ : children42+43 const body = html`${raw(docType)}${jsx(44 RequestContext.Provider,45 { value: c },33- (component ? component({ children, ...(props || {}) }) : children) as any46+ // eslint-disable-next-line @typescript-eslint/no-explicit-any47+ currentLayout as any48 )}`49 50 if (options?.stream) {51 return c.body(renderToReadableStream(body), {10 unmodified lines62 }63 }64 65 export const jsxRenderer = (52- component?: FC<PropsForRenderer>,66+ component?: FC<PropsWithChildren<PropsForRenderer & { Layout: FC }>>,67 options?: RendererOptions68 ): MiddlewareHandler =>69 function jsxRenderer(c, next) {56- /* eslint-disable @typescript-eslint/no-explicit-any */57- c.setRenderer(createRenderer(c, component, options) as any)70+ const Layout = (c.getLayout() ?? Fragment) as FC71+ if (component) {72+ c.setLayout((props) => {73+ return component({ ...props, Layout })74+ })75+ }76+ c.setRenderer(createRenderer(c, Layout, component, options) as any)77 return next()78 }79 80 export const useRequestContext = <10 unmodified linesmodified:deno_dist/middleware/jwt/index.ts+3 added-2 removed
1 import type { Context } from '../../context.ts'2+import { getCookie } from '../../helper.ts'3 import { HTTPException } from '../../http-exception.ts'4 import type { MiddlewareHandler } from '../../types.ts'5 import { Jwt } from '../../utils/jwt/index.ts'6 import type { AlgorithmTypes } from '../../utils/jwt/types.ts'19 unmodified lines26 throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.')27 }28 29 return async function jwt(ctx, next) {29- const credentials = ctx.req.headers.get('Authorization')30+ const credentials = ctx.req.raw.headers.get('Authorization')31 let token32 if (credentials) {33 const parts = credentials.split(/\s+/)34 if (parts.length !== 2) {7 unmodified lines42 } else {43 token = parts[1]44 }45 } else if (options.cookie) {45- token = ctx.req.cookie(options.cookie)46+ token = getCookie(ctx)[options.cookie]47 }48 49 if (!token) {50 throw new HTTPException(401, {50 unmodified linesmodified:deno_dist/preset/quick.ts+2 added-2 removed
1 unmodified line2 import type { HonoOptions } from '../hono-base.ts'3 import { LinearRouter } from '../router/linear-router/index.ts'4 import { SmartRouter } from '../router/smart-router/index.ts'5 import { TrieRouter } from '../router/trie-router/index.ts'6-import type { Env, Schema } from '../types.ts'6+import type { BlankSchema, Env, Schema } from '../types.ts'7 8 export class Hono<9 E extends Env = Env,10- S extends Schema = {},10+ S extends Schema = BlankSchema,11 BasePath extends string = '/'12 > extends HonoBase<E, S, BasePath> {13 constructor(options: HonoOptions<E> = {}) {14 super(options)5 unmodified linesmodified:deno_dist/preset/tiny.ts+2 added-2 removed
1 import { HonoBase } from '../hono-base.ts'2 import type { HonoOptions } from '../hono-base.ts'3 import { PatternRouter } from '../router/pattern-router/index.ts'4-import type { Env, Schema } from '../types.ts'4+import type { BlankSchema, Env, Schema } from '../types.ts'5 6 export class Hono<7 E extends Env = Env,8- S extends Schema = {},8+ S extends Schema = BlankSchema,9 BasePath extends string = '/'10 > extends HonoBase<E, S, BasePath> {11 constructor(options: HonoOptions<E> = {}) {12 super(options)3 unmodified linesmodified:deno_dist/router/linear-router/router.ts+3 added-3 removed
18 unmodified lines19 }20 21 match(method: string, path: string): Result<T> {22 const handlers: [T, Params][] = []23- ROUTES_LOOP: for (let i = 0; i < this.routes.length; i++) {23+ ROUTES_LOOP: for (let i = 0, len = this.routes.length; i < len; i++) {24 const [routeMethod, routePath, handler] = this.routes[i]25 if (routeMethod !== method && routeMethod !== METHOD_NAME_ALL) {26 continue27 }12 unmodified lines40 const endsWithStar = routePath.charCodeAt(routePath.length - 1) === 4241 const parts = (endsWithStar ? routePath.slice(0, -2) : routePath).split(splitByStarRe)42 43 const lastIndex = parts.length - 144- for (let j = 0, pos = 0; j < parts.length; j++) {44+ for (let j = 0, pos = 0, len = parts.length; j < len; j++) {45 const part = parts[j]46 const index = path.indexOf(part, pos)47 if (index !== pos) {48 continue ROUTES_LOOP20 unmodified lines69 const params: Record<string, string> = {}70 const parts = routePath.match(splitPathRe) as string[]71 72 const lastIndex = parts.length - 173- for (let j = 0, pos = 0; j < parts.length; j++) {73+ for (let j = 0, pos = 0, len = parts.length; j < len; j++) {74 if (pos === -1 || pos >= path.length) {75 continue ROUTES_LOOP76 }77 55 unmodified linesmodified:deno_dist/utils/jwt/types.ts-6 removed
3 unmodified lines4 this.name = 'JwtAlgorithmNotImplemented'5 }6 }7 8-/**9- * Export for backward compatibility10- * @deprecated Use JwtAlgorithmNotImplemented instead11- **/12-export const JwtAlorithmNotImplemented = JwtAlgorithmNotImplemented13-8 export class JwtTokenInvalid extends Error {9 constructor(token: string) {10 super(`invalid JWT token: ${token}`)11 this.name = 'JwtTokenInvalid'36 unmodified linesmodified:deno_dist/utils/body.ts+3 added-2 removed
1-import type { HonoRequest } from '../request.ts'1+import { HonoRequest } from '../request.ts'2 3 export type BodyData = Record<string, string | File | (string | File)[]>4 export type ParseBodyOptions = {5 /**19 unmodified lines25 export const parseBody = async <T extends BodyData = BodyData>(26 request: HonoRequest | Request,27 options: ParseBodyOptions = { all: false }28 ): Promise<T> => {29+ const headers = request instanceof HonoRequest ? request.raw.headers : request.headers29- const contentType = request.headers.get('Content-Type')30+ const contentType = headers.get('Content-Type')31 32 if (isFormDataContent(contentType)) {33 return parseFormData<T>(request, options)34 }68 unmodified linesmodified:deno_dist/utils/cookie.ts+1 added-1 removed
34 unmodified lines35 ): Promise<boolean> => {36 try {37 const signatureBinStr = atob(base64Signature)38 const signature = new Uint8Array(signatureBinStr.length)39- for (let i = 0; i < signatureBinStr.length; i++) {39+ for (let i = 0, len = signatureBinStr.length; i < len; i++) {40 signature[i] = signatureBinStr.charCodeAt(i)41 }42 return await crypto.subtle.verify(algorithm, secret, signature, new TextEncoder().encode(value))43 } catch (e) {122 unmodified linesmodified:deno_dist/utils/encode.ts+1 added-1 removed
8 unmodified lines9 // btoa does not support utf-8 characters. So we need a little bit hack.10 export const encodeBase64 = (buf: ArrayBufferLike): string => {11 let binary = ''12 const bytes = new Uint8Array(buf)13- for (let i = 0; i < bytes.length; i++) {13+ for (let i = 0, len = bytes.length; i < len; i++) {14 binary += String.fromCharCode(bytes[i])15 }16 return btoa(binary)17 }12 unmodified linesmodified:deno_dist/utils/html.ts+2 added-2 removed
3 unmodified lines4 Stream: 3,5 } as const6 type HtmlEscapedCallbackOpts = {7 buffer?: [string]8- phase: typeof HtmlEscapedCallbackPhase[keyof typeof HtmlEscapedCallbackPhase]8+ phase: (typeof HtmlEscapedCallbackPhase)[keyof typeof HtmlEscapedCallbackPhase]9 context: object // An object unique to each JSX tree. This object is used as the WeakMap key.10 }11 export type HtmlEscapedCallback = (opts: HtmlEscapedCallbackOpts) => Promise<string> | undefined12 export type HtmlEscaped = {104 unmodified lines117 }118 119 export const resolveCallback = async (120 str: string | HtmlEscapedString,121- phase: typeof HtmlEscapedCallbackPhase[keyof typeof HtmlEscapedCallbackPhase],121+ phase: (typeof HtmlEscapedCallbackPhase)[keyof typeof HtmlEscapedCallbackPhase],122 preserveCallbacks: boolean,123 context: object,124 buffer?: [string]125 ): Promise<string> => {25 unmodified linesmodified:deno_dist/utils/http-status.ts+57 added-1 removed
1+export type InfoStatusCode = 100 | 101 | 102 | 1032+export type SuccessStatusCode = 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 2263+export type DeprecatedStatusCode = 305 | 3064+export type RedirectStatusCode = 300 | 301 | 302 | 303 | 304 | DeprecatedStatusCode | 307 | 3085+export type ClientErrorStatusCode =6+ | 4007+ | 4018+ | 4029+ | 40310+ | 40411+ | 40512+ | 40613+ | 40714+ | 40815+ | 40916+ | 41017+ | 41118+ | 41219+ | 41320+ | 41421+ | 41522+ | 41623+ | 41724+ | 41825+ | 42126+ | 42227+ | 42328+ | 42429+ | 42530+ | 42631+ | 42832+ | 42933+ | 43134+ | 45135+export type ServerErrorStatusCode = 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 51136+/**37+ * `UnOfficalStatusCode` can be used to specify an informal status code.38+ * @example39+ *40+ * ```ts41+ * app.get('/', (c) => {42+ * return c.text("hono is cool", 666 as UnOfficalStatusCode)43+ * })44+ * ```45+ */46+export type UnOfficalStatusCode = -147+48+/**49+ * If you want to use an unofficial status, use `UnOfficalStatusCode`.50+ */1-export type StatusCode = number51+export type StatusCode =52+ | InfoStatusCode53+ | SuccessStatusCode54+ | RedirectStatusCode55+ | ClientErrorStatusCode56+ | ServerErrorStatusCode57+ | UnOfficalStatusCodemodified:deno_dist/utils/mime.ts+10 added-26 removed
1-export const getMimeType = (filename: string): string | undefined => {1+export const getMimeType = (filename: string, mimes = baseMimes): string | undefined => {2 const regexp = /\.([a-zA-Z0-9]+?)$/3 const match = filename.match(regexp)4 if (!match) {5 return4 unmodified lines10 }11 return mimeType12 }13 14+export const getExtension = (mimeType: string): string | undefined => {15+ for (const ext in baseMimes) {16+ if (baseMimes[ext] === mimeType) {17+ return ext18+ }19+ }20+}21+14-const mimes: Record<string, string> = {22+const baseMimes: Record<string, string> = {23 aac: 'audio/aac',16- abw: 'application/x-abiword',17- arc: 'application/x-freearc',24 avi: 'video/x-msvideo',25 avif: 'image/avif',26 av1: 'video/av1',21- azw: 'application/vnd.amazon.ebook',27 bin: 'application/octet-stream',28 bmp: 'image/bmp',24- bz: 'application/x-bzip',25- bz2: 'application/x-bzip2',26- csh: 'application/x-csh',29 css: 'text/css',30 csv: 'text/csv',29- doc: 'application/msword',30- docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',31 eot: 'application/vnd.ms-fontobject',32 epub: 'application/epub+zip',33 gif: 'image/gif',34 gz: 'application/gzip',35 htm: 'text/html',36 html: 'text/html',37 ico: 'image/x-icon',38 ics: 'text/calendar',39- jar: 'application/java-archive',39 jpeg: 'image/jpeg',40 jpg: 'image/jpeg',41 js: 'text/javascript',42 json: 'application/json',4 unmodified lines47 mjs: 'text/javascript',48 mp3: 'audio/mpeg',49 mp4: 'video/mp4',50 mpeg: 'video/mpeg',52- mpkg: 'application/vnd.apple.installer+xml',53- odp: 'application/vnd.oasis.opendocument.presentation',54- ods: 'application/vnd.oasis.opendocument.spreadsheet',55- odt: 'application/vnd.oasis.opendocument.text',51 oga: 'audio/ogg',52 ogv: 'video/ogg',53 ogx: 'application/ogg',54 opus: 'audio/opus',55 otf: 'font/otf',56 pdf: 'application/pdf',62- php: 'application/php',57 png: 'image/png',64- ppt: 'application/vnd.ms-powerpoint',65- pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',58 rtf: 'application/rtf',67- sh: 'application/x-sh',59 svg: 'image/svg+xml',69- swf: 'application/x-shockwave-flash',70- tar: 'application/x-tar',60 tif: 'image/tiff',61 tiff: 'image/tiff',62 ts: 'video/mp2t',63 ttf: 'font/ttf',64 txt: 'text/plain',76- vsd: 'application/vnd.visio',65 wasm: 'application/wasm',66 webm: 'video/webm',67 weba: 'audio/webm',68 webp: 'image/webp',69 woff: 'font/woff',70 woff2: 'font/woff2',71 xhtml: 'application/xhtml+xml',84- xls: 'application/vnd.ms-excel',85- xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',72 xml: 'application/xml',87- xul: 'application/vnd.mozilla.xul+xml',73 zip: 'application/zip',74 '3gp': 'video/3gpp',75 '3g2': 'video/3gpp2',91- '7z': 'application/x-7z-compressed',76 gltf: 'model/gltf+json',77 glb: 'model/gltf-binary',78 }modified:deno_dist/utils/types.ts+2 added-4 removed
17 unmodified lines18 : never19 20 export type IfAnyThenEmptyObject<T> = 0 extends 1 & T ? {} : T21 22-export type IntersectNonAnyTypes<T extends any[]> = T extends [infer Head, ...infer Rest]23- ? IfAnyThenEmptyObject<Head> & IntersectNonAnyTypes<Rest>24- : {}25-22 export type JSONPrimitive = string | boolean | number | null | undefined23 export type JSONArray = (JSONPrimitive | JSONObject | JSONArray)[]24 export type JSONObject = { [key: string]: JSONPrimitive | JSONArray | JSONObject | object }25 export type JSONValue = JSONObject | JSONArray | JSONPrimitive21 unmodified lines47 48 export type HasRequiredKeys<BaseType extends object> = RequiredKeysOf<BaseType> extends never49 ? false50 : true51+52+export type IsAny<T> = boolean extends (T extends never ? true : false) ? true : falsemodified:deno_dist/validator/validator.ts+18 added-31 removed
1 import type { Context } from '../context.ts'2 import { getCookie } from '../helper/cookie/index.ts'3+import { HTTPException } from '../http-exception.ts'4 import type { Env, ValidationTargets, MiddlewareHandler, TypedResponse } from '../types.ts'5 import type { BodyData } from '../utils/body.ts'6 import { bufferToFormData } from '../utils/buffer.ts'7 20 unmodified lines28 P extends string,29 M extends string,30 U extends ValidationTargetByMethod<M>,31 OutputType = ValidationTargets[U],32+ OutputTypeExcludeResponseType = ExcludeResponseType<OutputType>,33 P2 extends string = P,34 V extends {33- in: { [K in U]: unknown extends InputType ? OutputType : InputType }34- out: { [K in U]: ExcludeResponseType<OutputType> }35+ in: {36+ [K in U]: K extends 'json'37+ ? InputType38+ : { [K2 in keyof OutputTypeExcludeResponseType]: ValidationTargets[K][K2] }39+ }40+ out: { [K in U]: OutputTypeExcludeResponseType }41 } = {36- in: { [K in U]: unknown extends InputType ? OutputType : InputType }37- out: { [K in U]: ExcludeResponseType<OutputType> }42+ in: {43+ [K in U]: K extends 'json'44+ ? InputType45+ : { [K2 in keyof OutputTypeExcludeResponseType]: ValidationTargets[K][K2] }46+ }47+ out: { [K in U]: OutputTypeExcludeResponseType }48 },49 // eslint-disable-next-line @typescript-eslint/no-explicit-any50 E extends Env = any51 >(12 unmodified lines64 switch (target) {65 case 'json':66 if (!contentType || !contentType.startsWith('application/json')) {67 const message = `Invalid HTTP header: Content-Type=${contentType}`58- console.error(message)59- return c.json(60- {61- success: false,62- message,63- },64- 40065- )68+ throw new HTTPException(400, { message })69 }70 /**71 * Get the arrayBuffer first, create JSON object via Response,72 * and cache the arrayBuffer in the c.req.bodyCache.3 unmodified lines76 value = await new Response(arrayBuffer).json()77 c.req.bodyCache.json = value78 c.req.bodyCache.arrayBuffer = arrayBuffer79 } catch {77- console.error('Error: Malformed JSON in request body')78- return c.json(79- {80- success: false,81- message: 'Malformed JSON in request body',82- },83- 40084- )80+ const message = 'Malformed JSON in request body'81+ throw new HTTPException(400, { message })82 }83 break84 case 'form': {85 try {11 unmodified lines97 }98 } catch (e) {99 let message = 'Malformed FormData request.'100 message += e instanceof Error ? ` ${e.message}` : ` ${String(e)}`104- return c.json(105- {106- success: false,107- message,108- },109- 400110- )101+ throw new HTTPException(400, { message })102 }103 break104 }105 case 'query':2 unmodified lines108 return v.length === 1 ? [k, v[0]] : [k, v]109 })110 )111 break121- case 'queries':122- value = c.req.queries()123- console.log('Warnings: Validate type `queries` is deprecated. Use `query` instead.')124- break112 case 'param':113 value = c.req.param() as Record<string, string>114 break115 case 'header':18 unmodified linesmodified:deno_dist/context.ts+186 added-125 removed
1-import type { Runtime } from './helper/adapter/index.ts'1+import type { FC } from './jsx/index.ts'2+import type { PropsForRenderer } from './middleware/jsx-renderer/index.ts'3 import type { HonoRequest } from './request.ts'4 import type { Env, FetchEventLike, NotFoundHandler, Input, TypedResponse } from './types.ts'4-import type { CookieOptions } from './utils/cookie.ts'5-import { serialize } from './utils/cookie.ts'5 import { resolveCallback, HtmlEscapedCallbackPhase } from './utils/html.ts'7-import type { StatusCode } from './utils/http-status.ts'8-import { StreamingApi } from './utils/stream.ts'9-import type { JSONValue, InterfaceToType, JSONParsed } from './utils/types.ts'6+import type { RedirectStatusCode, StatusCode } from './utils/http-status.ts'7+import type { JSONValue, InterfaceToType, JSONParsed, IsAny } from './utils/types.ts'8 9 type HeaderRecord = Record<string, string | string[]>10 type Data = string | ArrayBuffer | ReadableStream11 82 unmodified lines94 // eslint-disable-next-line @typescript-eslint/no-explicit-any95 P extends string = any,96 I extends Input = {}97 > {98+ /**99+ * `.req` is the instance of {@link HonoRequest}.100+ */101 req: HonoRequest<P, I['out']>102+ /**103+ * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.104+ * @example105+ * ```ts106+ * // Environment object for Cloudflare Workers107+ * app.get('*', async c => {108+ * const counter = c.env.COUNTER109+ * })110+ * ```111+ * @see https://hono.dev/api/context#env112+ */113 env: E['Bindings'] = {}114 private _var: E['Variables'] = {}115 finalized: boolean = false116+ /**117+ * `.error` can get the error object from the middleware if the Handler throws an error.118+ * @example119+ * ```ts120+ * app.use('*', async (c, next) => {121+ * await next()122+ * if (c.error) {123+ * // do something...124+ * }125+ * })126+ * ```127+ * @see https://hono.dev/api/context#error128+ */129 error: Error | undefined = undefined130 131 #status: StatusCode = 200132 #executionCtx: FetchEventLike | ExecutionContext | undefined133 #headers: Headers | undefined = undefined134 #preparedHeaders: Record<string, string> | undefined = undefined135 #res: Response | undefined136 #isFresh = true137+ private layout: FC<PropsForRenderer & { Layout: FC }> | undefined = undefined138 private renderer: Renderer = (content: string | Promise<string>) => this.html(content)139 private notFoundHandler: NotFoundHandler<E> = () => new Response()140 141 constructor(req: HonoRequest<P, I['out']>, options?: ContextOptions<E>) {6 unmodified lines148 }149 }150 }151 152+ /**153+ * @see https://hono.dev/api/context#event154+ */155 get event(): FetchEventLike {156 if (this.#executionCtx && 'respondWith' in this.#executionCtx) {157 return this.#executionCtx158 } else {159 throw Error('This context has no FetchEvent')160 }161 }162 163+ /**164+ * @see https://hono.dev/api/context#executionctx165+ */166 get executionCtx(): ExecutionContext {167 if (this.#executionCtx) {168 return this.#executionCtx as ExecutionContext169 } else {170 throw Error('This context has no ExecutionContext')171 }172 }173 174+ /**175+ * @see https://hono.dev/api/context#res176+ */177 get res(): Response {178 this.#isFresh = false179 return (this.#res ||= new Response('404 Not Found', { status: 404 }))180 }17 unmodified lines198 this.#res = _res199 this.finalized = true200 }201 202+ /**203+ * `.render()` can create a response within a layout.204+ * @example205+ * ```ts206+ * app.get('/', (c) => {207+ * return c.render('Hello!')208+ * })209+ * ```210+ * @see https://hono.dev/api/context#render-setrenderer211+ */212 // eslint-disable-next-line @typescript-eslint/ban-ts-comment213 // @ts-ignore214 // eslint-disable-next-line @typescript-eslint/no-explicit-any215 render: Renderer = (...args: any[]) => this.renderer(...args)216 217+ /**218+ * `.setRenderer()` can set the layout in the custom middleware.219+ * @example220+ * ```tsx221+ * app.use('*', async (c, next) => {222+ * c.setRenderer((content) => {223+ * return c.html(224+ * <html>225+ * <body>226+ * <p>{content}</p>227+ * </body>228+ * </html>229+ * )230+ * })231+ * await next()232+ * })233+ * ```234+ * @see https://hono.dev/api/context#render-setrenderer235+ */236+ // @ts-expect-error It is unknown how many arguments the renderer will receive.237+ // eslint-disable-next-line @typescript-eslint/no-explicit-any238+ render: Renderer = (...args: any[]) => this.renderer(...args)239+240+ setLayout = (layout: FC<PropsForRenderer & { Layout: FC }>) => (this.layout = layout)241+ getLayout = () => this.layout242+243 setRenderer = (renderer: Renderer) => {244 this.renderer = renderer245 }246 247+ /**248+ * `.header()` can set headers.249+ * @example250+ * ```ts251+ * app.get('/welcome', (c) => {252+ * // Set headers253+ * c.header('X-Message', 'Hello!')254+ * c.header('Content-Type', 'text/plain')255+ *256+ * return c.body('Thank you for coming')257+ * })258+ * ```259+ * @see https://hono.dev/api/context#body260+ */261 header = (name: string, value: string | undefined, options?: { append?: boolean }): void => {262 // Clear the header263 if (value === undefined) {264 if (this.#headers) {36 unmodified lines301 this.#isFresh = false302 this.#status = status303 }304 305+ /**306+ * `.set()` can set the value specified by the key.307+ * @example308+ * ```ts309+ * app.use('*', async (c, next) => {310+ * c.set('message', 'Hono is cool!!')311+ * await next()312+ * })313+ * ```314+ * @see https://hono.dev/api/context#set-get315+```316+ */317 set: Set<E> = (key: string, value: unknown) => {318 this._var ??= {}319 this._var[key as string] = value320 }321 322+ /**323+ * `.get()` can use the value specified by the key.324+ * @example325+ * ```ts326+ * app.get('/', (c) => {327+ * const message = c.get('message')328+ * return c.text(`The message is "${message}"`)329+ * })330+ * ```331+ * @see https://hono.dev/api/context#set-get332+ */333 get: Get<E> = (key: string) => {334 return this._var ? this._var[key] : undefined335 }336 337+ /**338+ * `.var` can access the value of a variable.339+ * @example340+ * ```ts341+ * const result = c.var.client.oneMethod()342+ * ```343+ * @see https://hono.dev/api/context#var344+ */345 // c.var.propName is a read-only230- get var(): Readonly<E['Variables'] & ContextVariableMap> {346+ get var(): Readonly<347+ // eslint-disable-next-line @typescript-eslint/no-explicit-any348+ ContextVariableMap & (IsAny<E['Variables']> extends true ? Record<string, any> : E['Variables'])349+ > {350 return { ...this._var } as never351 }352 353 newResponse: NewResponse = (46 unmodified lines400 headers: this.#headers,401 })402 }403 404+ /**405+ * `.body()` can return the HTTP response.406+ * You can set headers with `.header()` and set HTTP status code with `.status`.407+ * This can also be set in `.text()`, `.json()` and so on.408+ * @example409+ * ```ts410+ * app.get('/welcome', (c) => {411+ * // Set headers412+ * c.header('X-Message', 'Hello!')413+ * c.header('Content-Type', 'text/plain')414+ * // Set HTTP status code415+ * c.status(201)416+ *417+ * // Return the response body418+ * return c.body('Thank you for coming')419+ * })420+ * ```421+ * @see https://hono.dev/api/context#body422+ */423 body: BodyRespond = (424 data: Data | null,425 arg?: StatusCode | ResponseInit,426 headers?: HeaderRecord2 unmodified lines429 ? this.newResponse(data, arg, headers)430 : this.newResponse(data, arg)431 }432 433+ /**434+ * `.text()` can render text as `Content-Type:text/plain`.435+ * @example436+ * ```ts437+ * app.get('/say', (c) => {438+ * return c.text('Hello!')439+ * })440+ * ```441+ * @see https://hono.dev/api/context#text442+ */443 text: TextRespond = (444 text: string,445 arg?: StatusCode | ResponseInit,446 headers?: HeaderRecord11 unmodified lines458 ? this.newResponse(text, arg, headers)459 : this.newResponse(text, arg)460 }461 462+ /**463+ * `.json()` can render JSON as `Content-Type:application/json`.464+ * @example465+ * ```ts466+ * app.get('/api', (c) => {467+ * return c.json({ message: 'Hello!' })468+ * })469+ * ```470+ * @see https://hono.dev/api/context#json471+ */472 json: JSONRespond = <T>(473 object: InterfaceToType<T> extends JSONValue ? T : JSONValue,474 arg?: StatusCode | ResponseInit,475 headers?: HeaderRecord13 unmodified lines489 typeof arg === 'number' ? this.newResponse(body, arg, headers) : this.newResponse(body, arg)490 ) as any491 }492 335- /**336- * @deprecated337- * `c.jsonT()` will be removed in v4.338- * Use `c.json()` instead of `c.jsonT()`.339- * `c.json()` now returns data type, so you can just replace `c.jsonT()` to `c.json()`.340- */341- jsonT: JSONRespond = <T>(342- object: InterfaceToType<T> extends JSONValue ? T : JSONValue,343- arg?: StatusCode | ResponseInit,344- headers?: HeaderRecord345- ): Response &346- TypedResponse<347- InterfaceToType<T> extends JSONValue348- ? JSONValue extends InterfaceToType<T>349- ? never350- : T351- : never352- > => {353- // eslint-disable-next-line @typescript-eslint/no-explicit-any354- return this.json(object, arg as any, headers) as any355- }356-493 html: HTMLRespond = (494 html: string | Promise<string>,495 arg?: StatusCode | ResponseInit,496 headers?: HeaderRecord20 unmodified lines517 ? this.newResponse(html as string, arg, headers)518 : this.newResponse(html as string, arg)519 }520 521+ /**522+ * `.redirect()` can Redirect, default status code is 302.523+ * @example524+ * ```ts525+ * app.get('/redirect', (c) => {526+ * return c.redirect('/')527+ * })528+ * app.get('/redirect-permanently', (c) => {529+ * return c.redirect('/', 301)530+ * })531+ * ```532+ * @see https://hono.dev/api/context#redirect533+ */385- redirect = (location: string, status: StatusCode = 302): Response => {534+ redirect = (location: string, status: RedirectStatusCode = 302): Response => {535 this.#headers ??= new Headers()536 this.#headers.set('Location', location)537 return this.newResponse(null, status)538 }539 391- /** @deprecated392- * Use `streamText()` in `hono/streaming` instead of `c.streamText()`. The `c.streamText()` will be removed in v4.393- */394- streamText = (395- cb: (stream: StreamingApi) => Promise<void>,396- arg?: StatusCode | ResponseInit,397- headers?: HeaderRecord398- ): Response => {399- headers ??= {}400- this.header('content-type', TEXT_PLAIN)401- this.header('x-content-type-options', 'nosniff')402- this.header('transfer-encoding', 'chunked')403- return this.stream(cb, arg, headers)404- }405-406- /** @deprecated407- * Use `stream()` in `hono/streaming` instead of `c.stream()`. The `c.stream()` will be removed in v4.408- */409- stream = (410- cb: (stream: StreamingApi) => Promise<void>,411- arg?: StatusCode | ResponseInit,412- headers?: HeaderRecord413- ): Response => {414- const { readable, writable } = new TransformStream()415- const stream = new StreamingApi(writable, readable)416- cb(stream).finally(() => stream.close())417-418- return typeof arg === 'number'419- ? this.newResponse(stream.responseReadable, arg, headers)420- : this.newResponse(stream.responseReadable, arg)421- }422-423- /** @deprecated424- * Use Cookie Middleware instead of `c.cookie()`. The `c.cookie()` will be removed in v4.425- *540+ /**541+ * `.notFound()` can return the Not Found Response.542 * @example427- *428- * import { setCookie } from 'hono/cookie'429- * // ...430- * app.get('/', (c) => {431- * setCookie(c, 'key', 'value')432- * //...543+ * ```ts544+ * app.get('/notfound', (c) => {545+ * return c.notFound()546 * })547+ * ```548+ * @see https://hono.dev/api/context#notfound549 */435- cookie = (name: string, value: string, opt?: CookieOptions): void => {436- const cookie = serialize(name, value, opt)437- this.header('set-cookie', cookie, { append: true })438- }439-550 notFound = (): Response | Promise<Response> => {441- // eslint-disable-next-line @typescript-eslint/ban-ts-comment442- // @ts-ignore551 return this.notFoundHandler(this)552 }445-446- /** @deprecated447- * Use `getRuntimeKey()` exported from `hono/adapter` instead of `c.runtime()`. The `c.runtime()` will be removed in v4.448- *449- * @example450- *451- * import { getRuntimeKey } from 'hono/adapter'452- * // ...453- * app.get('/', (c) => {454- * const key = getRuntimeKey()455- * //...456- * })457- */458- get runtime(): Runtime {459- // eslint-disable-next-line @typescript-eslint/no-explicit-any460- const global = globalThis as any461-462- if (global?.Deno !== undefined) {463- return 'deno'464- }465-466- if (global?.Bun !== undefined) {467- return 'bun'468- }469-470- if (typeof global?.WebSocketPair === 'function') {471- return 'workerd'472- }473-474- if (typeof global?.EdgeRuntime === 'string') {475- return 'edge-light'476- }477-478- if (global?.fastly !== undefined) {479- return 'fastly'480- }481-482- if (global?.__lagon__ !== undefined) {483- return 'lagon'484- }485-486- if (global?.process?.release?.name === 'node') {487- return 'node'488- }489-490- return 'other'491- }553 }modified:deno_dist/helper.ts+2 added
1 // This file is for Deno to import helpers from `hono/helper.ts`.2+export * from './helper/accepts/index.ts'3 export * from './helper/adapter/index.ts'4 export * from './helper/cookie/index.ts'5 export * from './helper/css/index.ts'6 export * from './helper/factory/index.ts'7 export * from './helper/html/index.ts'8 export * from './helper/streaming/index.ts'9 export * from './helper/testing/index.ts'10 export * from './helper/dev/index.ts'11+export * from './adapter/deno/ssg.ts'modified:deno_dist/hono-base.ts+94 added-59 removed
23 unmodified lines24 import { getPath, getPathNoStrict, getQueryStrings, mergePath } from './utils/url.ts'25 26 export const COMPOSED_HANDLER = Symbol('composedHandler')27 28-type Methods = typeof METHODS[number] | typeof METHOD_NAME_ALL_LOWERCASE28+type Methods = (typeof METHODS)[number] | typeof METHOD_NAME_ALL_LOWERCASE29 30 function defineDynamicClass(): {31 new <E extends Env = Env, S extends Schema = {}, BasePath extends string = '/'>(): {32 [M in Methods]: HandlerInterface<E, M, S, BasePath>14 unmodified lines47 if (err instanceof HTTPException) {48 return err.getResponse()49 }50 console.error(err)51- const message = 'Internal Server Error'52- return c.text(message, 500)51+ return c.text('Internal Server Error', 500)52 }53 54 type GetPath<E extends Env> = (request: Request, options?: { env?: E['Bindings'] }) => string55 56 export type HonoOptions<E extends Env> = {57+ /**58+ * `strict` option specifies whether to distinguish whether the last path is a directory or not.59+ * @default true60+ * @see https://hono.dev/api/hono#strict-mode61+ */62 strict?: boolean63+ /**64+ * `router` option specifices which router to use.65+ * ```ts66+ * const app = new Hono({ router: new RegExpRouter() })67+ * ```68+ * @see https://hono.dev/api/hono#router-option69+ */70 router?: Router<[H, RouterRoute]>71+ /**72+ * `getPath` can handle the host header value.73+ * @example74+ * ```ts75+ * const app = new Hono({76+ * getPath: (req) =>77+ * '/' + req.headers.get('host') + req.url.replace(/^https?:\/\/[^/]+(\/[^?]*)/, '$1'),78+ * })79+ *80+ * app.get('/www1.example.com/hello', () => c.text('hello www1'))81+ *82+ * // A following request will match the route:83+ * // new Request('http://www1.example.com/hello', {84+ * // headers: { host: 'www1.example.com' },85+ * // })86+ * ```87+ * @see https://hono.dev/api/routing#routing-with-host-header-value88+ */89 getPath?: GetPath<E>90 }91 92 class Hono<35 unmodified lines128 }129 })130 131 // Implementation of app.on(method, path, ...handlers[])103- this.on = (method: string | string[], path: string, ...handlers: H[]) => {132+ this.on = (method: string | string[], path: string | string[], ...handlers: H[]) => {133 if (!method) {134 return this135 }136+ for (const p of [path].flat()) {107- this.#path = path108- for (const m of [method].flat()) {109- handlers.map((handler) => {110- this.addRoute(m.toUpperCase(), this.#path, handler)111- })137+ this.#path = p138+ for (const m of [method].flat()) {139+ handlers.map((handler) => {140+ this.addRoute(m.toUpperCase(), this.#path, handler)141+ })142+ }143 }144 // eslint-disable-next-line @typescript-eslint/no-explicit-any145 return this as any146 }3 unmodified lines150 this.use = (arg1: string | MiddlewareHandler<any>, ...handlers: MiddlewareHandler<any>[]) => {151 if (typeof arg1 === 'string') {152 this.#path = arg1153 } else {154+ this.#path = '*'155 handlers.unshift(arg1)156 }157 handlers.map((handler) => {158 this.addRoute(METHOD_NAME_ALL, this.#path, handler)50 unmodified lines209 })210 return this211 }212 213+ /**214+ * `.basePath()` allows base paths to be specified.215+ * @example216+ * ```ts217+ * const api = new Hono().basePath('/api')218+ * ```219+ * @see https://hono.dev/api/routing#base-path220+ */221 basePath<SubPath extends string>(path: SubPath): Hono<E, S, MergePath<BasePath, SubPath>> {222 const subApp = this.clone()223 subApp._basePath = mergePath(this._basePath, path)224 return subApp225 }226 227+ /**228+ * `.onError()` handles an error and returns a customized Response.229+ * ```ts230+ * app.onError((err, c) => {231+ * console.error(`${err}`)232+ * return c.text('Custom Error Message', 500)233+ * })234+ * ```235+ */236 onError = (handler: ErrorHandler<E>) => {237 this.errorHandler = handler238 return this239 }240 241+ /**242+ * `.notFound()` allows you to customize a Not Found Response.243+ * ```ts244+ * app.notFound((c) => {245+ * return c.text('Custom 404 Message', 404)246+ * })247+ * ```248+ * @see https://hono.dev/api/hono#not-found249+ */250 notFound = (handler: NotFoundHandler<E>) => {251 this.notFoundHandler = handler252 return this253 }254 197- /**198- * @deprecated199- * Use `showRoutes()` utility methods provided by 'hono/dev' instead of `app.showRoutes()`.200- * `app.showRoutes()` will be removed in v4.201- * @example202- * You could rewrite `app.showRoutes()` as follows203- * import { showRoutes } from 'hono/dev'204- * showRoutes(app)205- */206- showRoutes() {207- const length = 8208- this.routes.map((route) => {209- console.log(210- `\x1b[32m${route.method}\x1b[0m ${' '.repeat(length - route.method.length)} ${route.path}`211- )212- })213- }214-255 mount(256 path: string,257 // eslint-disable-next-line @typescript-eslint/no-explicit-any258 applicationHandler: (request: Request, ...args: any) => Response | Promise<Response>,28 unmodified lines287 this.addRoute(METHOD_NAME_ALL, mergePath(path, '*'), handler)288 return this289 }290 251- /**252- * @deprecated253- * `app.routerName()` will be removed in v4.254- * Use `getRouterName()` in `hono/dev` instead of `app.routerName()`.255- */256- get routerName() {257- this.matchRoute('GET', '/')258- return this.router.name259- }260-261- /**262- * @deprecated263- * `app.head()` is no longer used.264- * `app.get()` implicitly handles the HEAD method.265- */266- head = () => {267- console.warn('`app.head()` is no longer used. `app.get()` implicitly handles the HEAD method.')268- return this269- }270-291 private addRoute(method: string, path: string, handler: H) {292 method = method.toUpperCase()293 path = mergePath(this._basePath, path)294 const r: RouterRoute = { path: path, method: method, handler: handler }36 unmodified lines331 // Do not `compose` if it has only one handler332 if (matchResult[0].length === 1) {333 let res: ReturnType<H>334 try {315- res = matchResult[0][0][0][0](c, async () => {316- c.res = await this.notFoundHandler(c)317- })335+ res = matchResult[0][0][0][0](c, async () => {})336+ if (!res) {337+ return this.notFoundHandler(c)338+ }339 } catch (err) {340 return this.handleError(err, c)341 }342 16 unmodified lines359 throw new Error(360 'Context is not finalized. You may forget returning Response object or `await next()`'361 )362 }363+364 return context.res365 } catch (err) {366 return this.handleError(err, c)367 }368 })()369 }370 371 /**350- * @deprecated351- * `app.handleEvent()` will be removed in v4.352- * Use `app.fetch()` instead of `app.handleEvent()`.372+ * `.fetch()` will be entry point of your app.373+ * @see https://hono.dev/api/hono#fetch374 */354- handleEvent = (event: FetchEventLike) => {355- return this.dispatch(event.request, event, undefined, event.request.method)356- }357-375 fetch = (request: Request, Env?: E['Bindings'] | {}, executionCtx?: ExecutionContext) => {376 return this.dispatch(request, executionCtx, Env, request.method)377 }378 379+ /**380+ * `.request()` is a useful method for testing.381+ * You can pass a URL or pathname to send a GET request.382+ * app will return a Response object.383+ * ```ts384+ * test('GET /hello is ok', async () => {385+ * const res = await app.request('/hello')386+ * expect(res.status).toBe(200)387+ * })388+ * ```389+ * @see https://hono.dev/api/hono#request390+ */391 request = (392 input: RequestInfo | URL,393 requestInit?: RequestInit,394 Env?: E['Bindings'] | {},10 unmodified lines405 const req = new Request(path, requestInit)406 return this.fetch(req, Env, executionCtx)407 }408 409+ /**410+ * `.fire()` automatically adds a global fetch event listener.411+ * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.412+ * @see https://hono.dev/api/hono#fire413+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API414+ * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/415+ */416 fire = () => {381- // eslint-disable-next-line @typescript-eslint/ban-ts-comment382- // @ts-ignore417+ // @ts-expect-error `event` is not the type expected by addEventListener418 addEventListener('fetch', (event: FetchEventLike): void => {419 event.respondWith(this.dispatch(event.request, event, undefined, event.request.method))420 })421 }3 unmodified linesmodified:deno_dist/hono.ts+2 added-2 removed
1 unmodified line2 import type { HonoOptions } from './hono-base.ts'3 import { RegExpRouter } from './router/reg-exp-router/index.ts'4 import { SmartRouter } from './router/smart-router/index.ts'5 import { TrieRouter } from './router/trie-router/index.ts'6-import type { Env, Schema } from './types.ts'6+import type { BlankSchema, Env, Schema } from './types.ts'7 8 export class Hono<9 E extends Env = Env,10- S extends Schema = {},10+ S extends Schema = BlankSchema,11 BasePath extends string = '/'12 > extends HonoBase<E, S, BasePath> {13 constructor(options: HonoOptions<E> = {}) {14 super(options)7 unmodified linesmodified:deno_dist/http-exception.ts+18 added
3 unmodified lines4 res?: Response5 message?: string6 }7 8+/**9+ * `HTTPException` must be used when a fatal error such as authentication failure occurs.10+ * @example11+ * ```ts12+ * import { HTTPException } from 'hono/http-exception'13+ *14+ * // ...15+ *16+ * app.post('/auth', async (c, next) => {17+ * // authentication18+ * if (authorized === false) {19+ * throw new HTTPException(401, { message: 'Custom error message' })20+ * }21+ * await next()22+ * })23+ * ```24+ * @see https://hono.dev/api/exception25+ */26 export class HTTPException extends Error {27 readonly res?: Response28 readonly status: StatusCode29 constructor(status: StatusCode = 500, options?: HTTPExceptionOptions) {13 unmodified linesmodified:deno_dist/middleware.ts-2 removed
1 // This file is for Deno to import middleware from `hono/middleware.ts`.2 export * from './middleware/basic-auth/index.ts'3 export * from './middleware/bearer-auth/index.ts'4 export * from './middleware/cache/index.ts'5-export * from './helper/cookie/index.ts' // will be moved to helper.ts in v45 export * from './middleware/compress/index.ts'6 export * from './middleware/cors/index.ts'7 export * from './middleware/csrf/index.ts'8 export * from './middleware/etag/index.ts'10-export * from './helper/html/index.ts' // will be moved to helper.ts in v49 export * from './jsx/index.ts'10 export * from './middleware/jsx-renderer/index.ts'11 export { jwt } from './middleware/jwt/index.ts'12 export * from './middleware/logger/index.ts'5 unmodified linesmodified:deno_dist/README.md+2 added-2 removed
24 unmodified lines25 [](https://doc.deno.land/https/deno.land/x/hono/mod.ts)26 [](https://discord.gg/KMh2eNSdxV)27 28 Hono - _**\[炎\] means flame🔥 in Japanese**_ - is a small, simple, and ultrafast web framework for the Edges.29-It works on any JavaScript runtime: Cloudflare Workers, Fastly Compute, Deno, Bun, Vercel, Lagon, AWS Lambda, Lambda@Edge, and Node.js.29+It works on any JavaScript runtime: Cloudflare Workers, Fastly Compute, Deno, Bun, Vercel, AWS Lambda, Lambda@Edge, and Node.js.30 31 Fast, but not only fast.32 33 ```ts14 unmodified lines48 ## Features49 50 - **Ultrafast** 🚀 - The router `RegExpRouter` is really fast. Not using linear loops. Fast.51 - **Lightweight** 🪶 - The `hono/tiny` preset is under 14kB. Hono has zero dependencies and uses only the Web Standard API.52-- **Multi-runtime** 🌍 - Works on Cloudflare Workers, Fastly Compute, Deno, Bun, Lagon, AWS Lambda, Lambda@Edge, or Node.js. The same code runs on all platforms.52+- **Multi-runtime** 🌍 - Works on Cloudflare Workers, Fastly Compute, Deno, Bun, AWS Lambda, Lambda@Edge, or Node.js. The same code runs on all platforms.53 - **Batteries Included** 🔋 - Hono has built-in middleware, custom middleware, and third-party middleware. Batteries included.54 - **Delightful DX** 😃 - Super clean APIs. First-class TypeScript support. Now, we've got "Types".55 56 ## Benchmarks49 unmodified linesmodified:deno_dist/request.ts+158 added-91 removed
10 unmodified lines11 RouterRoute,12 } from './types.ts'13 import { parseBody } from './utils/body.ts'14 import type { BodyData, ParseBodyOptions } from './utils/body.ts'15-import type { Cookie } from './utils/cookie.ts'16-import { parse } from './utils/cookie.ts'15 import type { UnionToIntersection } from './utils/types.ts'16 import { getQueryParam, getQueryParams, decodeURIComponent_ } from './utils/url.ts'17 18 type Body = {5 unmodified lines24 }25 type BodyCache = Partial<Body & { parsedBody: BodyData }>26 27 export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {28+ /**29+ * `.raw` can get the raw Request object.30+ * @example31+ * ```ts32+ * // For Cloudflare Workers33+ * app.post('/', async (c) => {34+ * const metadata = c.req.raw.cf?.hostMetadata?35+ * ...36+ * })37+ * ```38+ * @see https://hono.dev/api/request#raw39+ */40 raw: Request41 42 #validatedData: { [K in keyof ValidationTargets]?: {} } // Short name of validatedData43 #matchResult: Result<[unknown, RouterRoute]>44 routeIndex: number = 045+ /**46+ * `.path` can get the pathname of the request.47+ * @example48+ * ```ts49+ * app.get('/about/me', (c) => {50+ * const pathname = c.req.path // `/about/me`51+ * })52+ * ```53+ * @see https://hono.dev/api/request#path54+ */55 path: string56 bodyCache: BodyCache = {}57 58 constructor(6 unmodified lines65 this.#matchResult = matchResult66 this.#validatedData = {}67 }68 69+ /**70+ * `.req.param()` gets the path parameters.71+ * @example72+ * ```ts73+ * const name = c.req.param('name')74+ * // or all parameters at once75+ * const { id, comment_id } = c.req.param()76+ * ```77+ * @see https://hono.dev/api/routing#path-parameter78+ */79 param<P2 extends string = P>(80 key: RemoveQuestion<ParamKeys<P2>>81 ): UndefinedIfHavingQuestion<ParamKeys<P2>>82 param<P2 extends string = P>(): UnionToIntersection<ParamKeyToRecord<ParamKeys<P2>>>25 unmodified lines108 private getParamValue(paramKey: any): string | undefined {109 return this.#matchResult[1] ? this.#matchResult[1][paramKey as any] : paramKey110 }111 112+ /**113+ * `.query()` can get querystring parameters.114+ * @example115+ * ```ts116+ * // Query params117+ * app.get('/search', (c) => {118+ * const query = c.req.query('q')119+ * })120+ *121+ * // Get all params at once122+ * app.get('/search', (c) => {123+ * const { q, limit, offset } = c.req.query()124+ * })125+ * ```126+ * @see https://hono.dev/api/request#query127+ */128 query(key: string): string | undefined129 query(): Record<string, string>130 query(key?: string) {131 return getQueryParam(this.url, key)132 }133 134+ /**135+ * `.queries()` can get multiple querystring parameter values, e.g. /search?tags=A&tags=B136+ * @example137+ * ```ts138+ * app.get('/search', (c) => {139+ * // tags will be string[]140+ * const tags = c.req.queries('tags')141+ * })142+ * ```143+ * @see https://hono.dev/api/request#queries144+ */145 queries(key: string): string[] | undefined146 queries(): Record<string, string[]>147 queries(key?: string) {148 return getQueryParams(this.url, key)149 }150 151+ /**152+ * `.header()` can get the request header value.153+ * @example154+ * ```ts155+ * app.get('/', (c) => {156+ * const userAgent = c.req.header('User-Agent')157+ * })158+ * ```159+ * @see https://hono.dev/api/request#header160+ */161 header(name: string): string | undefined162 header(): Record<string, string>163 header(name?: string) {164 if (name) {6 unmodified lines171 })172 return headerData173 }174 108- /** @deprecated109- * Use Cookie Middleware instead of `c.req.cookie()`. The `c.req.cookie()` will be removed in v4.110- *175+ /**176+ * `.parseBody()` can parse Request body of type `multipart/form-data` or `application/x-www-form-urlencoded`177 * @example112- *113- * import { getCookie } from 'hono/cookie'114- * // ...115- * app.get('/', (c) => c.text(getCookie(c, 'cookie-name')))178+ * ```ts179+ * app.post('/entry', async (c) => {180+ * const body = await c.req.parseBody()181+ * })182+ * ```183+ * @see https://hono.dev/api/request#parsebody184 */117- cookie(key: string): string | undefined118-119- /** @deprecated120- * Use Cookie Middleware instead of `c.req.cookie()`. The `c.req.cookie()` will be removed in v4.121- *122- * @example123- *124- * import { getCookie } from 'hono/cookie'125- * // ...126- * app.get('/', (c) => c.json(getCookie(c)))127- */128- cookie(): Cookie129-130- cookie(key?: string) {131- const cookie = this.raw.headers.get('Cookie')132- if (!cookie) {133- return134- }135- const obj = parse(cookie)136- if (key) {137- const value = obj[key]138- return value139- } else {140- return obj141- }142- }143-185 async parseBody<T extends BodyData = BodyData>(options?: ParseBodyOptions): Promise<T> {186 if (this.bodyCache.parsedBody) {187 return this.bodyCache.parsedBody as T188 }19 unmodified lines208 }209 return (bodyCache[key] = raw[key]())210 }211 212+ /**213+ * `.json()` can parse Request body of type `application/json`214+ * @example215+ * ```ts216+ * app.post('/entry', async (c) => {217+ * const body = await c.req.json()218+ * })219+ * ```220+ * @see https://hono.dev/api/request#json221+ */222 json<T = any>(): Promise<T> {223 return this.cachedBody('json')224 }225 226+ /**227+ * `.text()` can parse Request body of type `text/plain`228+ * @example229+ * ```ts230+ * app.post('/entry', async (c) => {231+ * const body = await c.req.text()232+ * })233+ * ```234+ * @see https://hono.dev/api/request#text235+ */236 text(): Promise<string> {237 return this.cachedBody('text')238 }239 240+ /**241+ * `.arrayBuffer()` parse Request body as an `ArrayBuffer`242+ * @example243+ * ```ts244+ * app.post('/entry', async (c) => {245+ * const body = await c.req.arrayBuffer()246+ * })247+ * ```248+ * @see https://hono.dev/api/request#arraybuffer249+ */250 arrayBuffer(): Promise<ArrayBuffer> {251 return this.cachedBody('arrayBuffer')252 }253 13 unmodified lines267 valid(target: keyof ValidationTargets) {268 return this.#validatedData[target] as unknown269 }270 271+ /**272+ * `.url()` can get the request url strings.273+ * @example274+ * ```ts275+ * app.get('/about/me', (c) => {276+ * const url = c.req.url // `http://localhost:8787/about/me`277+ * ...278+ * })279+ * ```280+ * @see https://hono.dev/api/request#url281+ */282 get url() {283 return this.raw.url284 }285 286+ /**287+ * `.method()` can get the method name of the request.288+ * @example289+ * ```ts290+ * app.get('/about/me', (c) => {291+ * const method = c.req.method // `GET`292+ * })293+ * ```294+ * @see https://hono.dev/api/request#method295+ */296 get method() {297 return this.raw.method298 }299 300+ /**301+ * `.matchedRoutes()` can return a matched route in the handler302+ * @example303+ * ```ts304+ * app.use('*', async function logger(c, next) {305+ * await next()306+ * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {307+ * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')308+ * console.log(309+ * method,310+ * ' ',311+ * path,312+ * ' '.repeat(Math.max(10 - path.length, 0)),313+ * name,314+ * i === c.req.routeIndex ? '<- respond from here' : ''315+ * )316+ * })317+ * })318+ * ```319+ * @see https://hono.dev/api/request#matchedroutes320+ */321 get matchedRoutes(): RouterRoute[] {322 return this.#matchResult[0].map(([[, route]]) => route)323 }324 212- get routePath(): string {213- return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path214- }215-216- /** @deprecated217- * Use `c.req.raw.headers` instead of `c.req.headers`. The `c.req.headers` will be removed in v4.218- * Or you can get the header values with using `c.req.header`.325+ /**326+ * `routePath()` can retrieve the path registered within the handler327 * @example220- *221- * app.get('/', (c) => {222- * const userAgent = c.req.header('User-Agent')223- * //...328+ * ```ts329+ * app.get('/posts/:id', (c) => {330+ * return c.json({ path: c.req.routePath })331 * })332+ * ```333+ * @see https://hono.dev/api/request#routepath334 */226- get headers() {227- return this.raw.headers335+ get routePath(): string {336+ return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path337 }229-230- /** @deprecated231- * Use `c.req.raw.body` instead of `c.req.body`. The `c.req.body` will be removed in v4.232- */233- get body() {234- return this.raw.body235- }236-237- /** @deprecated238- * Use `c.req.raw.bodyUsed` instead of `c.req.bodyUsed`. The `c.req.bodyUsed` will be removed in v4.239- */240- get bodyUsed() {241- return this.raw.bodyUsed242- }243-244- /** @deprecated245- * Use `c.req.raw.integrity` instead of `c.req.integrity`. The `c.req.integrity` will be removed in v4.246- */247- get integrity() {248- return this.raw.integrity249- }250-251- /** @deprecated252- * Use `c.req.raw.keepalive` instead of `c.req.keepalive`. The `c.req.keepalive` will be removed in v4.253- */254- get keepalive() {255- return this.raw.keepalive256- }257-258- /** @deprecated259- * Use `c.req.raw.referrer` instead of `c.req.referrer`. The `c.req.referrer` will be removed in v4.260- */261- get referrer() {262- return this.raw.referrer263- }264-265- /** @deprecated266- * Use `c.req.raw.signal` instead of `c.req.signal`. The `c.req.signal` will be removed in v4.267- */268- get signal() {269- return this.raw.signal270- }338 }modified:deno_dist/types.ts+70 added-92 removed
1 unmodified line2 /* eslint-disable @typescript-eslint/no-explicit-any */3 /* eslint-disable @typescript-eslint/ban-types */4 import type { Context } from './context.ts'5 import type { Hono } from './hono.ts'6-import type { IntersectNonAnyTypes, RemoveBlankRecord, UnionToIntersection } from './utils/types.ts'6+import type { IfAnyThenEmptyObject, RemoveBlankRecord, UnionToIntersection } from './utils/types.ts'7 8 ////////////////////////////////////////9 ////// //////10 ////// Values //////14 unmodified lines25 in?: Partial<ValidationTargets>26 out?: Partial<{ [K in keyof ValidationTargets]: unknown }>27 }28 29+export type BlankSchema = {}30+export type BlankInput = {}31+32 ////////////////////////////////////////33 ////// //////34 ////// Routes //////35 ////// //////15 unmodified lines51 52 export type Handler<53 E extends Env = any,54 P extends string = any,52- I extends Input = Input,55+ I extends Input = BlankInput,56 R extends HandlerResponse<any> = any57 > = (c: Context<E, P, I>, next: Next) => R58 59 export type MiddlewareHandler<4 unmodified lines64 65 export type H<66 E extends Env = any,67 P extends string = any,65- I extends Input = {},68+ I extends Input = BlankInput,69 R extends HandlerResponse<any> = any70 > = Handler<E, P, I, R> | MiddlewareHandler<E, P, I>71 72 export type NotFoundHandler<E extends Env = any> = (c: Context<E>) => Response | Promise<Response>18 unmodified lines91 92 // app.get(handler)93 <94 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,92- I extends Input = {},95+ I extends Input = BlankInput,96 R extends HandlerResponse<any> = any,97 E2 extends Env = E98 >(99 handler: H<E2, P, I, R>5 unmodified lines105 106 // app.get(handler x2)107 <108 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,106- I extends Input = {},109+ I extends Input = BlankInput,110 I2 extends Input = I,111 R extends HandlerResponse<any> = any,112 E2 extends Env = E,113 E3 extends Env = IntersectNonAnyTypes<[E, E2]>8 unmodified lines122 // app.get(handler x 3)123 <124 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,125 R extends HandlerResponse<any> = any,123- I extends Input = {},126+ I extends Input = BlankInput,127 I2 extends Input = I,128 I3 extends Input = I & I2,129 E2 extends Env = E,130 E3 extends Env = E,9 unmodified lines140 // app.get(handler x 4)141 <142 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,143 R extends HandlerResponse<any> = any,141- I extends Input = {},144+ I extends Input = BlankInput,145 I2 extends Input = I,146 I3 extends Input = I & I2,147 I4 extends Input = I & I2 & I3,148 E2 extends Env = E,11 unmodified lines160 // app.get(handler x 5)161 <162 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,163 R extends HandlerResponse<any> = any,161- I extends Input = {},164+ I extends Input = BlankInput,165 I2 extends Input = I,166 I3 extends Input = I & I2,167 I4 extends Input = I & I2 & I3,168 I5 extends Input = I & I2 & I3 & I4,13 unmodified lines182 // app.get(handler x 6)183 <184 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,185 R extends HandlerResponse<any> = any,183- I extends Input = {},186+ I extends Input = BlankInput,187 I2 extends Input = I,188 I3 extends Input = I & I2,189 I4 extends Input = I & I2 & I3,190 I5 extends Input = I & I2 & I3 & I4,22 unmodified lines213 // app.get(handler x 7)214 <215 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,216 R extends HandlerResponse<any> = any,214- I extends Input = {},217+ I extends Input = BlankInput,218 I2 extends Input = I,219 I3 extends Input = I & I2,220 I4 extends Input = I & I2 & I3,221 I5 extends Input = I & I2 & I3 & I4,25 unmodified lines247 // app.get(handler x 8)248 <249 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,250 R extends HandlerResponse<any> = any,248- I extends Input = {},251+ I extends Input = BlankInput,252 I2 extends Input = I,253 I3 extends Input = I & I2,254 I4 extends Input = I & I2 & I3,255 I5 extends Input = I & I2 & I3 & I4,28 unmodified lines284 // app.get(handler x 9)285 <286 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,287 R extends HandlerResponse<any> = any,285- I extends Input = {},288+ I extends Input = BlankInput,289 I2 extends Input = I,290 I3 extends Input = I & I2,291 I4 extends Input = I & I2 & I3,292 I5 extends Input = I & I2 & I3 & I4,31 unmodified lines324 // app.get(handler x 10)325 <326 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,327 R extends HandlerResponse<any> = any,325- I extends Input = {},328+ I extends Input = BlankInput,329 I2 extends Input = I,330 I3 extends Input = I & I2,331 I4 extends Input = I & I2 & I3,332 I5 extends Input = I & I2 & I3 & I4,33 unmodified lines366 367 // app.get(...handlers[])368 <369 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,367- I extends Input = {},370+ I extends Input = BlankInput,371 R extends HandlerResponse<any> = any372 >(373 ...handlers: H<E, P, I, R>[]374 ): Hono<E, S & ToSchema<M, P, I['in'], MergeTypedResponseData<R>>, BasePath>13 unmodified lines388 <389 P extends string,390 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,391 R extends HandlerResponse<any> = any,389- I extends Input = {},392+ I extends Input = BlankInput,393 E2 extends Env = E394 >(395 path: P,396 handler: H<E2, MergedPath, I, R>394- ): Hono<395- IntersectNonAnyTypes<[E, E2]>,396- S & ToSchema<M, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>,397- BasePath398- >397+ ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>, BasePath>398 399 // app.get(path, handler x2)400 <401 P extends string,402 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,403 R extends HandlerResponse<any> = any,405- I extends Input = {},404+ I extends Input = BlankInput,405 I2 extends Input = I,406 E2 extends Env = E,407 E3 extends Env = IntersectNonAnyTypes<[E, E2]>408 >(409 path: P,410 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2, R>]412- ): Hono<413- IntersectNonAnyTypes<[E, E2, E3]>,414- S & ToSchema<M, MergePath<BasePath, P>, I2['in'], MergeTypedResponseData<R>>,415- BasePath416- >411+ ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I2['in'], MergeTypedResponseData<R>>, BasePath>412 413 // app.get(path, handler x3)414 <415 P extends string,416 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,417 R extends HandlerResponse<any> = any,423- I extends Input = {},418+ I extends Input = BlankInput,419 I2 extends Input = I,420 I3 extends Input = I & I2,421 E2 extends Env = E,422 E3 extends Env = E,423 E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>424 >(425 path: P,426 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2>, H<E4, MergedPath, I3, R>]432- ): Hono<433- IntersectNonAnyTypes<[E, E2, E3, E4]>,434- S & ToSchema<M, MergePath<BasePath, P>, I3['in'], MergeTypedResponseData<R>>,435- BasePath436- >427+ ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I3['in'], MergeTypedResponseData<R>>, BasePath>428 429 // app.get(path, handler x4)430 <431 P extends string,432 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,433 R extends HandlerResponse<any> = any,443- I extends Input = {},434+ I extends Input = BlankInput,435 I2 extends Input = I,436 I3 extends Input = I & I2,437 I4 extends Input = I & I2 & I3,438 E2 extends Env = E,7 unmodified lines446 H<E3, MergedPath, I2>,447 H<E4, MergedPath, I3>,448 H<E5, MergedPath, I4, R>449 ]459- ): Hono<460- IntersectNonAnyTypes<[E, E2, E3, E4, E5]>,461- S & ToSchema<M, MergePath<BasePath, P>, I4['in'], MergeTypedResponseData<R>>,462- BasePath463- >450+ ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I4['in'], MergeTypedResponseData<R>>, BasePath>451 452 // app.get(path, handler x5)453 <454 P extends string,455 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,456 R extends HandlerResponse<any> = any,470- I extends Input = {},457+ I extends Input = BlankInput,458 I2 extends Input = I,459 I3 extends Input = I & I2,460 I4 extends Input = I & I2 & I3,461 I5 extends Input = I & I2 & I3 & I4,10 unmodified lines472 H<E4, MergedPath, I3>,473 H<E5, MergedPath, I4>,474 H<E6, MergedPath, I5, R>475 ]489- ): Hono<490- IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>,491- S & ToSchema<M, MergePath<BasePath, P>, I5['in'], MergeTypedResponseData<R>>,492- BasePath493- >476+ ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I5['in'], MergeTypedResponseData<R>>, BasePath>477 478 // app.get(path, handler x6)479 <480 P extends string,481 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,482 R extends HandlerResponse<any> = any,500- I extends Input = {},483+ I extends Input = BlankInput,484 I2 extends Input = I,485 I3 extends Input = I & I2,486 I4 extends Input = I & I2 & I3,487 I5 extends Input = I & I2 & I3 & I4,13 unmodified lines501 H<E5, MergedPath, I4>,502 H<E6, MergedPath, I5>,503 H<E7, MergedPath, I6, R>504 ]522- ): Hono<523- IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>,524- S & ToSchema<M, MergePath<BasePath, P>, I6['in'], MergeTypedResponseData<R>>,525- BasePath526- >505+ ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I6['in'], MergeTypedResponseData<R>>, BasePath>506 507 // app.get(path, handler x7)508 <509 P extends string,510 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,511 R extends HandlerResponse<any> = any,533- I extends Input = {},512+ I extends Input = BlankInput,513 I2 extends Input = I,514 I3 extends Input = I & I2,515 I4 extends Input = I & I2 & I3,516 I5 extends Input = I & I2 & I3 & I4,16 unmodified lines533 H<E6, MergedPath, I5>,534 H<E7, MergedPath, I6>,535 H<E8, MergedPath, I7, R>536 ]558- ): Hono<559- IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>,560- S & ToSchema<M, MergePath<BasePath, P>, I7['in'], MergeTypedResponseData<R>>,561- BasePath562- >537+ ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I7['in'], MergeTypedResponseData<R>>, BasePath>538 539 // app.get(path, handler x8)540 <541 P extends string,542 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,543 R extends HandlerResponse<any> = any,569- I extends Input = {},544+ I extends Input = BlankInput,545 I2 extends Input = I,546 I3 extends Input = I & I2,547 I4 extends Input = I & I2 & I3,548 I5 extends Input = I & I2 & I3 & I4,19 unmodified lines568 H<E7, MergedPath, I6>,569 H<E8, MergedPath, I7>,570 H<E9, MergedPath, I8, R>571 ]597- ): Hono<598- IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>,599- S & ToSchema<M, MergePath<BasePath, P>, I8['in'], MergeTypedResponseData<R>>,600- BasePath601- >572+ ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I8['in'], MergeTypedResponseData<R>>, BasePath>573 574 // app.get(path, handler x9)575 <576 P extends string,577 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,578 R extends HandlerResponse<any> = any,608- I extends Input = {},579+ I extends Input = BlankInput,580 I2 extends Input = I,581 I3 extends Input = I & I2,582 I4 extends Input = I & I2 & I3,583 I5 extends Input = I & I2 & I3 & I4,22 unmodified lines606 H<E8, MergedPath, I7>,607 H<E9, MergedPath, I8>,608 H<E10, MergedPath, I9, R>609 ]639- ): Hono<640- IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>,641- S & ToSchema<M, MergePath<BasePath, P>, I9['in'], MergeTypedResponseData<R>>,642- BasePath643- >610+ ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I9['in'], MergeTypedResponseData<R>>, BasePath>611 612 // app.get(path, handler x10)613 <614 P extends string,615 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,616 R extends HandlerResponse<any> = any,650- I extends Input = {},617+ I extends Input = BlankInput,618 I2 extends Input = I,619 I3 extends Input = I & I2,620 I4 extends Input = I & I2 & I3,621 I5 extends Input = I & I2 & I3 & I4,26 unmodified lines648 H<E10, MergedPath, I9>,649 H<E11, MergedPath, I10, R>650 ]651 ): Hono<685- IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11]>,652+ E,653 S & ToSchema<M, MergePath<BasePath, P>, I10['in'], MergeTypedResponseData<R>>,654 BasePath655 >656 657 // app.get(path, ...handlers[])691- <P extends string, I extends Input = {}, R extends HandlerResponse<any> = any>(658+ <P extends string, I extends Input = BlankInput, R extends HandlerResponse<any> = any>(659 path: P,660 ...handlers: H<E, MergePath<BasePath, P>, I, R>[]661 ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>, BasePath>662 }217 unmodified lines880 M extends string,881 P extends string,882 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,883 R extends HandlerResponse<any> = any,917- I extends Input = {},884+ I extends Input = BlankInput,885 E2 extends Env = E886 >(887 method: M,888 path: P,9 unmodified lines898 M extends string,899 P extends string,900 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,901 R extends HandlerResponse<any> = any,935- I extends Input = {},902+ I extends Input = BlankInput,903 I2 extends Input = I,904 E2 extends Env = E,905 E3 extends Env = IntersectNonAnyTypes<[E, E2]>906 >(11 unmodified lines918 M extends string,919 P extends string,920 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,921 R extends HandlerResponse<any> = any,955- I extends Input = {},922+ I extends Input = BlankInput,923 I2 extends Input = I,924 I3 extends Input = I & I2,925 E2 extends Env = E,926 E3 extends Env = E,13 unmodified lines940 M extends string,941 P extends string,942 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,943 R extends HandlerResponse<any> = any,977- I extends Input = {},944+ I extends Input = BlankInput,945 I2 extends Input = I,946 I3 extends Input = I & I2,947 I4 extends Input = I & I2 & I3,948 E2 extends Env = E,20 unmodified lines969 M extends string,970 P extends string,971 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,972 R extends HandlerResponse<any> = any,1006- I extends Input = {},973+ I extends Input = BlankInput,974 I2 extends Input = I,975 I3 extends Input = I & I2,976 I4 extends Input = I & I2 & I3,977 I5 extends Input = I & I2 & I3 & I4,23 unmodified lines1001 M extends string,1002 P extends string,1003 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1004 R extends HandlerResponse<any> = any,1038- I extends Input = {},1005+ I extends Input = BlankInput,1006 I2 extends Input = I,1007 I3 extends Input = I & I2,1008 I4 extends Input = I & I2 & I3,1009 I5 extends Input = I & I2 & I3 & I4,26 unmodified lines1036 M extends string,1037 P extends string,1038 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1039 R extends HandlerResponse<any> = any,1073- I extends Input = {},1040+ I extends Input = BlankInput,1041 I2 extends Input = I,1042 I3 extends Input = I & I2,1043 I4 extends Input = I & I2 & I3,1044 I5 extends Input = I & I2 & I3 & I4,29 unmodified lines1074 M extends string,1075 P extends string,1076 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1077 R extends HandlerResponse<any> = any,1111- I extends Input = {},1078+ I extends Input = BlankInput,1079 I2 extends Input = I,1080 I3 extends Input = I & I2,1081 I4 extends Input = I & I2 & I3,1082 I5 extends Input = I & I2 & I3 & I4,32 unmodified lines1115 M extends string,1116 P extends string,1117 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1118 R extends HandlerResponse<any> = any,1152- I extends Input = {},1119+ I extends Input = BlankInput,1120 I2 extends Input = I,1121 I3 extends Input = I & I2,1122 I4 extends Input = I & I2 & I3,1123 I5 extends Input = I & I2 & I3 & I4,34 unmodified lines1158 <1159 M extends string,1160 P extends string,1161 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1195- I extends Input = {},1162+ I extends Input = BlankInput,1163 I2 extends Input = I,1164 I3 extends Input = I & I2,1165 I4 extends Input = I & I2 & I3,1166 I5 extends Input = I & I2 & I3 & I4,46 unmodified lines1213 Ms extends string[],1214 P extends string,1215 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1216 R extends HandlerResponse<any> = any,1250- I extends Input = {},1217+ I extends Input = BlankInput,1218 E2 extends Env = E1219 >(1220 methods: Ms,1221 path: P,9 unmodified lines1231 Ms extends string[],1232 P extends string,1233 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1234 R extends HandlerResponse<any> = any,1268- I extends Input = {},1235+ I extends Input = BlankInput,1236 I2 extends Input = I,1237 E2 extends Env = E,1238 E3 extends Env = IntersectNonAnyTypes<[E, E2]>1239 >(11 unmodified lines1251 Ms extends string[],1252 P extends string,1253 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1254 R extends HandlerResponse<any> = any,1288- I extends Input = {},1255+ I extends Input = BlankInput,1256 I2 extends Input = I,1257 I3 extends Input = I & I2,1258 E2 extends Env = E,1259 E3 extends Env = E,13 unmodified lines1273 Ms extends string[],1274 P extends string,1275 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1276 R extends HandlerResponse<any> = any,1310- I extends Input = {},1277+ I extends Input = BlankInput,1278 I2 extends Input = I,1279 I3 extends Input = I & I2,1280 I4 extends Input = I & I2 & I3,1281 E2 extends Env = E,20 unmodified lines1302 Ms extends string[],1303 P extends string,1304 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1305 R extends HandlerResponse<any> = any,1339- I extends Input = {},1306+ I extends Input = BlankInput,1307 I2 extends Input = I,1308 I3 extends Input = I & I2,1309 I4 extends Input = I & I2 & I3,1310 I5 extends Input = I & I2 & I3 & I4,23 unmodified lines1334 Ms extends string[],1335 P extends string,1336 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1337 R extends HandlerResponse<any> = any,1371- I extends Input = {},1338+ I extends Input = BlankInput,1339 I2 extends Input = I,1340 I3 extends Input = I & I2,1341 I4 extends Input = I & I2 & I3,1342 I5 extends Input = I & I2 & I3 & I4,26 unmodified lines1369 Ms extends string[],1370 P extends string,1371 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1372 R extends HandlerResponse<any> = any,1406- I extends Input = {},1373+ I extends Input = BlankInput,1374 I2 extends Input = I,1375 I3 extends Input = I & I2,1376 I4 extends Input = I & I2 & I3,1377 I5 extends Input = I & I2 & I3 & I4,29 unmodified lines1407 Ms extends string[],1408 P extends string,1409 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1410 R extends HandlerResponse<any> = any,1444- I extends Input = {},1411+ I extends Input = BlankInput,1412 I2 extends Input = I,1413 I3 extends Input = I & I2,1414 I4 extends Input = I & I2 & I3,1415 I5 extends Input = I & I2 & I3 & I4,31 unmodified lines1447 <1448 Ms extends string[],1449 P extends string,1450 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1484- I extends Input = {},1451+ I extends Input = BlankInput,1452 I2 extends Input = I,1453 I3 extends Input = I & I2,1454 I4 extends Input = I & I2 & I3,1455 I5 extends Input = I & I2 & I3 & I4,40 unmodified lines1496 <1497 Ms extends string[],1498 P extends string,1499 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1533- I extends Input = {},1500+ I extends Input = BlankInput,1501 I2 extends Input = I,1502 I3 extends Input = I & I2,1503 I4 extends Input = I & I2 & I3,1504 I5 extends Input = I & I2 & I3 & I4,48 unmodified lines1553 E,1554 S & ToSchema<string, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>,1555 BasePath1556 >1557+1558+ // app.on(method | method[], path[], ...handlers[])1559+ <I extends Input = BlankInput, R extends HandlerResponse<any> = any>(1560+ methods: string | string[],1561+ paths: string[],1562+ ...handlers: H<E, any, I, R>[]1563+ ): Hono<E, S & ToSchema<string, string, I['in'], MergeTypedResponseData<R>>, BasePath>1564 }1565 1566 type ExtractKey<S> = S extends Record<infer Key, unknown>1567 ? Key extends string109 unmodified lines1677 export type ValidationTargets = {1678 json: any1679 form: Record<string, string | File>1680 query: Record<string, string | string[]>1707- queries: Record<string, string[]> // Deprecated. Will be obsolete in v4.1681 param: Record<string, string>1682 header: Record<string, string>1683 cookie: Record<string, string>1684 }50 unmodified lines1735 export type ExtractSchema<T> = UnionToIntersection<1736 T extends Hono<infer _, infer S, any> ? S : never1737 >1738 1739+type EnvOrEmpty<T> = T extends Env ? (Env extends T ? {} : T) : T1740+type IntersectNonAnyTypes<T extends any[]> = T extends [infer Head, ...infer Rest]1741+ ? IfAnyThenEmptyObject<EnvOrEmpty<Head>> & IntersectNonAnyTypes<Rest>1742+ : {}1743+1744 ////////////////////////////////////////1745 ////// //////1746 ////// FetchEvent //////1747 ////// //////8 unmodified linesmodified:docs/CONTRIBUTING.md+17 added-1 removed
16 unmodified lines17 18 Although, don't worry!19 Hono is tested well, polished by the contributors, and used by many developers. And I'll try my best to make Hono cool, beautiful, and ultrafast.20 21+## Installing dependencies22+23+The `honojs/hono` project uses [Bun](https://bun.sh/) as its package manager. Developers should install Bun.24+25+After that, please install the dependency environment.26+27+```txt28+bun install29+```30+31+If you can't do that, there is also a `yarn.lock` file, so you can do the same with the `yarn` command.32+33+```txt34+yarn install --frozen-lockfile35+```36+37 ## PRs38 23-Please ensure your PR passes tests with `yarn test:all`. Also please ensure the Deno code is generated with `yarn denoify`.39+Please ensure your PR passes tests with `bun run test` or `yarn test`. Also please ensure the Deno code is generated with `yarn denoify`.40 41 ## Third-party middleware42 43 Third-party middleware is not in the core.19 unmodified linesmodified:docs/MIGRATION.md+38 added
1 # Migration Guide2 3+## v3.12.x to v4.0.04+5+There are some breaking changes.6+7+### Removal of deprecated features8+9+- AWS Lambda Adapter - `LambdaFunctionUrlRequestContext` is obsolete. Use `ApiGatewayRequestContextV2` instead.10+- Next.js Adapter - `hono/nextjs` is obsolete. Use `hono/vercel` instead.11+- Context - `c.jsonT()` is obsolete. Use `c.json()` instead.12+- Context - `c.stream()` and `c.streamText()` are obsolete. Use `stream()` and `streamText()` in `hono/streaming` instead.13+- Context - `c.env()` is obsolete. Use `getRuntimeKey()` in `hono/adapter` instead.14+- Hono - `app.showRoutes()` is obsolete. Use `showRoutes()` in `hono/dev` instead.15+- Hono - `app.routerName` is obsolete. Use `getRouterName()` in `hono/dev` instead.16+- Hono - `app.head()` is no longer used. `app.get()` implicitly handles the HEAD method.17+- Hono - `app.handleEvent()` is obsolete. Use `app.fetch()` instead.18+- HonoRequest - `req.cookie()` is obsolete. Use `getCookie()` in `hono/cookie` instead.19+- HonoRequest - `headers()`, `body()`, `bodyUsed()`, `integrity()`, `keepalive()`, `referrer()`, and `signal()` are obsolete. Use the methods in `req.raw` such as `req.raw.headers()`.20+21+### `serveStatic` in Cloudflare Workers Adapter requires `manifest`22+23+If you use the Cloudflare Workers adapter's `serve-static`, you should specify the `manifest` option.24+25+```ts26+import manifest from '__STATIC_CONTENT_MANIFEST'27+28+// ...29+30+app.use('/static/*', serveStatic({ root: './assets', manifest }))31+```32+33+### Others34+35+- The default value of `docType` option in JSX Renderer Middleware is now `true`.36+- `FC` in `hono/jsx` does not pass `children`. Use `PropsWithChildren`.37+- Some Mime Types are removed https://github.com/honojs/hono/pull/2119.38+- Types for chaining routes with middleware matter: https://github.com/honojs/hono/pull/2046.39+- Types for the validator matter: https://github.com/honojs/hono/pull/2130.40+41 ## v2.7.8 to v3.0.042 43 There are some breaking changes.44 In addition to the following, type mismatches may occur.233 unmodified linesmodified:runtime_tests/bun/index.test.tsx+64 added-3 removed
1-import { describe, expect, it, mock, beforeEach } from 'bun:test'2-import { serveStatic } from '../../src/adapter/bun'1+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest'2+import { serveStatic, toSSG } from '../../src/adapter/bun'3 import { Context } from '../../src/context'4 import { env, getRuntimeKey } from '../../src/helper/adapter'5 import { Hono } from '../../src/index'6 // eslint-disable-next-line @typescript-eslint/no-unused-vars70 unmodified lines77 })78 79 describe('Serve Static Middleware', () => {80 const app = new Hono()81- const onNotFound = mock(() => {})81+ const onNotFound = vi.fn(() => {})82 app.all('/favicon.ico', serveStatic({ path: './runtime_tests/bun/favicon.ico' }))83 app.all(84 '/favicon-notfound.ico',85 serveStatic({ path: './runtime_tests/bun/favicon-notfound.ico', onNotFound })122 unmodified lines208 expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')209 expect(await res.text()).toBe('<html><p>hello</p></html>')210 })211 })212+213+describe('toSSG function', () => {214+ let app: Hono215+216+ beforeEach(() => {217+ app = new Hono()218+ app.get('/', (c) => c.text('Hello, World!'))219+ app.get('/about', (c) => c.text('About Page'))220+ app.get('/about/some', (c) => c.text('About Page 2tier'))221+ app.post('/about/some/thing', (c) => c.text('About Page 3tier'))222+ app.get('/bravo', (c) => c.html('Bravo Page'))223+ app.get('/Charlie', async (c, next) => {224+ c.setRenderer((content, head) => {225+ return c.html(226+ <html>227+ <head>228+ <title>{head.title || ''}</title>229+ </head>230+ <body>231+ <p>{content}</p>232+ </body>233+ </html>234+ )235+ })236+ await next()237+ })238+ app.get('/Charlie', (c) => {239+ return c.render('Hello!', { title: 'Charlies Page' })240+ })241+ })242+243+ it('Should correctly generate static HTML files for Hono routes', async () => {244+ const result = await toSSG(app, { dir: './static' })245+ expect(result.success).toBeTruly246+ expect(result.error).toBeUndefined()247+ expect(result.files).toBeDefined()248+ afterAll(async () => {249+ await deleteDirectory('./static')250+ })251+ })252+})253+254+const fs = require('fs').promises255+const path = require('path')256+257+async function deleteDirectory(dirPath) {258+ if (259+ await fs260+ .stat(dirPath)261+ .then((stat) => stat.isDirectory())262+ .catch(() => false)263+ ) {264+ for (const entry of await fs.readdir(dirPath)) {265+ const entryPath = path.join(dirPath, entry)266+ await deleteDirectory(entryPath)267+ }268+ await fs.rmdir(dirPath)269+ } else {270+ await fs.unlink(dirPath)271+ }272+}added:runtime_tests/bun/vitest.config.ts+9 added
1+/// <reference types="vitest" />2+import { defineConfig } from 'vitest/config'3+4+export default defineConfig({5+ test: {6+ globals: true,7+ include: ['**/runtime_tests/bun/**/*.+(ts|tsx|js)'],8+ },9+})added:runtime_tests/deno/deno.json+5 added
1+{2+ "compilerOptions": {3+ "lib": ["deno.ns", "dom", "dom.iterable"]4+ }5+}added:runtime_tests/deno/deno.lock+21 added
1+{2+ "version": "3",3+ "packages": {4+ "specifiers": {5+ "npm:@types/node": "npm:@types/node@18.16.19"6+ },7+ "npm": {8+ "@types/node@18.16.19": {9+ "integrity": "sha512-IXl7o+R9iti9eBW4Wg2hx1xQDig183jj7YLn8F7udNceyfkbn1ZxmzZXuak20gR40D7pIkIY1kYGx5VIGbaHKA==",10+ "dependencies": {}11+ }12+ }13+ },14+ "remote": {15+ "https://deno.land/std@0.147.0/fmt/colors.ts": "6f9340b7fb8cc25a993a99e5efc56fe81bb5af284ff412129dd06df06f53c0b4",16+ "https://deno.land/std@0.147.0/testing/_diff.ts": "029a00560b0d534bc0046f1bce4bd36b3b41ada3f2a3178c85686eb2ff5f1413",17+ "https://deno.land/std@0.147.0/testing/_format.ts": "0d8dc79eab15b67cdc532826213bbe05bccfd276ca473a50a3fc7bbfb7260642",18+ "https://deno.land/std@0.147.0/testing/asserts.ts": "c17254748504f449c98476b78f4d206ca47cffc826e415026f09d7600c19535e",19+ "https://deno.land/std@0.147.0/testing/mock.ts": "d9630b551fe59a81b3c214c1a6ccb67819b6e34fc20e3424a659528fe1f572c1"20+ }21+}modified:runtime_tests/deno/middleware.test.tsx+1 added
1 /** @jsx jsx */2 /** @jsxFrag Fragment */3+// eslint-disable-next-line @typescript-eslint/no-unused-vars4 import { basicAuth, jsx, Fragment, serveStatic, jwt } from '../../deno_dist/middleware.ts'5 import { Hono } from '../../deno_dist/mod.ts'6 import { assertEquals, assertMatch, assertSpyCall, assertSpyCalls, spy } from './deps.ts'7 137 unmodified linesadded:runtime_tests/deno/ssg.test.tsx+57 added
1+/** @jsx jsx */2+/** @jsxFrag Fragment */3+4+import { toSSG } from '../../deno_dist/helper.ts'5+// eslint-disable-next-line @typescript-eslint/no-unused-vars6+import { jsx } from '../../deno_dist/middleware.ts'7+import { Hono } from '../../deno_dist/mod.ts'8+import { assertEquals } from '../deno/deps.ts'9+10+Deno.test('toSSG function', async () => {11+ const app = new Hono()12+ app.get('/', (c) => c.text('Hello, World!'))13+ app.get('/about', (c) => c.text('About Page'))14+ app.get('/about/some', (c) => c.text('About Page 2tier'))15+ app.post('/about/some/thing', (c) => c.text('About Page 3tier'))16+ app.get('/bravo', (c) => c.html('Bravo Page'))17+ app.get('/Charlie', async (c, next) => {18+ c.setRenderer((content) => {19+ return c.html(20+ <html>21+ <body>22+ <p>{content}</p>23+ </body>24+ </html>25+ )26+ })27+ await next()28+ })29+ app.get('/Charlie', (c) => {30+ return c.render('Hello!')31+ })32+33+ const result = await toSSG(app, { dir: './ssg-static' })34+ assertEquals(result.success, true)35+ assertEquals(result.error, undefined)36+ assertEquals(result.files !== undefined, true)37+38+ await deleteDirectory('./ssg-static')39+})40+41+async function deleteDirectory(dirPath: string): Promise<void> {42+ try {43+ const stat = await Deno.stat(dirPath)44+45+ if (stat.isDirectory) {46+ for await (const dirEntry of Deno.readDir(dirPath)) {47+ const entryPath = `${dirPath}/${dirEntry.name}`48+ await deleteDirectory(entryPath)49+ }50+ await Deno.remove(dirPath)51+ } else {52+ await Deno.remove(dirPath)53+ }54+ } catch (error) {55+ console.error(`Error deleting directory: ${error}`)56+ }57+}modified:runtime_tests/deno-jsx/deno.precompile.json+2 added-1 removed
1 {2 "compilerOptions": {3 "jsx": "precompile",4- "jsxImportSource": "hono/jsx"4+ "jsxImportSource": "hono/jsx",5+ "lib": ["deno.ns", "dom"]6 },7 "imports": {8 "hono/jsx/jsx-runtime": "../../deno_dist/jsx/jsx-runtime.ts",9 "../../deno_dist/jsx/jsx-runtime": "../../deno_dist/jsx/jsx-runtime.ts"2 unmodified linesmodified:runtime_tests/deno-jsx/deno.react-jsx.json+2 added-1 removed
1 {2 "compilerOptions": {3 "jsx": "react-jsx",4- "jsxImportSource": "hono/jsx"4+ "jsxImportSource": "hono/jsx",5+ "lib": ["deno.ns", "dom"]6 },7 "imports": {8 "hono/jsx/jsx-runtime": "../../deno_dist/jsx/jsx-runtime.ts",9 "../../deno_dist/jsx/jsx-runtime": "../../deno_dist/jsx/jsx-runtime.ts"2 unmodified linesmodified:runtime_tests/deno-jsx/jsx.test.tsx+2 added
35 unmodified lines36 )37 38 const chunks: string[] = []39 const textDecoder = new TextDecoder()40+ // eslint-disable-next-line @typescript-eslint/no-explicit-any41 for await (const chunk of stream as any) {42 chunks.push(textDecoder.decode(chunk))43 }44 15 unmodified lines60 )61 62 const chunks: string[] = []63 const textDecoder = new TextDecoder()64+ // eslint-disable-next-line @typescript-eslint/no-explicit-any65 for await (const chunk of stream as any) {66 chunks.push(textDecoder.decode(chunk))67 }68 13 unmodified linesdeleted:runtime_tests/lagon/.env.lagon-1 removed
1-NAME=Lagondeleted:runtime_tests/lagon/index.test.ts-206 removed
1-describe('Example', () => {2- test('GET /', async () => {3- const res = await fetch('http://127.0.0.1:1234')4- expect(res.status).toBe(200)5- expect(await res.text()).toBe('Hono!!')6- expect(res.headers.get('x-powered-by')).toBe('Hono')7- expect(res.headers.get('x-response-time')).toContain('ms')8- })9-10- test('GET /hello/anything', async () => {11- const res = await fetch('http://127.0.0.1:1234/hello/anything')12- expect(res.status).toBe(404)13- expect(res.headers.get('x-message')).toBe('This is addHeader middleware!')14- })15-16- test('GET /hello', async () => {17- const res = await fetch('http://127.0.0.1:1234/hello')18- expect(res.status).toBe(200)19- expect(await res.text()).toBe('This is /hello')20- })21-22- test('GET /runtime', async () => {23- const res = await fetch('http://127.0.0.1:1234/runtime')24- expect(res.status).toBe(200)25- expect(await res.text()).toBe('lagon')26- })27-28- test('GET /env', async () => {29- const res = await fetch('http://127.0.0.1:1234/env')30- expect(res.status).toBe(200)31- expect(await res.text()).toBe('Lagon')32- })33-34- test('GET /entry/:id', async () => {35- const res = await fetch('http://127.0.0.1:1234/entry/42')36- expect(res.status).toBe(200)37- expect(await res.text()).toBe('Your ID is 42')38- })39-40- describe('/book', () => {41- test('GET /book', async () => {42- const res = await fetch('http://127.0.0.1:1234/book')43- expect(res.status).toBe(200)44- expect(await res.text()).toBe('List Books')45- })46-47- test('GET /book/:id', async () => {48- const res = await fetch('http://127.0.0.1:1234/book/3')49- expect(res.status).toBe(200)50- expect(await res.text()).toBe('Get Book: 3')51- })52-53- test('POST /book', async () => {54- const res = await fetch('http://127.0.0.1:1234/book', {55- method: 'POST',56- })57- expect(res.status).toBe(200)58- expect(await res.text()).toBe('Create Book')59- })60- })61-62- test('GET /redirect', async () => {63- const res = await fetch('http://127.0.0.1:1234/redirect', {64- redirect: 'manual',65- })66- expect(res.status).toBe(302)67- expect(res.headers.get('location')).toBe('/')68- })69-70- describe('/basic-auth', () => {71- test('GET /basic-auth/anyroute unauthorized', async () => {72- const res = await fetch('http://127.0.0.1:1234/basic-auth/anyroute')73- expect(res.status).toBe(401)74- expect(await res.text()).toBe('Unauthorized')75- })76-77- test('GET /basic-auth/anyroute', async () => {78- const res = await fetch('http://127.0.0.1:1234/basic-auth/anyroute', {79- headers: {80- authorization: `Basic ${btoa('hono:acoolproject')}`,81- },82- })83- expect(res.status).toBe(200)84- expect(await res.text()).toBe('You are authorized')85- })86- })87-88- describe('/bearer-auth', () => {89- test('GET /bearer-auth/anyroute unauthorized', async () => {90- const res = await fetch('http://127.0.0.1:1234/bearer-auth/anyroute')91- expect(res.status).toBe(401)92- expect(await res.text()).toBe('Unauthorized')93- })94-95- test('GET /bearer-auth/anyroute', async () => {96- const res = await fetch('http://127.0.0.1:1234/bearer-auth/anyroute', {97- headers: {98- authorization: 'Bearer secrettoken',99- },100- })101- expect(res.status).toBe(200)102- expect(await res.text()).toBe('You are authorized')103- })104- })105-106- test('GET /etag/cached', async () => {107- const res = await fetch('http://127.0.0.1:1234/etag/cached')108- expect(res.status).toBe(200)109- expect(res.headers.get('etag')).toBe('"90ea638841fff3c326fc22cbd156f1146ac0ac02"')110- expect(await res.text()).toBe('Is this cached?')111- })112-113- test('GET /fetch-url', async () => {114- const res = await fetch('http://127.0.0.1:1234/fetch-url')115- expect(res.status).toBe(200)116- expect(await res.text()).toBe('https://example.com/ is 200')117- })118-119- test('GET /user-agent', async () => {120- const res = await fetch('http://127.0.0.1:1234/user-agent', {121- headers: {122- 'user-agent': 'Lagon',123- },124- })125- expect(res.status).toBe(200)126- expect(await res.text()).toBe('Your UserAgent is Lagon')127- })128-129- test('GET /api/posts', async () => {130- const res = await fetch('http://127.0.0.1:1234/api/posts')131- expect(res.status).toBe(200)132- expect(await res.json()).toEqual([133- { id: 1, title: 'Good Morning' },134- { id: 2, title: 'Good Aternoon' },135- { id: 3, title: 'Good Evening' },136- { id: 4, title: 'Good Night' },137- ])138- })139-140- test('POST /api/posts', async () => {141- const res = await fetch('http://127.0.0.1:1234/api/posts', {142- method: 'POST',143- })144- expect(res.status).toBe(201)145- expect(await res.json()).toEqual({ message: 'Created!' })146- })147-148- test('GET /api/default-route', async () => {149- const res = await fetch('http://127.0.0.1:1234/api/default-route')150- expect(res.status).toBe(404)151- expect(await res.text()).toBe('API endpoint is not found')152- })153-154- describe('/form', () => {155- test('POST /form x-www-form-urlencoded', async () => {156- const res = await fetch('http://127.0.0.1:1234/form', {157- method: 'POST',158- headers: {159- 'content-type': 'application/x-www-form-urlencoded',160- },161- body: 'username=john&password=Pa%24%24w0rd',162- })163- expect(res.status).toBe(200)164- expect(await res.json()).toEqual({165- password: 'Pa$$w0rd',166- username: 'john',167- })168- })169-170- test('POST /form', async () => {171- const res = await fetch('http://127.0.0.1:1234/form', {172- method: 'POST',173- headers: {174- 'content-type':175- 'multipart/form-data; boundary=---------------------------9051914041544843365972754266',176- },177- body: `-----------------------------9051914041544843365972754266178-Content-Disposition: form-data; name="hello"179-180-world!181------------------------------9051914041544843365972754266182-Content-Disposition: form-data; name="description"183-184-this is another field185------------------------------9051914041544843365972754266--`,186- })187- expect(res.status).toBe(200)188- expect(await res.json()).toEqual({189- description: 'this is another field',190- hello: 'world!',191- })192- })193- })194-195- test('GET /error', async () => {196- const res = await fetch('http://127.0.0.1:1234/error')197- expect(res.status).toBe(500)198- expect(await res.text()).toBe('Custom Error Message')199- })200-201- test('GET /api/default-route', async () => {202- const res = await fetch('http://127.0.0.1:1234/api/default-route')203- expect(res.status).toBe(404)204- expect(await res.text()).toBe('API endpoint is not found')205- })206-})deleted:runtime_tests/lagon/index.ts-132 removed
1-import { Hono } from '../../src'2-import { env, getRuntimeKey } from '../../src/helper/adapter'3-import { HTTPException } from '../../src/http-exception'4-import { basicAuth } from '../../src/middleware/basic-auth'5-import { bearerAuth } from '../../src/middleware/bearer-auth'6-import { etag } from '../../src/middleware/etag'7-import { poweredBy } from '../../src/middleware/powered-by'8-import { prettyJSON } from '../../src/middleware/pretty-json'9-10-const app = new Hono()11-12-// Mount Builtin Middleware13-app.use('*', poweredBy())14-// app.use('*', logger())15-app.use(16- '/basic-auth/*',17- basicAuth({18- username: 'hono',19- password: 'acoolproject',20- })21-)22-app.use(23- '/bearer-auth/*',24- bearerAuth({25- token: 'secrettoken',26- })27-)28-app.use('/etag/*', etag())29-30-app.get('/env', (c) => {31- const { NAME } = env<{ NAME: string }>(c)32- return c.text(NAME)33-})34-35-// Custom Middleware36-// Add Custom Header37-app.use('/hello/*', async (c, next) => {38- await next()39- c.header('X-message', 'This is addHeader middleware!')40-})41-42-// Add X-Response-Time header43-app.use('*', async (c, next) => {44- const start = Date.now()45- await next()46- const ms = Date.now() - start47- c.header('X-Response-Time', `${ms}ms`)48-})49-50-// Custom Not Found Message51-app.notFound((c) => {52- return c.text('Custom 404 Not Found', 404)53-})54-55-// Error handling56-app.onError((err, c) => {57- if (err instanceof HTTPException) {58- return err.getResponse()59- }60- console.error(`${err}`)61- return c.text('Custom Error Message', 500)62-})63-64-// Routing65-app.get('/', (c) => c.text('Hono!!'))66-// Use Response object directly67-app.get('/hello', () => new Response('This is /hello'))68-69-app.get('/runtime', () => new Response(getRuntimeKey()))70-71-// Named parameter72-app.get('/entry/:id', (c) => {73- const id = c.req.param('id')74- return c.text(`Your ID is ${id}`)75-})76-77-// Nested route78-const book = new Hono()79-book.get('/', (c) => c.text('List Books'))80-book.get('/:id', (c) => {81- const id = c.req.param('id')82- return c.text('Get Book: ' + id)83-})84-book.post('/', (c) => c.text('Create Book'))85-app.route('/book', book)86-87-// Redirect88-app.get('/redirect', (c) => c.redirect('/'))89-// Authentication required90-app.get('/basic-auth/*', (c) => c.text('You are authorized'))91-app.get('/bearer-auth/*', (c) => c.text('You are authorized'))92-// ETag93-app.get('/etag/cached', (c) => c.text('Is this cached?'))94-95-// Async96-app.get('/fetch-url', async (c) => {97- const response = await fetch('https://example.com/')98- return c.text(`https://example.com/ is ${response.status}`)99-})100-101-// Request headers102-app.get('/user-agent', (c) => {103- const userAgent = c.req.header('User-Agent')104- return c.text(`Your UserAgent is ${userAgent}`)105-})106-107-// JSON108-app.get('/api/posts', prettyJSON(), (c) => {109- const posts = [110- { id: 1, title: 'Good Morning' },111- { id: 2, title: 'Good Aternoon' },112- { id: 3, title: 'Good Evening' },113- { id: 4, title: 'Good Night' },114- ]115- return c.json(posts)116-})117-// status code118-app.post('/api/posts', (c) => c.json({ message: 'Created!' }, 201))119-// default route120-app.get('/api/*', (c) => c.text('API endpoint is not found', 404))121-122-app.post('/form', async (c) => {123- const body = await c.req.parseBody()124- return c.json(body)125-})126-127-// Throw Error128-app.get('/error', () => {129- throw Error('Error has occurred')130-})131-132-export const handler = app.fetchdeleted:runtime_tests/lagon/vitest.config.ts-10 removed
1-/// <reference types="vitest" />2-import { defineConfig } from 'vitest/config'3-4-export default defineConfig({5- test: {6- globals: true,7- include: ['**/(*.)+(test).+(ts|tsx)'],8- exclude: ['vitest.config.ts'],9- },10-})modified:src/adapter/aws-lambda/custom-context.ts-5 removed
85 unmodified lines86 elb: {87 targetGroupArn: string88 }89 }90-91-/**92- * @deprecated Use ApiGatewayRequestContextV2 instead.93- */94-export type LambdaFunctionUrlRequestContext = ApiGatewayRequestContextV2modified:src/adapter/aws-lambda/index.ts-1 removed
3 unmodified lines4 export type {5 ApiGatewayRequestContext,6 ApiGatewayRequestContextV2,7 ALBRequestContext,8- LambdaFunctionUrlRequestContext,8 } from './custom-context'9 export type { LambdaContext } from './types'modified:src/adapter/bun/index.ts+1 added
1 // @denoify-ignore2 export { serveStatic } from './serve-static'3+export { bunFileSystemModule, toSSG } from './ssg'modified:src/adapter/bun/serve-static.ts+7 added-1 removed
6 unmodified lines7 8 export type ServeStaticOptions<E extends Env = Env> = {9 root?: string10 path?: string11+ mimes?: Record<string, string>12 rewriteRequestPath?: (path: string) => string13 onNotFound?: (path: string, c: Context<E>) => void | Promise<void>14 }15 26 unmodified lines42 // @ts-ignore43 const file = Bun.file(path)44 const isExists = await file.exists()45 if (isExists) {46+ let mimeType: string | undefined = undefined47+ if (options.mimes) {48+ mimeType = getMimeType(path, options.mimes) ?? getMimeType(path)49+ } else {45- const mimeType = getMimeType(path)50+ mimeType = getMimeType(path)51+ }52 if (mimeType) {53 c.header('Content-Type', mimeType)54 }55 // Return Response object8 unmodified linesadded:src/adapter/bun/ssg.ts+28 added
1+// @denoify-ignore2+/* eslint-disable @typescript-eslint/ban-ts-comment */3+import { toSSG as baseToSSG } from '../../helper/ssg'4+import type { FileSystemModule, ToSSGAdaptorInterface } from '../../helper/ssg'5+6+// @ts-ignore7+const { write } = Bun8+9+/**10+ * @experimental11+ * `bunFileSystemModule` is an experimental feature.12+ * The API might be changed.13+ */14+export const bunFileSystemModule: FileSystemModule = {15+ writeFile: async (path, data) => {16+ await write(path, data)17+ },18+ mkdir: async () => {},19+}20+21+/**22+ * @experimental23+ * `toSSG` is an experimental feature.24+ * The API might be changed.25+ */26+export const toSSG: ToSSGAdaptorInterface = async (app, options) => {27+ return baseToSSG(app, bunFileSystemModule, options)28+}modified:src/adapter/cloudflare-pages/handler.test.ts-14 removed
29 unmodified lines30 requestURL: 'http://localhost/api/foo',31 })32 })33 34- it('Should return 200 response with path', async () => {35- const request = new Request('http://localhost/api/foo')36- const app = new Hono()37- app.get('/foo', (c) => {38- return c.text('/api/foo')39- })40- const handler = handle(app, '/api')41- // eslint-disable-next-line @typescript-eslint/ban-ts-comment42- // @ts-ignore43- const res = await handler({ request })44- expect(res.status).toBe(200)45- expect(await res.text()).toBe('/api/foo')46- })47-34 it('Should not use `basePath()` if path argument is not passed', async () => {35 const request = new Request('http://localhost/api/error')36 const app = new Hono().basePath('/api')37 14 unmodified linesmodified:src/adapter/cloudflare-pages/handler.ts+12 added-21 removed
1 // @denoify-ignore2-import { Hono } from '../../hono'3-import type { Env, MiddlewareHandler } from '../../types'2+import type { Hono } from '../../hono'3+import type { MiddlewareHandler } from '../../types'4 5 // Ref: https://github.com/cloudflare/workerd/blob/main/types/defines/pages.d.ts6 7 // eslint-disable-next-line @typescript-eslint/no-explicit-any13 unmodified lines21 22 interface HandleInterface {23 // eslint-disable-next-line @typescript-eslint/no-explicit-any24 (app: Hono<any, any, any>): (eventContext: EventContext) => Response | Promise<Response>25- /** @deprecated26- * Use `app.basePath()` to set a sub path instead of passing the second argument.27- * The `handle` will have only one argument in v4.28- */29- <E extends Env, S extends {}, BasePath extends string>(app: Hono<E, S, BasePath>, path: string): (30- eventContext: EventContext31- ) => Response | Promise<Response>25 }26 34-export const handle: HandleInterface =35- (subApp: Hono, path?: string) => (eventContext: EventContext) => {36- const app = path ? new Hono().route(path, subApp as never) : subApp37- return app.fetch(38- eventContext.request,39- { ...eventContext.env, eventContext },40- {41- waitUntil: eventContext.waitUntil,42- passThroughOnException: eventContext.passThroughOnException,43- }44- )45- }27+export const handle: HandleInterface = (app: Hono) => (eventContext: EventContext) => {28+ return app.fetch(29+ eventContext.request,30+ { ...eventContext.env, eventContext },31+ {32+ waitUntil: eventContext.waitUntil,33+ passThroughOnException: eventContext.passThroughOnException,34+ }35+ )36+}37 38 declare abstract class FetcherLike {39 fetch(input: RequestInfo, init?: RequestInit): Promise<Response>40 }17 unmodified linesmodified:src/adapter/cloudflare-workers/serve-static-module.ts+1 added-7 removed
1 // @denoify-ignore2-// eslint-disable-next-line @typescript-eslint/ban-ts-comment3-// @ts-ignore2 // For ES module mode5-import manifest from '__STATIC_CONTENT_MANIFEST'3 import type { Env } from '../../types'4 import type { ServeStaticOptions } from './serve-static'5 import { serveStatic } from './serve-static'6 10-const module = <E extends Env = Env>(11- options: Omit<ServeStaticOptions<E>, 'namespace'> = { root: '' }12-) => {13- options.manifest ??= manifest7+const module = <E extends Env = Env>(options: Omit<ServeStaticOptions<E>, 'namespace'>) => {8 return serveStatic<E>(options)9 }10 11 export { module as serveStatic }modified:src/adapter/cloudflare-workers/serve-static.test.ts+41 added-5 removed
9 unmodified lines10 'assets/static/top/index.abcdef.html': '<h1>Top</h1>',11 'static-no-root/plain.abcdef.txt': 'That is plain.txt',12 'assets/static/options/foo.abcdef.txt': 'With options',13 'assets/.static/plain.abcdef.txt': 'In the dot',14+ 'assets/static/video/morning-routine.abcdef.m3u8': 'Good morning',15+ 'assets/static/video/morning-routine1.abcdef.ts': 'Good',16+ 'assets/static/video/introduction.abcdef.mp4': 'Let me introduce myself',17 }18 const manifest = JSON.stringify({19 'assets/static/plain.txt': 'assets/static/plain.abcdef.txt',20 'assets/static/hono.html': 'assets/static/hono.abcdef.html',13 unmodified lines34 35 describe('ServeStatic Middleware', () => {36 const app = new Hono()37 const onNotFound = vi.fn(() => {})35- app.use('/static/*', serveStatic({ root: './assets', onNotFound }))36- app.use('/static-no-root/*', serveStatic())38+ app.use('/static/*', serveStatic({ root: './assets', onNotFound, manifest }))39+ app.use('/static-no-root/*', serveStatic({ manifest }))40 app.use(41 '/dot-static/*',42 serveStatic({43 root: './assets',44 rewriteRequestPath: (path) => path.replace(/^\/dot-static/, '/.static'),45+ manifest,46 })47 )48 49 beforeEach(() => onNotFound.mockClear())59 unmodified lines109 })110 111 describe('With `file` options', () => {112 const app = new Hono()109- app.get('/foo/*', serveStatic({ path: './assets/static/hono.html' }))110- app.get('/bar/*', serveStatic({ path: './static/hono.html', root: './assets' }))113+ app.get('/foo/*', serveStatic({ path: './assets/static/hono.html', manifest }))114+ app.get('/bar/*', serveStatic({ path: './static/hono.html', root: './assets', manifest }))115 116 it('Should return hono.html', async () => {117 const res = await app.request('http://localhost/foo/fallback')118 expect(res.status).toBe(200)6 unmodified lines125 expect(await res.text()).toBe('<h1>Hono!</h1>')126 })127 })128 129+describe('With `mimes` options', () => {130+ const mimes = {131+ m3u8: 'application/vnd.apple.mpegurl',132+ ts: 'video/mp2t',133+ }134+ const manifest = {135+ 'assets/static/video/morning-routine.m3u8': 'assets/static/video/morning-routine.abcdef.m3u8',136+ 'assets/static/video/morning-routine1.ts': 'assets/static/video/morning-routine1.abcdef.ts',137+ 'assets/static/video/introduction.mp4': 'assets/static/video/introduction.abcdef.mp4',138+ }139+140+ const app = new Hono()141+ app.use('/static/*', serveStatic({ root: './assets', mimes, manifest }))142+143+ it('Should return content-type of m3u8', async () => {144+ const res = await app.request('http://localhost/static/video/morning-routine.m3u8')145+ expect(res.status).toBe(200)146+ expect(res.headers.get('Content-Type')).toBe('application/vnd.apple.mpegurl')147+ })148+ it('Should return content-type of ts', async () => {149+ const res = await app.request('http://localhost/static/video/morning-routine1.ts')150+ expect(res.status).toBe(200)151+ expect(res.headers.get('Content-Type')).toBe('video/mp2t')152+ })153+ it('Should return content-type of default on Hono', async () => {154+ const res = await app.request('http://localhost/static/video/introduction.mp4')155+ expect(res.status).toBe(200)156+ expect(res.headers.get('Content-Type')).toBe('video/mp4')157+ })158+})159+160 describe('With middleware', () => {161 const app = new Hono()162 const md1 = async (c: Context, next: Next) => {163 await next()5 unmodified lines169 }170 171 app.use('/static/*', md1)172 app.use('/static/*', md2)138- app.use('/static/*', serveStatic({ root: './assets' }))173+ app.use('/static/*', serveStatic({ root: './assets', manifest }))174 app.get('/static/foo', (c) => {175 return c.text('bar')176 })177 27 unmodified lines205 root: './assets',206 onNotFound: (_, c) => {207 expectTypeOf(c.env).toEqualTypeOf<Env['Bindings']>()208 },209+ manifest,210 })211 )212 })213 })modified:src/adapter/cloudflare-workers/serve-static.ts+9 added-3 removed
7 unmodified lines8 9 export type ServeStaticOptions<E extends Env = Env> = {10 root?: string11 path?: string12+ mimes?: Record<string, string>12- manifest?: object | string13+ manifest: object | string14 namespace?: KVNamespace15 rewriteRequestPath?: (path: string) => string16 onNotFound?: (path: string, c: Context<E>) => void | Promise<void>17 }1 unmodified line19 const DEFAULT_DOCUMENT = 'index.html'20 21 // This middleware is available only on Cloudflare Workers.22 export const serveStatic = <E extends Env = Env>(22- options: ServeStaticOptions<E> = { root: '' }23+ options: ServeStaticOptions<E>24 ): MiddlewareHandler => {25 return async (c, next) => {26 // Do nothing if Response is already set27 if (c.finalized) {20 unmodified lines48 namespace: options.namespace ? options.namespace : c.env ? c.env.__STATIC_CONTENT : undefined,49 })50 51 if (content) {52+ let mimeType: string | undefined = undefined53+ if (options.mimes) {54+ mimeType = getMimeType(path, options.mimes) ?? getMimeType(path)55+ } else {51- const mimeType = getMimeType(path)56+ mimeType = getMimeType(path)57+ }58 if (mimeType) {59 c.header('Content-Type', mimeType)60 }61 // Return Response object8 unmodified linesadded:src/adapter/deno/deno.d.ts+19 added
1+declare namespace Deno {2+ /**3+ * Creates a new directory with the specified path.4+ *5+ * @param path The path to create a directory.6+ * @param options Options for creating a directory.7+ * @returns A promise that resolves when the directory is created.8+ */9+ export function mkdir(path: string, options?: { recursive?: boolean }): Promise<void>10+11+ /**12+ * Write a new file, with the specified path and data.13+ *14+ * @param path The path to the file to write.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>19+}modified:src/adapter/deno/index.ts+1 added
1 export { serveStatic } from './serve-static'2+export { toSSG, denoFileSystemModule } from './ssg'modified:src/adapter/deno/serve-static.ts+1 added
8 unmodified lines9 10 export type ServeStaticOptions<E extends Env = Env> = {11 root?: string12 path?: string13+ mimes?: Record<string, string>14 rewriteRequestPath?: (path: string) => string15 onNotFound?: (path: string, c: Context<E>) => void | Promise<void>16 }17 48 unmodified linesadded:src/adapter/deno/ssg.ts+27 added
1+import { toSSG as baseToSSG } from '../../helper/ssg/index'2+import type { FileSystemModule, ToSSGAdaptorInterface } from '../../helper/ssg/index'3+4+/**5+ * @experimental6+ * `denoFileSystemModule` is an experimental feature.7+ * The API might be changed.8+ */9+export const denoFileSystemModule: FileSystemModule = {10+ writeFile: async (path, data) => {11+ const uint8Data =12+ typeof data === 'string' ? new TextEncoder().encode(data) : new Uint8Array(data)13+ await Deno.writeFile(path, uint8Data)14+ },15+ mkdir: async (path, options) => {16+ return Deno.mkdir(path, { recursive: options?.recursive ?? false })17+ },18+}19+20+/**21+ * @experimental22+ * `toSSG` is an experimental feature.23+ * The API might be changed.24+ */25+export const toSSG: ToSSGAdaptorInterface = async (app, options) => {26+ return baseToSSG(app, denoFileSystemModule, options)27+}deleted:src/adapter/nextjs/handler.test.ts-43 removed
1-import { Hono } from '../../hono'2-import { handle } from './handler'3-4-describe('Adapter for Next.js', () => {5- it('Should return 200 response', async () => {6- const app = new Hono()7- app.get('/api/foo', (c) => {8- return c.text('/api/foo')9- })10- const handler = handle(app)11- const req = new Request('http://localhost/api/foo')12- const res = await handler(req)13- expect(res.status).toBe(200)14- expect(await res.text()).toBe('/api/foo')15- })16-17- it('Should return 200 response with path', async () => {18- const app = new Hono()19- app.get('/foo', (c) => {20- return c.text('/api/foo')21- })22- const handler = handle(app, '/api')23- const req = new Request('http://localhost/api/foo')24- const res = await handler(req)25- expect(res.status).toBe(200)26- expect(await res.text()).toBe('/api/foo')27- })28-29- it('Should not use `route()` if path argument is not passed', async () => {30- const app = new Hono().basePath('/api')31-32- app.onError((e) => {33- throw e34- })35- app.get('/error', () => {36- throw new Error('Custom Error')37- })38-39- const handler = handle(app)40- const req = new Request('http://localhost/api/error')41- expect(() => handler(req)).toThrowError('Custom Error')42- })43-})deleted:src/adapter/nextjs/handler.ts-25 removed
1-// @denoify-ignore2-import { Hono } from '../../hono'3-import type { Env } from '../../types'4-5-interface HandleInterface {6- /** @deprecated7- * `hono/nextjs` will become obsolete in v4.8- * Use `hono/vercel` instead.9- */10- // eslint-disable-next-line @typescript-eslint/no-explicit-any11- (subApp: Hono<any, any, any>): (req: Request) => Response | Promise<Response>12- /** @deprecated13- * Use `app.basePath()` to set a sub path instead of passing the second argument.14- * The `handle` will have only one argument in v4.15- */16- <E extends Env, S extends {}, BasePath extends string>(17- subApp: Hono<E, S, BasePath>,18- path: string19- ): (req: Request) => Response | Promise<Response>20-}21-22-export const handle: HandleInterface = (subApp: Hono, path?: string) => (req: Request) => {23- const app = path ? new Hono().route(path, subApp as never) : subApp24- return app.fetch(req)25-}deleted:src/adapter/nextjs/index.ts-2 removed
1-// @denoify-ignore2-export { handle } from './handler'modified:src/client/client.test.ts+4 added-38 removed
1-/* eslint-disable @typescript-eslint/no-explicit-any */1 /* eslint-disable @typescript-eslint/no-unused-vars */2+/* eslint-disable @typescript-eslint/no-explicit-any */3 /* eslint-disable @typescript-eslint/ban-ts-comment */4-import FormData from 'form-data'4 import { rest } from 'msw'5 import { setupServer } from 'msw/node'7-import _fetch, { Request as NodeFetchRequest } from 'node-fetch'6 import { vi, expectTypeOf } from 'vitest'7 import { Hono } from '../hono'8 import { parse } from '../utils/cookie'9 import type { Equal, Expect } from '../utils/types'10 import { validator } from '../validator'11 import { hc } from './client'12 import type { InferRequestType, InferResponseType } from './types'13 16-// @ts-ignore17-global.fetch = _fetch18-// @ts-ignore19-global.Request = NodeFetchRequest20-// @ts-ignore21-global.FormData = FormData22-14 describe('Basic - JSON', () => {15 const app = new Hono()16 17 const route = app111 unmodified lines129 filter: 'fake',130 })131 }132 )142- .get(143- '/posts',144- validator('queries', () => {145- return {146- tags: ['a', 'b'],147- }148- }),149- (c) => {150- const data = c.req.valid('queries')151- return c.json(data)152- }153- )133 .put(134 '/posts/:id',135 validator('form', () => {136 return {98 unmodified lines235 filter: null,236 })237 })238 260- it('Should get 200 response - queries', async () => {261- const res = await client.posts.$get({262- queries: {263- tags: ['A', 'B', 'C'],264- },265- })266-267- expect(res.status).toBe(200)268- expect(await res.json()).toEqual({269- tags: ['A', 'B', 'C'],270- })271- })272-239 it('Should get 200 response - form, params', async () => {240 const res = await client.posts[':id'].$put({241 form: {242 title: 'Good Night',78 unmodified lines321 const req = client.index.$get322 323 type Actual = InferRequestType<typeof req>324 type Expected = {359- age: string360- name: string325+ age: string | string[]326+ name: string | string[]327 }328 type verify = Expect<Equal<Expected, Actual['query']>>329 })330 210 unmodified lines541 542 describe('Optional parameters in JSON response', () => {543 it('Should return the correct type', async () => {544 const app = new Hono().get('/', (c) => {579- return c.jsonT({ message: 'foo' } as { message?: string })545+ return c.json({ message: 'foo' } as { message?: string })546 })547 type AppType = typeof app548 const client = hc<AppType>('', { fetch: app.request })549 const res = await client.index.$get()54 unmodified linesmodified:src/client/client.ts-9 removed
57 unmodified lines58 }59 }60 }61 62- if (args.queries) {63- for (const [k, v] of Object.entries(args.queries)) {64- for (const v2 of v) {65- this.queryParams ||= new URLSearchParams()66- this.queryParams.append(k, v2)67- }68- }69- }70-62 if (args.form) {63 const form = new FormData()64 for (const [k, v] of Object.entries(args.form)) {65 form.append(k, v)88 unmodified linesmodified:src/client/types.ts+1 added-1 removed
1 import type { Hono } from '../hono'2 import type { Schema } from '../types'3 import type { HasRequiredKeys } from '../utils/types'4 5-type HonoRequest = typeof Hono.prototype['request']5+type HonoRequest = (typeof Hono.prototype)['request']6 7 export type ClientRequestOptions<T = unknown> = keyof T extends never8 ? {9 headers?: Record<string, string>111 unmodified linesadded:src/helper/accepts/accepts.test.ts+180 added
1+import { Hono } from '../..'2+import type { Accept, acceptsConfig, acceptsOptions } from './accepts'3+import { parseAccept, defaultMatch, accepts } from './accepts'4+5+describe('parseAccept', () => {6+ test('should parse accept header', () => {7+ const acceptHeader =8+ 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8;level=1;foo=bar'9+ const accepts = parseAccept(acceptHeader)10+ expect(accepts).toEqual([11+ { type: 'text/html', params: {}, q: 1 },12+ { type: 'application/xhtml+xml', params: {}, q: 1 },13+ { type: 'application/xml', params: { q: '0.9' }, q: 0.9 },14+ { type: 'image/webp', params: {}, q: 1 },15+ { type: '*/*', params: { q: '0.8', level: '1', foo: 'bar' }, q: 0.8 },16+ ])17+ })18+})19+20+describe('defaultMatch', () => {21+ test('should return default support', () => {22+ const accepts: Accept[] = [23+ { type: 'text/html', params: {}, q: 1 },24+ { type: 'application/xhtml+xml', params: {}, q: 1 },25+ { type: 'application/xml', params: { q: '0.9' }, q: 0.9 },26+ { type: 'image/webp', params: {}, q: 1 },27+ { type: '*/*', params: { q: '0.8' }, q: 0.8 },28+ ]29+ const config: acceptsConfig = {30+ header: 'Accept',31+ supports: ['text/html'],32+ default: 'text/html',33+ }34+ const result = defaultMatch(accepts, config)35+ expect(result).toBe('text/html')36+ })37+})38+39+describe('accepts', () => {40+ test('should return matched support', () => {41+ const c = {42+ req: {43+ header: () => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',44+ },45+ // eslint-disable-next-line @typescript-eslint/no-explicit-any46+ } as any47+ const options: acceptsConfig = {48+ header: 'Accept',49+ supports: ['application/xml', 'text/html'],50+ default: 'application/json',51+ }52+ const result = accepts(c, options)53+ expect(result).toBe('text/html')54+ })55+56+ test('should return default support if no matched support', () => {57+ const c = {58+ req: {59+ header: () => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',60+ },61+ // eslint-disable-next-line @typescript-eslint/no-explicit-any62+ } as any63+ const options: acceptsConfig = {64+ header: 'Accept',65+ supports: ['application/json'],66+ default: 'text/html',67+ }68+ const result = accepts(c, options)69+ expect(result).toBe('text/html')70+ })71+72+ test('should return default support if no accept header', () => {73+ const c = {74+ req: {75+ header: () => undefined,76+ },77+ // eslint-disable-next-line @typescript-eslint/no-explicit-any78+ } as any79+ const options: acceptsConfig = {80+ header: 'Accept',81+ supports: ['application/json'],82+ default: 'text/html',83+ }84+ const result = accepts(c, options)85+ expect(result).toBe('text/html')86+ })87+88+ test('should return matched support with custom match function', () => {89+ const c = {90+ req: {91+ header: () => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',92+ },93+ // eslint-disable-next-line @typescript-eslint/no-explicit-any94+ } as any95+ // this match function will return the least q value96+ const match = (accepts: Accept[], config: acceptsConfig) => {97+ const { supports, default: defaultSupport } = config98+ const accept = accepts99+ .sort((a, b) => a.q - b.q)100+ .find((accept) => supports.includes(accept.type))101+ return accept ? accept.type : defaultSupport102+ }103+ const options: acceptsOptions = {104+ header: 'Accept',105+ supports: ['application/xml', 'text/html'],106+ default: 'application/json',107+ match,108+ }109+ const result = accepts(c, options)110+ expect(result).toBe('application/xml')111+ })112+})113+114+describe('Usage', () => {115+ test('decide compression by Accept-Encoding header', async () => {116+ const app = new Hono()117+ app.get('/compressed', async (c) => {118+ const encoding = accepts(c, {119+ header: 'Accept-Encoding',120+ supports: ['gzip', 'deflate'],121+ default: 'identity',122+ })123+ const COMPRESS_DATA = 'COMPRESS_DATA'124+ const readable = new ReadableStream({125+ start(controller) {126+ controller.enqueue(new TextEncoder().encode(COMPRESS_DATA))127+ controller.close()128+ },129+ })130+131+ if (encoding === 'gzip') {132+ c.header('Content-Encoding', 'gzip')133+ return c.body(readable.pipeThrough(new CompressionStream('gzip')))134+ }135+ if (encoding === 'deflate') {136+ c.header('Content-Encoding', 'deflate')137+ return c.body(readable.pipeThrough(new CompressionStream('deflate')))138+ }139+140+ c.body(COMPRESS_DATA)141+ })142+143+ const req1 = await app.request('/compressed', { headers: { 'Accept-Encoding': 'deflate' } })144+ const req2 = await app.request('/compressed', { headers: { 'Accept-Encoding': 'gzip' } })145+ const req3 = await app.request('/compressed', {146+ headers: { 'Accept-Encoding': 'gzip;q=0.5,deflate' },147+ })148+ const req4 = await app.request('/compressed', { headers: { 'Accept-Encoding': 'br' } })149+150+ expect(req1.headers.get('Content-Encoding')).toBe('deflate')151+ expect(req2.headers.get('Content-Encoding')).toBe('gzip')152+ expect(req3.headers.get('Content-Encoding')).toBe('deflate')153+ expect(req4.headers.get('Content-Encoding')).toBeNull()154+ })155+156+ test('decide language by Accept-Language header', async () => {157+ const app = new Hono()158+ const SUPPORTED_LANGS = ['en', 'ja', 'zh']159+ app.get('/*', async (c) => {160+ const lang = accepts(c, {161+ header: 'Accept-Language',162+ supports: SUPPORTED_LANGS,163+ default: 'en',164+ })165+ const isLangedPath = SUPPORTED_LANGS.some((l) => c.req.path.startsWith(`/${l}`))166+ if (isLangedPath) {167+ return c.body(`lang: ${lang}`)168+ }169+170+ return c.redirect(`/${lang}${c.req.path}`)171+ })172+173+ const req1 = await app.request('/foo', { headers: { 'Accept-Language': 'en=0.8,ja' } })174+ const req2 = await app.request('/en/foo', { headers: { 'Accept-Language': 'en' } })175+176+ expect(req1.status).toBe(302)177+ expect(req1.headers.get('Location')).toBe('/ja/foo')178+ expect(await req2.text()).toBe('lang: en')179+ })180+})added:src/helper/accepts/accepts.ts+73 added
1+import type { Context } from '../../context'2+3+export type AcceptHeader =4+ | 'Accept'5+ | 'Accept-Charset'6+ | 'Accept-Encoding'7+ | 'Accept-Language'8+ | 'Accept-Patch'9+ | 'Accept-Post'10+ | 'Accept-Ranges'11+12+export interface Accept {13+ type: string14+ params: Record<string, string>15+ q: number16+}17+18+export interface acceptsConfig {19+ header: AcceptHeader20+ supports: string[]21+ default: string22+}23+24+export interface acceptsOptions extends acceptsConfig {25+ match?: (accepts: Accept[], config: acceptsConfig) => string26+}27+28+export const parseAccept = (acceptHeader: string) => {29+ // Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.830+ const accepts = acceptHeader.split(',') // ['text/html', 'application/xhtml+xml', 'application/xml;q=0.9', 'image/webp', '*/*;q=0.8']31+ return accepts.map((accept) => {32+ const [type, ...params] = accept.trim().split(';') // ['application/xml', 'q=0.9']33+ const q = params.find((param) => param.startsWith('q=')) // 'q=0.9'34+ return {35+ type,36+ params: params.reduce((acc, param) => {37+ const [key, value] = param.split('=')38+ return { ...acc, [key.trim()]: value.trim() }39+ }, {}),40+ q: q ? parseFloat(q.split('=')[1]) : 1,41+ }42+ })43+}44+45+export const defaultMatch = (accepts: Accept[], config: acceptsConfig) => {46+ const { supports, default: defaultSupport } = config47+ const accept = accepts.sort((a, b) => b.q - a.q).find((accept) => supports.includes(accept.type))48+ return accept ? accept.type : defaultSupport49+}50+51+/**52+ * Match the accept header with the given options.53+ * @example54+ * ```ts55+ * app.get('/users', (c) => {56+ * const lang = accepts(c, {57+ * header: 'Accept-Language',58+ * supports: ['en', 'zh'],59+ * default: 'en',60+ * })61+ * })62+ * ```63+ */64+export const accepts = (c: Context, options: acceptsOptions) => {65+ const acceptHeader = c.req.header(options.header)66+ if (!acceptHeader) {67+ return options.default68+ }69+ const accepts = parseAccept(acceptHeader)70+ const match = options.match || defaultMatch71+72+ return match(accepts, options)73+}added:src/helper/accepts/index.ts+1 added
1+export { accepts } from './accepts'added:src/helper/adapter/index.test.ts+9 added
1+import { getRuntimeKey } from '.'2+3+describe('getRuntimeKey', () => {4+ it('Should return the current runtime key', () => {5+ // Now, using the `bun run test` command.6+ // But `vitest` depending Node.js will run this test so the RuntimeKey will be `node`.7+ expect(getRuntimeKey()).toBe('node')8+ })9+})modified:src/helper/adapter/index.ts+1 added-13 removed
1 import type { Context } from '../../context'2 3-export type Runtime =4- | 'node'5- | 'deno'6- | 'bun'7- | 'workerd'8- | 'fastly'9- | 'edge-light'10- | 'lagon'11- | 'other'3+export type Runtime = 'node' | 'deno' | 'bun' | 'workerd' | 'fastly' | 'edge-light' | 'other'4 5 export const env = <T extends Record<string, unknown>, C extends Context = Context<{}>>(6 c: C,7 runtime?: Runtime7 unmodified lines15 const runtimeEnvHandlers: Record<string, () => T> = {16 bun: () => globalEnv,17 node: () => globalEnv,18 'edge-light': () => globalEnv,27- lagon: () => globalEnv,19 deno: () => {20 // eslint-disable-next-line @typescript-eslint/ban-ts-comment21 // @ts-ignore22 return Deno.env.toObject() as T25 unmodified lines48 }49 if (global?.fastly !== undefined) {50 return 'fastly'51 }61- if (global?.__lagon__ !== undefined) {62- return 'lagon'63- }52 if (global?.process?.release?.name === 'node') {53 return 'node'54 }55 2 unmodified linesadded:src/helper/css/common.test.tsx+496 added
1+/* eslint-disable quotes */2+// eslint-disable-next-line @typescript-eslint/no-unused-vars3+import { jsx, Fragment } from '../../jsx'4+import type {5+ css as cssHelper,6+ keyframes as keyframesHelper,7+ viewTransition as viewTransitionHelper,8+ rawCssString as rawCssStringHelper,9+ Style as StyleComponent,10+} from './index'11+12+it.skip('this file only exports test runners.', () => {})13+14+interface Support {15+ nest: boolean16+}17+export const renderTest = (18+ getEnv: () => {19+ css: typeof cssHelper20+ keyframes: typeof keyframesHelper21+ viewTransition: typeof viewTransitionHelper22+ rawCssString: typeof rawCssStringHelper23+ // eslint-disable-next-line @typescript-eslint/no-explicit-any24+ toString: (template: any) => Promise<string>25+ Style: typeof StyleComponent26+ support: Support27+ }28+) => {29+ const { support } = getEnv()30+31+ let css: typeof cssHelper32+ let keyframes: typeof keyframesHelper33+ let viewTransition: typeof viewTransitionHelper34+ let rawCssString: typeof rawCssStringHelper35+ // eslint-disable-next-line @typescript-eslint/no-explicit-any36+ let toString: (template: any) => Promise<string>37+ let Style: typeof StyleComponent38+ beforeEach(() => {39+ ;({ css, keyframes, viewTransition, rawCssString, toString, Style } = getEnv())40+ })41+42+ describe('render css', () => {43+ it('Should render CSS styles with JSX', async () => {44+ const headerClass = css`45+ background-color: blue;46+ `47+ const template = (48+ <>49+ <Style />50+ <h1 class={headerClass}>Hello!</h1>51+ </>52+ )53+ expect(await toString(template)).toBe(54+ '<style id="hono-css">.css-2458908649{background-color:blue}</style><h1 class="css-2458908649">Hello!</h1>'55+ )56+ })57+58+ it('Should render CSS with keyframes', async () => {59+ const animation = keyframes`60+ from {61+ opacity: 0;62+ }63+ to {64+ opacity: 1;65+ }66+ `67+ const headerClass = css`68+ background-color: blue;69+ animation: ${animation} 1s ease-in-out;70+ `71+ const template = (72+ <>73+ <Style />74+ <h1 class={headerClass}>Hello!</h1>75+ </>76+ )77+ expect(await toString(template)).toBe(78+ '<style id="hono-css">.css-1580801783{background-color:blue;animation:css-9294673 1s ease-in-out}@keyframes css-9294673{from{opacity:0}to{opacity:1}}</style><h1 class="css-1580801783">Hello!</h1>'79+ )80+ })81+82+ it('Should not output the same class name multiple times.', async () => {83+ const headerClass = css`84+ background-color: blue;85+ `86+ const headerClass2 = css`87+ background-color: blue;88+ `89+ const template = (90+ <>91+ <Style />92+ <h1 class={headerClass}>Hello!</h1>93+ <h1 class={headerClass2}>Hello2!</h1>94+ </>95+ )96+ expect(await toString(template)).toBe(97+ '<style id="hono-css">.css-2458908649{background-color:blue}</style><h1 class="css-2458908649">Hello!</h1><h1 class="css-2458908649">Hello2!</h1>'98+ )99+ })100+101+ it('Should render CSS with variable', async () => {102+ const headerClass = css`103+ background-color: blue;104+ content: '${"I'm a variable!"}';105+ `106+ const template = (107+ <>108+ <Style />109+ <h1 class={headerClass}>Hello!</h1>110+ </>111+ )112+ expect(await toString(template)).toBe(113+ '<style id="hono-css">.css-4027435072{background-color:blue;content:\'I\\\'m a variable!\'}</style><h1 class="css-4027435072">Hello!</h1>'114+ )115+ })116+117+ it('Should escape </style>', async () => {118+ const headerClass = css`119+ background-color: blue;120+ content: '${'</style>'}';121+ `122+ const template = (123+ <>124+ <Style />125+ <h1 class={headerClass}>Hello!</h1>126+ </>127+ )128+ expect(await toString(template)).toBe(129+ '<style id="hono-css">.css-372954897{background-color:blue;content:\'<\\/style>\'}</style><h1 class="css-372954897">Hello!</h1>'130+ )131+ })132+133+ it('Should not escape URL', async () => {134+ const headerClass = css`135+ background-color: blue;136+ background: url('${'http://www.example.com/path/to/file.jpg'}');137+ `138+ const template = (139+ <>140+ <Style />141+ <h1 class={headerClass}>Hello!</h1>142+ </>143+ )144+ expect(await toString(template)).toBe(145+ '<style id="hono-css">.css-1321888780{background-color:blue;background:url(\'http://www.example.com/path/to/file.jpg\')}</style><h1 class="css-1321888780">Hello!</h1>'146+ )147+ })148+149+ it('Should render CSS with escaped variable', async () => {150+ const headerClass = css`151+ background-color: blue;152+ content: '${rawCssString('say "Hello!"')}';153+ `154+ const template = (155+ <>156+ <Style />157+ <h1 class={headerClass}>Hello!</h1>158+ </>159+ )160+ expect(await toString(template)).toBe(161+ '<style id="hono-css">.css-2238574885{background-color:blue;content:\'say "Hello!"\'}</style><h1 class="css-2238574885">Hello!</h1>'162+ )163+ })164+165+ it('Should render CSS with number', async () => {166+ const headerClass = css`167+ background-color: blue;168+ font-size: ${1}rem;169+ `170+ const template = (171+ <>172+ <Style />173+ <h1 class={headerClass}>Hello!</h1>174+ </>175+ )176+ expect(await toString(template)).toBe(177+ '<style id="hono-css">.css-1847536026{background-color:blue;font-size:1rem}</style><h1 class="css-1847536026">Hello!</h1>'178+ )179+ })180+181+ it('Should render CSS with array', async () => {182+ const animation = keyframes`183+ from {184+ opacity: 0;185+ }186+ to {187+ opacity: 1;188+ }189+ `190+ const headerClass = css`191+ background-color: blue;192+ animation: ${animation} 1s ease-in-out;193+ `194+ const extendedHeaderClass = css`195+ ${headerClass}196+ color: red;197+ `198+ const template = (199+ <>200+ <Style />201+ <h1 class={extendedHeaderClass}>Hello!</h1>202+ </>203+ )204+ expect(await toString(template)).toBe(205+ '<style id="hono-css">.css-2558359670{background-color:blue;animation:css-9294673 1s ease-in-out;color:red}@keyframes css-9294673{from{opacity:0}to{opacity:1}}</style><h1 class="css-2558359670">Hello!</h1>'206+ )207+ })208+209+ it.runIf(support.nest)(210+ 'Should be used as a class name for syntax `${className} {`',211+ async () => {212+ const headerClass = css`213+ font-weight: bold;214+ `215+ const containerClass = css`216+ ${headerClass} {217+ h1 {218+ color: red;219+ }220+ }221+ `222+ const template = (223+ <>224+ <Style />225+ <div class={containerClass}>226+ <h1 class={headerClass}>Hello!</h1>227+ </div>228+ </>229+ )230+ expect(await toString(template)).toBe(231+ '<style id="hono-css">.css-4220297002{.css-1032195302{h1{color:red}}}.css-1032195302{font-weight:bold}</style><div class="css-4220297002"><h1 class="css-1032195302">Hello!</h1></div>'232+ )233+ }234+ )235+236+ it('Should be inserted to global if style string starts with :-hono-root', async () => {237+ const globalClass = css`238+ :-hono-global {239+ html {240+ color: red;241+ }242+ body {243+ display: flex;244+ }245+ }246+ `247+ const template = (248+ <>249+ <Style />250+ <div class={globalClass}>251+ <h1>Hello!</h1>252+ </div>253+ </>254+ )255+ expect(await toString(template)).toBe(256+ '<style id="hono-css">html{color:red}body{display:flex}</style><div class=""><h1>Hello!</h1></div>'257+ )258+ })259+260+ it.runIf(support.nest)(261+ 'Should be inserted to global if style string starts with :-hono-root and extends class name',262+ async () => {263+ const headerClass = css`264+ display: flex;265+ `266+ const specialHeaderClass = css`267+ :-hono-global {268+ ${headerClass} {269+ h1 {270+ color: red;271+ }272+ }273+ }274+ `275+ const template = (276+ <>277+ <Style />278+ <div class={specialHeaderClass}>279+ <h1>Hello!</h1>280+ </div>281+ </>282+ )283+ expect(await toString(template)).toBe(284+ '<style id="hono-css">.css-3980466870{h1{color:red}}.css-3980466870{display:flex}</style><div class="css-3980466870"><h1>Hello!</h1></div>'285+ )286+ }287+ )288+289+ it('Should be inserted as global css if passed css`` to Style component', async () => {290+ const headerClass = css`291+ font-size: 1rem;292+ `293+ const template = (294+ <>295+ <Style>{css`296+ html {297+ color: red;298+ }299+ body {300+ display: flex;301+ }302+ `}</Style>303+ <div>304+ <h1 class={headerClass}>Hello!</h1>305+ </div>306+ </>307+ )308+ expect(await toString(template)).toBe(309+ '<style id="hono-css">html{color:red}body{display:flex}.css-1740067317{font-size:1rem}</style><div><h1 class="css-1740067317">Hello!</h1></div>'310+ )311+ })312+313+ it('Should be ignored :-hono-root inside Style component', async () => {314+ const headerClass = css`315+ font-size: 1rem;316+ `317+ const template = (318+ <>319+ <Style>{css`320+ :-hono-global {321+ html {322+ color: red;323+ }324+ body {325+ display: flex;326+ }327+ }328+ `}</Style>329+ <div>330+ <h1 class={headerClass}>Hello!</h1>331+ </div>332+ </>333+ )334+ expect(await toString(template)).toBe(335+ '<style id="hono-css">html{color:red}body{display:flex}.css-1740067317{font-size:1rem}</style><div><h1 class="css-1740067317">Hello!</h1></div>'336+ )337+ })338+339+ describe('viewTransition', () => {340+ it('Should render CSS with unique view-transition-name', async () => {341+ const transition = viewTransition()342+ const template = (343+ <>344+ <Style />345+ <h1 class={transition}>Hello!</h1>346+ </>347+ )348+ expect(await toString(template)).toBe(349+ '<style id="hono-css">.css-1644952339{view-transition-name:css-1644952339}</style><h1 class="css-1644952339">Hello!</h1>'350+ )351+ })352+353+ it('Should render CSS with css and keyframes', async () => {354+ const kf = keyframes`355+ from {356+ opacity: 0;357+ }358+ to {359+ opacity: 1;360+ }361+ `362+ const transition = viewTransition(css`363+ ::view-transition-old() {364+ animation-name: ${kf};365+ }366+ ::view-transition-new() {367+ animation-name: ${kf};368+ }369+ `)370+ const headerClass = css`371+ ${transition}372+ background-color: blue;373+ `374+ const template = (375+ <>376+ <Style />377+ <h1 class={headerClass}>Hello!</h1>378+ </>379+ )380+ expect(await toString(template)).toBe(381+ '<style id="hono-css">.css-1245070278{view-transition-name:css-399742870;background-color:blue}@keyframes css-9294673{from{opacity:0}to{opacity:1}}::view-transition-old(css-399742870){animation-name:css-9294673}::view-transition-new(css-399742870){animation-name:css-9294673}</style><h1 class="css-1245070278">Hello!</h1>'382+ )383+ })384+385+ it('Should works as a template tag function', async () => {386+ const kf = keyframes`387+ from {388+ opacity: 0;389+ }390+ to {391+ opacity: 1;392+ }393+ `394+ const transition = viewTransition`395+ ::view-transition-old() {396+ animation-name: ${kf};397+ }398+ ::view-transition-new() {399+ animation-name: ${kf};400+ }401+ `402+ const headerClass = css`403+ ${transition}404+ background-color: blue;405+ `406+ const template = (407+ <>408+ <Style />409+ <h1 class={headerClass}>Hello!</h1>410+ </>411+ )412+ expect(await toString(template)).toBe(413+ '<style id="hono-css">.css-1245070278{view-transition-name:css-399742870;background-color:blue}@keyframes css-9294673{from{opacity:0}to{opacity:1}}::view-transition-old(css-399742870){animation-name:css-9294673}::view-transition-new(css-399742870){animation-name:css-9294673}</style><h1 class="css-1245070278">Hello!</h1>'414+ )415+ })416+ })417+418+ it.runIf(support.nest)('Should render sub CSS with keyframe', async () => {419+ const headerClass = css`420+ background-color: blue;421+ ${[1, 2].map(422+ (i) =>423+ css`424+ :nth-child(${i}) {425+ color: red;426+ }427+ `428+ )}429+ `430+ const template = (431+ <>432+ <Style />433+ <h1 class={headerClass}>Hello!</h1>434+ </>435+ )436+ expect(await toString(template)).toBe(437+ '<style id="hono-css">.css-1539881271{background-color:blue;:nth-child(1){color:red}:nth-child(2){color:red}}</style><h1 class="css-1539881271">Hello!</h1>'438+ )439+ })440+441+ it('Should be generated deferent class name for deferent first line comment even if the content is the same', async () => {442+ const headerClassA = css`443+ /* class A */444+ display: flex;445+ `446+ const headerClassB = css`447+ /* class B */448+ display: flex;449+ `450+ const template = (451+ <>452+ <Style />453+ <h1 class={headerClassA}>Hello!</h1>454+ <h1 class={headerClassB}>Hello!</h1>455+ </>456+ )457+ expect(await toString(template)).toBe(458+ '<style id="hono-css">.css-3170754153{display:flex}.css-896513246{display:flex}</style><h1 class="css-3170754153">Hello!</h1><h1 class="css-896513246">Hello!</h1>'459+ )460+ })461+462+ describe('Booleans, Null, and Undefined Are Ignored', () => {463+ it.each([true, false, undefined, null])('%s', async (value) => {464+ const headerClass = css`465+ ${value}466+ background-color: blue;467+ `468+ const template = (469+ <>470+ <Style />471+ <h1 class={headerClass}>Hello!</h1>472+ </>473+ )474+ expect(await toString(template)).toBe(475+ '<style id="hono-css">.css-2458908649{background-color:blue}</style><h1 class="css-2458908649">Hello!</h1>'476+ )477+ })478+479+ it('falsy value', async () => {480+ const value = 0481+ const headerClass = css`482+ padding: ${value};483+ `484+ const template = (485+ <>486+ <Style />487+ <h1 class={headerClass}>Hello!</h1>488+ </>489+ )490+ expect(await toString(template)).toBe(491+ '<style id="hono-css">.css-478287868{padding:0}</style><h1 class="css-478287868">Hello!</h1>'492+ )493+ })494+ })495+ })496+}added:src/helper/css/common.ts+243 added
1+// provide utility functions for css helper both on server and client2+export const PSEUDO_GLOBAL_SELECTOR = ':-hono-global'3+export const isPseudoGlobalSelectorRe = new RegExp(`^${PSEUDO_GLOBAL_SELECTOR}{(.*)}$`)4+export const DEFAULT_STYLE_ID = 'hono-css'5+6+export const SELECTOR = Symbol()7+export const CLASS_NAME = Symbol()8+export const STYLE_STRING = Symbol()9+export const SELECTORS = Symbol()10+export const EXTERNAL_CLASS_NAMES = Symbol()11+const CSS_ESCAPED = Symbol()12+13+export interface CssClassName {14+ [SELECTOR]: string15+ [CLASS_NAME]: string16+ [STYLE_STRING]: string17+ [SELECTORS]: CssClassName[]18+ [EXTERNAL_CLASS_NAMES]: string[]19+}20+21+export const IS_CSS_ESCAPED = Symbol()22+23+interface CssEscapedString {24+ [CSS_ESCAPED]: string25+}26+27+/**28+ * @experimental29+ * `rawCssString` is an experimental feature.30+ * The API might be changed.31+ */32+export const rawCssString = (value: string): CssEscapedString => {33+ return {34+ [CSS_ESCAPED]: value,35+ }36+}37+38+/**39+ * Used the goober'code as a reference:40+ * https://github.com/cristianbote/goober/blob/master/src/core/to-hash.js41+ * MIT License, Copyright (c) 2019 Cristian Bote42+ */43+const toHash = (str: string): string => {44+ let i = 0,45+ out = 1146+ while (i < str.length) {47+ out = (101 * out + str.charCodeAt(i++)) >>> 048+ }49+ return 'css-' + out50+}51+52+const cssStringReStr = [53+ '"(?:(?:\\\\[\\s\\S]|[^"\\\\])*)"', // double quoted string54+ // eslint-disable-next-line quotes55+ "'(?:(?:\\\\[\\s\\S]|[^'\\\\])*)'", // single quoted string56+].join('|')57+const minifyCssRe = new RegExp(58+ [59+ '(' + cssStringReStr + ')', // $1: quoted string60+61+ '(?:' +62+ [63+ '^\\s+', // head whitespace64+ '\\/\\*.*?\\*\\/\\s*', // multi-line comment65+ '\\/\\/.*\\n\\s*', // single-line comment66+ '\\s+$', // tail whitespace67+ ].join('|') +68+ ')',69+70+ '\\s*;\\s*(}|$)\\s*', // $2: trailing semicolon71+ '\\s*([{};:,])\\s*', // $3: whitespace around { } : , ;72+ '(\\s)\\s+', // $4: 2+ spaces73+ ].join('|'),74+ 'g'75+)76+77+export const minify = (css: string): string => {78+ return css.replace(minifyCssRe, (_, $1, $2, $3, $4) => $1 || $2 || $3 || $4 || '')79+}80+81+type CssVariableBasicType =82+ | CssClassName83+ | CssEscapedString84+ | string85+ | number86+ | boolean87+ | null88+ | undefined89+type CssVariableAsyncType = Promise<CssVariableBasicType>90+type CssVariableArrayType = (CssVariableBasicType | CssVariableAsyncType)[]91+export type CssVariableType = CssVariableBasicType | CssVariableAsyncType | CssVariableArrayType92+93+export const buildStyleString = (94+ strings: TemplateStringsArray,95+ values: CssVariableType[]96+): [string, string, CssClassName[], string[]] => {97+ const selectors: CssClassName[] = []98+ const externalClassNames: string[] = []99+100+ const label = strings[0].match(/^\s*\/\*(.*?)\*\//)?.[1] || ''101+ let styleString = ''102+ for (let i = 0, len = strings.length; i < len; i++) {103+ styleString += strings[i]104+ let vArray = values[i]105+ if (typeof vArray === 'boolean' || vArray === null || vArray === undefined) {106+ continue107+ }108+109+ if (!Array.isArray(vArray)) {110+ vArray = [vArray]111+ }112+ for (let j = 0, len = vArray.length; j < len; j++) {113+ let value = vArray[j]114+ if (typeof value === 'boolean' || value === null || value === undefined) {115+ continue116+ }117+ if (typeof value === 'string') {118+ if (/([\\"'\/])/.test(value)) {119+ styleString += value.replace(/([\\"']|(?<=<)\/)/g, '\\$1')120+ } else {121+ styleString += value122+ }123+ } else if (typeof value === 'number') {124+ styleString += value125+ } else if ((value as CssEscapedString)[CSS_ESCAPED]) {126+ styleString += (value as CssEscapedString)[CSS_ESCAPED]127+ } else if ((value as CssClassName)[CLASS_NAME].startsWith('@keyframes ')) {128+ selectors.push(value as CssClassName)129+ styleString += ` ${(value as CssClassName)[CLASS_NAME].substring(11)} `130+ } else {131+ if (strings[i + 1]?.match(/^\s*{/)) {132+ // assume this value is a class name133+ selectors.push(value as CssClassName)134+ value = `.${(value as CssClassName)[CLASS_NAME]}`135+ } else {136+ selectors.push(...(value as CssClassName)[SELECTORS])137+ externalClassNames.push(...(value as CssClassName)[EXTERNAL_CLASS_NAMES])138+ value = (value as CssClassName)[STYLE_STRING]139+ const valueLen = value.length140+ if (valueLen > 0) {141+ const lastChar = value[valueLen - 1]142+ if (lastChar !== ';' && lastChar !== '}') {143+ value += ';'144+ }145+ }146+ }147+ styleString += `${value || ''}`148+ }149+ }150+ }151+152+ return [label, minify(styleString), selectors, externalClassNames]153+}154+155+export const cssCommon = (156+ strings: TemplateStringsArray,157+ values: CssVariableType[]158+): CssClassName => {159+ let [label, thisStyleString, selectors, externalClassNames] = buildStyleString(strings, values)160+ const isPseudoGlobal = isPseudoGlobalSelectorRe.exec(thisStyleString)161+ if (isPseudoGlobal) {162+ thisStyleString = isPseudoGlobal[1]163+ }164+ const selector = (isPseudoGlobal ? PSEUDO_GLOBAL_SELECTOR : '') + toHash(label + thisStyleString)165+ const className = (166+ isPseudoGlobal ? selectors.map((s) => s[CLASS_NAME]) : [selector, ...externalClassNames]167+ ).join(' ')168+169+ return {170+ [SELECTOR]: selector,171+ [CLASS_NAME]: className,172+ [STYLE_STRING]: thisStyleString,173+ [SELECTORS]: selectors,174+ [EXTERNAL_CLASS_NAMES]: externalClassNames,175+ }176+}177+178+export const cxCommon = (179+ args: (string | boolean | null | undefined | CssClassName)[]180+): (string | boolean | null | undefined | CssClassName)[] => {181+ for (let i = 0, len = args.length; i < len; i++) {182+ const arg = args[i]183+ if (typeof arg === 'string') {184+ args[i] = {185+ [SELECTOR]: '',186+ [CLASS_NAME]: '',187+ [STYLE_STRING]: '',188+ [SELECTORS]: [],189+ [EXTERNAL_CLASS_NAMES]: [arg],190+ }191+ }192+ }193+194+ return args195+}196+197+export const keyframesCommon = (198+ strings: TemplateStringsArray,199+ ...values: CssVariableType[]200+): CssClassName => {201+ const [label, styleString] = buildStyleString(strings, values)202+ return {203+ [SELECTOR]: '',204+ [CLASS_NAME]: `@keyframes ${toHash(label + styleString)}`,205+ [STYLE_STRING]: styleString,206+ [SELECTORS]: [],207+ [EXTERNAL_CLASS_NAMES]: [],208+ }209+}210+211+type ViewTransitionType = {212+ (strings: TemplateStringsArray, values: CssVariableType[]): CssClassName213+ (content: CssClassName): CssClassName214+ (): CssClassName215+}216+217+let viewTransitionNameIndex = 0218+export const viewTransitionCommon: ViewTransitionType = ((219+ strings: TemplateStringsArray | CssClassName | undefined,220+ values: CssVariableType[]221+): CssClassName => {222+ if (!strings) {223+ // eslint-disable-next-line @typescript-eslint/no-explicit-any224+ strings = [`/* h-v-t ${viewTransitionNameIndex++} */`] as any225+ }226+ const content = Array.isArray(strings)227+ ? cssCommon(strings as TemplateStringsArray, values)228+ : (strings as CssClassName)229+230+ const transitionName = content[CLASS_NAME]231+ // eslint-disable-next-line @typescript-eslint/no-explicit-any232+ const res = cssCommon(['view-transition-name:', ''] as any, [transitionName])233+234+ content[CLASS_NAME] = PSEUDO_GLOBAL_SELECTOR + content[CLASS_NAME]235+ content[STYLE_STRING] = content[STYLE_STRING].replace(236+ /(?<=::view-transition(?:[a-z-]*)\()(?=\))/g,237+ transitionName238+ )239+ res[CLASS_NAME] = res[SELECTOR] = transitionName240+ res[SELECTORS] = [...content[SELECTORS], content]241+242+ return res243+}) as ViewTransitionTypemodified:src/helper/css/index.test.tsx+28 added-246 removed
1+/* eslint-disable quotes */2 import { Hono } from '../../'3 import { html } from '../../helper/html'4+// eslint-disable-next-line @typescript-eslint/no-unused-vars3-import { jsx, Fragment, JSXNode } from '../../jsx'5+import { jsx, Fragment, isValidElement } from '../../jsx'6+import type { JSXNode } from '../../jsx'7 import { Suspense, renderToReadableStream } from '../../jsx/streaming'8 import type { HtmlEscapedString } from '../../utils/html'9 import { HtmlEscapedCallbackPhase, resolveCallback } from '../../utils/html'10+import { renderTest } from './common.test'7-import { css, cx, keyframes, rawCssString, Style, createCssContext } from './index'11+import { css, cx, keyframes, viewTransition, rawCssString, Style, createCssContext } from './index'12 13 async function toString(14 template: JSXNode | Promise<HtmlEscapedString> | Promise<string> | HtmlEscapedString15 ) {12- if (template instanceof Promise) template = (await template) as HtmlEscapedString13- if (template instanceof JSXNode) template = template.toString() as Promise<HtmlEscapedString>16+ if (template instanceof Promise) {17+ template = (await template) as HtmlEscapedString18+ }19+ if (isValidElement(template)) {20+ template = template.toString() as Promise<HtmlEscapedString>21+ }22 return resolveCallback(await template, HtmlEscapedCallbackPhase.Stringify, false, template)23 }24 25 async function toCSS(4 unmodified lines30 .replace(/\.css-\d+/g, '.css-123')31 }32 33 describe('CSS Helper', () => {26- describe('render css', () => {27- it('Should render CSS styles with JSX', async () => {28- const headerClass = css`29- background-color: blue;30- `31- const template = (32- <>33- <Style />34- <h1 class={headerClass}>Hello!</h1>35- </>36- )37- expect(await toString(template)).toBe(38- '<style id="hono-css">.css-2458908649{background-color:blue}</style><h1 class="css-2458908649">Hello!</h1>'39- )40- })34+ renderTest(() => {35+ return {36+ css,37+ Style,38+ keyframes,39+ viewTransition,40+ rawCssString,41+ createCssContext,42+ toString,43+ toCSS,44+ support: {45+ nest: true,46+ },47+ }48+ })49 50+ describe('with `html` tag function', () => {51 it('Should render CSS styles with `html` tag function', async () => {52 const headerClass = css`53 background-color: blue;54 `3 unmodified lines58 `<style id="hono-css">.css-2458908649{background-color:blue}</style>59 <h1 class="css-2458908649">Hello!</h1>`60 )61 })53-54- it('Should render CSS with keyframes', async () => {55- const animation = keyframes`56- from {57- opacity: 0;58- }59- to {60- opacity: 1;61- }62- `63- const headerClass = css`64- background-color: blue;65- animation: ${animation} 1s ease-in-out;66- `67- const template = (68- <>69- <Style />70- <h1 class={headerClass}>Hello!</h1>71- </>72- )73- expect(await toString(template)).toBe(74- '<style id="hono-css">.css-1580801783{background-color:blue;animation:css-9294673 1s ease-in-out}@keyframes css-9294673{from{opacity:0}to{opacity:1}}</style><h1 class="css-1580801783">Hello!</h1>'75- )76- })77-78- it('Should not output the same class name multiple times.', async () => {79- const headerClass = css`80- background-color: blue;81- `82- const headerClass2 = css`83- background-color: blue;84- `85- const template = (86- <>87- <Style />88- <h1 class={headerClass}>Hello!</h1>89- <h1 class={headerClass2}>Hello2!</h1>90- </>91- )92- expect(await toString(template)).toBe(93- '<style id="hono-css">.css-2458908649{background-color:blue}</style><h1 class="css-2458908649">Hello!</h1><h1 class="css-2458908649">Hello2!</h1>'94- )95- })96-97- it('Should render CSS with variable', async () => {98- const headerClass = css`99- background-color: blue;100- content: '${'I\'m a variable!'}';101- `102- const template = (103- <>104- <Style />105- <h1 class={headerClass}>Hello!</h1>106- </>107- )108- expect(await toString(template)).toBe(109- '<style id="hono-css">.css-4027435072{background-color:blue;content:\'I\\\'m a variable!\'}</style><h1 class="css-4027435072">Hello!</h1>'110- )111- })112-113- it('Should escape </style>', async () => {114- const headerClass = css`115- background-color: blue;116- content: '${'</style>'}';117- `118- const template = (119- <>120- <Style />121- <h1 class={headerClass}>Hello!</h1>122- </>123- )124- expect(await toString(template)).toBe(125- '<style id="hono-css">.css-372954897{background-color:blue;content:\'<\\/style>\'}</style><h1 class="css-372954897">Hello!</h1>'126- )127- })128-129- it('Should not escape URL', async () => {130- const headerClass = css`131- background-color: blue;132- background: url('${'http://www.example.com/path/to/file.jpg'}');133- `134- const template = (135- <>136- <Style />137- <h1 class={headerClass}>Hello!</h1>138- </>139- )140- expect(await toString(template)).toBe(141- '<style id="hono-css">.css-1321888780{background-color:blue;background:url(\'http://www.example.com/path/to/file.jpg\')}</style><h1 class="css-1321888780">Hello!</h1>'142- )143- })144-145- it('Should render CSS with escaped variable', async () => {146- const headerClass = css`147- background-color: blue;148- content: '${rawCssString('say "Hello!"')}';149- `150- const template = (151- <>152- <Style />153- <h1 class={headerClass}>Hello!</h1>154- </>155- )156- expect(await toString(template)).toBe(157- '<style id="hono-css">.css-2238574885{background-color:blue;content:\'say "Hello!"\'}</style><h1 class="css-2238574885">Hello!</h1>'158- )159- })160-161- it('Should render CSS with async variable', async () => {162- const headerClass = css`163- background-color: blue;164- content: '${(async () => {165- await new Promise((resolve) => setTimeout(resolve, 100))166- return 'I\'m an async variable!'167- })()}';168- `169- const template = (170- <>171- <Style />172- <h1 class={headerClass}>Hello!</h1>173- </>174- )175- expect(await toString(template)).toBe(176- '<style id="hono-css">.css-1399451752{background-color:blue;content:\'I\\\'m an async variable!\'}</style><h1 class="css-1399451752">Hello!</h1>'177- )178- })179-180- it('Should render CSS with number', async () => {181- const headerClass = css`182- background-color: blue;183- font-size: ${1}rem;184- `185- const template = (186- <>187- <Style />188- <h1 class={headerClass}>Hello!</h1>189- </>190- )191- expect(await toString(template)).toBe(192- '<style id="hono-css">.css-1847536026{background-color:blue;font-size:1rem}</style><h1 class="css-1847536026">Hello!</h1>'193- )194- })195-196- it('Should render CSS with array', async () => {197- const animation = keyframes`198- from {199- opacity: 0;200- }201- to {202- opacity: 1;203- }204- `205- const headerClass = css`206- background-color: blue;207- animation: ${animation} 1s ease-in-out;208- `209- const extendedHeaderClass = css`210- ${headerClass}211- color: red;212- `213- const template = (214- <>215- <Style />216- <h1 class={extendedHeaderClass}>Hello!</h1>217- </>218- )219- expect(await toString(template)).toBe(220- '<style id="hono-css">.css-2558359670{background-color:blue;animation:css-9294673 1s ease-in-out;color:red}@keyframes css-9294673{from{opacity:0}to{opacity:1}}</style><h1 class="css-2558359670">Hello!</h1>'221- )222- })223-224- describe('Booleans, Null, and Undefined Are Ignored', () => {225- it.each([true, false, undefined, null])('%s', async (value) => {226- const headerClass = css`227- ${value}228- background-color: blue;229- `230- const template = (231- <>232- <Style />233- <h1 class={headerClass}>Hello!</h1>234- </>235- )236- expect(await toString(template)).toBe(237- '<style id="hono-css">.css-2458908649{background-color:blue}</style><h1 class="css-2458908649">Hello!</h1>'238- )239- })240-241- it('falsy value', async () => {242- const value = 0243- const headerClass = css`244- padding: ${value};245- `246- const template = (247- <>248- <Style />249- <h1 class={headerClass}>Hello!</h1>250- </>251- )252- expect(await toString(template)).toBe(253- '<style id="hono-css">.css-478287868{padding:0}</style><h1 class="css-478287868">Hello!</h1>'254- )255- })256- })62 })63 259- it('Should render sub CSS with keyframe', async () => {260- const headerClass = css`261- background-color: blue;262- ${[1, 2].map(263- (i) =>264- css`265- :nth-child(${i}) {266- color: red;267- }268- `269- )}270- `271- const template = (272- <>273- <Style />274- <h1 class={headerClass}>Hello!</h1>275- </>276- )277- expect(await toString(template)).toBe(278- '<style id="hono-css">.css-1539881271{background-color:blue;:nth-child(1){color:red}:nth-child(2){color:red}}</style><h1 class="css-1539881271">Hello!</h1>'279- )280- })281-64 describe('cx()', () => {65 it('Should render CSS with cx()', async () => {66 const btn = css`67 border-radius: 4px;188 unmodified linesmodified:src/helper/css/index.ts+75 added-194 removed
1 import { raw } from '../../helper/html'2+import { DOM_RENDERER } from '../../jsx/constants'3+import { createCssJsxDomObjects } from '../../jsx/dom/css'4 import type { HtmlEscapedCallback, HtmlEscapedString } from '../../utils/html'5+import type { CssClassName as CssClassNameCommon, CssVariableType } from './common'6+import {7+ SELECTOR,8+ CLASS_NAME,9+ STYLE_STRING,10+ SELECTORS,11+ PSEUDO_GLOBAL_SELECTOR,12+ DEFAULT_STYLE_ID,13+ cssCommon,14+ cxCommon,15+ keyframesCommon,16+ viewTransitionCommon,17+} from './common'18+export { rawCssString } from './common'19 4-const IS_CSS_CLASS_NAME = Symbol('IS_CSS_CLASS_NAME')5-const STYLE_STRING = Symbol('STYLE_STRING')6-const SELECTORS = Symbol('SELECTORS')7-const EXTERNAL_CLASS_NAMES = Symbol('EXTERNAL_CLASS_NAMES')8-type CssClassName = HtmlEscapedString & {20+type CssClassName = HtmlEscapedString & CssClassNameCommon9- [IS_CSS_CLASS_NAME]: true10- [STYLE_STRING]: string11- // eslint-disable-next-line @typescript-eslint/ban-types12- [SELECTORS]: String[]13- [EXTERNAL_CLASS_NAMES]: string[]14-}21 16-type CssEscaped = {17- isCssEscaped: true18-}19-type CssEscapedString = string & CssEscaped20-21-/**22- * @experimental23- * `rawCssString` is an experimental feature.24- * The API might be changed.25- */26-export const rawCssString = (value: string): CssEscapedString => {27- const escapedString = new String(value) as CssEscapedString28- escapedString.isCssEscaped = true29- return escapedString30-}31-32-const DEFAULT_STYLE_ID = 'hono-css'33-34-/**35- * Used the goober'code as a reference:36- * https://github.com/cristianbote/goober/blob/master/src/core/to-hash.js37- * MIT License, Copyright (c) 2019 Cristian Bote38- */39-const toHash = (str: string): string => {40- let i = 0,41- out = 1142- while (i < str.length) {43- out = (101 * out + str.charCodeAt(i++)) >>> 044- }45- return 'css-' + out46-}47-48-const cssStringReStr = [49- '"(?:(?:\\\\[\\s\\S]|[^"\\\\])*)"', // double quoted string50- // eslint-disable-next-line quotes51- "'(?:(?:\\\\[\\s\\S]|[^'\\\\])*)'", // single quoted string52-].join('|')53-const minifyCssRe = new RegExp(54- [55- '(' + cssStringReStr + ')', // $1: quoted string56-57- '(?:' +58- [59- '^\\s+', // head whitespace60- '\\/\\*.*?\\*\\/\\s*', // multi-line comment61- '\\/\\/.*\\n\\s*', // single-line comment62- '\\s+$', // tail whitespace63- ].join('|') +64- ')',65-66- ';\\s*(}|$)\\s*', // $2: trailing semicolon67- '\\s*([{};:,])\\s*', // $3: whitespace around { } : , ;68- '(\\s)\\s+', // $4: 2+ spaces69- ].join('|'),70- 'g'71-)72-73-const minify = (css: string): string => {74- return css.replace(minifyCssRe, (_, $1, $2, $3, $4) => $1 || $2 || $3 || $4 || '')75-}76-22 type usedClassNameData = [23 Record<string, string>, // class name to add24 Record<string, true> // class name already added25 ]81-// eslint-disable-next-line @typescript-eslint/ban-types82-type CssVariableBasicType = string | String | number | boolean | null | undefined83-type CssVariableAsyncType = Promise<CssVariableBasicType>84-type CssVariableArrayType = (CssVariableBasicType | CssVariableAsyncType)[]85-type CssVariableType = CssVariableBasicType | CssVariableAsyncType | CssVariableArrayType26 87-const buildStyleString = async (88- strings: TemplateStringsArray,89- values: CssVariableType[],90- // eslint-disable-next-line @typescript-eslint/ban-types91- selectors: String[],92- externalClassNames: string[]93-): Promise<string> => {94- let styleString = ''95- for (let i = 0; i < strings.length; i++) {96- styleString += strings[i]97- let vArray = values[i]98- if (typeof vArray === 'boolean' || vArray === null || vArray === undefined) {99- continue100- }101-102- if (!Array.isArray(vArray)) {103- vArray = [vArray] as CssVariableArrayType104- }105- for (let j = 0; j < vArray.length; j++) {106- let value = (107- vArray[j] instanceof Promise ? await vArray[j] : vArray[j]108- ) as CssVariableBasicType109- if (typeof value === 'boolean' || value === null || value === undefined) {110- continue111- }112- if (typeof value === 'number') {113- styleString += value114- } else if (value.startsWith('@keyframes ')) {115- selectors.push(value)116- styleString += ` ${value.substring(11)} `117- } else {118- if ((value as CssClassName)[IS_CSS_CLASS_NAME]) {119- selectors.push(...(value as CssClassName)[SELECTORS])120- externalClassNames.push(...(value as CssClassName)[EXTERNAL_CLASS_NAMES])121- value = (value as CssClassName)[STYLE_STRING]122- if (value.length > 0) {123- const lastChar = value[value.length - 1]124- if (lastChar !== ';' && lastChar !== '}') {125- value += ';'126- }127- }128- } else if (129- !(value as CssEscapedString).isCssEscaped &&130- /([\\"'\/])/.test(value as string)131- ) {132- value = value.replace(/([\\"']|(?<=<)\/)/g, '\\$1')133- }134- styleString += `${value || ''}`135- }136- }137- }138-139- return minify(styleString)140-}141-27 /**28 * @experimental29 * `createCssContext` is an experimental feature.30 * The API might be changed.31 */32 export const createCssContext = ({ id }: { id: Readonly<string> }) => {33+ const [cssJsxDomObject, StyleRenderToDom] = createCssJsxDomObjects({ id })34+35 const contextMap: WeakMap<object, usedClassNameData> = new WeakMap()36 37 const replaceStyleRe = new RegExp(`(<style id="${id}">.*?)(</style>)`)38 152- const css = async (153- strings: TemplateStringsArray,154- ...values: CssVariableType[]155- ): Promise<string> => {156- // eslint-disable-next-line @typescript-eslint/ban-types157- const selectors: String[] = []158- const externalClassNames: string[] = []159- const thisStyleString = await buildStyleString(strings, values, selectors, externalClassNames)160- const thisSelector = toHash(thisStyleString)161- const className = new String([thisSelector, ...externalClassNames].join(' ')) as CssClassName162-39+ const newCssClassNameObject = (cssClassName: CssClassNameCommon): Promise<string> => {40 const appendStyle: HtmlEscapedCallback = ({ buffer, context }): Promise<string> | undefined => {41 const [toAdd, added] = contextMap.get(context) as usedClassNameData42 const names = Object.keys(toAdd)43 3 unmodified lines47 48 let stylesStr = ''49 names.forEach((className) => {50 added[className] = true51+ stylesStr += className.startsWith(PSEUDO_GLOBAL_SELECTOR)52+ ? toAdd[className]174- stylesStr += `${className[0] === '@' ? '' : '.'}${className}{${toAdd[className]}}`53+ : `${className[0] === '@' ? '' : '.'}${className}{${toAdd[className]}}`54 })55 contextMap.set(context, [{}, added])56 57 if (buffer && replaceStyleRe.test(buffer[0])) {17 unmodified lines75 contextMap.set(context, [{}, {}])76 }77 const [toAdd, added] = contextMap.get(context) as usedClassNameData78 let allAdded = true200- if (!added[thisSelector]) {79+ if (!added[cssClassName[SELECTOR]]) {80 allAdded = false202- toAdd[thisSelector] = thisStyleString81+ toAdd[cssClassName[SELECTOR]] = cssClassName[STYLE_STRING]82 }204- selectors.forEach((className) => {205- if (!added[`${className}`]) {206- allAdded = false207- toAdd[`${className}`] = (className as CssClassName)[STYLE_STRING]83+ cssClassName[SELECTORS].forEach(84+ ({ [CLASS_NAME]: className, [STYLE_STRING]: styleString }) => {85+ if (!added[className]) {86+ allAdded = false87+ toAdd[className] = styleString88+ }89 }209- })90+ )91 if (allAdded) {92 return93 }94 95 return Promise.resolve(raw('', [appendStyle]))96 }97 217- Object.assign(className, {218- isEscaped: true,219- callbacks: [addClassNameToContext],220- [IS_CSS_CLASS_NAME]: true,221- [STYLE_STRING]: thisStyleString,222- [SELECTORS]: selectors,223- [EXTERNAL_CLASS_NAMES]: externalClassNames,224- })98+ const className = new String(cssClassName[CLASS_NAME]) as CssClassName99+ Object.assign(className, cssClassName)100+ ;(className as HtmlEscapedString).isEscaped = true101+ ;(className as HtmlEscapedString).callbacks = [addClassNameToContext]102+ const promise = Promise.resolve(className)103+ Object.assign(promise, cssClassName)104+ promise.toString = cssJsxDomObject.toString105+ return promise106+ }107 226- return className as string108+ const css = (strings: TemplateStringsArray, ...values: CssVariableType[]): Promise<string> => {109+ return newCssClassNameObject(cssCommon(strings, values))110 }111 229- const cx = async (230- ...args: (string | boolean | null | undefined | Promise<string | boolean | null | undefined>)[]112+ const cx = (113+ ...args: (CssClassName | Promise<string> | string | boolean | null | undefined)[]114 ): Promise<string> => {232- const resolvedArgs = await Promise.all(args)233- for (let i = 0; i < resolvedArgs.length; i++) {234- const arg = resolvedArgs[i]235- if (typeof arg === 'string' && !(arg as CssClassName)[IS_CSS_CLASS_NAME]) {236- const externalClassName = new String(arg) as CssClassName237- resolvedArgs[i] = Object.assign(externalClassName, {238- isEscaped: true,239- [IS_CSS_CLASS_NAME]: true,240- [STYLE_STRING]: '',241- [SELECTORS]: [],242- [EXTERNAL_CLASS_NAMES]: [arg],243- })244- }245- }246-115 // eslint-disable-next-line @typescript-eslint/no-explicit-any248- return css(Array(resolvedArgs.length).fill('') as any, ...resolvedArgs)116+ args = cxCommon(args as any) as any117+ // eslint-disable-next-line @typescript-eslint/no-explicit-any118+ return css(Array(args.length).fill('') as any, ...args)119 }120 251- const keyframes = async (252- strings: TemplateStringsArray,253- ...values: CssVariableType[]254- ): // eslint-disable-next-line @typescript-eslint/ban-types255- Promise<String> => {256- const styleString = await buildStyleString(strings, values, [], [])257- const className = new String(`@keyframes ${toHash(styleString)}`)258- Object.assign(className as CssClassName, {259- isEscaped: true,260- [IS_CSS_CLASS_NAME]: true,261- [STYLE_STRING]: styleString,262- [SELECTORS]: [],263- [EXTERNAL_CLASS_NAMES]: [],264- })265- return className121+ const keyframes = keyframesCommon122+123+ type ViewTransitionType = {124+ (strings: TemplateStringsArray, ...values: CssVariableType[]): Promise<string>125+ (content: Promise<string>): Promise<string>126+ (): Promise<string>127 }128+ const viewTransition: ViewTransitionType = ((129+ strings: TemplateStringsArray | Promise<string> | undefined,130+ ...values: CssVariableType[]131+ ): Promise<string> => {132+ // eslint-disable-next-line @typescript-eslint/no-explicit-any133+ return newCssClassNameObject(viewTransitionCommon(strings as any, values))134+ }) as ViewTransitionType135 268- const Style = () => raw(`<style id="${id}"></style>`)136+ const Style = ({ children }: { children?: Promise<string> } = {}) =>137+ children138+ ? raw(`<style id="${id}">${(children as unknown as CssClassName)[STYLE_STRING]}</style>`)139+ : raw(`<style id="${id}"></style>`)140+ // eslint-disable-next-line @typescript-eslint/no-explicit-any141+ ;(Style as any)[DOM_RENDERER] = StyleRenderToDom142 143 return {144 css,145 cx,146 keyframes,147+ viewTransition: viewTransition as ViewTransitionType,148 Style,149 }150 }151 21 unmodified lines173 export const keyframes = defaultContext.keyframes174 175 /**176 * @experimental177+ * `viewTransition` is an experimental feature.178+ * The API might be changed.179+ */180+export const viewTransition = defaultContext.viewTransition181+182+/**183+ * @experimental184 * `Style` is an experimental feature.185 * The API might be changed.186 */187 export const Style = defaultContext.Stylemodified:src/helper/factory/index.test.ts+2 added-2 removed
96 unmodified lines97 }),98 (c) => {99 const foo = c.var.foo100 const { page } = c.req.valid('query')101- return c.jsonT({ page, foo })101+ return c.json({ page, foo })102 }103 )104 const routes = app.get('/posts', ...handlers)105 49 unmodified lines155 const foo = c.var.foo156 const { auth } = c.req.valid('header')157 const { page } = c.req.valid('query')158 const { id } = c.req.valid('json')159- return c.jsonT({ auth, page, foo, id })159+ return c.json({ auth, page, foo, id })160 }161 )162 const routes = app.get('/posts', ...handlers)163 33 unmodified linesmodified:src/helper/factory/index.ts-60 removed
1 /* eslint-disable @typescript-eslint/no-explicit-any */2 import type { Env, Input, MiddlewareHandler, H, HandlerResponse } from '../../types'3 4-/**5- * @experimental6- * `Factory` class is an experimental feature.7- * The API might be changed.8- */4 export class Factory<E extends Env = any, P extends string = any> {5 createMiddleware = <I extends Input = {}>(middleware: MiddlewareHandler<E, P, I>) => middleware6 12- /**13- * @experimental14- * `createHandlers` is an experimental feature.15- * The API might be changed.16- */7 createHandlers<I extends Input = {}>(handler1: H<E, P, I>): [H<E, P, I>]8 9 // handler x220- /**21- * @experimental22- * `createHandlers` is an experimental feature.23- * The API might be changed.24- */10 createHandlers<I extends Input = {}, I2 extends Input = I, R extends HandlerResponse<any> = any>(11 handler1: H<E, P, I, R>,12 handler2: H<E, P, I2, R>13 ): [H<E, P, I, R>, H<E, P, I2, R>]14 15 // handler x331- /**32- * @experimental33- * `createHandlers` is an experimental feature.34- * The API might be changed.35- */16 createHandlers<17 I extends Input = {},18 I2 extends Input = I,19 I3 extends Input = I & I2,4 unmodified lines24 handler3: H<E, P, I3, R>25 ): [H<E, P, I, R>, H<E, P, I2, R>, H<E, P, I3, R>]26 27 // handler x448- /**49- * @experimental50- * `createHandlers` is an experimental feature.51- * The API might be changed.52- */28 createHandlers<29 I extends Input = {},30 I2 extends Input = I,31 I3 extends Input = I & I2,6 unmodified lines38 handler4: H<E, P, I4, R>39 ): [H<E, P, I, R>, H<E, P, I2, R>, H<E, P, I3, R>, H<E, P, I4, R>]40 41 // handler x567- /**68- * @experimental69- * `createHandlers` is an experimental feature.70- * The API might be changed.71- */42 createHandlers<43 I extends Input = {},44 I2 extends Input = I,45 I3 extends Input = I & I2,8 unmodified lines54 handler5: H<E, P, I5, R>55 ): [H<E, P, I, R>, H<E, P, I2, R>, H<E, P, I3, R>, H<E, P, I4, R>, H<E, P, I5, R>]56 57 // handler x688- /**89- * @experimental90- * `createHandlers` is an experimental feature.91- * The API might be changed.92- */58 createHandlers<59 I extends Input = {},60 I2 extends Input = I,61 I3 extends Input = I & I2,10 unmodified lines72 handler6: H<E, P, I6, R>73 ): [H<E, P, I, R>, H<E, P, I2, R>, H<E, P, I3, R>, H<E, P, I4, R>, H<E, P, I5, R>, H<E, P, I6, R>]74 75 // handler x7111- /**112- * @experimental113- * `createHandlers` is an experimental feature.114- * The API might be changed.115- */76 createHandlers<77 I extends Input = {},78 I2 extends Input = I,79 I3 extends Input = I & I2,20 unmodified lines100 H<E, P, I7, R>101 ]102 103 // handler x8144- /**145- * @experimental146- * `createHandlers` is an experimental feature.147- * The API might be changed.148- */104 createHandlers<105 I extends Input = {},106 I2 extends Input = I,107 I3 extends Input = I & I2,23 unmodified lines131 H<E, P, I8, R>132 ]133 134 // handler x9180- /**181- * @experimental182- * `createHandlers` is an experimental feature.183- * The API might be changed.184- */135 createHandlers<136 I extends Input = {},137 I2 extends Input = I,138 I3 extends Input = I & I2,26 unmodified lines165 H<E, P, I9, R>166 ]167 168 // handler x10219- /**220- * @experimental221- * `createHandlers` is an experimental feature.222- * The API might be changed.223- */169 createHandlers<170 I extends Input = {},171 I2 extends Input = I,172 I3 extends Input = I & I2,33 unmodified lines206 return handlers.filter((handler) => handler !== undefined)207 }208 }209 265-/**266- * @experimental267- * `createFactory` is an experimental feature.268- * The API might be changed.269- */210 export const createFactory = <E extends Env = any, P extends string = any>() => new Factory<E, P>()211 212 export const createMiddleware = <E extends Env = any, P extends string = any, I extends Input = {}>(213 middleware: MiddlewareHandler<E, P, I>1 unmodified lineadded:src/helper/ssg/index.test.tsx+349 added
1+import { beforeEach, describe, expect, it } from 'vitest'2+import { Hono } from '../../hono'3+// eslint-disable-next-line @typescript-eslint/no-unused-vars4+import { jsx } from '../../jsx'5+import { poweredBy } from '../../middleware/powered-by'6+import {7+ fetchRoutesContent,8+ saveContentToFiles,9+ ssgParams,10+ toSSG,11+ disableSSG,12+ onlySSG,13+} from './index'14+import type {15+ BeforeRequestHook,16+ AfterResponseHook,17+ AfterGenerateHook,18+ FileSystemModule,19+} from './index'20+21+describe('toSSG function', () => {22+ let app: Hono23+24+ const postParams = [{ post: '1' }, { post: '2' }]25+26+ beforeEach(() => {27+ app = new Hono()28+ app.all('/', (c) => c.html('Hello, World!'))29+ app.get('/about', (c) => c.html('About Page'))30+ app.get('/about/some', (c) => c.text('About Page 2tier'))31+ app.post('/about/some/thing', (c) => c.text('About Page 3tier'))32+ app.get('/bravo', (c) => c.html('Bravo Page'))33+ app.get('/Charlie', async (c, next) => {34+ c.setRenderer((content, head) => {35+ return c.html(36+ <html>37+ <head>38+ <title>{head.title || ''}</title>39+ </head>40+ <body>41+ <p>{content}</p>42+ </body>43+ </html>44+ )45+ })46+ await next()47+ })48+ app.get('/Charlie', (c) => {49+ return c.render('Hello!', { title: 'Charlies Page' })50+ })51+52+ // Included params53+ app.get(54+ '/post/:post',55+ ssgParams(() => postParams),56+ (c) => c.html(<h1>{c.req.param('post')}</h1>)57+ )58+59+ app.get(60+ '/user/:user_id',61+ ssgParams([{ user_id: '1' }, { user_id: '2' }, { user_id: '3' }]),62+ (c) => c.html(<h1>{c.req.param('user_id')}</h1>)63+ )64+65+ type Env = {66+ Bindings: {67+ FOO_DB: string68+ }69+ Variables: {70+ FOO_VAR: string71+ }72+ }73+74+ app.get(75+ '/env-type-check',76+ ssgParams<Env>((c) => {77+ expectTypeOf<typeof c.env.FOO_DB>().toBeString()78+ expectTypeOf<typeof c.var.FOO_VAR>().toBeString()79+ return []80+ })81+ )82+ })83+ it('Should correctly generate static HTML files for Hono routes', async () => {84+ const fsMock: FileSystemModule = {85+ writeFile: vi.fn(() => Promise.resolve()),86+ mkdir: vi.fn(() => Promise.resolve()),87+ }88+89+ const htmlMap = await fetchRoutesContent(app)90+91+ for (const postParam of postParams) {92+ const html = htmlMap.get(`/post/${postParam.post}`)93+ expect(html?.content).toBe(`<h1>${postParam.post}</h1>`)94+ }95+96+ for (let i = 1; i <= 3; i++) {97+ const html = htmlMap.get(`/user/${i}`)98+ expect(html?.content).toBe(`<h1>${i}</h1>`)99+ }100+101+ const files = await saveContentToFiles(htmlMap, fsMock, './static')102+103+ expect(files.length).toBeGreaterThan(0)104+ expect(fsMock.mkdir).toHaveBeenCalledWith(expect.any(String), {105+ recursive: true,106+ })107+ expect(fsMock.writeFile).toHaveBeenCalled()108+ })109+110+ it('Should handle file system errors correctly in saveContentToFiles', async () => {111+ const fsMock: FileSystemModule = {112+ writeFile: vi.fn(() => Promise.reject(new Error('Write error'))),113+ mkdir: vi.fn(() => Promise.resolve()),114+ }115+116+ try {117+ const htmlMap = await fetchRoutesContent(app)118+ await saveContentToFiles(htmlMap, fsMock, './static')119+ expect(true).toBe(false) // This should not be reached120+ } catch (error) {121+ if (error instanceof Error) {122+ expect(error.message).toBe('Write error')123+ } else {124+ throw error125+ }126+ }127+ })128+129+ it('Should handle overall process errors correctly in toSSG', async () => {130+ const fsMock: FileSystemModule = {131+ writeFile: vi.fn(() => Promise.reject(new Error('Write error'))),132+ mkdir: vi.fn(() => Promise.resolve()),133+ }134+135+ const result = await toSSG(app, fsMock, { dir: './static' })136+137+ expect(result.success).toBe(false)138+ expect(result.error).toBeDefined()139+ expect(result.files).toStrictEqual([])140+ })141+142+ it('Should correctly generate files with the expected paths', async () => {143+ const fsMock: FileSystemModule = {144+ writeFile: vi.fn(() => Promise.resolve()),145+ mkdir: vi.fn(() => Promise.resolve()),146+ }147+148+ const htmlMap = await fetchRoutesContent(app)149+ await saveContentToFiles(htmlMap, fsMock, './static')150+151+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', expect.any(String))152+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/about.html', expect.any(String))153+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/about/some.txt', expect.any(String))154+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/about/some/thing.txt', expect.any(String))155+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/about.html', expect.any(String))156+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo.html', expect.any(String))157+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/Charlie.html', expect.any(String))158+ })159+160+ it('should modify the request if the hook is provided', async () => {161+ const fsMock: FileSystemModule = {162+ writeFile: vi.fn(() => Promise.resolve()),163+ mkdir: vi.fn(() => Promise.resolve()),164+ }165+ const beforeRequestHook: BeforeRequestHook = (req) => {166+ if (req.method === 'GET') {167+ return req168+ }169+ return false170+ }171+ const result = await toSSG(app, fsMock, { beforeRequestHook })172+ expect(result.files).toHaveLength(11)173+ })174+175+ it('should skip the route if the request hook returns false', async () => {176+ const beforeRequest: BeforeRequestHook = () => false177+ const htmlMap = await fetchRoutesContent(app, beforeRequest)178+ expect(htmlMap.size).toBe(0)179+ })180+181+ it('should modify the response if the hook is provided', async () => {182+ const afterResponseHook: AfterResponseHook = (res) => {183+ if (res.status === 200 || res.status === 500) {184+ return res185+ }186+ return false187+ }188+ const fsMock: FileSystemModule = {189+ writeFile: vi.fn(() => Promise.resolve()),190+ mkdir: vi.fn(() => Promise.resolve()),191+ }192+ const result = await toSSG(app, fsMock, { afterResponseHook })193+ expect(result.files).toHaveLength(10)194+ })195+196+ it('should skip the route if the response hook returns false', async () => {197+ const afterResponse: AfterResponseHook = () => false198+ const htmlMap = await fetchRoutesContent(app, undefined, afterResponse)199+ expect(htmlMap.size).toBe(0)200+ })201+202+ it('should execute additional processing using afterGenerateHook', async () => {203+ const fsMock: FileSystemModule = {204+ writeFile: vi.fn(() => Promise.resolve()),205+ mkdir: vi.fn(() => Promise.resolve()),206+ }207+ const afterGenerateHookMock: AfterGenerateHook = vi.fn((result) => {208+ if (result.files) {209+ result.files.forEach((file) => console.log(file))210+ }211+ })212+213+ await toSSG(app, fsMock, { dir: './static', afterGenerateHook: afterGenerateHookMock })214+215+ expect(afterGenerateHookMock).toHaveBeenCalled()216+ expect(afterGenerateHookMock).toHaveBeenCalledWith(expect.anything())217+ })218+})219+220+describe('fetchRoutesContent function', () => {221+ let app: Hono222+223+ beforeEach(() => {224+ app = new Hono()225+ app.get('/text', (c) => c.text('Text Response'))226+ app.get('/html', (c) => c.html('<p>HTML Response</p>'))227+ app.get('/json', (c) => c.json({ message: 'JSON Response' }))228+ app.use('*', poweredBy())229+ })230+231+ it('should fetch the correct content and MIME type for each route', async () => {232+ const htmlMap = await fetchRoutesContent(app)233+ expect(htmlMap.get('/text')).toEqual({234+ content: 'Text Response',235+ mimeType: 'text/plain',236+ })237+ expect(htmlMap.get('/html')).toEqual({238+ content: '<p>HTML Response</p>',239+ mimeType: 'text/html',240+ })241+ expect(htmlMap.get('/json')).toEqual({242+ content: '{"message":"JSON Response"}',243+ mimeType: 'application/json',244+ })245+ })246+247+ it('should skip middleware routes', async () => {248+ const htmlMap = await fetchRoutesContent(app)249+ expect(htmlMap.has('*')).toBeFalsy()250+ })251+252+ it('should handle errors correctly', async () => {253+ vi.spyOn(app, 'fetch').mockRejectedValue(new Error('Network error'))254+ await expect(fetchRoutesContent(app)).rejects.toThrow('Network error')255+ vi.restoreAllMocks()256+ })257+})258+259+describe('saveContentToFiles function', () => {260+ let fsMock: FileSystemModule261+ let htmlMap: Map<string, { content: string | ArrayBuffer; mimeType: string }>262+263+ beforeEach(() => {264+ fsMock = {265+ writeFile: vi.fn(() => Promise.resolve()),266+ mkdir: vi.fn(() => Promise.resolve()),267+ }268+ htmlMap = new Map([269+ ['/', { content: 'Home Page', mimeType: 'text/html' }],270+ ['/about', { content: 'About Page', mimeType: 'text/html' }],271+ ['/about/', { content: 'About Page', mimeType: 'text/html' }],272+ ])273+ })274+275+ it('should correctly create files with the right content and paths', async () => {276+ await saveContentToFiles(htmlMap, fsMock, './static')277+278+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', 'Home Page')279+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/about.html', 'About Page')280+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/about/index.html', 'About Page')281+ })282+283+ it('should correctly create directories if they do not exist', async () => {284+ await saveContentToFiles(htmlMap, fsMock, './static')285+286+ expect(fsMock.mkdir).toHaveBeenCalledWith('static', { recursive: true })287+ })288+289+ it('should handle file writing or directory creation errors', async () => {290+ const fsMock: FileSystemModule = {291+ writeFile: vi.fn(() => Promise.resolve()),292+ mkdir: vi.fn(() => Promise.reject(new Error('File write error'))),293+ }294+295+ await expect(saveContentToFiles(htmlMap, fsMock, './static')).rejects.toThrow(296+ 'File write error'297+ )298+ })299+})300+301+describe('Dynamic route handling', () => {302+ let app: Hono303+ beforeEach(() => {304+ app = new Hono()305+ app.get('/shops/:id', (c) => c.html('Shop Page'))306+ app.get('/shops/:id/:comments([0-9]+)', (c) => c.html('Comments Page'))307+ app.get('/foo/*', (c) => c.html('Foo Page'))308+ app.get('/foo:bar', (c) => c.html('Foo Bar Page'))309+ })310+311+ it('should skip /shops/:id dynamic route', async () => {312+ const htmlMap = await fetchRoutesContent(app)313+ expect(htmlMap.has('/shops/:id')).toBeFalsy()314+ })315+316+ it('should skip /shops/:id/:comments([0-9]+) dynamic route', async () => {317+ const htmlMap = await fetchRoutesContent(app)318+ expect(htmlMap.has('/shops/:id/:comments([0-9]+)')).toBeFalsy()319+ })320+321+ it('should skip /foo/* dynamic route', async () => {322+ const htmlMap = await fetchRoutesContent(app)323+ expect(htmlMap.has('/foo/*')).toBeFalsy()324+ })325+326+ it('should not skip /foo:bar dynamic route', async () => {327+ const htmlMap = await fetchRoutesContent(app)328+ expect(htmlMap.has('/foo:bar')).toBeTruthy()329+ })330+})331+332+describe('disableSSG/onlySSG middlewares', () => {333+ const app = new Hono()334+ app.get('/', (c) => c.html(<h1>Hello</h1>))335+ app.get('/api', disableSSG(), (c) => c.text('an-api'))336+ app.get('/static-page', onlySSG(), (c) => c.html(<h1>Welcome to my site</h1>))337+338+ it('Should not generate the page if disableSSG is set', async () => {339+ const htmlMap = await fetchRoutesContent(app)340+ expect(htmlMap.has('/')).toBe(true)341+ expect(htmlMap.has('/static-page')).toBe(true)342+ expect(htmlMap.has('/api')).toBe(false)343+ })344+345+ it('Should return 404 response if onlySSG() is set', async () => {346+ const res = await app.request('/static-page')347+ expect(res.status).toBe(404)348+ })349+})added:src/helper/ssg/index.ts+286 added
1+import { replaceUrlParam } from '../../client/utils'2+import type { Context } from '../../context'3+import { inspectRoutes } from '../../helper/dev'4+import type { Hono } from '../../hono'5+import type { Env, MiddlewareHandler, Schema } from '../../types'6+import { bufferToString } from '../../utils/buffer'7+import { getExtension } from '../../utils/mime'8+import { joinPaths, dirname } from './utils'9+10+export const X_HONO_SSG_HEADER_KEY = 'x-hono-ssg'11+export const X_HONO_DISABLE_SSG_HEADER_KEY = 'x-hono-disable-ssg'12+13+/**14+ * @experimental15+ * `FileSystemModule` is an experimental feature.16+ * The API might be changed.17+ */18+export interface FileSystemModule {19+ writeFile(path: string, data: string | Uint8Array): Promise<void>20+ mkdir(path: string, options: { recursive: boolean }): Promise<void | string>21+}22+23+/**24+ * @experimental25+ * `ToSSGResult` is an experimental feature.26+ * The API might be changed.27+ */28+export interface ToSSGResult {29+ success: boolean30+ files: string[]31+ error?: Error32+}33+34+const generateFilePath = (routePath: string, outDir: string, mimeType: string) => {35+ const extension = determineExtension(mimeType)36+ if (routePath === '/') {37+ return joinPaths(outDir, `index.${extension}`)38+ }39+ if (routePath.endsWith('/')) {40+ return joinPaths(outDir, routePath, `index.${extension}`)41+ }42+ return joinPaths(outDir, `${routePath}.${extension}`)43+}44+45+const parseResponseContent = async (response: Response): Promise<string | ArrayBuffer> => {46+ const contentType = response.headers.get('Content-Type')47+48+ try {49+ if (contentType?.includes('text') || contentType?.includes('json')) {50+ return await response.text()51+ } else {52+ return await response.arrayBuffer()53+ }54+ } catch (error) {55+ throw new Error(56+ `Error processing response: ${error instanceof Error ? error.message : 'Unknown error'}`57+ )58+ }59+}60+61+const determineExtension = (mimeType: string): string => {62+ switch (mimeType) {63+ case 'text/html':64+ return 'html'65+ case 'text/xml':66+ case 'application/xml':67+ return 'xml'68+ default: {69+ return getExtension(mimeType) || 'html'70+ }71+ }72+}73+74+interface SSGParam {75+ [key: string]: string76+}77+type SSGParams = SSGParam[]78+79+interface SSGParamsMiddleware {80+ <E extends Env = Env>(81+ generateParams: (c: Context<E>) => SSGParams | Promise<SSGParams>82+ ): MiddlewareHandler<E>83+ <E extends Env = Env>(params: SSGParams): MiddlewareHandler<E>84+}85+86+type AddedSSGDataRequest = Request & {87+ ssgParams?: SSGParams88+}89+/**90+ * Define SSG Route91+ */92+export const ssgParams: SSGParamsMiddleware = (params) => async (c, next) => {93+ ;(c.req.raw as AddedSSGDataRequest).ssgParams = Array.isArray(params) ? params : await params(c)94+ await next()95+}96+97+export type BeforeRequestHook = (req: Request) => Request | false98+export type AfterResponseHook = (res: Response) => Response | false99+export type AfterGenerateHook = (result: ToSSGResult) => void | Promise<void>100+101+export interface ToSSGOptions {102+ dir?: string103+ beforeRequestHook?: BeforeRequestHook104+ afterResponseHook?: AfterResponseHook105+ afterGenerateHook?: AfterGenerateHook106+}107+108+/**109+ * @experimental110+ * `fetchRoutesContent` is an experimental feature.111+ * The API might be changed.112+ */113+export const fetchRoutesContent = async <114+ E extends Env = Env,115+ S extends Schema = {},116+ BasePath extends string = '/'117+>(118+ app: Hono<E, S, BasePath>,119+ beforeRequestHook?: BeforeRequestHook,120+ afterResponseHook?: AfterResponseHook121+): Promise<Map<string, { content: string | ArrayBuffer; mimeType: string }>> => {122+ const htmlMap = new Map<string, { content: string | ArrayBuffer; mimeType: string }>()123+ const baseURL = 'http://localhost'124+125+ for (const route of inspectRoutes(app)) {126+ if (route.isMiddleware) {127+ continue128+ }129+130+ // GET Route Info131+ const thisRouteBaseURL = new URL(route.path, baseURL).toString()132+133+ let forGetInfoURLRequest = new Request(thisRouteBaseURL) as AddedSSGDataRequest134+ forGetInfoURLRequest.headers.set(X_HONO_SSG_HEADER_KEY, 'true')135+ if (beforeRequestHook) {136+ const maybeRequest = beforeRequestHook(forGetInfoURLRequest)137+ if (!maybeRequest) {138+ continue139+ }140+ forGetInfoURLRequest = maybeRequest as unknown as AddedSSGDataRequest141+ }142+ await app.fetch(forGetInfoURLRequest)143+144+ if (!forGetInfoURLRequest.ssgParams) {145+ if (isDynamicRoute(route.path)) {146+ continue147+ }148+ forGetInfoURLRequest.ssgParams = [{}]149+ }150+151+ for (const param of forGetInfoURLRequest.ssgParams) {152+ const replacedUrlParam = replaceUrlParam(route.path, param)153+ let response = await app.request(replacedUrlParam, forGetInfoURLRequest)154+ if (response.headers.get(X_HONO_DISABLE_SSG_HEADER_KEY)) {155+ continue156+ }157+ if (afterResponseHook) {158+ const maybeResponse = afterResponseHook(response)159+ if (!maybeResponse) {160+ continue161+ }162+ response = maybeResponse163+ }164+ const mimeType = response.headers.get('Content-Type')?.split(';')[0] || 'text/plain'165+ const content = await parseResponseContent(response)166+ htmlMap.set(replacedUrlParam, {167+ mimeType,168+ content,169+ })170+ }171+ }172+173+ return htmlMap174+}175+176+const isDynamicRoute = (path: string): boolean => {177+ return path.split('/').some((segment) => segment.startsWith(':') || segment.includes('*'))178+}179+180+/**181+ * @experimental182+ * `saveContentToFiles` is an experimental feature.183+ * The API might be changed.184+ */185+export const saveContentToFiles = async (186+ htmlMap: Map<string, { content: string | ArrayBuffer; mimeType: string }>,187+ fsModule: FileSystemModule,188+ outDir: string189+): Promise<string[]> => {190+ const files: string[] = []191+192+ for (const [routePath, { content, mimeType }] of htmlMap) {193+ const filePath = generateFilePath(routePath, outDir, mimeType)194+ const dirPath = dirname(filePath)195+196+ await fsModule.mkdir(dirPath, { recursive: true })197+ if (typeof content === 'string') {198+ await fsModule.writeFile(filePath, content)199+ } else if (content instanceof ArrayBuffer) {200+ await fsModule.writeFile(filePath, bufferToString(content))201+ }202+ files.push(filePath)203+ }204+205+ return files206+}207+208+/**209+ * @experimental210+ * `ToSSGInterface` is an experimental feature.211+ * The API might be changed.212+ */213+export interface ToSSGInterface<214+ E extends Env = Env,215+ S extends Schema = {},216+ BasePath extends string = '/'217+> {218+ (219+ app: Hono<E, S, BasePath>,220+ fsModule: FileSystemModule,221+ options?: ToSSGOptions222+ ): Promise<ToSSGResult>223+}224+225+/**226+ * @experimental227+ * `ToSSGAdaptorInterface` is an experimental feature.228+ * The API might be changed.229+ */230+export interface ToSSGAdaptorInterface<231+ E extends Env = Env,232+ S extends Schema = {},233+ BasePath extends string = '/'234+> {235+ (app: Hono<E, S, BasePath>, options?: ToSSGOptions): Promise<ToSSGResult>236+}237+238+/**239+ * @experimental240+ * `toSSG` is an experimental feature.241+ * The API might be changed.242+ */243+export const toSSG: ToSSGInterface = async (app, fs, options) => {244+ let result: ToSSGResult | undefined = undefined245+ try {246+ const outputDir = options?.dir ?? './static'247+ const maps = await fetchRoutesContent(248+ app,249+ options?.beforeRequestHook,250+ options?.afterResponseHook251+ )252+ const files = await saveContentToFiles(maps, fs, outputDir)253+ result = { success: true, files }254+ } catch (error) {255+ const errorObj = error instanceof Error ? error : new Error(String(error))256+ result = { success: false, files: [], error: errorObj }257+ }258+ await options?.afterGenerateHook?.(result)259+ return result260+}261+262+/**263+ * @experimental264+ * `disableSSG` is an experimental feature.265+ * The API might be changed.266+ */267+268+export const disableSSG = (): MiddlewareHandler =>269+ async function disableSSG(c, next) {270+ await next()271+ c.header(X_HONO_DISABLE_SSG_HEADER_KEY, 'true')272+ }273+274+/**275+ * @experimental276+ * `onlySSG` is an experimental feature.277+ * The API might be changed.278+ */279+export const onlySSG = (): MiddlewareHandler =>280+ async function onlySSG(c, next) {281+ const headerValue = c.req.raw.headers.get(X_HONO_SSG_HEADER_KEY)282+ if (headerValue) {283+ await next()284+ }285+ return c.notFound()286+ }added:src/helper/ssg/utils.test.ts+33 added
1+import { describe, it, expect } from 'vitest'2+import { joinPaths, dirname } from './utils'3+4+describe('joinPath', () => {5+ it('Should joined path is valid.', () => {6+ expect(joinPaths('test')).toBe('test') //single7+ expect(joinPaths('.test')).toBe('.test') //single with dot8+ expect(joinPaths('/.test')).toBe('/.test') //single with dot with root9+ expect(joinPaths('test', 'test2')).toBe('test/test2') // single and single10+ expect(joinPaths('test', 'test2', '../test3')).toBe('test/test3') // single and single and single with parent11+ expect(joinPaths('.', '../')).toBe('..') // dot and parent12+ expect(joinPaths('test/', 'test2/')).toBe('test/test2') // trailing slashes13+ expect(joinPaths('./test', './test2')).toBe('test/test2') // dot and slash14+ expect(joinPaths('', 'test')).toBe('test') // empty path15+ expect(joinPaths('/test', '/test2')).toBe('/test/test2') // root path16+ expect(joinPaths('../', 'test')).toBe('../test') // parent and single17+ expect(joinPaths('test', '..', 'test2')).toBe('test2') // single triple dot and single18+ expect(joinPaths('test', '...', 'test2')).toBe('test/.../test2') // single triple dot and single19+ expect(joinPaths('test', './test2', '.test3.')).toBe('test/test2/.test3.') // single and single with slash and single with dot20+ expect(joinPaths('test', '../', '.test2')).toBe('.test2') // single and parent and single with dot21+ expect(joinPaths('.test../test2/../')).toBe('.test..') //shuffle22+ expect(joinPaths('.test./.test2/../')).toBe('.test.') //shuffle223+ })24+ it('Should windows path is valid.', () => {25+ expect(joinPaths('a\\b\\c', 'd\\e')).toBe('a/b/c/d/e')26+ })27+})28+describe('dirname', () => {29+ it('Should dirname is valid.', () => {30+ expect(dirname('parent/child')).toBe('parent')31+ expect(dirname('windows\\test.txt')).toBe('windows')32+ })33+})added:src/helper/ssg/utils.ts+47 added
1+/**2+ * Get dirname3+ * @param path File Path4+ * @returns Parent dir path5+ */6+export const dirname = (path: string) => {7+ const splitedPath = path.split(/[\/\\]/)8+ return splitedPath.slice(0, -1).join('/') // Windows supports slash path9+}10+11+const normalizePath = (path: string) => {12+ return path.replace(/(\\)/g, '/').replace(/\/$/g, '')13+}14+15+const handleDotDot = (resultPaths: string[]) => {16+ if (resultPaths.length === 0) {17+ resultPaths.push('..')18+ } else {19+ resultPaths.pop()20+ }21+}22+23+const handleNonDot = (path: string, resultPaths: string[]) => {24+ path = path.replace(/^\.(?!.)/, '')25+ if (path !== '') {26+ resultPaths.push(path)27+ }28+}29+30+const handleSegments = (paths: string[], resultPaths: string[]) => {31+ for (const path of paths) {32+ // Handle `..` or `../`33+ if (path === '..') {34+ handleDotDot(resultPaths)35+ } else {36+ // Handle `.` or `./`37+ handleNonDot(path, resultPaths)38+ }39+ }40+}41+42+export const joinPaths = (...paths: string[]) => {43+ paths = paths.map(normalizePath)44+ const resultPaths: string[] = []45+ handleSegments(paths.join('/').split('/'), resultPaths)46+ return (paths[0][0] === '/' ? '/' : '') + resultPaths.join('/')47+}added:src/jsx/dom/components.test.tsx+223 added
1+import { JSDOM } from 'jsdom'2+import { Suspense as SuspenseCommon, ErrorBoundary as ErrorBoundaryCommon } from '..' // for common3+// run tests by old style jsx default4+// hono/jsx/jsx-runtime and hono/jsx/dom/jsx-runtime are tested in their respective settings5+// eslint-disable-next-line @typescript-eslint/no-unused-vars6+import { jsx } from '..'7+import { use, useState } from '../hooks'8+import { Suspense as SuspenseDom, ErrorBoundary as ErrorBoundaryDom } from '.' // for dom9+import { render } from '.'10+11+runner('Common', SuspenseCommon, ErrorBoundaryCommon)12+runner('DOM', SuspenseDom, ErrorBoundaryDom)13+14+function runner(15+ name: string,16+ Suspense: typeof SuspenseDom,17+ ErrorBoundary: typeof ErrorBoundaryDom18+) {19+ describe(name, () => {20+ beforeAll(() => {21+ global.requestAnimationFrame = (cb) => setTimeout(cb)22+ })23+24+ describe('Suspense', () => {25+ 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+ })36+37+ it('has no lazy load content', async () => {38+ const App = <Suspense fallback={<div>Loading...</div>}>Hello</Suspense>39+ render(App, root)40+ expect(root.innerHTML).toBe('Hello')41+ })42+43+ it('with use()', async () => {44+ let resolve: (value: number) => void = () => {}45+ const promise = new Promise<number>((_resolve) => (resolve = _resolve))46+ const Content = () => {47+ const num = use(promise)48+ return <p>{num}</p>49+ }50+ const Component = () => {51+ return (52+ <Suspense fallback={<div>Loading...</div>}>53+ <Content />54+ </Suspense>55+ )56+ }57+ const App = <Component />58+ render(App, root)59+ expect(root.innerHTML).toBe('<div>Loading...</div>')60+ resolve(1)61+ await new Promise((resolve) => setTimeout(resolve))62+ expect(root.innerHTML).toBe('<p>1</p>')63+ })64+65+ it('with use() nested', async () => {66+ let resolve: (value: number) => void = () => {}67+ const promise = new Promise<number>((_resolve) => (resolve = _resolve))68+ const Content = () => {69+ const num = use(promise)70+ return <p>{num}</p>71+ }72+ let resolve2: (value: number) => void = () => {}73+ const promise2 = new Promise<number>((_resolve) => (resolve2 = _resolve))74+ const Content2 = () => {75+ const num = use(promise2)76+ return <p>{num}</p>77+ }78+ const Component = () => {79+ return (80+ <Suspense fallback={<div>Loading...</div>}>81+ <Content />82+ <Suspense fallback={<div>More...</div>}>83+ <Content2 />84+ </Suspense>85+ </Suspense>86+ )87+ }88+ const App = <Component />89+ render(App, root)90+ expect(root.innerHTML).toBe('<div>Loading...</div>')91+ resolve(1)92+ await new Promise((resolve) => setTimeout(resolve))93+ expect(root.innerHTML).toBe('<p>1</p><div>More...</div>')94+ resolve2(2)95+ await new Promise((resolve) => setTimeout(resolve))96+ expect(root.innerHTML).toBe('<p>1</p><p>2</p>')97+ })98+99+ it('race condition', async () => {100+ let resolve: (value: number) => void = () => {}101+ const promise = new Promise<number>((_resolve) => (resolve = _resolve))102+ const Content = () => {103+ const num = use(promise)104+ return <p>{num}</p>105+ }106+ const Component = () => {107+ const [show, setShow] = useState(false)108+ return (109+ <div>110+ <button onClick={() => setShow((s) => !s)}>{show ? 'Hide' : 'Show'}</button>111+ {show && (112+ <Suspense fallback={<div>Loading...</div>}>113+ <Content />114+ </Suspense>115+ )}116+ </div>117+ )118+ }119+ const App = <Component />120+ render(App, root)121+ expect(root.innerHTML).toBe('<div><button>Show</button></div>')122+ root.querySelector('button')?.click()123+ await Promise.resolve()124+ expect(root.innerHTML).toBe('<div><button>Hide</button><div>Loading...</div></div>')125+ root.querySelector('button')?.click()126+ await Promise.resolve()127+ expect(root.innerHTML).toBe('<div><button>Show</button></div>')128+ root.querySelector('button')?.click()129+ await Promise.resolve()130+ expect(root.innerHTML).toBe('<div><button>Hide</button><div>Loading...</div></div>')131+ resolve(2)132+ await Promise.resolve()133+ await Promise.resolve()134+ expect(root.innerHTML).toBe('<div><button>Hide</button><p>2</p></div>')135+ })136+ })137+138+ describe('ErrorBoundary', () => {139+ let dom: JSDOM140+ let root: HTMLElement141+ beforeEach(() => {142+ dom = new JSDOM('<html><body><div id="root"></div></body></html>', {143+ runScripts: 'dangerously',144+ })145+ global.document = dom.window.document146+ global.HTMLElement = dom.window.HTMLElement147+ global.Text = dom.window.Text148+ root = document.getElementById('root') as HTMLElement149+ })150+151+ it('has no error', async () => {152+ const App = (153+ <ErrorBoundary fallback={<div>Error</div>}>154+ <div>OK</div>155+ </ErrorBoundary>156+ )157+ render(App, root)158+ expect(root.innerHTML).toBe('<div>OK</div>')159+ })160+161+ it('has error', async () => {162+ const Component = () => {163+ throw new Error('error')164+ }165+ const App = (166+ <ErrorBoundary fallback={<div>Error</div>}>167+ <Component />168+ </ErrorBoundary>169+ )170+ render(App, root)171+ expect(root.innerHTML).toBe('<div>Error</div>')172+ })173+174+ it('has no error with Suspense', async () => {175+ let resolve: (value: number) => void = () => {}176+ const promise = new Promise<number>((_resolve) => (resolve = _resolve))177+ const Content = () => {178+ const num = use(promise)179+ return <p>{num}</p>180+ }181+ const Component = () => {182+ return (183+ <ErrorBoundary fallback={<div>Error</div>}>184+ <Suspense fallback={<div>Loading...</div>}>185+ <Content />186+ </Suspense>187+ </ErrorBoundary>188+ )189+ }190+ const App = <Component />191+ render(App, root)192+ expect(root.innerHTML).toBe('<div>Loading...</div>')193+ resolve(1)194+ await new Promise((resolve) => setTimeout(resolve))195+ expect(root.innerHTML).toBe('<p>1</p>')196+ })197+198+ it('has error with Suspense', async () => {199+ let resolve: (value: number) => void = () => {}200+ const promise = new Promise<number>((_resolve) => (resolve = _resolve))201+ const Content = () => {202+ use(promise)203+ throw new Error('error')204+ }205+ const Component = () => {206+ return (207+ <ErrorBoundary fallback={<div>Error</div>}>208+ <Suspense fallback={<div>Loading...</div>}>209+ <Content />210+ </Suspense>211+ </ErrorBoundary>212+ )213+ }214+ const App = <Component />215+ render(App, root)216+ expect(root.innerHTML).toBe('<div>Loading...</div>')217+ resolve(1)218+ await new Promise((resolve) => setTimeout(resolve))219+ expect(root.innerHTML).toBe('<div>Error</div>')220+ })221+ })222+ })223+}added:src/jsx/dom/components.ts+39 added
1+import type { FC, PropsWithChildren, Child } from '..'2+import type { FallbackRender, ErrorHandler } from '../components'3+import { DOM_ERROR_HANDLER } from '../constants'4+import { Fragment } from './jsx-runtime'5+6+/* eslint-disable @typescript-eslint/no-explicit-any */7+export const ErrorBoundary: FC<8+ PropsWithChildren<{9+ fallback?: Child10+ fallbackRender?: FallbackRender11+ onError?: ErrorHandler12+ }>13+> = (({ children, fallback, fallbackRender, onError }: any) => {14+ const res = Fragment({ children })15+ ;(res as any)[DOM_ERROR_HANDLER] = (err: any) => {16+ if (err instanceof Promise) {17+ throw err18+ }19+ onError?.(err)20+ return fallbackRender?.(err) || fallback21+ }22+ return res23+}) as any24+25+export const Suspense: FC<PropsWithChildren<{ fallback: any }>> = (({26+ children,27+ fallback,28+}: any) => {29+ const res = Fragment({ children })30+ ;(res as any)[DOM_ERROR_HANDLER] = (err: any, retry: () => void) => {31+ if (!(err instanceof Promise)) {32+ throw err33+ }34+ err.finally(retry)35+ return fallback36+ }37+ return res38+}) as any39+/* eslint-enable @typescript-eslint/no-explicit-any */added:src/jsx/dom/context.test.tsx+135 added
1+import { JSDOM } from 'jsdom'2+import { createContext as createContextCommon, useContext as useContextCommon } from '..' // for common3+import { use, Suspense } from '..'4+// run tests by old style jsx default5+// hono/jsx/jsx-runtime and hono/jsx/dom/jsx-runtime are tested in their respective settings6+// eslint-disable-next-line @typescript-eslint/no-unused-vars7+import { jsx, Fragment } from '..'8+import { createContext as createContextDom, useContext as useContextDom } from '.' // for dom9+import { render } from '.'10+11+runner('Common', createContextCommon, useContextCommon)12+runner('DOM', createContextDom, useContextDom)13+14+function runner(15+ name: string,16+ createContext: typeof createContextCommon,17+ useContext: typeof useContextCommon18+) {19+ describe(name, () => {20+ beforeAll(() => {21+ global.requestAnimationFrame = (cb) => setTimeout(cb)22+ })23+24+ describe('Context', () => {25+ 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+ })36+37+ it('simple context', async () => {38+ const Context = createContext(0)39+ const Content = () => {40+ const num = useContext(Context)41+ return <p>{num}</p>42+ }43+ const Component = () => {44+ return (45+ <Context.Provider value={1}>46+ <Content />47+ </Context.Provider>48+ )49+ }50+ const App = <Component />51+ render(App, root)52+ expect(root.innerHTML).toBe('<p>1</p>')53+ })54+55+ it('multiple provider', async () => {56+ const Context = createContext(0)57+ const Content = () => {58+ const num = useContext(Context)59+ return <p>{num}</p>60+ }61+ const Component = () => {62+ return (63+ <>64+ <Context.Provider value={1}>65+ <Content />66+ </Context.Provider>67+ <Context.Provider value={2}>68+ <Content />69+ </Context.Provider>70+ </>71+ )72+ }73+ const App = <Component />74+ render(App, root)75+ expect(root.innerHTML).toBe('<p>1</p><p>2</p>')76+ })77+78+ it('nested provider', async () => {79+ const Context = createContext(0)80+ const Content = () => {81+ const num = useContext(Context)82+ return <p>{num}</p>83+ }84+ const Component = () => {85+ return (86+ <>87+ <Context.Provider value={1}>88+ <Content />89+ <Context.Provider value={3}>90+ <Content />91+ </Context.Provider>92+ <Content />93+ </Context.Provider>94+ </>95+ )96+ }97+ const App = <Component />98+ render(App, root)99+ expect(root.innerHTML).toBe('<p>1</p><p>3</p><p>1</p>')100+ })101+102+ it('inside Suspense', async () => {103+ const promise = Promise.resolve(2)104+ const AsyncComponent = () => {105+ const num = use(promise)106+ return <p>{num}</p>107+ }108+ const Context = createContext(0)109+ const Content = () => {110+ const num = useContext(Context)111+ return <p>{num}</p>112+ }113+ const Component = () => {114+ return (115+ <>116+ <Context.Provider value={1}>117+ <Content />118+ <Suspense fallback={<div>Loading...</div>}>119+ <Context.Provider value={3}>120+ <Content />121+ <AsyncComponent />122+ </Context.Provider>123+ </Suspense>124+ <Content />125+ </Context.Provider>126+ </>127+ )128+ }129+ const App = <Component />130+ render(App, root)131+ expect(root.innerHTML).toBe('<p>1</p><div>Loading...</div><p>1</p>')132+ })133+ })134+ })135+}added:src/jsx/dom/context.ts+42 added
1+import type { Child } from '../base'2+import { DOM_ERROR_HANDLER } from '../constants'3+import type { Context } from '../context'4+import { globalContexts } from '../context'5+import { Fragment } from './jsx-runtime'6+7+export const createContextProviderFunction =8+ <T>(values: T[]) =>9+ ({ value, children }: { value: T; children: Child[] }) => {10+ const res = Fragment({11+ children: [12+ {13+ tag: () => {14+ values.push(value)15+ },16+ },17+ ...(children as Child[]),18+ {19+ tag: () => {20+ values.pop()21+ },22+ },23+ ],24+ })25+ // eslint-disable-next-line @typescript-eslint/no-explicit-any26+ ;(res as any)[DOM_ERROR_HANDLER] = (err: unknown) => {27+ values.pop()28+ throw err29+ }30+ return res31+ }32+33+export const createContext = <T>(defaultValue: T): Context<T> => {34+ const values = [defaultValue]35+ const context = {36+ values,37+ // eslint-disable-next-line @typescript-eslint/no-explicit-any38+ Provider: createContextProviderFunction(values) as any,39+ }40+ globalContexts.push(context)41+ return context42+}added:src/jsx/dom/css.test.tsx+109 added
1+import { JSDOM } from 'jsdom'2+// run tests by old style jsx default3+// hono/jsx/jsx-runtime and hono/jsx/dom/jsx-runtime are tested in their respective settings4+// eslint-disable-next-line @typescript-eslint/no-unused-vars5+import { jsx } from '..'6+import type { JSXNode } from '..'7+import { Style, css, rawCssString, createCssContext } from '../../helper/css'8+import { minify } from '../../helper/css/common'9+import { renderTest } from '../../helper/css/common.test'10+import { render } from '.'11+12+describe('Style and css for jsx/dom', () => {13+ beforeAll(() => {14+ global.requestAnimationFrame = (cb) => setTimeout(cb)15+ })16+17+ let dom: JSDOM18+ let root: HTMLElement19+ beforeEach(() => {20+ dom = new JSDOM('<html><body><div id="root"></div></body></html>', {21+ runScripts: 'dangerously',22+ })23+ global.document = dom.window.document24+ global.HTMLElement = dom.window.HTMLElement25+ global.Text = dom.window.Text26+ root = document.getElementById('root') as HTMLElement27+ })28+29+ it('<Style />', async () => {30+ const App = () => {31+ return (32+ <div>33+ <Style />34+ <div35+ class={css`36+ color: red;37+ `}38+ >39+ red40+ </div>41+ </div>42+ )43+ }44+ render(<App />, root)45+ expect(root.innerHTML).toBe(46+ '<div><style id="hono-css"></style><div class="css-3142110215">red</div></div>'47+ )48+ await Promise.resolve()49+ expect(root.querySelector('style')?.sheet?.cssRules[0].cssText).toBe(50+ '.css-3142110215 {color: red;}'51+ )52+ })53+54+ it('<Style>{css`global`}</Style>', async () => {55+ const App = () => {56+ return (57+ <div>58+ <Style>{css`59+ color: red;60+ `}</Style>61+ <div62+ class={css`63+ color: red;64+ `}65+ >66+ red67+ </div>68+ </div>69+ )70+ }71+ render(<App />, root)72+ expect(root.innerHTML).toBe(73+ '<div><style id="hono-css">color:red</style><div class="css-3142110215">red</div></div>'74+ )75+ })76+})77+78+describe('render', () => {79+ renderTest(() => {80+ const cssContext = createCssContext({ id: 'hono-css' })81+82+ const dom = new JSDOM('<html><body><div id="root"></div></body></html>', {83+ runScripts: 'dangerously',84+ })85+ global.document = dom.window.document86+ global.HTMLElement = dom.window.HTMLElement87+ global.Text = dom.window.Text88+ const root = document.getElementById('root') as HTMLElement89+90+ const toString = async (node: JSXNode) => {91+ render(node, root)92+ await Promise.resolve()93+ const style = root.querySelector('style')94+ if (style) {95+ style.textContent = minify(96+ [...(style.sheet?.cssRules || [])].map((r) => r.cssText).join('') || ''97+ )98+ }99+ return root.innerHTML100+ }101+102+ return {103+ toString,104+ rawCssString,105+ ...cssContext,106+ support: { nest: false },107+ }108+ })109+})added:src/jsx/dom/css.ts+206 added
1+import type { FC, PropsWithChildren } from '..'2+import type { CssClassName, CssVariableType } from '../../helper/css/common'3+import {4+ SELECTOR,5+ CLASS_NAME,6+ STYLE_STRING,7+ SELECTORS,8+ PSEUDO_GLOBAL_SELECTOR,9+ DEFAULT_STYLE_ID,10+ cssCommon,11+ cxCommon,12+ keyframesCommon,13+ viewTransitionCommon,14+} from '../../helper/css/common'15+export { rawCssString } from '../../helper/css/common'16+17+const splitRule = (rule: string): string[] => {18+ const result: string[] = []19+ let startPos = 020+ let depth = 021+ for (let i = 0, len = rule.length; i < len; i++) {22+ const char = rule[i]23+24+ // consume quote25+ // eslint-disable-next-line quotes26+ if (char === "'" || char === '"') {27+ const quote = char28+ i++29+ for (; i < len; i++) {30+ if (rule[i] === '\\') {31+ i++32+ continue33+ }34+ if (rule[i] === quote) {35+ break36+ }37+ }38+ continue39+ }40+41+ // comments are removed from the rule in advance42+43+ if (char === '{') {44+ depth++45+ continue46+ }47+ if (char === '}') {48+ depth--49+ if (depth === 0) {50+ result.push(rule.slice(startPos, i + 1))51+ startPos = i + 152+ }53+ continue54+ }55+ }56+ return result57+}58+59+export const createCssJsxDomObjects = ({ id }: { id: Readonly<string> }) => {60+ let styleSheet: CSSStyleSheet | null | undefined = undefined61+ const findStyleSheet = (): [CSSStyleSheet, Set<string>] | [] => {62+ if (!styleSheet) {63+ styleSheet = document.querySelector<HTMLStyleElement>(`style#${id}`)64+ ?.sheet as CSSStyleSheet | null65+ if (styleSheet) {66+ // eslint-disable-next-line @typescript-eslint/no-explicit-any67+ ;(styleSheet as any).addedStyles = new Set<string>()68+ }69+ }70+ // eslint-disable-next-line @typescript-eslint/no-explicit-any71+ return styleSheet ? [styleSheet, (styleSheet as any).addedStyles] : []72+ }73+74+ const insertRule = (className: string, styleString: string) => {75+ const [sheet, addedStyles] = findStyleSheet()76+ if (!sheet || !addedStyles) {77+ Promise.resolve().then(() => {78+ if (!findStyleSheet()[0]) {79+ throw new Error('style sheet not found')80+ }81+ insertRule(className, styleString)82+ })83+ return84+ }85+86+ if (!addedStyles.has(className)) {87+ addedStyles.add(className)88+ ;(className.startsWith(PSEUDO_GLOBAL_SELECTOR)89+ ? splitRule(styleString)90+ : [`${className[0] === '@' ? '' : '.'}${className}{${styleString}}`]91+ ).forEach((rule) => {92+ sheet.insertRule(rule, sheet.cssRules.length)93+ })94+ }95+ }96+97+ const cssObject = {98+ toString(this: CssClassName): string {99+ const selector = this[SELECTOR]100+ insertRule(selector, this[STYLE_STRING])101+ this[SELECTORS].forEach(({ [CLASS_NAME]: className, [STYLE_STRING]: styleString }) => {102+ insertRule(className, styleString)103+ })104+105+ return this[CLASS_NAME]106+ },107+ }108+109+ // eslint-disable-next-line @typescript-eslint/no-explicit-any110+ const Style: FC<PropsWithChildren<void>> = ({ children }) =>111+ ({112+ tag: 'style',113+ children: (Array.isArray(children) ? children : [children]).map(114+ (c) => (c as unknown as CssClassName)[STYLE_STRING]115+ ),116+ props: { id },117+ // eslint-disable-next-line @typescript-eslint/no-explicit-any118+ } as any)119+120+ return [cssObject, Style] as const121+}122+123+/**124+ * @experimental125+ * `createCssContext` is an experimental feature.126+ * The API might be changed.127+ */128+export const createCssContext = ({ id }: { id: Readonly<string> }) => {129+ const [cssObject, Style] = createCssJsxDomObjects({ id })130+131+ const newCssClassNameObject = (cssClassName: CssClassName): string => {132+ cssClassName.toString = cssObject.toString133+ return cssClassName as unknown as string134+ }135+136+ const css = (strings: TemplateStringsArray, ...values: CssVariableType[]): string => {137+ return newCssClassNameObject(cssCommon(strings, values))138+ }139+140+ const cx = (...args: (string | boolean | null | undefined)[]): string => {141+ // eslint-disable-next-line @typescript-eslint/no-explicit-any142+ args = cxCommon(args as any) as any143+ // eslint-disable-next-line @typescript-eslint/no-explicit-any144+ return css(Array(args.length).fill('') as any, ...args)145+ }146+147+ const keyframes = keyframesCommon148+149+ type ViewTransitionType = {150+ (strings: TemplateStringsArray, ...values: CssVariableType[]): string151+ (content: string): string152+ (): string153+ }154+ const viewTransition: ViewTransitionType = ((155+ strings: TemplateStringsArray | string | undefined,156+ ...values: CssVariableType[]157+ ) => {158+ // eslint-disable-next-line @typescript-eslint/no-explicit-any159+ return newCssClassNameObject(viewTransitionCommon(strings as any, values))160+ }) as ViewTransitionType161+162+ return {163+ css,164+ cx,165+ keyframes,166+ viewTransition,167+ Style,168+ }169+}170+171+const defaultContext = createCssContext({ id: DEFAULT_STYLE_ID })172+173+/**174+ * @experimental175+ * `css` is an experimental feature.176+ * The API might be changed.177+ */178+export const css = defaultContext.css179+180+/**181+ * @experimental182+ * `cx` is an experimental feature.183+ * The API might be changed.184+ */185+export const cx = defaultContext.cx186+187+/**188+ * @experimental189+ * `keyframes` is an experimental feature.190+ * The API might be changed.191+ */192+export const keyframes = defaultContext.keyframes193+194+/**195+ * @experimental196+ * `viewTransition` is an experimental feature.197+ * The API might be changed.198+ */199+export const viewTransition = defaultContext.viewTransition200+201+/**202+ * @experimental203+ * `Style` is an experimental feature.204+ * The API might be changed.205+ */206+export const Style = defaultContext.Styleadded:src/jsx/dom/index.test.tsx+1023 added
1+import { JSDOM } from 'jsdom'2+import 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-vars6+import { jsx, Fragment } from '..'7+import type { RefObject } from '../hooks'8+import { useState, useEffect, useLayoutEffect, useCallback, useRef, useMemo } from '../hooks'9+import type { NodeObject } from './render'10+import { memo, isValidElement, cloneElement } from '.'11+import { render, cloneElement as cloneElementForDom } from '.'12+13+const getContainer = (element: JSX.Element): DocumentFragment | HTMLElement | undefined => {14+ return (element as unknown as NodeObject).c15+}16+17+describe('DOM', () => {18+ beforeAll(() => {19+ global.requestAnimationFrame = (cb) => setTimeout(cb)20+ })21+22+ let dom: JSDOM23+ let root: HTMLElement24+ beforeEach(() => {25+ dom = new JSDOM('<html><body><div id="root"></div></body></html>', {26+ runScripts: 'dangerously',27+ })28+ global.document = dom.window.document29+ global.HTMLElement = dom.window.HTMLElement30+ global.Text = dom.window.Text31+ root = document.getElementById('root') as HTMLElement32+ })33+34+ it('simple App', () => {35+ const App = <h1>Hello</h1>36+ render(App, root)37+ expect(root.innerHTML).toBe('<h1>Hello</h1>')38+ })39+40+ it('replace', () => {41+ dom.window.document.body.innerHTML = '<div id="root">Existing content</div>'42+ root = document.getElementById('root') as HTMLElement43+ const App = <h1>Hello</h1>44+ render(App, root)45+ expect(root.innerHTML).toBe('<h1>Hello</h1>')46+ })47+48+ it('render text directly', () => {49+ const App = () => <>{'Hello'}</>50+ render(<App />, root)51+ expect(root.innerHTML).toBe('Hello')52+ })53+54+ describe('attribute', () => {55+ it('simple', () => {56+ const App = () => <div id='app' class='app' />57+ render(<App />, root)58+ expect(root.innerHTML).toBe('<div id="app" class="app"></div>')59+ })60+61+ it('boolean', () => {62+ const App = () => <div hidden />63+ render(<App />, root)64+ expect(root.innerHTML).toBe('<div hidden=""></div>')65+ })66+67+ it('style', () => {68+ const App = () => <div style={{ fontSize: '10px' }} />69+ render(<App />, root)70+ expect(root.innerHTML).toBe('<div style="font-size: 10px;"></div>')71+ })72+73+ it('update style', () => {74+ const App = () => <div style={{ fontSize: '10px' }} />75+ render(<App />, root)76+ expect(root.innerHTML).toBe('<div style="font-size: 10px;"></div>')77+ })78+79+ it('style with string', async () => {80+ const App = () => {81+ const [style, setStyle] = useState<{ fontSize?: string; color?: string }>({82+ fontSize: '10px',83+ })84+ return <div style={style} onClick={() => setStyle({ color: 'red' })} />85+ }86+ render(<App />, root)87+ expect(root.innerHTML).toBe('<div style="font-size: 10px;"></div>')88+ root.querySelector('div')?.click()89+ await Promise.resolve()90+ expect(root.innerHTML).toBe('<div style="color: red;"></div>')91+ })92+93+ it('toString() is called', () => {94+ const App = () => <div x-value={{ toString: () => 'value' }} />95+ render(<App />, root)96+ expect(root.innerHTML).toBe('<div x-value="value"></div>')97+ })98+99+ it('ref', () => {100+ const App = () => {101+ const ref = useRef<HTMLDivElement>(null)102+ return <div ref={ref} />103+ }104+ render(<App />, root)105+ expect(root.innerHTML).toBe('<div></div>')106+ })107+108+ it('ref with callback', () => {109+ const ref = useRef<HTMLDivElement>(null)110+ const App = () => {111+ return <div ref={(node: HTMLDivElement) => (ref.current = node)} />112+ }113+ render(<App />, root)114+ expect(root.innerHTML).toBe('<div></div>')115+ expect(ref.current).toBeInstanceOf(HTMLElement)116+ })117+ })118+119+ describe('replace content', () => {120+ it('text to text', async () => {121+ let setCount: (count: number) => void = () => {}122+ const App = () => {123+ const [count, _setCount] = useState(0)124+ setCount = _setCount125+ return <>{count}</>126+ }127+ render(<App />, root)128+ expect(root.innerHTML).toBe('0')129+ setCount(1)130+ await Promise.resolve()131+ expect(root.innerHTML).toBe('1')132+ })133+134+ it('text to element', async () => {135+ let setCount: (count: number) => void = () => {}136+ const App = () => {137+ const [count, _setCount] = useState(0)138+ setCount = _setCount139+ return count === 0 ? <>{count}</> : <div>{count}</div>140+ }141+ render(<App />, root)142+ expect(root.innerHTML).toBe('0')143+ setCount(1)144+ await Promise.resolve()145+ expect(root.innerHTML).toBe('<div>1</div>')146+ })147+148+ it('element to element', async () => {149+ let setCount: (count: number) => void = () => {}150+ const App = () => {151+ const [count, _setCount] = useState(0)152+ setCount = _setCount153+ return <div>{count}</div>154+ }155+ const app = <App />156+ render(app, root)157+ const container = getContainer(app) as HTMLElement158+ expect(root.innerHTML).toBe('<div>0</div>')159+160+ const insertBeforeSpy = vi.spyOn(container, 'insertBefore')161+ setCount(1)162+ await Promise.resolve()163+ expect(root.innerHTML).toBe('<div>1</div>')164+ expect(insertBeforeSpy).not.toHaveBeenCalled()165+ })166+167+ it('element to text to element', async () => {168+ let setCount: (count: number) => void = () => {}169+ const App = () => {170+ const [count, _setCount] = useState(0)171+ setCount = _setCount172+ return count % 2 === 0 ? <div>{count}</div> : <>{count}</>173+ }174+ render(<App />, root)175+ expect(root.innerHTML).toBe('<div>0</div>')176+ setCount(1)177+ await Promise.resolve()178+ expect(root.innerHTML).toBe('1')179+ setCount(2)180+ await Promise.resolve()181+ expect(root.innerHTML).toBe('<div>2</div>')182+ })183+184+ it('text to child component to text', async () => {185+ let setCount: (count: number) => void = () => {}186+ const Child = () => {187+ return <div>Child</div>188+ }189+ const App = () => {190+ const [count, _setCount] = useState(0)191+ setCount = _setCount192+ return count % 2 === 0 ? <>{count}</> : <Child />193+ }194+ render(<App />, root)195+ expect(root.innerHTML).toBe('0')196+ setCount(1)197+ await Promise.resolve()198+ expect(root.innerHTML).toBe('<div>Child</div>')199+ setCount(2)200+ await Promise.resolve()201+ expect(root.innerHTML).toBe('2')202+ })203+ })204+205+ describe('Event', () => {206+ it('bubbling phase', async () => {207+ const clicked: string[] = []208+ const App = () => {209+ return (210+ <div211+ onClick={() => {212+ clicked.push('div')213+ }}214+ >215+ <button216+ onClick={() => {217+ clicked.push('button')218+ }}219+ >220+ Click221+ </button>222+ </div>223+ )224+ }225+ render(<App />, root)226+ expect(root.innerHTML).toBe('<div><button>Click</button></div>')227+ root.querySelector('button')?.click()228+ expect(clicked).toEqual(['button', 'div'])229+ })230+231+ it('ev.stopPropagation()', async () => {232+ const clicked: string[] = []233+ const App = () => {234+ return (235+ <div236+ onClick={() => {237+ clicked.push('div')238+ }}239+ >240+ <button241+ onClick={(ev) => {242+ ev.stopPropagation()243+ clicked.push('button')244+ }}245+ >246+ Click247+ </button>248+ </div>249+ )250+ }251+ render(<App />, root)252+ expect(root.innerHTML).toBe('<div><button>Click</button></div>')253+ root.querySelector('button')?.click()254+ expect(clicked).toEqual(['button'])255+ })256+257+ it('capture phase', async () => {258+ const clicked: string[] = []259+ const App = () => {260+ return (261+ <div262+ onClickCapture={(ev) => {263+ ev.stopPropagation()264+ clicked.push('div')265+ }}266+ >267+ <button268+ onClickCapture={() => {269+ clicked.push('button')270+ }}271+ >272+ Click273+ </button>274+ </div>275+ )276+ }277+ render(<App />, root)278+ expect(root.innerHTML).toBe('<div><button>Click</button></div>')279+ root.querySelector('button')?.click()280+ expect(clicked).toEqual(['div'])281+ })282+283+ it('remove capture phase event', async () => {284+ const clicked: string[] = []285+ const App = () => {286+ const [canceled, setCanceled] = useState(false)287+ return (288+ <div289+ {...(canceled290+ ? {}291+ : {292+ onClickCapture: () => {293+ clicked.push('div')294+ },295+ })}296+ >297+ <button298+ onClickCapture={() => {299+ setCanceled(true)300+ clicked.push('button')301+ }}302+ >303+ Click304+ </button>305+ </div>306+ )307+ }308+ render(<App />, root)309+ expect(root.innerHTML).toBe('<div><button>Click</button></div>')310+ root.querySelector('button')?.click()311+ expect(clicked).toEqual(['div', 'button'])312+ await Promise.resolve()313+ root.querySelector('button')?.click()314+ expect(clicked).toEqual(['div', 'button', 'button'])315+ })316+ })317+318+ it('simple Counter', async () => {319+ const Counter = () => {320+ const [count, setCount] = useState(0)321+ return (322+ <div>323+ <p>Count: {count}</p>324+ <button onClick={() => setCount(count + 1)}>+</button>325+ </div>326+ )327+ }328+ const app = <Counter />329+ render(app, root)330+ expect(root.innerHTML).toBe('<div><p>Count: 0</p><button>+</button></div>')331+ const button = root.querySelector('button') as HTMLButtonElement332+ button.click()333+ await Promise.resolve()334+ expect(root.innerHTML).toBe('<div><p>Count: 1</p><button>+</button></div>')335+ })336+337+ it('multiple useState()', async () => {338+ let called = 0339+ const Counter = () => {340+ const [countA, setCountA] = useState(0)341+ const [countB, setCountB] = useState(0)342+ called++343+ return (344+ <div>345+ <p>A: {countA}</p>346+ <button onClick={() => setCountA(countA + 1)}>+</button>347+ <p>B: {countB}</p>348+ <button onClick={() => setCountB(countB + 1)}>+</button>349+ </div>350+ )351+ }352+ const app = <Counter />353+ render(app, root)354+ expect(root.innerHTML).toBe(355+ '<div><p>A: 0</p><button>+</button><p>B: 0</p><button>+</button></div>'356+ )357+ expect(called).toBe(1)358+ const [buttonA, buttonB] = root.querySelectorAll('button')359+ for (let i = 0; i < 3; i++) {360+ buttonA.click()361+ await Promise.resolve()362+ }363+ for (let i = 0; i < 4; i++) {364+ buttonB.click()365+ await Promise.resolve()366+ }367+ expect(root.innerHTML).toBe(368+ '<div><p>A: 3</p><button>+</button><p>B: 4</p><button>+</button></div>'369+ )370+ expect(called).toBe(8)371+ })372+373+ it('multiple update state calls at once in onClick attributes', async () => {374+ let called = 0375+ const Counter = () => {376+ const [countA, setCountA] = useState(0)377+ const [countB, setCountB] = useState(0)378+ called++379+ return (380+ <div>381+ <button382+ onClick={() => {383+ setCountA(countA + 1)384+ setCountB(countB + 2)385+ }}386+ >387+ +388+ </button>389+ {countA} {countB}390+ </div>391+ )392+ }393+ const app = <Counter />394+ render(app, root)395+ expect(root.innerHTML).toBe('<div><button>+</button>0 0</div>')396+ expect(called).toBe(1)397+ root.querySelector('button')?.click()398+ expect(called).toBe(1)399+ await Promise.resolve()400+ expect(called).toBe(2)401+ })402+403+ it('multiple update state calls at once in dom events', async () => {404+ let called = 0405+ const Counter = () => {406+ const [countA, setCountA] = useState(0)407+ const [countB, setCountB] = useState(0)408+ const buttonRef = useRef<HTMLButtonElement>(null)409+ called++410+411+ useEffect(() => {412+ buttonRef.current?.addEventListener('click', () => {413+ setCountA(countA + 1)414+ setCountB(countB + 2)415+ })416+ }, [])417+418+ return (419+ <div>420+ <button ref={buttonRef}>+</button>421+ {countA} {countB}422+ </div>423+ )424+ }425+ const app = <Counter />426+ render(app, root)427+ expect(root.innerHTML).toBe('<div><button>+</button>0 0</div>')428+ expect(called).toBe(1)429+ await new Promise((resolve) => setTimeout(resolve))430+ root.querySelector('button')?.click()431+ expect(called).toBe(1)432+ await Promise.resolve()433+ expect(called).toBe(2)434+ })435+436+ it('nested useState()', async () => {437+ const ChildCounter = () => {438+ const [count, setCount] = useState(0)439+ return (440+ <div>441+ <p>Child Count: {count}</p>442+ <button onClick={() => setCount(count + 1)}>+</button>443+ </div>444+ )445+ }446+ const Counter = () => {447+ const [count, setCount] = useState(0)448+ return (449+ <div>450+ <p>Count: {count}</p>451+ <button onClick={() => setCount(count + 1)}>+</button>452+ <ChildCounter />453+ </div>454+ )455+ }456+ const app = <Counter />457+ render(app, root)458+ expect(root.innerHTML).toBe(459+ '<div><p>Count: 0</p><button>+</button><div><p>Child Count: 0</p><button>+</button></div></div>'460+ )461+ const [button, childButton] = root.querySelectorAll('button')462+ for (let i = 0; i < 5; i++) {463+ button.click()464+ await Promise.resolve()465+ }466+ for (let i = 0; i < 6; i++) {467+ childButton.click()468+ await Promise.resolve()469+ }470+ expect(root.innerHTML).toBe(471+ '<div><p>Count: 5</p><button>+</button><div><p>Child Count: 6</p><button>+</button></div></div>'472+ )473+ })474+475+ it('switch child component', async () => {476+ const Even = () => <p>Even</p>477+ const Odd = () => <div>Odd</div>478+ const Counter = () => {479+ const [count, setCount] = useState(0)480+ return (481+ <div>482+ {count % 2 === 0 ? <Even /> : <Odd />}483+ <button onClick={() => setCount(count + 1)}>+</button>484+ </div>485+ )486+ }487+ const app = <Counter />488+ render(app, root)489+ expect(root.innerHTML).toBe('<div><p>Even</p><button>+</button></div>')490+ const button = root.querySelector('button') as HTMLButtonElement491+ button.click()492+ await Promise.resolve()493+ expect(root.innerHTML).toBe('<div><div>Odd</div><button>+</button></div>')494+ button.click()495+ await Promise.resolve()496+ expect(root.innerHTML).toBe('<div><p>Even</p><button>+</button></div>')497+ })498+499+ it('add/remove/swap item', async () => {500+ const TodoApp = () => {501+ const [todos, setTodos] = useState(['a', 'b', 'c'])502+ return (503+ <div>504+ {todos.map((todo) => (505+ <div key={todo}>{todo}</div>506+ ))}507+ <button onClick={() => setTodos([...todos, 'd'])}>add</button>508+ <button onClick={() => setTodos(todos.slice(0, -1))}>remove</button>509+ <button onClick={() => setTodos([todos[0], todos[2], todos[1], todos[3] || ''])}>510+ swap511+ </button>512+ </div>513+ )514+ }515+ const app = <TodoApp />516+ render(app, root)517+ expect(root.innerHTML).toBe(518+ '<div><div>a</div><div>b</div><div>c</div><button>add</button><button>remove</button><button>swap</button></div>'519+ )520+ const [addButton] = root.querySelectorAll('button')521+ addButton.click()522+ await Promise.resolve()523+ expect(root.innerHTML).toBe(524+ '<div><div>a</div><div>b</div><div>c</div><div>d</div><button>add</button><button>remove</button><button>swap</button></div>'525+ )526+ const [, , swapButton] = root.querySelectorAll('button')527+ swapButton.click()528+ await Promise.resolve()529+ expect(root.innerHTML).toBe(530+ '<div><div>a</div><div>c</div><div>b</div><div>d</div><button>add</button><button>remove</button><button>swap</button></div>'531+ )532+ const [, removeButton] = root.querySelectorAll('button')533+ removeButton.click()534+ await Promise.resolve()535+ expect(root.innerHTML).toBe(536+ '<div><div>a</div><div>c</div><div>b</div><button>add</button><button>remove</button><button>swap</button></div>'537+ )538+ })539+540+ it('setState for unnamed function', async () => {541+ const Input = ({ label, onInput }: { label: string; onInput: (value: string) => void }) => {542+ return (543+ <div>544+ <label>{label}</label>545+ <input546+ onInput={(e: InputEvent) => onInput((e.target as HTMLInputElement)?.value || '')}547+ />548+ </div>549+ )550+ }551+ const Form = () => {552+ const [values, setValues] = useState<{ [key: string]: string }>({})553+ return (554+ <form>555+ <Input label='Name' onInput={(value) => setValues({ ...values, name: value })} />556+ <Input label='Email' onInput={(value) => setValues({ ...values, email: value })} />557+ <span>{JSON.stringify(values)}</span>558+ </form>559+ )560+ }561+ const app = <Form />562+ render(app, root)563+ expect(root.innerHTML).toBe(564+ '<form><div><label>Name</label><input></div><div><label>Email</label><input></div><span>{}</span></form>'565+ )566+ const [nameInput] = root.querySelectorAll('input')567+ nameInput.value = 'John'568+ nameInput.dispatchEvent(new dom.window.Event('input'))569+ await Promise.resolve()570+ expect(root.innerHTML).toBe(571+ '<form><div><label>Name</label><input></div><div><label>Email</label><input></div><span>{"name":"John"}</span></form>'572+ )573+ const [, emailInput] = root.querySelectorAll('input')574+ emailInput.value = 'john@example.com'575+ emailInput.dispatchEvent(new dom.window.Event('input'))576+ await Promise.resolve()577+ expect(root.innerHTML).toBe(578+ '<form><div><label>Name</label><input></div><div><label>Email</label><input></div><span>{"name":"John","email":"john@example.com"}</span></form>'579+ )580+ })581+582+ describe('className', () => {583+ it('should convert to class attribute for intrinsic elements', () => {584+ const App = <h1 className='h1'>Hello</h1>585+ render(App, root)586+ expect(root.innerHTML).toBe('<h1 class="h1">Hello</h1>')587+ })588+589+ it('should convert to class attribute for custom elements', () => {590+ const App = <custom-element className='h1'>Hello</custom-element>591+ render(App, root)592+ expect(root.innerHTML).toBe('<custom-element class="h1">Hello</custom-element>')593+ })594+595+ it('should not convert to class attribute for custom components', () => {596+ const App: FC<{ className: string }> = ({ className }) => (597+ <div data-class-name={className}>Hello</div>598+ )599+ render(<App className='h1' />, root)600+ expect(root.innerHTML).toBe('<div data-class-name="h1">Hello</div>')601+ })602+ })603+604+ it('memo', async () => {605+ let renderCount = 0606+ const Counter = ({ count }: { count: number }) => {607+ renderCount++608+ return (609+ <div>610+ <p>Count: {count}</p>611+ </div>612+ )613+ }614+ const MemoCounter = memo(Counter)615+ const App = () => {616+ const [count, setCount] = useState(0)617+ return (618+ <div>619+ <MemoCounter count={Math.min(count, 1)} />620+ <button onClick={() => setCount(count + 1)}>+</button>621+ </div>622+ )623+ }624+ const app = <App />625+ render(app, root)626+ expect(root.innerHTML).toBe('<div><div><p>Count: 0</p></div><button>+</button></div>')627+ expect(renderCount).toBe(1)628+ root.querySelector('button')?.click()629+ await Promise.resolve()630+ expect(root.innerHTML).toBe('<div><div><p>Count: 1</p></div><button>+</button></div>')631+ expect(renderCount).toBe(2)632+ root.querySelector('button')?.click()633+ await Promise.resolve()634+ expect(root.innerHTML).toBe('<div><div><p>Count: 1</p></div><button>+</button></div>')635+ expect(renderCount).toBe(2)636+ })637+638+ it('useRef', async () => {639+ const Input = ({ label, ref }: { label: string; ref: RefObject<HTMLInputElement> }) => {640+ return (641+ <div>642+ <label>{label}</label>643+ <input ref={ref} />644+ </div>645+ )646+ }647+ const Form = () => {648+ const [values, setValues] = useState<{ [key: string]: string }>({})649+ const nameRef = useRef<HTMLInputElement>(null)650+ const emailRef = useRef<HTMLInputElement>(null)651+ return (652+ <form>653+ <Input label='Name' ref={nameRef} />654+ <Input label='Email' ref={emailRef} />655+ <button656+ onClick={(ev: Event) => {657+ ev.preventDefault()658+ setValues({659+ name: nameRef.current?.value || '',660+ email: emailRef.current?.value || '',661+ })662+ }}663+ >664+ serialize665+ </button>666+ <span>{JSON.stringify(values)}</span>667+ </form>668+ )669+ }670+ const app = <Form />671+ render(app, root)672+ expect(root.innerHTML).toBe(673+ '<form><div><label>Name</label><input></div><div><label>Email</label><input></div><button>serialize</button><span>{}</span></form>'674+ )675+ const [nameInput, emailInput] = root.querySelectorAll('input')676+ nameInput.value = 'John'677+ emailInput.value = 'john@example.com'678+ const [button] = root.querySelectorAll('button')679+ button.click()680+ await Promise.resolve()681+ expect(root.innerHTML).toBe(682+ '<form><div><label>Name</label><input></div><div><label>Email</label><input></div><button>serialize</button><span>{"name":"John","email":"john@example.com"}</span></form>'683+ )684+ })685+686+ describe('useEffect', () => {687+ it('simple', async () => {688+ const Counter = () => {689+ const [count, setCount] = useState(0)690+ useEffect(() => {691+ setCount(count + 1)692+ }, [])693+ return <div>{count}</div>694+ }695+ const app = <Counter />696+ render(app, root)697+ await new Promise((resolve) => setTimeout(resolve))698+ await Promise.resolve()699+ expect(root.innerHTML).toBe('<div>1</div>')700+ })701+702+ it('multiple', async () => {703+ const Counter = () => {704+ const [count, setCount] = useState(0)705+ useEffect(() => {706+ setCount((c) => c + 1)707+ }, [])708+ useEffect(() => {709+ setCount((c) => c + 1)710+ }, [])711+ return <div>{count}</div>712+ }713+ const app = <Counter />714+ render(app, root)715+ await new Promise((resolve) => setTimeout(resolve))716+ await Promise.resolve()717+ expect(root.innerHTML).toBe('<div>2</div>')718+ })719+720+ it('cleanup', async () => {721+ const Child = ({ parent }: { parent: RefObject<HTMLElement> }) => {722+ useEffect(() => {723+ return () => {724+ parent.current?.setAttribute('data-cleanup', 'true')725+ }726+ }, [])727+ return <div>Child</div>728+ }729+ const Parent = () => {730+ const [show, setShow] = useState(true)731+ const ref = useRef<HTMLElement>(null)732+ return (733+ <div ref={ref}>734+ {show && <Child parent={ref} />}735+ <button onClick={() => setShow(false)}>hide</button>736+ </div>737+ )738+ }739+ const app = <Parent />740+ render(app, root)741+ expect(root.innerHTML).toBe('<div><div>Child</div><button>hide</button></div>')742+ await new Promise((resolve) => setTimeout(resolve))743+ const [button] = root.querySelectorAll('button')744+ button.click()745+ await Promise.resolve()746+ expect(root.innerHTML).toBe('<div data-cleanup="true"><button>hide</button></div>')747+ })748+749+ it('cleanup for deps', async () => {750+ let effectCount = 0751+ let cleanupCount = 0752+753+ const App = () => {754+ const [count, setCount] = useState(0)755+ const [count2, setCount2] = useState(0)756+ useEffect(() => {757+ effectCount++758+ return () => {759+ cleanupCount++760+ }761+ }, [count])762+ return (763+ <div>764+ <p>{count}</p>765+ <p>{count2}</p>766+ <button onClick={() => setCount(count + 1)}>+</button>767+ <button onClick={() => setCount2(count2 + 1)}>+</button>768+ </div>769+ )770+ }771+ const app = <App />772+ render(app, root)773+ await new Promise((resolve) => setTimeout(resolve))774+ expect(effectCount).toBe(1)775+ expect(cleanupCount).toBe(0)776+ root.querySelectorAll('button')[0].click() // count++777+ await Promise.resolve()778+ await new Promise((resolve) => setTimeout(resolve))779+ expect(effectCount).toBe(2)780+ expect(cleanupCount).toBe(1)781+ root.querySelectorAll('button')[1].click() // count2++782+ await Promise.resolve()783+ expect(effectCount).toBe(2)784+ expect(cleanupCount).toBe(1)785+ })786+ })787+788+ describe('useLayoutEffect', () => {789+ it('simple', async () => {790+ const Counter = () => {791+ const [count, setCount] = useState(0)792+ useLayoutEffect(() => {793+ setCount(count + 1)794+ }, [])795+ return <div>{count}</div>796+ }797+ const app = <Counter />798+ render(app, root)799+ await Promise.resolve()800+ expect(root.innerHTML).toBe('<div>1</div>')801+ })802+803+ it('multiple', async () => {804+ const Counter = () => {805+ const [count, setCount] = useState(0)806+ useLayoutEffect(() => {807+ setCount((c) => c + 1)808+ }, [])809+ useLayoutEffect(() => {810+ setCount((c) => c + 1)811+ }, [])812+ return <div>{count}</div>813+ }814+ const app = <Counter />815+ render(app, root)816+ await Promise.resolve()817+ expect(root.innerHTML).toBe('<div>2</div>')818+ })819+820+ it('cleanup', async () => {821+ const Child = ({ parent }: { parent: RefObject<HTMLElement> }) => {822+ useLayoutEffect(() => {823+ return () => {824+ parent.current?.setAttribute('data-cleanup', 'true')825+ }826+ }, [])827+ return <div>Child</div>828+ }829+ const Parent = () => {830+ const [show, setShow] = useState(true)831+ const ref = useRef<HTMLElement>(null)832+ return (833+ <div ref={ref}>834+ {show && <Child parent={ref} />}835+ <button onClick={() => setShow(false)}>hide</button>836+ </div>837+ )838+ }839+ const app = <Parent />840+ render(app, root)841+ expect(root.innerHTML).toBe('<div><div>Child</div><button>hide</button></div>')842+ const [button] = root.querySelectorAll('button')843+ button.click()844+ await Promise.resolve()845+ expect(root.innerHTML).toBe('<div data-cleanup="true"><button>hide</button></div>')846+ })847+848+ it('cleanup for deps', async () => {849+ let effectCount = 0850+ let cleanupCount = 0851+852+ const App = () => {853+ const [count, setCount] = useState(0)854+ const [count2, setCount2] = useState(0)855+ useLayoutEffect(() => {856+ effectCount++857+ return () => {858+ cleanupCount++859+ }860+ }, [count])861+ return (862+ <div>863+ <p>{count}</p>864+ <p>{count2}</p>865+ <button onClick={() => setCount(count + 1)}>+</button>866+ <button onClick={() => setCount2(count2 + 1)}>+</button>867+ </div>868+ )869+ }870+ const app = <App />871+ render(app, root)872+ expect(effectCount).toBe(1)873+ expect(cleanupCount).toBe(0)874+ root.querySelectorAll('button')[0].click() // count++875+ await Promise.resolve()876+ expect(effectCount).toBe(2)877+ expect(cleanupCount).toBe(1)878+ root.querySelectorAll('button')[1].click() // count2++879+ await Promise.resolve()880+ expect(effectCount).toBe(2)881+ expect(cleanupCount).toBe(1)882+ })883+ })884+885+ describe('useCallback', () => {886+ it('deferent callbacks', async () => {887+ const callbackSet = new Set<Function>()888+ const Counter = () => {889+ const [count, setCount] = useState(0)890+ const increment = useCallback(() => {891+ setCount(count + 1)892+ }, [count])893+ callbackSet.add(increment)894+ return (895+ <div>896+ <p>{count}</p>897+ <button onClick={increment}>+</button>898+ </div>899+ )900+ }901+ const app = <Counter />902+ render(app, root)903+ expect(root.innerHTML).toBe('<div><p>0</p><button>+</button></div>')904+ const button = root.querySelector('button') as HTMLButtonElement905+ button.click()906+ await Promise.resolve()907+ expect(root.innerHTML).toBe('<div><p>1</p><button>+</button></div>')908+ expect(callbackSet.size).toBe(2)909+ })910+911+ it('same callback', async () => {912+ const callbackSet = new Set<Function>()913+ const Counter = () => {914+ const [count, setCount] = useState(0)915+ const increment = useCallback(() => {916+ setCount(count + 1)917+ }, [count])918+ callbackSet.add(increment)919+920+ const [count2, setCount2] = useState(0)921+ return (922+ <div>923+ <p>{count}</p>924+ <button onClick={increment}>+</button>925+ <p>{count2}</p>926+ <button onClick={() => setCount2(count2 + 1)}>+</button>927+ </div>928+ )929+ }930+ const app = <Counter />931+ render(app, root)932+ expect(root.innerHTML).toBe('<div><p>0</p><button>+</button><p>0</p><button>+</button></div>')933+ const [, button] = root.querySelectorAll('button')934+ button.click()935+ await Promise.resolve()936+ expect(root.innerHTML).toBe('<div><p>0</p><button>+</button><p>1</p><button>+</button></div>')937+ expect(callbackSet.size).toBe(1)938+ })939+ })940+941+ describe('useMemo', () => {942+ it('simple', async () => {943+ let factoryCalled = 0944+ const Counter = () => {945+ const [count, setCount] = useState(0)946+ const [count2, setCount2] = useState(0)947+ const memo = useMemo(() => {948+ factoryCalled++949+ return count + 1950+ }, [count])951+ return (952+ <div>953+ <p>{count}</p>954+ <p>{count2}</p>955+ <p>{memo}</p>956+ <button onClick={() => setCount(count + 1)}>+</button>957+ <button onClick={() => setCount2(count2 + 1)}>+</button>958+ </div>959+ )960+ }961+ const app = <Counter />962+ render(app, root)963+ expect(root.innerHTML).toBe(964+ '<div><p>0</p><p>0</p><p>1</p><button>+</button><button>+</button></div>'965+ )966+ expect(factoryCalled).toBe(1)967+ root.querySelectorAll('button')[0].click()968+ await Promise.resolve()969+ expect(root.innerHTML).toBe(970+ '<div><p>1</p><p>0</p><p>2</p><button>+</button><button>+</button></div>'971+ )972+ expect(factoryCalled).toBe(2)973+ root.querySelectorAll('button')[1].click()974+ await Promise.resolve()975+ expect(root.innerHTML).toBe(976+ '<div><p>1</p><p>1</p><p>2</p><button>+</button><button>+</button></div>'977+ )978+ expect(factoryCalled).toBe(2)979+ })980+ })981+982+ describe('isValidElement', () => {983+ it('valid', () => {984+ expect(isValidElement(<div />)).toBe(true)985+ })986+987+ it('invalid', () => {988+ expect(isValidElement({})).toBe(false)989+ })990+ })991+992+ describe('cloneElement', () => {993+ it('simple', async () => {994+ const App = () => {995+ const [count, setCount] = useState(0)996+ return <div>{cloneElement(<p>{count}</p>, { onClick: () => setCount(count + 1) })}</div>997+ }998+ const app = <App />999+ render(app, root)1000+ expect(root.innerHTML).toBe('<div><p>0</p></div>')1001+ root.querySelector('p')?.click()1002+ await Promise.resolve()1003+ expect(root.innerHTML).toBe('<div><p>1</p></div>')1004+ })1005+ })1006+1007+ describe('dom-specific cloneElement', () => {1008+ it('simple', async () => {1009+ const App = () => {1010+ const [count, setCount] = useState(0)1011+ return (1012+ <div>{cloneElementForDom(<p>{count}</p>, { onClick: () => setCount(count + 1) })}</div>1013+ )1014+ }1015+ const app = <App />1016+ render(app, root)1017+ expect(root.innerHTML).toBe('<div><p>0</p></div>')1018+ root.querySelector('p')?.click()1019+ await Promise.resolve()1020+ expect(root.innerHTML).toBe('<div><p>1</p></div>')1021+ })1022+ })1023+})added:src/jsx/dom/index.ts+38 added
1+export {2+ useState,3+ useEffect,4+ useRef,5+ useCallback,6+ use,7+ startTransition,8+ useTransition,9+ useDeferredValue,10+ startViewTransition,11+ useViewTransition,12+ useMemo,13+ useLayoutEffect,14+} from '../hooks'15+export { render } from './render'16+export { Suspense, ErrorBoundary } from './components'17+export { useContext } from '../context'18+export type { Context } from '../context'19+export { createContext } from './context'20+export { memo, isValidElement } from '../base'21+22+import type { Props, Child, JSXNode } from '../base'23+import { jsx } from './jsx-runtime'24+export const cloneElement = <T extends JSXNode | JSX.Element>(25+ element: T,26+ props: Props,27+ ...children: Child[]28+): T => {29+ return jsx(30+ (element as JSXNode).tag,31+ {32+ ...(element as JSXNode).props,33+ ...props,34+ children: children.length ? children : (element as JSXNode).children,35+ },36+ (element as JSXNode).key37+ ) as T38+}added:src/jsx/dom/jsx-dev-runtime.ts+23 added
1+import type { Props } from '../base'2+import { normalizeIntrinsicElementProps } from '../utils'3+4+export const jsxDEV = (tag: string | Function, props: Props, key?: string) => {5+ if (typeof tag === 'string') {6+ normalizeIntrinsicElementProps(props)7+ }8+ let children9+ if (props && 'children' in props) {10+ children = props.children11+ delete props['children']12+ } else {13+ children = []14+ }15+ return {16+ tag,17+ props,18+ key,19+ children: Array.isArray(children) ? children : [children],20+ }21+}22+23+export const Fragment = (props: Record<string, unknown>) => jsxDEV('', props, undefined)added:src/jsx/dom/jsx-runtime.ts+2 added
1+export { jsxDEV as jsx, Fragment } from './jsx-dev-runtime'2+export { jsxDEV as jsxs } from './jsx-dev-runtime'added:src/jsx/dom/render.ts+450 added
1+import type { JSXNode } from '../base'2+import type { FC, Child, Props } from '../base'3+import { DOM_RENDERER, DOM_ERROR_HANDLER, DOM_STASH } from '../constants'4+import type { Context as JSXContext } from '../context'5+import { globalContexts as globalJSXContexts } from '../context'6+import type { EffectData } from '../hooks'7+import { STASH_EFFECT } from '../hooks'8+9+const eventAliasMap: Record<string, string> = {10+ Change: 'Input',11+ DoubleClick: 'DblClick',12+}13+14+// eslint-disable-next-line @typescript-eslint/no-explicit-any15+export type HasRenderToDom = FC<any> & { [DOM_RENDERER]: FC<any> }16+// eslint-disable-next-line @typescript-eslint/no-explicit-any17+export type ErrorHandler = (error: any, retry: () => void) => Child | undefined18+19+type Container = HTMLElement | DocumentFragment20+type LocalJSXContexts = [JSXContext<unknown>, unknown][] | undefined21+22+export type NodeObject = {23+ pP: Props | undefined // previous props24+ nN: Node | undefined // next node25+ vC: Node[] // virtual dom children26+ vR: Node[] // virtual dom children to remove27+ s?: Node[] // shadow virtual dom children28+ c: Container | undefined // container29+ e: HTMLElement | Text | undefined // rendered element30+ [DOM_STASH]:31+ | [32+ number, // current hook index33+ // eslint-disable-next-line @typescript-eslint/no-explicit-any34+ any[][], // stash for hooks35+ LocalJSXContexts // context36+ ]37+ | [38+ number,39+ // eslint-disable-next-line @typescript-eslint/no-explicit-any40+ any[][]41+ ]42+} & JSXNode43+type NodeString = [string] & {44+ e?: Text45+ // like a NodeObject46+ vC: undefined47+ nN: undefined48+ // from JSXNode49+ key: undefined50+ tag: undefined51+}52+export type Node = NodeString | NodeObject53+54+export type PendingType =55+ | 0 // no pending56+ | 1 // global57+ | 2 // hook58+export type UpdateHook = (59+ context: Context,60+ node: Node,61+ cb: (context: Context) => void62+) => Promise<void>63+export type Context =64+ | [65+ PendingType, // PendingType66+ boolean, // got an error67+ UpdateHook, // update hook68+ boolean // is in view transition69+ ]70+ | [PendingType, boolean, UpdateHook]71+ | [PendingType, boolean]72+ | [PendingType]73+ | []74+75+export const buildDataStack: [Context, Node][] = []76+77+const isNodeString = (node: Node): node is NodeString => Array.isArray(node)78+79+const getEventSpec = (key: string): [string, boolean] | undefined => {80+ const match = key.match(/^on([A-Z][a-zA-Z]+?)((?<!Pointer)Capture)?$/)81+ if (match) {82+ const [, eventName, capture] = match83+ return [(eventAliasMap[eventName] || eventName).toLowerCase(), !!capture]84+ }85+ return undefined86+}87+88+const applyProps = (container: HTMLElement, attributes: Props, oldAttributes?: Props) => {89+ attributes ||= {}90+ for (const [key, value] of Object.entries(attributes)) {91+ if (!oldAttributes || oldAttributes[key] !== value) {92+ const eventSpec = getEventSpec(key)93+ if (eventSpec) {94+ if (typeof value !== 'function') {95+ throw new Error(`Event handler for "${key}" is not a function`)96+ }97+98+ if (oldAttributes) {99+ container.removeEventListener(eventSpec[0], oldAttributes[key], eventSpec[1])100+ }101+ container.addEventListener(eventSpec[0], value, eventSpec[1])102+ } else if (key === 'dangerouslySetInnerHTML' && value) {103+ container.innerHTML = value.__html104+ } else if (key === 'ref') {105+ if (typeof value === 'function') {106+ value(container)107+ } else if ('current' in value) {108+ value.current = container109+ }110+ } else if (key === 'style') {111+ if (typeof value === 'string') {112+ container.style.cssText = value113+ } else {114+ container.style.cssText = ''115+ Object.assign(container.style, value)116+ }117+ } else {118+ if (value === null || value === undefined || value === false) {119+ container.removeAttribute(key)120+ } else if (value === true) {121+ container.setAttribute(key, '')122+ } else if (typeof value === 'string' || typeof value === 'number') {123+ container.setAttribute(key, value as string)124+ } else {125+ container.setAttribute(key, value.toString())126+ }127+ }128+ }129+ }130+ if (oldAttributes) {131+ for (const [key, value] of Object.entries(oldAttributes)) {132+ if (!(key in attributes)) {133+ const eventSpec = getEventSpec(key)134+ if (eventSpec) {135+ container.removeEventListener(eventSpec[0], value, eventSpec[1])136+ } else if (key === 'ref') {137+ if (typeof value === 'function') {138+ value(null)139+ } else {140+ value.current = null141+ }142+ } else {143+ container.removeAttribute(key)144+ }145+ }146+ }147+ }148+}149+150+const invokeTag = (context: Context, node: NodeObject): Child[] => {151+ if (node.s) {152+ const res = node.s153+ node.s = undefined154+ return res155+ }156+157+ node[DOM_STASH][0] = 0158+ buildDataStack.push([context, node])159+ const func = (node.tag as HasRenderToDom)[DOM_RENDERER] || node.tag160+ try {161+ return [162+ func.call(null, {163+ ...node.props,164+ children: node.children,165+ }),166+ ]167+ } finally {168+ buildDataStack.pop()169+ }170+}171+172+const getNextChildren = (173+ node: NodeObject,174+ container: Container,175+ nextChildren: Node[],176+ childrenToRemove: Node[],177+ callbacks: EffectData[]178+) => {179+ childrenToRemove.push(...node.vR)180+ if (typeof node.tag === 'function') {181+ node[DOM_STASH][1][STASH_EFFECT]?.forEach((data: EffectData) => callbacks.push(data))182+ }183+ node.vC.forEach((child) => {184+ if (isNodeString(child)) {185+ nextChildren.push(child)186+ } else {187+ if (typeof child.tag === 'function' || child.tag === '') {188+ child.c = container189+ getNextChildren(child, container, nextChildren, childrenToRemove, callbacks)190+ } else {191+ nextChildren.push(child)192+ childrenToRemove.push(...child.vR)193+ }194+ }195+ })196+}197+198+const findInsertBefore = (node: Node | undefined): ChildNode | null => {199+ if (!node) {200+ return null201+ } else if (node.e) {202+ return node.e203+ }204+205+ if (node.vC) {206+ for (let i = 0, len = node.vC.length; i < len; i++) {207+ const e = findInsertBefore(node.vC[i])208+ if (e) {209+ return e210+ }211+ }212+ }213+214+ return findInsertBefore(node.nN)215+}216+217+const removeNode = (node: Node) => {218+ if (!isNodeString(node)) {219+ node[DOM_STASH]?.[1][STASH_EFFECT]?.forEach((data: EffectData) => data[2]?.())220+ node.vC?.forEach(removeNode)221+ }222+ node.e?.remove()223+ node.tag = undefined224+}225+226+const apply = (node: NodeObject, container: Container) => {227+ if (node.tag === undefined) {228+ return229+ }230+231+ node.c = container232+ applyNodeObject(node, container)233+}234+235+const applyNode = (node: Node, container: Container) => {236+ if (isNodeString(node)) {237+ container.textContent = node[0]238+ } else {239+ applyNodeObject(node, container)240+ }241+}242+243+const applyNodeObject = (node: NodeObject, container: Container) => {244+ const next: Node[] = []245+ const remove: Node[] = []246+ const callbacks: EffectData[] = []247+ getNextChildren(node, container, next, remove, callbacks)248+ let offset = container.childNodes.length249+ const insertBefore = findInsertBefore(node.nN) || next.find((n) => n.e)?.e250+ if (insertBefore) {251+ for (let i = 0; i < offset; i++) {252+ if (container.childNodes[i] === insertBefore) {253+ offset = i254+ break255+ }256+ }257+ }258+259+ for (let i = 0, len = next.length; i < len; i++, offset++) {260+ const child = next[i]261+262+ let el: HTMLElement | Text263+ if (isNodeString(child)) {264+ if (child.e) {265+ child.e.textContent = child[0]266+ }267+ el = child.e ||= document.createTextNode(child[0])268+ } else {269+ el = child.e ||= document.createElement(child.tag as string)270+ applyProps(el as HTMLElement, child.props, child.pP)271+ applyNode(child, el as HTMLElement)272+ }273+ if (container.childNodes[offset] !== el) {274+ container.insertBefore(el, container.childNodes[offset] || null)275+ }276+ }277+ remove.forEach(removeNode)278+ callbacks.forEach(([, cb]) => cb?.())279+ requestAnimationFrame(() => {280+ callbacks.forEach(([, , , cb]) => cb?.())281+ })282+}283+284+export const build = (285+ context: Context,286+ node: NodeObject,287+ topLevelErrorHandlerNode: NodeObject | undefined,288+ children?: Child[]289+): void => {290+ if (node.tag === undefined) {291+ return292+ }293+294+ let errorHandler: ErrorHandler | undefined295+ children ||= typeof node.tag == 'function' ? invokeTag(context, node) : node.children296+ if ((children[0] as JSXNode)?.tag === '') {297+ // eslint-disable-next-line @typescript-eslint/no-explicit-any298+ errorHandler = (children[0] as any)[DOM_ERROR_HANDLER] as ErrorHandler299+ topLevelErrorHandlerNode ||= node300+ }301+ const oldVChildren: Node[] = node.vC ? [...node.vC] : []302+ const vChildren: Node[] = []303+ const vChildrenToRemove: Node[] = []304+ let prevNode: Node | undefined305+ try {306+ children.flat().forEach((c: Child) => {307+ let child = buildNode(c)308+ if (child) {309+ if (prevNode) {310+ prevNode.nN = child311+ }312+ prevNode = child313+314+ if (typeof child.tag === 'function' && globalJSXContexts.length > 0) {315+ child[DOM_STASH][2] = globalJSXContexts.map((c) => [c, c.values.at(-1)])316+ }317+318+ let oldChild: Node | undefined319+ const i = oldVChildren.findIndex((c) => c.key === (child as Node).key)320+ if (i !== -1) {321+ oldChild = oldVChildren[i]322+ oldVChildren.splice(i, 1)323+ }324+325+ if (oldChild) {326+ if (isNodeString(child)) {327+ if (!isNodeString(oldChild)) {328+ vChildrenToRemove.push(oldChild)329+ } else {330+ oldChild[0] = child[0] // update text content331+ child = oldChild332+ }333+ } else if (oldChild.tag !== child.tag) {334+ vChildrenToRemove.push(oldChild)335+ } else {336+ oldChild.pP = oldChild.props337+ oldChild.props = child.props338+ oldChild.children = child.children339+ child = oldChild340+ }341+ }342+343+ if (!isNodeString(child)) {344+ build(context, child, topLevelErrorHandlerNode)345+ }346+ vChildren.push(child)347+ }348+ })349+ node.vC = vChildren350+ vChildrenToRemove.push(...oldVChildren)351+ node.vR = vChildrenToRemove352+ } catch (e) {353+ if (errorHandler) {354+ const fallback = errorHandler(e, () =>355+ update([0, false, context[2] as UpdateHook], topLevelErrorHandlerNode as NodeObject)356+ )357+ if (fallback) {358+ if (context[0] === 1) {359+ context[1] = true360+ } else {361+ build(context, node, topLevelErrorHandlerNode, [fallback])362+ }363+ return364+ }365+ }366+ throw e367+ }368+}369+370+const buildNode = (node: Child): Node | undefined => {371+ if (node === undefined || node === null || typeof node === 'boolean') {372+ return undefined373+ } else if (typeof node === 'string' || typeof node === 'number') {374+ return [node.toString()] as NodeString375+ } else {376+ if (typeof (node as JSXNode).tag === 'function') {377+ ;(node as NodeObject)[DOM_STASH] = [0, []]378+ }379+ return node as NodeObject380+ }381+}382+383+const replaceContainer = (node: NodeObject, from: DocumentFragment, to: Container) => {384+ if (node.c === from) {385+ node.c = to386+ node.vC.forEach((child) => replaceContainer(child as NodeObject, from, to))387+ }388+}389+390+const updateSync = (context: Context, node: NodeObject) => {391+ node[DOM_STASH][2]?.forEach(([c, v]) => {392+ c.values.push(v)393+ })394+ build(context, node, undefined)395+ node[DOM_STASH][2]?.forEach(([c]) => {396+ c.values.pop()397+ })398+ if (context[0] !== 1 || !context[1]) {399+ apply(node, node.c as Container)400+ }401+}402+403+type UpdateMapResolve = (node: NodeObject | undefined) => void404+const updateMap = new WeakMap<NodeObject, [UpdateMapResolve, Function]>()405+export const update = async (406+ context: Context,407+ node: NodeObject408+): Promise<NodeObject | undefined> => {409+ const existing = updateMap.get(node)410+ if (existing) {411+ // execute only the last update() call, so the previous update will be canceled.412+ existing[0](undefined)413+ }414+415+ let resolve: UpdateMapResolve | undefined416+ const promise = new Promise<NodeObject | undefined>((r) => (resolve = r))417+ updateMap.set(node, [418+ resolve as UpdateMapResolve,419+ () => {420+ if (context[2]) {421+ context[2](context, node, (context) => {422+ updateSync(context, node)423+ }).then(() => (resolve as UpdateMapResolve)(node))424+ } else {425+ updateSync(context, node)426+ ;(resolve as UpdateMapResolve)(node)427+ }428+ },429+ ])430+431+ await Promise.resolve()432+433+ const latest = updateMap.get(node)434+ if (latest) {435+ updateMap.delete(node)436+ latest[1]()437+ }438+439+ return promise440+}441+442+export const render = (jsxNode: unknown, container: Container) => {443+ const node = buildNode({ tag: '', children: [jsxNode] } as JSXNode) as NodeObject444+ build([], node, undefined)445+446+ const fragment = document.createDocumentFragment()447+ apply(node, fragment)448+ replaceContainer(node, fragment, container)449+ container.replaceChildren(fragment)450+}added:src/jsx/hooks/dom.test.tsx+446 added
1+import { JSDOM } from 'jsdom'2+// run tests by old style jsx default3+// hono/jsx/jsx-runtime and hono/jsx/dom/jsx-runtime are tested in their respective settings4+// eslint-disable-next-line @typescript-eslint/no-unused-vars5+import { jsx, Fragment } from '..'6+import { Suspense } from '../dom'7+import { render } from '../dom'8+import {9+ useState,10+ use,11+ startTransition,12+ useTransition,13+ useDeferredValue,14+ startViewTransition,15+ useViewTransition,16+} from '.'17+18+describe('startTransition()', () => {19+ beforeAll(() => {20+ global.requestAnimationFrame = (cb) => setTimeout(cb)21+ })22+23+ let dom: JSDOM24+ let root: HTMLElement25+ beforeEach(() => {26+ dom = new JSDOM('<html><body><div id="root"></div></body></html>', {27+ runScripts: 'dangerously',28+ })29+ global.document = dom.window.document30+ global.HTMLElement = dom.window.HTMLElement31+ global.Text = dom.window.Text32+ root = document.getElementById('root') as HTMLElement33+ })34+35+ it('no error', async () => {36+ const App = () => {37+ const [count, setCount] = useState(0)38+ return (39+ <Suspense fallback={<div>Loading...</div>}>40+ <div>41+ <button42+ onClick={() => {43+ startTransition(() => {44+ setCount((c) => c + 1)45+ })46+ }}47+ >48+ {count}49+ </button>50+ </div>51+ </Suspense>52+ )53+ }54+ render(<App />, root)55+ expect(root.innerHTML).toBe('<div><button>0</button></div>')56+ root.querySelector('button')?.click()57+ await Promise.resolve()58+ expect(root.innerHTML).toBe('<div><button>1</button></div>')59+ })60+61+ it('got an error', async () => {62+ let resolve: () => void63+ const promise = new Promise<void>((r) => (resolve = r))64+65+ const Counter = ({ count }: { count: number }) => {66+ use(promise)67+ return <div>{count}</div>68+ }69+70+ const App = () => {71+ const [count, setCount] = useState(0)72+ return (73+ <Suspense fallback={<div>Loading...</div>}>74+ <div>75+ <button76+ onClick={() => {77+ startTransition(() => {78+ setCount((c) => c + 1)79+ })80+ }}81+ >82+ {count ? <Counter count={count} /> : count}83+ </button>84+ </div>85+ </Suspense>86+ )87+ }88+ render(<App />, root)89+ expect(root.innerHTML).toBe('<div><button>0</button></div>')90+ root.querySelector('button')?.click()91+ expect(root.innerHTML).toBe('<div><button>0</button></div>')92+ resolve!()93+ await new Promise((r) => setTimeout(r))94+ expect(root.innerHTML).toBe('<div><button><div>1</div></button></div>')95+ })96+})97+98+describe('useTransition()', () => {99+ let dom: JSDOM100+ let root: HTMLElement101+ beforeEach(() => {102+ dom = new JSDOM('<html><body><div id="root"></div></body></html>', {103+ runScripts: 'dangerously',104+ })105+ global.document = dom.window.document106+ global.HTMLElement = dom.window.HTMLElement107+ global.requestAnimationFrame = (cb: Function) => setTimeout(cb)108+ global.Text = dom.window.Text109+ root = document.getElementById('root') as HTMLElement110+ })111+112+ it('pending', async () => {113+ let called = 0114+ const App = () => {115+ const [count, setCount] = useState(0)116+ const [isPending, startTransition] = useTransition()117+ called++118+119+ return (120+ <div>121+ <button122+ onClick={() => {123+ startTransition(() => {124+ setCount((c) => c + 1)125+ })126+ }}127+ >128+ {isPending ? 'Pending...' : count}129+ </button>130+ </div>131+ )132+ }133+ render(<App />, root)134+ expect(root.innerHTML).toBe('<div><button>0</button></div>')135+ root.querySelector('button')?.click()136+ await Promise.resolve()137+ expect(root.innerHTML).toBe('<div><button>Pending...</button></div>')138+ expect(called).toBe(2)139+ await new Promise((r) => setTimeout(r))140+ await new Promise((r) => setTimeout(r))141+ expect(root.innerHTML).toBe('<div><button>1</button></div>')142+ expect(called).toBe(3)143+ })144+145+ it('multiple setState at once', async () => {146+ let called = 0147+ const App = () => {148+ const [count1, setCount1] = useState(0)149+ const [count2, setCount2] = useState(0)150+ const [isPending, startTransition] = useTransition()151+ called++152+153+ return (154+ <div>155+ <button156+ onClick={() => {157+ startTransition(() => {158+ setCount1((c) => c + 1)159+ setCount2((c) => c + 2)160+ })161+ }}162+ >163+ {isPending ? 'Pending...' : count1 + count2}164+ </button>165+ </div>166+ )167+ }168+ render(<App />, root)169+ expect(root.innerHTML).toBe('<div><button>0</button></div>')170+ root.querySelector('button')?.click()171+ await Promise.resolve()172+ expect(root.innerHTML).toBe('<div><button>Pending...</button></div>')173+ expect(called).toBe(2)174+ await new Promise((r) => setTimeout(r))175+ await new Promise((r) => setTimeout(r))176+ expect(root.innerHTML).toBe('<div><button>3</button></div>')177+ expect(called).toBe(3)178+ })179+180+ it('multiple startTransaction at once', async () => {181+ let called = 0182+ const App = () => {183+ const [count1, setCount1] = useState(0)184+ const [count2, setCount2] = useState(0)185+ const [isPending, startTransition] = useTransition()186+ called++187+188+ return (189+ <div>190+ <button191+ onClick={() => {192+ startTransition(() => {193+ setCount1((c) => c + 1)194+ })195+ startTransition(() => {196+ setCount2((c) => c + 2)197+ })198+ }}199+ >200+ {isPending ? 'Pending...' : count1 + count2}201+ </button>202+ </div>203+ )204+ }205+ render(<App />, root)206+ expect(root.innerHTML).toBe('<div><button>0</button></div>')207+ expect(called).toBe(1)208+ root.querySelector('button')?.click()209+ await Promise.resolve()210+ expect(root.innerHTML).toBe('<div><button>Pending...</button></div>')211+ expect(called).toBe(2)212+ await new Promise((r) => setTimeout(r))213+ await new Promise((r) => setTimeout(r))214+ expect(root.innerHTML).toBe('<div><button>3</button></div>')215+ expect(called).toBe(3) // + isPending=true + isPending=false216+ })217+})218+219+describe('useDeferredValue()', () => {220+ let dom: JSDOM221+ let root: HTMLElement222+ beforeEach(() => {223+ dom = new JSDOM('<html><body><div id="root"></div></body></html>', {224+ runScripts: 'dangerously',225+ })226+ global.document = dom.window.document227+ global.HTMLElement = dom.window.HTMLElement228+ global.Text = dom.window.Text229+ root = document.getElementById('root') as HTMLElement230+ })231+232+ it('deferred', async () => {233+ const promiseMap = {} as Record<number, Promise<number>>234+ const getPromise = (count: number) => {235+ return (promiseMap[count] ||= new Promise((r) => setTimeout(() => r(count + 1))))236+ }237+ const ShowCount = ({ count }: { count: number }) => {238+ if (count === 0) {239+ return <div>0</div>240+ }241+242+ const c = use(getPromise(count))243+ return <div>{c}</div>244+ }245+246+ const App = () => {247+ const [count, setCount] = useState(0)248+ const c = useDeferredValue(count)249+ return (250+ <>251+ <div>252+ <button onClick={() => setCount((c) => c + 1)}>+1</button>253+ </div>254+ <Suspense fallback={<div>Loading...</div>}>255+ <ShowCount count={c} />256+ </Suspense>257+ </>258+ )259+ }260+ render(<App />, root)261+ expect(root.innerHTML).toBe('<div><button>+1</button></div><div>0</div>')262+ root.querySelector('button')?.click()263+ await Promise.resolve()264+ expect(root.innerHTML).toBe('<div><button>+1</button></div><div>0</div>')265+ await new Promise((r) => setTimeout(r))266+ expect(root.innerHTML).toBe('<div><button>+1</button></div><div>2</div>')267+ })268+})269+270+describe('startViewTransition()', () => {271+ let dom: JSDOM272+ let root: HTMLElement273+ beforeEach(() => {274+ dom = new JSDOM('<html><body><div id="root"></div></body></html>', {275+ runScripts: 'dangerously',276+ })277+ global.document = dom.window.document278+ global.HTMLElement = dom.window.HTMLElement279+ global.Text = dom.window.Text280+ root = document.getElementById('root') as HTMLElement281+ })282+ afterEach(() => {283+ // eslint-disable-next-line @typescript-eslint/no-explicit-any284+ delete (dom.window.document as any).startViewTransition285+ })286+287+ it('supported browser', async () => {288+ // eslint-disable-next-line @typescript-eslint/no-explicit-any289+ ;(dom.window.document as any).startViewTransition = vi.fn((cb: Function) => {290+ Promise.resolve().then(() => cb())291+ return { finished: Promise.resolve() }292+ })293+294+ const App = () => {295+ const [count, setCount] = useState(0)296+ return (297+ <Suspense fallback={<div>Loading...</div>}>298+ <div>299+ <button300+ onClick={() => {301+ startViewTransition(() => {302+ setCount((c) => c + 1)303+ })304+ }}305+ >306+ {count}307+ </button>308+ </div>309+ </Suspense>310+ )311+ }312+ render(<App />, root)313+ expect(root.innerHTML).toBe('<div><button>0</button></div>')314+ root.querySelector('button')?.click()315+ await Promise.resolve()316+ expect(root.innerHTML).toBe('<div><button>0</button></div>')317+ await Promise.resolve() // updated in microtask318+ expect(root.innerHTML).toBe('<div><button>1</button></div>')319+ })320+321+ it('unsupported browser', async () => {322+ const App = () => {323+ const [count, setCount] = useState(0)324+ return (325+ <Suspense fallback={<div>Loading...</div>}>326+ <div>327+ <button328+ onClick={() => {329+ startViewTransition(() => {330+ setCount((c) => c + 1)331+ })332+ }}333+ >334+ {count}335+ </button>336+ </div>337+ </Suspense>338+ )339+ }340+ render(<App />, root)341+ expect(root.innerHTML).toBe('<div><button>0</button></div>')342+ root.querySelector('button')?.click()343+ await Promise.resolve()344+ expect(root.innerHTML).toBe('<div><button>1</button></div>')345+ })346+347+ it('with useTransition()', async () => {348+ // eslint-disable-next-line @typescript-eslint/no-explicit-any349+ ;(dom.window.document as any).startViewTransition = vi.fn((cb: Function) => {350+ Promise.resolve().then(() => cb())351+ return { finished: Promise.resolve() }352+ })353+354+ let called = 0355+ const App = () => {356+ const [count, setCount] = useState(0)357+ const [isPending, startTransition] = useTransition()358+ called++359+360+ return (361+ <div>362+ <button363+ onClick={() => {364+ startViewTransition(() => {365+ startTransition(() => {366+ setCount((c) => c + 1)367+ })368+ })369+ }}370+ >371+ {isPending ? 'Pending...' : count}372+ </button>373+ </div>374+ )375+ }376+ render(<App />, root)377+ expect(root.innerHTML).toBe('<div><button>0</button></div>')378+ root.querySelector('button')?.click()379+ await new Promise((r) => setTimeout(r))380+ expect(root.innerHTML).toBe('<div><button>Pending...</button></div>')381+ expect(called).toBe(2)382+ await new Promise((r) => setTimeout(r))383+ await new Promise((r) => setTimeout(r))384+ expect(root.innerHTML).toBe('<div><button>1</button></div>')385+ expect(called).toBe(3)386+ })387+})388+389+describe('useViewTransition()', () => {390+ let dom: JSDOM391+ let root: HTMLElement392+ beforeEach(() => {393+ dom = new JSDOM('<html><body><div id="root"></div></body></html>', {394+ runScripts: 'dangerously',395+ })396+ global.document = dom.window.document397+ global.HTMLElement = dom.window.HTMLElement398+ global.Text = dom.window.Text399+ root = document.getElementById('root') as HTMLElement400+ })401+ afterEach(() => {402+ // eslint-disable-next-line @typescript-eslint/no-explicit-any403+ delete (dom.window.document as any).startViewTransition404+ })405+406+ it('supported browser', async () => {407+ let resolved: (() => void) | undefined408+ const promise = new Promise<void>((r) => (resolved = r))409+ let called = 0410+ // eslint-disable-next-line @typescript-eslint/no-explicit-any411+ ;(global.document as any).startViewTransition = vi.fn((cb: Function) => {412+ Promise.resolve().then(() => cb())413+ return { finished: promise }414+ })415+416+ const App = () => {417+ const [count, setCount] = useState(0)418+ const [isUpdating, startViewTransition] = useViewTransition()419+ called++420+421+ return (422+ <div>423+ <button424+ onClick={() => {425+ startViewTransition(() => {426+ setCount((c) => c + 1)427+ })428+ }}429+ >430+ {isUpdating ? 'Pending...' : count}431+ </button>432+ </div>433+ )434+ }435+ render(<App />, root)436+ expect(root.innerHTML).toBe('<div><button>0</button></div>')437+ root.querySelector('button')?.click()438+ await new Promise((r) => setTimeout(r))439+ expect(root.innerHTML).toBe('<div><button>Pending...</button></div>')440+ expect(called).toBe(2)441+ resolved?.()442+ await new Promise((r) => setTimeout(r))443+ expect(root.innerHTML).toBe('<div><button>1</button></div>')444+ expect(called).toBe(3)445+ })446+})added:src/jsx/hooks/index.ts+324 added
1+import { DOM_STASH } from '../constants'2+import { buildDataStack, update, build } from '../dom/render'3+import type { Node, NodeObject, Context, PendingType, UpdateHook } from '../dom/render'4+5+type UpdateStateFunction<T> = (newState: T | ((currentState: T) => T)) => void6+7+const STASH_SATE = 08+export const STASH_EFFECT = 19+const STASH_CALLBACK = 210+const STASH_USE = 311+const STASH_MEMO = 412+13+export type EffectData = [14+ readonly unknown[] | undefined, // deps15+ (() => void | (() => void)) | undefined, // layout effect16+ (() => void) | undefined, // cleanup17+ (() => void) | undefined // effect18+]19+20+const resolvedPromiseValueMap = new WeakMap<Promise<unknown>, unknown>()21+22+const isDepsChanged = (23+ prevDeps: readonly unknown[] | undefined,24+ deps: readonly unknown[] | undefined25+): boolean =>26+ !prevDeps ||27+ !deps ||28+ prevDeps.length !== deps.length ||29+ deps.some((dep, i) => dep !== prevDeps[i])30+31+let viewTransitionState:32+ | [33+ boolean, // isUpdating34+ boolean // useViewTransition() is called35+ ]36+ | undefined = undefined37+38+const documentStartViewTransition: (cb: () => void) => { finished: Promise<void> } = (cb) => {39+ // eslint-disable-next-line @typescript-eslint/no-explicit-any40+ if ((document as any)?.startViewTransition) {41+ // eslint-disable-next-line @typescript-eslint/no-explicit-any42+ return (document as any).startViewTransition(cb)43+ } else {44+ cb()45+ return { finished: Promise.resolve() }46+ }47+}48+49+let updateHook: UpdateHook | undefined = undefined50+const viewTransitionHook = (51+ context: Context,52+ node: Node,53+ cb: (context: Context) => void54+): Promise<void> => {55+ const state: [boolean, boolean] = [true, false]56+ let lastVC = node.vC57+ return documentStartViewTransition(() => {58+ if (lastVC === node.vC) {59+ viewTransitionState = state60+ cb(context)61+ viewTransitionState = undefined62+ lastVC = node.vC63+ }64+ }).finished.then(() => {65+ if (state[1] && lastVC === node.vC) {66+ state[0] = false67+ viewTransitionState = state68+ cb(context)69+ viewTransitionState = undefined70+ }71+ })72+}73+74+export const startViewTransition = (callback: () => void): void => {75+ updateHook = viewTransitionHook76+77+ try {78+ callback()79+ } finally {80+ updateHook = undefined81+ }82+}83+84+export const useViewTransition = (): [boolean, (callback: () => void) => void] => {85+ const buildData = buildDataStack.at(-1) as [Context, NodeObject]86+ if (!buildData) {87+ return [false, () => {}]88+ }89+90+ if (viewTransitionState) {91+ viewTransitionState[1] = true92+ }93+ return [!!viewTransitionState?.[0], startViewTransition]94+}95+96+const pendingStack: PendingType[] = []97+const runCallback = (type: PendingType, callback: Function): void => {98+ pendingStack.push(type)99+ try {100+ callback()101+ } finally {102+ pendingStack.pop()103+ }104+}105+106+export const startTransition = (callback: () => void): void => {107+ runCallback(1, callback)108+}109+const startTransitionHook = (callback: () => void): void => {110+ runCallback(2, callback)111+}112+113+export const useTransition = (): [boolean, (callback: () => void) => void] => {114+ const buildData = buildDataStack.at(-1) as [Context, NodeObject]115+ if (!buildData) {116+ return [false, () => {}]117+ }118+ const [context] = buildData119+ return [context[0] === 2, startTransitionHook]120+}121+122+export const useDeferredValue = <T>(value: T): T => {123+ const buildData = buildDataStack.at(-1) as [Context, NodeObject]124+ if (buildData) {125+ buildData[0][0] = 1126+ }127+ return value128+}129+130+const setShadow = (node: Node) => {131+ if (node.vC) {132+ node.s = node.vC133+ // eslint-disable-next-line @typescript-eslint/no-explicit-any134+ ;(node as any).vC = undefined135+ }136+ // eslint-disable-next-line @typescript-eslint/no-explicit-any137+ ;(node as any).s?.forEach(setShadow)138+}139+140+export const useState = <T>(initialState: T | (() => T)): [T, UpdateStateFunction<T>] => {141+ const resolveInitialState = () =>142+ typeof initialState === 'function' ? (initialState as () => T)() : initialState143+144+ const buildData = buildDataStack.at(-1) as [unknown, NodeObject]145+ if (!buildData) {146+ return [resolveInitialState(), () => {}]147+ }148+ const [, node] = buildData149+150+ const stateArray = (node[DOM_STASH][1][STASH_SATE] ||= [])151+ const hookIndex = node[DOM_STASH][0]++152+153+ return (stateArray[hookIndex] ||= [154+ resolveInitialState(),155+ (newState: T | ((currentState: T) => T)) => {156+ const localUpdateHook = updateHook157+ const stateData = stateArray[hookIndex]158+ if (typeof newState === 'function') {159+ newState = (newState as (currentState: T) => T)(stateData[0])160+ }161+162+ if (newState !== stateData[0]) {163+ stateData[0] = newState164+ if (pendingStack.length) {165+ const pendingType = pendingStack.at(-1) as PendingType166+ update([pendingType, false, localUpdateHook as UpdateHook], node).then((node) => {167+ if (!node || pendingType !== 2) {168+ return169+ }170+171+ const lastVC = node.vC172+173+ const addUpdateTask = () => {174+ setTimeout(() => {175+ // `node` is not rerendered after current transition176+ if (lastVC !== node.vC) {177+ return178+ }179+180+ const shadowNode = Object.assign({}, node) as NodeObject181+182+ // eslint-disable-next-line @typescript-eslint/no-explicit-any183+ ;(shadowNode as any).vC = undefined // delete the prev build data and build with clean state184+ build([], shadowNode, undefined)185+ setShadow(shadowNode) // save the `shadowNode.vC` of the virtual DOM of the build result as a result of shadow virtual DOM `shadowNode.s`186+187+ node.s = shadowNode.s188+ update([0, false, localUpdateHook as UpdateHook], node)189+ })190+ }191+192+ if (localUpdateHook) {193+ // wait for next animation frame, then invoke `update()`194+ requestAnimationFrame(addUpdateTask)195+ } else {196+ addUpdateTask()197+ }198+ })199+ } else {200+ update([0, false, localUpdateHook as UpdateHook], node)201+ }202+ }203+ },204+ ])205+}206+207+const useEffectCommon = (208+ index: number,209+ effect: () => void | (() => void),210+ deps?: readonly unknown[]211+): void => {212+ const buildData = buildDataStack.at(-1) as [unknown, NodeObject]213+ if (!buildData) {214+ return215+ }216+ const [, node] = buildData217+218+ const effectDepsArray = (node[DOM_STASH][1][STASH_EFFECT] ||= [])219+ const hookIndex = node[DOM_STASH][0]++220+221+ const [prevDeps, , prevCleanup] = (effectDepsArray[hookIndex] ||= [])222+ if (isDepsChanged(prevDeps, deps)) {223+ if (prevCleanup) {224+ prevCleanup()225+ }226+ const runner = () => {227+ data[index] = undefined // clear this effect in order to avoid calling effect twice228+ data[2] = effect() as (() => void) | undefined229+ }230+ const data: EffectData = [deps, undefined, undefined, undefined]231+ data[index] = runner232+ effectDepsArray[hookIndex] = data233+ }234+}235+export const useEffect = (effect: () => void | (() => void), deps?: readonly unknown[]): void =>236+ useEffectCommon(3, effect, deps)237+export const useLayoutEffect = (238+ effect: () => void | (() => void),239+ deps?: readonly unknown[]240+): void => useEffectCommon(1, effect, deps)241+242+export const useCallback = <T extends (...args: unknown[]) => unknown>(243+ callback: T,244+ deps: readonly unknown[]245+): T => {246+ const buildData = buildDataStack.at(-1) as [unknown, NodeObject]247+ if (!buildData) {248+ return callback249+ }250+ const [, node] = buildData251+252+ const callbackArray = (node[DOM_STASH][1][STASH_CALLBACK] ||= [])253+ const hookIndex = node[DOM_STASH][0]++254+255+ const prevDeps = callbackArray[hookIndex]256+ if (isDepsChanged(prevDeps?.[1], deps)) {257+ callbackArray[hookIndex] = [callback, deps]258+ } else {259+ callback = callbackArray[hookIndex][0] as T260+ }261+ return callback262+}263+264+export type RefObject<T> = { current: T | null }265+export const useRef = <T>(initialValue: T | null): RefObject<T> => {266+ return { current: initialValue }267+}268+269+export const use = <T>(promise: Promise<T>): T => {270+ const cachedRes = resolvedPromiseValueMap.get(promise) as [T] | [undefined, unknown] | undefined271+ if (cachedRes) {272+ if (cachedRes.length === 2) {273+ throw cachedRes[1]274+ }275+ return cachedRes[0] as T276+ }277+ promise278+ .then((res) => resolvedPromiseValueMap.set(promise, [res]))279+ .catch((e) => resolvedPromiseValueMap.set(promise, [undefined, e]))280+281+ const buildData = buildDataStack.at(-1) as [unknown, NodeObject]282+ if (!buildData) {283+ throw promise284+ }285+ const [, node] = buildData286+287+ const promiseArray = (node[DOM_STASH][1][STASH_USE] ||= [])288+ const hookIndex = node[DOM_STASH][0]++289+290+ promise291+ .then((res) => {292+ promiseArray[hookIndex] = [res]293+ })294+ .catch((e) => {295+ promiseArray[hookIndex] = [undefined, e]296+ })297+298+ const res = promiseArray[hookIndex]299+ if (res) {300+ if (res.length === 2) {301+ throw res[1]302+ }303+ return res[0] as T304+ }305+306+ throw promise307+}308+309+export const useMemo = <T>(factory: () => T, deps: readonly unknown[]): T => {310+ const buildData = buildDataStack.at(-1) as [unknown, NodeObject]311+ if (!buildData) {312+ return factory()313+ }314+ const [, node] = buildData315+316+ const memoArray = (node[DOM_STASH][1][STASH_MEMO] ||= [])317+ const hookIndex = node[DOM_STASH][0]++318+319+ const prevDeps = memoArray[hookIndex]320+ if (isDepsChanged(prevDeps?.[1], deps)) {321+ memoArray[hookIndex] = [factory(), deps]322+ }323+ return memoArray[hookIndex][0] as T324+}added:src/jsx/base.ts+336 added
1+import { raw } from '../helper/html'2+import { escapeToBuffer, stringBufferToString } from '../utils/html'3+import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../utils/html'4+import type { Context } from './context'5+import { globalContexts } from './context'6+import type { IntrinsicElements as IntrinsicElementsDefined } from './intrinsic-elements'7+import { normalizeIntrinsicElementProps } from './utils'8+9+// eslint-disable-next-line @typescript-eslint/no-explicit-any10+export type Props = Record<string, any>11+export type FC<T = Props> = (props: T) => HtmlEscapedString | Promise<HtmlEscapedString>12+13+declare global {14+ // eslint-disable-next-line @typescript-eslint/no-namespace15+ namespace JSX {16+ type Element = HtmlEscapedString | Promise<HtmlEscapedString>17+ interface ElementChildrenAttribute {18+ children: Child19+ }20+ interface IntrinsicElements extends IntrinsicElementsDefined {21+ [tagName: string]: Props22+ }23+ }24+}25+26+const emptyTags = [27+ 'area',28+ 'base',29+ 'br',30+ 'col',31+ 'embed',32+ 'hr',33+ 'img',34+ 'input',35+ 'keygen',36+ 'link',37+ 'meta',38+ 'param',39+ 'source',40+ 'track',41+ 'wbr',42+]43+const booleanAttributes = [44+ 'allowfullscreen',45+ 'async',46+ 'autofocus',47+ 'autoplay',48+ 'checked',49+ 'controls',50+ 'default',51+ 'defer',52+ 'disabled',53+ 'formnovalidate',54+ 'hidden',55+ 'inert',56+ 'ismap',57+ 'itemscope',58+ 'loop',59+ 'multiple',60+ 'muted',61+ 'nomodule',62+ 'novalidate',63+ 'open',64+ 'playsinline',65+ 'readonly',66+ 'required',67+ 'reversed',68+ 'selected',69+]70+71+const childrenToStringToBuffer = (children: Child[], buffer: StringBuffer): void => {72+ for (let i = 0, len = children.length; i < len; i++) {73+ const child = children[i]74+ if (typeof child === 'string') {75+ escapeToBuffer(child, buffer)76+ } else if (typeof child === 'boolean' || child === null || child === undefined) {77+ continue78+ } else if (child instanceof JSXNode) {79+ child.toStringToBuffer(buffer)80+ } else if (81+ typeof child === 'number' ||82+ (child as unknown as { isEscaped: boolean }).isEscaped83+ ) {84+ ;(buffer[0] as string) += child85+ } else if (child instanceof Promise) {86+ buffer.unshift('', child)87+ } else {88+ // `child` type is `Child[]`, so stringify recursively89+ childrenToStringToBuffer(child, buffer)90+ }91+ }92+}93+94+type LocalContexts = [Context<unknown>, unknown][]95+export type Child = string | Promise<string> | number | JSXNode | Child[]96+export class JSXNode implements HtmlEscaped {97+ tag: string | Function98+ props: Props99+ key?: string100+ children: Child[]101+ isEscaped: true = true as const102+ localContexts?: LocalContexts103+ constructor(tag: string | Function, props: Props, children: Child[]) {104+ this.tag = tag105+ this.props = props106+ this.children = children107+ }108+109+ toString(): string | Promise<string> {110+ const buffer: StringBuffer = ['']111+ this.localContexts?.forEach(([context, value]) => {112+ context.values.push(value)113+ })114+ try {115+ this.toStringToBuffer(buffer)116+ } finally {117+ this.localContexts?.forEach(([context]) => {118+ context.values.pop()119+ })120+ }121+ return buffer.length === 1 ? buffer[0] : stringBufferToString(buffer)122+ }123+124+ toStringToBuffer(buffer: StringBuffer): void {125+ const tag = this.tag as string126+ const props = this.props127+ let { children } = this128+129+ buffer[0] += `<${tag}`130+131+ const propsKeys = Object.keys(props || {})132+133+ for (let i = 0, len = propsKeys.length; i < len; i++) {134+ const key = propsKeys[i]135+ const v = props[key]136+ // object to style strings137+ if (key === 'style' && typeof v === 'object') {138+ const styles = Object.keys(v)139+ .map((k) => {140+ const property = k.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`)141+ return `${property}:${v[k]}`142+ })143+ .join(';')144+ buffer[0] += ` style="${styles}"`145+ } else if (typeof v === 'string') {146+ buffer[0] += ` ${key}="`147+ escapeToBuffer(v, buffer)148+ buffer[0] += '"'149+ } else if (v === null || v === undefined) {150+ // Do nothing151+ } else if (typeof v === 'number' || (v as HtmlEscaped).isEscaped) {152+ buffer[0] += ` ${key}="${v}"`153+ } else if (typeof v === 'boolean' && booleanAttributes.includes(key)) {154+ if (v) {155+ buffer[0] += ` ${key}=""`156+ }157+ } else if (key === 'dangerouslySetInnerHTML') {158+ if (children.length > 0) {159+ throw 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'160+ }161+162+ children = [raw(v.__html)]163+ } else if (v instanceof Promise) {164+ buffer[0] += ` ${key}="`165+ buffer.unshift('"', v)166+ } else if (typeof v === 'function') {167+ if (!key.startsWith('on')) {168+ throw `Invalid prop '${key}' of type 'function' supplied to '${tag}'.`169+ }170+ // maybe event handler for client components, just ignore in server components171+ } else {172+ buffer[0] += ` ${key}="`173+ escapeToBuffer(v.toString(), buffer)174+ buffer[0] += '"'175+ }176+ }177+178+ if (emptyTags.includes(tag as string)) {179+ buffer[0] += '/>'180+ return181+ }182+183+ buffer[0] += '>'184+185+ childrenToStringToBuffer(children, buffer)186+187+ buffer[0] += `</${tag}>`188+ }189+}190+191+class JSXFunctionNode extends JSXNode {192+ toStringToBuffer(buffer: StringBuffer): void {193+ const { children } = this194+195+ const res = (this.tag as Function).call(null, {196+ ...this.props,197+ children: children.length <= 1 ? children[0] : children,198+ })199+200+ if (res instanceof Promise) {201+ if (globalContexts.length === 0) {202+ buffer.unshift('', res)203+ } else {204+ // save current contexts for resuming205+ const currentContexts: LocalContexts = globalContexts.map((c) => [c, c.values.at(-1)])206+ buffer.unshift(207+ '',208+ res.then((childRes) => {209+ if (childRes instanceof JSXNode) {210+ childRes.localContexts = currentContexts211+ }212+ return childRes213+ })214+ )215+ }216+ } else if (res instanceof JSXNode) {217+ res.toStringToBuffer(buffer)218+ } else if (typeof res === 'number' || (res as HtmlEscaped).isEscaped) {219+ buffer[0] += res220+ } else {221+ escapeToBuffer(res, buffer)222+ }223+ }224+}225+226+export class JSXFragmentNode extends JSXNode {227+ toStringToBuffer(buffer: StringBuffer): void {228+ childrenToStringToBuffer(this.children, buffer)229+ }230+}231+232+export const jsx = (233+ tag: string | Function,234+ props: Props,235+ ...children: (string | HtmlEscapedString)[]236+): JSXNode => {237+ let key238+ if (props) {239+ key = props?.key240+ delete props['key']241+ }242+ const node = jsxFn(tag, props, children)243+ node.key = key244+ return node245+}246+247+export const jsxFn = (248+ tag: string | Function,249+ props: Props,250+ children: (string | HtmlEscapedString)[]251+): JSXNode => {252+ if (typeof tag === 'function') {253+ return new JSXFunctionNode(tag, props, children)254+ } else {255+ normalizeIntrinsicElementProps(props)256+ return new JSXNode(tag, props, children)257+ }258+}259+260+const shallowEqual = (a: Props, b: Props): boolean => {261+ if (a === b) {262+ return true263+ }264+265+ const aKeys = Object.keys(a).sort()266+ const bKeys = Object.keys(b).sort()267+ if (aKeys.length !== bKeys.length) {268+ return false269+ }270+271+ for (let i = 0, len = aKeys.length; i < len; i++) {272+ if (273+ aKeys[i] === 'children' &&274+ bKeys[i] === 'children' &&275+ !a.children?.length &&276+ !b.children?.length277+ ) {278+ continue279+ } else if (a[aKeys[i]] !== b[aKeys[i]]) {280+ return false281+ }282+ }283+284+ return true285+}286+287+export const memo = <T>(288+ component: FC<T>,289+ propsAreEqual: (prevProps: Readonly<T>, nextProps: Readonly<T>) => boolean = shallowEqual290+): FC<T> => {291+ let computed: HtmlEscapedString | Promise<HtmlEscapedString> | undefined = undefined292+ let prevProps: T | undefined = undefined293+ return ((props: T & { children?: Child }): HtmlEscapedString | Promise<HtmlEscapedString> => {294+ if (prevProps && !propsAreEqual(prevProps, props)) {295+ computed = undefined296+ }297+ prevProps = props298+ return (computed ||= component(props))299+ }) as FC<T>300+}301+302+export const Fragment = ({303+ children,304+}: {305+ key?: string306+ children?: Child | HtmlEscapedString307+}): HtmlEscapedString => {308+ return new JSXFragmentNode(309+ '',310+ {},311+ Array.isArray(children) ? children : children ? [children] : []312+ ) as never313+}314+315+export const isValidElement = (element: unknown): element is JSXNode => {316+ return !!(317+ element &&318+ typeof element === 'object' &&319+ 'tag' in element &&320+ 'props' in element &&321+ 'children' in element322+ )323+}324+325+export const cloneElement = <T extends JSXNode | JSX.Element>(326+ element: T,327+ props: Partial<Props>,328+ ...children: Child[]329+): T => {330+ return jsxFn(331+ (element as JSXNode).tag,332+ { ...(element as JSXNode).props, ...props },333+ // eslint-disable-next-line @typescript-eslint/no-explicit-any334+ children.length ? children : ((element as JSXNode).children as any) || []335+ ) as T336+}modified:src/jsx/components.test.tsx+2 added-1 removed
1+/* eslint-disable @typescript-eslint/no-explicit-any */2 import { JSDOM } from 'jsdom'3 import type { HtmlEscapedString } from '../utils/html'4 import { HtmlEscapedCallbackPhase, resolveCallback as rawResolveCallback } from '../utils/html'5 import { ErrorBoundary } from './components'6 import { Suspense, renderToReadableStream } from './streaming'7 // eslint-disable-next-line @typescript-eslint/no-unused-vars7-import { jsx } from './index'8+import { jsx } from '.'9 10 function resolveCallback(template: string | HtmlEscapedString) {11 return rawResolveCallback(template, HtmlEscapedCallbackPhase.Stream, false, {})12 }466 unmodified linesmodified:src/jsx/components.ts+16 added-14 removed
1 import { raw } from '../helper/html'2-import {3- HtmlEscapedCallbackPhase,4- resolveCallback,5- type HtmlEscapedString,6- type HtmlEscapedCallback,7-} from '../utils/html'8-import type { FC, Child } from './index'2+import type { HtmlEscapedString, HtmlEscapedCallback } from '../utils/html'3+import { HtmlEscapedCallbackPhase, resolveCallback } from '../utils/html'4+import { DOM_RENDERER } from './constants'5+import { ErrorBoundary as ErrorBoundaryDomRenderer } from './dom/components'6+import type { HasRenderToDom } from './dom/render'7+import type { FC, PropsWithChildren, Child } from '.'8 9 let errorBoundaryCounter = 010 11 export const childrenToString = async (children: Child[]): Promise<HtmlEscapedString[]> => {8 unmodified lines20 }21 }22 }23 25-type ErrorHandler = (error: Error) => void26-type FallbackRender = (error: Error) => Child24+export type ErrorHandler = (error: Error) => void25+export type FallbackRender = (error: Error) => Child26 27 /**28 * @experimental29 * `ErrorBoundary` is an experimental feature.30 * The API might be changed.31 */33-export const ErrorBoundary: FC<{34- fallback?: Child35- fallbackRender?: FallbackRender36- onError?: ErrorHandler37-}> = async ({ children, fallback, fallbackRender, onError }) => {32+export const ErrorBoundary: FC<33+ PropsWithChildren<{34+ fallback?: Child35+ fallbackRender?: FallbackRender36+ onError?: ErrorHandler37+ }>38+> = async ({ children, fallback, fallbackRender, onError }) => {39 if (!children) {40 return raw('')41 }42 138 unmodified lines181 } else {182 return raw(resArray.join(''))183 }184 }185+;(ErrorBoundary as HasRenderToDom)[DOM_RENDERER] = ErrorBoundaryDomRendereradded:src/jsx/constants.ts+3 added
1+export const DOM_RENDERER = Symbol('RENDERER')2+export const DOM_ERROR_HANDLER = Symbol('ERROR_HANDLER')3+export const DOM_STASH = Symbol('STASH')added:src/jsx/context.ts+52 added
1+import { raw } from '../helper/html'2+import type { HtmlEscapedString } from '../utils/html'3+import { JSXFragmentNode } from './base'4+import { DOM_RENDERER } from './constants'5+import { createContextProviderFunction } from './dom/context'6+import type { FC, PropsWithChildren } from '.'7+8+export interface Context<T> {9+ values: T[]10+ Provider: FC<PropsWithChildren<{ value: T }>>11+}12+13+export const globalContexts: Context<unknown>[] = []14+15+export const createContext = <T>(defaultValue: T): Context<T> => {16+ const values = [defaultValue]17+ const context: Context<T> = {18+ values,19+ Provider(props): HtmlEscapedString | Promise<HtmlEscapedString> {20+ values.push(props.value)21+ let string22+ try {23+ string = props.children24+ ? (Array.isArray(props.children)25+ ? new JSXFragmentNode('', {}, props.children)26+ : props.children27+ ).toString()28+ : ''29+ } finally {30+ values.pop()31+ }32+33+ if (string instanceof Promise) {34+ return string.then((resString) =>35+ raw(resString, (resString as HtmlEscapedString).callbacks)36+ )37+ } else {38+ return raw(string)39+ }40+ },41+ }42+ // eslint-disable-next-line @typescript-eslint/no-explicit-any43+ ;(context.Provider as any)[DOM_RENDERER] = createContextProviderFunction(values)44+45+ globalContexts.push(context as Context<unknown>)46+47+ return context48+}49+50+export const useContext = <T>(context: Context<T>): T => {51+ return context.values.at(-1) as T52+}modified:src/jsx/index.test.tsx+39 added-4 removed
2 unmodified lines3 import { html } from '../helper/html'4 import { Hono } from '../hono'5 import { Suspense, renderToReadableStream } from './streaming'6 // eslint-disable-next-line @typescript-eslint/no-unused-vars7-import { jsx, memo, Fragment, createContext, useContext } from './index'8-import type { Context, FC } from './index'7+import { jsx, memo, Fragment, createContext, useContext } from '.'8+import type { Context, FC, PropsWithChildren } from '.'9 10 interface SiteData {11 title: string12 children?: any89 unmodified lines102 return <h1>Hello from async component</h1>103 }104 105 app.get('/', (c) => {106+ // prettier-ignore107 return c.html(108 html`<html><body>${(<AsyncComponent />)}</body></html>`109 )110 })181 unmodified lines292 )293 })294 })295 296+ describe('Function', () => {297+ it('should be ignored used in on* props', () => {298+ const onClick = () => {}299+ const template = <button onClick={onClick}>Click</button>300+ expect(template.toString()).toBe('<button>Click</button>')301+ })302+303+ it('should raise an error if used in other props', () => {304+ const onClick = () => {}305+ const template = <button data-handler={onClick}>Click</button>306+ expect(() => template.toString()).toThrow()307+ })308+ })309+310 // https://en.reactjs.org/docs/jsx-in-depth.html#functions-as-children311 describe('Functions as Children', () => {312 it('Function', () => {313 function Repeat(props: any) {13 unmodified lines327 }328 329 const template = <ListOfTenThings />330 expect(template.toString()).toBe(316- '<div><div key="0">This is item 0 in the list</div><div key="1">This is item 1 in the list</div><div key="2">This is item 2 in the list</div><div key="3">This is item 3 in the list</div><div key="4">This is item 4 in the list</div><div key="5">This is item 5 in the list</div><div key="6">This is item 6 in the list</div><div key="7">This is item 7 in the list</div><div key="8">This is item 8 in the list</div><div key="9">This is item 9 in the list</div></div>'331+ '<div><div>This is item 0 in the list</div><div>This is item 1 in the list</div><div>This is item 2 in the list</div><div>This is item 3 in the list</div><div>This is item 4 in the list</div><div>This is item 5 in the list</div><div>This is item 6 in the list</div><div>This is item 7 in the list</div><div>This is item 8 in the list</div><div>This is item 9 in the list</div></div>'332 )333 })334 })335 336 describe('FC', () => {337 it('Should define the type correctly', () => {323- const Layout: FC<{ title: string }> = (props) => {338+ const Layout: FC<PropsWithChildren<{ title: string }>> = (props) => {339 return (340 <html>341 <head>342 <title>{props.title}</title>47 unmodified lines390 })391 })392 })393 394+describe('className', () => {395+ it('should convert to class attribute for intrinsic elements', () => {396+ const template = <h1 className='h1'>Hello</h1>397+ expect(template.toString()).toBe('<h1 class="h1">Hello</h1>')398+ })399+400+ it('should convert to class attribute for custom elements', () => {401+ const template = <custom-element className='h1'>Hello</custom-element>402+ expect(template.toString()).toBe('<custom-element class="h1">Hello</custom-element>')403+ })404+405+ it('should not convert to class attribute for custom components', () => {406+ const CustomComponent: FC<{ className: string }> = ({ className }) => (407+ <div data-class-name={className}>Hello</div>408+ )409+ const template = <CustomComponent className='h1' />410+ expect(template.toString()).toBe('<div data-class-name="h1">Hello</div>')411+ })412+})413+414 describe('memo', () => {415 it('memoized', () => {416 let counter = 0417 const Header = memo(() => <title>Test Site {counter}</title>)305 unmodified linesmodified:src/jsx/index.ts+20 added-323 removed
1-import { raw } from '../helper/html'2-import { escapeToBuffer, stringBufferToString } from '../utils/html'3-import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../utils/html'4-import type { IntrinsicElements as IntrinsicElementsDefined } from './intrinsic-elements'1+export { jsx, memo, Fragment, isValidElement, cloneElement } from './base'2 export { ErrorBoundary } from './components'3+export { Suspense } from './streaming'4+export {5+ useState,6+ useEffect,7+ useRef,8+ useCallback,9+ use,10+ startTransition,11+ useTransition,12+ useDeferredValue,13+ startViewTransition,14+ useViewTransition,15+ useMemo,16+ useLayoutEffect,17+} from './hooks'18+export { createContext, useContext } from './context'19 7-// eslint-disable-next-line @typescript-eslint/no-explicit-any8-type Props = Record<string, any>9-10-declare global {11- // eslint-disable-next-line @typescript-eslint/no-namespace12- namespace JSX {13- type Element = HtmlEscapedString | Promise<HtmlEscapedString>14- interface ElementChildrenAttribute {15- children: Child16- }17- interface IntrinsicElements extends IntrinsicElementsDefined {18- [tagName: string]: Props19- }20- }21-}22-23-const emptyTags = [24- 'area',25- 'base',26- 'br',27- 'col',28- 'embed',29- 'hr',30- 'img',31- 'input',32- 'keygen',33- 'link',34- 'meta',35- 'param',36- 'source',37- 'track',38- 'wbr',39-]40-const booleanAttributes = [41- 'allowfullscreen',42- 'async',43- 'autofocus',44- 'autoplay',45- 'checked',46- 'controls',47- 'default',48- 'defer',49- 'disabled',50- 'formnovalidate',51- 'hidden',52- 'inert',53- 'ismap',54- 'itemscope',55- 'loop',56- 'multiple',57- 'muted',58- 'nomodule',59- 'novalidate',60- 'open',61- 'playsinline',62- 'readonly',63- 'required',64- 'reversed',65- 'selected',66-]67-68-const childrenToStringToBuffer = (children: Child[], buffer: StringBuffer): void => {69- for (let i = 0, len = children.length; i < len; i++) {70- const child = children[i]71- if (typeof child === 'string') {72- escapeToBuffer(child, buffer)73- } else if (typeof child === 'boolean' || child === null || child === undefined) {74- continue75- } else if (child instanceof JSXNode) {76- child.toStringToBuffer(buffer)77- } else if (78- typeof child === 'number' ||79- (child as unknown as { isEscaped: boolean }).isEscaped80- ) {81- ;(buffer[0] as string) += child82- } else if (child instanceof Promise) {83- buffer.unshift('', child)84- } else {85- // `child` type is `Child[]`, so stringify recursively86- childrenToStringToBuffer(child, buffer)87- }88- }89-}90-91-type LocalContexts = [Context<unknown>, unknown][]92-export type Child = string | Promise<string> | number | JSXNode | Child[]93-export class JSXNode implements HtmlEscaped {94- tag: string | Function95- props: Props96- children: Child[]97- isEscaped: true = true as const98- localContexts?: LocalContexts99- constructor(tag: string | Function, props: Props, children: Child[]) {100- this.tag = tag101- this.props = props102- this.children = children103- }104-105- toString(): string | Promise<string> {106- const buffer: StringBuffer = ['']107- this.localContexts?.forEach(([context, value]) => {108- context.values.push(value)109- })110- try {111- this.toStringToBuffer(buffer)112- } finally {113- this.localContexts?.forEach(([context]) => {114- context.values.pop()115- })116- }117- return buffer.length === 1 ? buffer[0] : stringBufferToString(buffer)118- }119-120- toStringToBuffer(buffer: StringBuffer): void {121- const tag = this.tag as string122- const props = this.props123- let { children } = this124-125- buffer[0] += `<${tag}`126-127- const propsKeys = Object.keys(props || {})128-129- for (let i = 0, len = propsKeys.length; i < len; i++) {130- const key = propsKeys[i]131- const v = props[key]132- // object to style strings133- if (key === 'style' && typeof v === 'object') {134- const styles = Object.keys(v)135- .map((k) => {136- const property = k.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`)137- return `${property}:${v[k]}`138- })139- .join(';')140- buffer[0] += ` style="${styles}"`141- } else if (typeof v === 'string') {142- buffer[0] += ` ${key}="`143- escapeToBuffer(v, buffer)144- buffer[0] += '"'145- } else if (v === null || v === undefined) {146- // Do nothing147- } else if (typeof v === 'number' || (v as HtmlEscaped).isEscaped) {148- buffer[0] += ` ${key}="${v}"`149- } else if (typeof v === 'boolean' && booleanAttributes.includes(key)) {150- if (v) {151- buffer[0] += ` ${key}=""`152- }153- } else if (key === 'dangerouslySetInnerHTML') {154- if (children.length > 0) {155- throw 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'156- }157-158- children = [raw(v.__html)]159- } else if (v instanceof Promise) {160- buffer[0] += ` ${key}="`161- buffer.unshift('"', v)162- } else {163- buffer[0] += ` ${key}="`164- escapeToBuffer(v.toString(), buffer)165- buffer[0] += '"'166- }167- }168-169- if (emptyTags.includes(tag as string)) {170- buffer[0] += '/>'171- return172- }173-174- buffer[0] += '>'175-176- childrenToStringToBuffer(children, buffer)177-178- buffer[0] += `</${tag}>`179- }180-}181-182-class JSXFunctionNode extends JSXNode {183- toStringToBuffer(buffer: StringBuffer): void {184- const { children } = this185-186- const res = (this.tag as Function).call(null, {187- ...this.props,188- children: children.length <= 1 ? children[0] : children,189- })190-191- if (res instanceof Promise) {192- if (globalContexts.length === 0) {193- buffer.unshift('', res)194- } else {195- // save current contexts for resuming196- const currentContexts: LocalContexts = globalContexts.map((c) => [197- c,198- c.values[c.values.length - 1],199- ])200- buffer.unshift(201- '',202- res.then((childRes) => {203- if (childRes instanceof JSXNode) {204- childRes.localContexts = currentContexts205- }206- return childRes207- })208- )209- }210- } else if (res instanceof JSXNode) {211- res.toStringToBuffer(buffer)212- } else if (typeof res === 'number' || (res as HtmlEscaped).isEscaped) {213- buffer[0] += res214- } else {215- escapeToBuffer(res, buffer)216- }217- }218-}219-220-class JSXFragmentNode extends JSXNode {221- toStringToBuffer(buffer: StringBuffer): void {222- childrenToStringToBuffer(this.children, buffer)223- }224-}225-226-export { jsxFn as jsx }227-const jsxFn = (228- tag: string | Function,229- props: Props,230- ...children: (string | HtmlEscapedString)[]231-): JSXNode => {232- if (typeof tag === 'function') {233- return new JSXFunctionNode(tag, props, children)234- } else {235- return new JSXNode(tag, props, children)236- }237-}238-239-export type FC<T = Props> = (240- props: T & { children?: Child }241-) => HtmlEscapedString | Promise<HtmlEscapedString>242-243-const shallowEqual = (a: Props, b: Props): boolean => {244- if (a === b) {245- return true246- }247-248- const aKeys = Object.keys(a)249- const bKeys = Object.keys(b)250- if (aKeys.length !== bKeys.length) {251- return false252- }253-254- for (let i = 0, len = aKeys.length; i < len; i++) {255- if (a[aKeys[i]] !== b[aKeys[i]]) {256- return false257- }258- }259-260- return true261-}262-263-export const memo = <T>(264- component: FC<T>,265- propsAreEqual: (prevProps: Readonly<T>, nextProps: Readonly<T>) => boolean = shallowEqual266-): FC<T> => {267- let computed = undefined268- let prevProps: T | undefined = undefined269- return ((props: T & { children?: Child }): HtmlEscapedString => {270- if (prevProps && !propsAreEqual(prevProps, props)) {271- computed = undefined272- }273- prevProps = props274- return (computed ||= component(props))275- }) as FC<T>276-}277-278-export const Fragment = (props: {279- key?: string280- children?: Child | HtmlEscapedString281-}): HtmlEscapedString => {282- return new JSXFragmentNode('', {}, props.children ? [props.children] : []) as never283-}284-285-export interface Context<T> {286- values: T[]287- Provider: FC<{ value: T }>288-}289-290-const globalContexts: Context<unknown>[] = []291-292-export const createContext = <T>(defaultValue: T): Context<T> => {293- const values = [defaultValue]294- const context: Context<T> = {295- values,296- Provider(props): HtmlEscapedString | Promise<HtmlEscapedString> {297- values.push(props.value)298- let string299- try {300- string = props.children301- ? (Array.isArray(props.children)302- ? new JSXFragmentNode('', {}, props.children)303- : props.children304- ).toString()305- : ''306- } finally {307- values.pop()308- }309-310- if (string instanceof Promise) {311- return string.then((resString) =>312- raw(resString, (resString as HtmlEscapedString).callbacks)313- )314- } else {315- return raw(string)316- }317- },318- }319- globalContexts.push(context as Context<unknown>)320- return context321-}322-323-export const useContext = <T>(context: Context<T>): T => {324- return context.values[context.values.length - 1]325-}20+// TODO: change to `export type *` after denoify bug is fixed21+// https://github.com/garronej/denoify/issues/12422+export * from './types'modified:src/jsx/intrinsic-elements.ts+126 added-1 removed
18 unmodified lines19 __html: string20 }21 }22 23- interface HTMLAttributes extends JSXAttributes, AnyAttributes {23+ interface EventAttributes {24+ onScroll?: (event: Event) => void25+ onScrollCapture?: (event: Event) => void26+ onScrollEnd?: (event: Event) => void27+ onScrollEndCapture?: (event: Event) => void28+ onWheel?: (event: WheelEvent) => void29+ onWheelCapture?: (event: WheelEvent) => void30+ onAnimationCancel?: (event: AnimationEvent) => void31+ onAnimationCancelCapture?: (event: AnimationEvent) => void32+ onAnimationEnd?: (event: AnimationEvent) => void33+ onAnimationEndCapture?: (event: AnimationEvent) => void34+ onAnimationIteration?: (event: AnimationEvent) => void35+ onAnimationIterationCapture?: (event: AnimationEvent) => void36+ onAnimationStart?: (event: AnimationEvent) => void37+ onAnimationStartCapture?: (event: AnimationEvent) => void38+ onCopy?: (event: ClipboardEvent) => void39+ onCopyCapture?: (event: ClipboardEvent) => void40+ onCut?: (event: ClipboardEvent) => void41+ onCutCapture?: (event: ClipboardEvent) => void42+ onPaste?: (event: ClipboardEvent) => void43+ onPasteCapture?: (event: ClipboardEvent) => void44+ onCompositionEnd?: (event: CompositionEvent) => void45+ onCompositionEndCapture?: (event: CompositionEvent) => void46+ onCompositionStart?: (event: CompositionEvent) => void47+ onCompositionStartCapture?: (event: CompositionEvent) => void48+ onCompositionUpdate?: (event: CompositionEvent) => void49+ onCompositionUpdateCapture?: (event: CompositionEvent) => void50+ onBlur?: (event: FocusEvent) => void51+ onBlurCapture?: (event: FocusEvent) => void52+ onFocus?: (event: FocusEvent) => void53+ onFocusCapture?: (event: FocusEvent) => void54+ onFocusIn?: (event: FocusEvent) => void55+ onFocusInCapture?: (event: FocusEvent) => void56+ onFocusOut?: (event: FocusEvent) => void57+ onFocusOutCapture?: (event: FocusEvent) => void58+ onFullscreenChange?: (event: Event) => void59+ onFullscreenChangeCapture?: (event: Event) => void60+ onFullscreenError?: (event: Event) => void61+ onFullscreenErrorCapture?: (event: Event) => void62+ onKeyDown?: (event: KeyboardEvent) => void63+ onKeyDownCapture?: (event: KeyboardEvent) => void64+ onKeyPress?: (event: KeyboardEvent) => void65+ onKeyPressCapture?: (event: KeyboardEvent) => void66+ onKeyUp?: (event: KeyboardEvent) => void67+ onKeyUpCapture?: (event: KeyboardEvent) => void68+ onAuxClick?: (event: MouseEvent) => void69+ onAuxClickCapture?: (event: MouseEvent) => void70+ onClick?: (event: MouseEvent) => void71+ onClickCapture?: (event: MouseEvent) => void72+ onContextMenu?: (event: MouseEvent) => void73+ onContextMenuCapture?: (event: MouseEvent) => void74+ onDoubleClick?: (event: MouseEvent) => void75+ onDoubleClickCapture?: (event: MouseEvent) => void76+ onMouseDown?: (event: MouseEvent) => void77+ onMouseDownCapture?: (event: MouseEvent) => void78+ onMouseEnter?: (event: MouseEvent) => void79+ onMouseEnterCapture?: (event: MouseEvent) => void80+ onMouseLeave?: (event: MouseEvent) => void81+ onMouseLeaveCapture?: (event: MouseEvent) => void82+ onMouseMove?: (event: MouseEvent) => void83+ onMouseMoveCapture?: (event: MouseEvent) => void84+ onMouseOut?: (event: MouseEvent) => void85+ onMouseOutCapture?: (event: MouseEvent) => void86+ onMouseOver?: (event: MouseEvent) => void87+ onMouseOverCapture?: (event: MouseEvent) => void88+ onMouseUp?: (event: MouseEvent) => void89+ onMouseUpCapture?: (event: MouseEvent) => void90+ onMouseWheel?: (event: WheelEvent) => void91+ onMouseWheelCapture?: (event: WheelEvent) => void92+ onGotPointerCapture?: (event: PointerEvent) => void93+ onGotPointerCaptureCapture?: (event: PointerEvent) => void94+ onLostPointerCapture?: (event: PointerEvent) => void95+ onLostPointerCaptureCapture?: (event: PointerEvent) => void96+ onPointerCancel?: (event: PointerEvent) => void97+ onPointerCancelCapture?: (event: PointerEvent) => void98+ onPointerDown?: (event: PointerEvent) => void99+ onPointerDownCapture?: (event: PointerEvent) => void100+ onPointerEnter?: (event: PointerEvent) => void101+ onPointerEnterCapture?: (event: PointerEvent) => void102+ onPointerLeave?: (event: PointerEvent) => void103+ onPointerLeaveCapture?: (event: PointerEvent) => void104+ onPointerMove?: (event: PointerEvent) => void105+ onPointerMoveCapture?: (event: PointerEvent) => void106+ onPointerOut?: (event: PointerEvent) => void107+ onPointerOutCapture?: (event: PointerEvent) => void108+ onPointerOver?: (event: PointerEvent) => void109+ onPointerOverCapture?: (event: PointerEvent) => void110+ onPointerUp?: (event: PointerEvent) => void111+ onPointerUpCapture?: (event: PointerEvent) => void112+ onTouchCancel?: (event: TouchEvent) => void113+ onTouchCancelCapture?: (event: TouchEvent) => void114+ onTouchEnd?: (event: TouchEvent) => void115+ onTouchEndCapture?: (event: TouchEvent) => void116+ onTouchMove?: (event: TouchEvent) => void117+ onTouchMoveCapture?: (event: TouchEvent) => void118+ onTouchStart?: (event: TouchEvent) => void119+ onTouchStartCapture?: (event: TouchEvent) => void120+ onTransitionCancel?: (event: TransitionEvent) => void121+ onTransitionCancelCapture?: (event: TransitionEvent) => void122+ onTransitionEnd?: (event: TransitionEvent) => void123+ onTransitionEndCapture?: (event: TransitionEvent) => void124+ onTransitionRun?: (event: TransitionEvent) => void125+ onTransitionRunCapture?: (event: TransitionEvent) => void126+ onTransitionStart?: (event: TransitionEvent) => void127+ onTransitionStartCapture?: (event: TransitionEvent) => void128+ onFormData?: (event: FormDataEvent) => void129+ onFormDataCapture?: (event: FormDataEvent) => void130+ onReset?: (event: Event) => void131+ onResetCapture?: (event: Event) => void132+ onSubmit?: (event: Event) => void133+ onSubmitCapture?: (event: Event) => void134+ onInvalid?: (event: Event) => void135+ onInvalidCapture?: (event: Event) => void136+ onSelect?: (event: Event) => void137+ onSelectCapture?: (event: Event) => void138+ onSelectChange?: (event: Event) => void139+ onSelectChangeCapture?: (event: Event) => void140+ onInput?: (event: InputEvent) => void141+ onInputCapture?: (event: InputEvent) => void142+ onBeforeInput?: (event: InputEvent) => void143+ onBeforeInputCapture?: (event: InputEvent) => void144+ onChange?: (event: Event) => void145+ onChangeCapture?: (event: Event) => void146+ }147+148+ interface HTMLAttributes extends JSXAttributes, EventAttributes, AnyAttributes {149 accesskey?: string | undefined150 autofocus?: boolean | undefined151 class?: string | Promise<string> | undefined152 contenteditable?: boolean | 'inherit' | undefined579 unmodified linesmodified:src/jsx/jsx-dev-runtime.ts+16 added-8 removed
1 import type { HtmlEscapedString } from '../utils/html'2-import { jsx } from '.'3-import type { JSXNode } from '.'4-export { Fragment } from '.'2+import { jsxFn } from './base'3+import type { JSXNode } from './base'4+export { Fragment } from './base'5 6-export function jsxDEV(tag: string | Function, props: Record<string, unknown>): JSXNode {6+export function jsxDEV(7+ tag: string | Function,8+ props: Record<string, unknown>,9+ key?: string10+): JSXNode {11+ let node: JSXNode12 if (!props || !('children' in props)) {8- return jsx(tag, props)13+ node = jsxFn(tag, props, [])14+ } else {15+ const children = props.children as string | HtmlEscapedString16+ delete props['children']17+ node = Array.isArray(children) ? jsxFn(tag, props, children) : jsxFn(tag, props, [children])18 }10- const children = props.children as string | HtmlEscapedString11- delete props['children']12- return Array.isArray(children) ? jsx(tag, props, ...children) : jsx(tag, props, children)19+ node.key = key20+ return node21 }modified:src/jsx/jsx-runtime.test.tsx+1 added-1 removed
29 unmodified lines30 const template = <span>{0}</span>31 expect(template.toString()).toBe('<span>0</span>')32 })33 })34-})34+})modified:src/jsx/streaming.test.tsx+65 added-2 removed
1+/* eslint-disable @typescript-eslint/no-explicit-any */2 import { JSDOM } from 'jsdom'3 import { raw } from '../helper/html'4 import { HtmlEscapedCallbackPhase, resolveCallback } from '../utils/html'5 import type { HtmlEscapedString } from '../utils/html'5-import { Suspense, renderToReadableStream } from './streaming'6 // eslint-disable-next-line @typescript-eslint/no-unused-vars7-import { jsx, Fragment } from './index'7+import { jsx, Fragment } from './base'8+import { use } from './hooks'9+import { Suspense, renderToReadableStream } from './streaming'10 11 function replacementResult(html: string) {12 const document = new JSDOM(html, { runScripts: 'dangerously' }).window.document13 document.querySelectorAll('template, script').forEach((e) => e.remove())544 unmodified lines558 chunks.push(textDecoder.decode(chunk))559 }560 561 expect(chunks).toEqual(['<h1>Hello</h1>'])562+563+ suspenseCounter++564 })565+566+ describe('use()', async () => {567+ it('render to string', async () => {568+ const Content = () => {569+ const promise = new Promise((resolve) => setTimeout(() => resolve('Hello from use()'), 0))570+ const message = use(promise)571+ return <h1>{message}</h1>572+ }573+574+ const str = await resolveCallback(575+ await (576+ <Suspense fallback={<p>Loading...</p>}>577+ <Content />578+ </Suspense>579+ ).toString(),580+ HtmlEscapedCallbackPhase.Stream,581+ false,582+ {}583+ )584+ expect(str).toEqual('<h1>Hello from use()</h1>')585+ })586+587+ it('render to stream', async () => {588+ const Content = () => {589+ const promise = new Promise((resolve) => setTimeout(() => resolve('Hello from use()'), 0))590+ const message = use(promise)591+ return <h1>{message}</h1>592+ }593+594+ const stream = renderToReadableStream(595+ <Suspense fallback={<p>Loading...</p>}>596+ <Content />597+ </Suspense>598+ )599+600+ const chunks = []601+ const textDecoder = new TextDecoder()602+ for await (const chunk of stream as any) {603+ chunks.push(textDecoder.decode(chunk))604+ }605+606+ expect(chunks).toEqual([607+ `<template id="H:${suspenseCounter}"></template><p>Loading...</p><!--/$-->`,608+ `<template><h1>Hello from use()</h1></template><script>609+((d,c,n) => {610+c=d.currentScript.previousSibling611+d=d.getElementById('H:${suspenseCounter}')612+if(!d)return613+do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')614+d.replaceWith(c.content)615+})(document)616+</script>`,617+ ])618+619+ expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(620+ '<h1>Hello from use()</h1>'621+ )622+ })623+ })624 })modified:src/jsx/streaming.ts+29 added-5 removed
1 import { raw } from '../helper/html'2 import { HtmlEscapedCallbackPhase, resolveCallback } from '../utils/html'3 import type { HtmlEscapedString } from '../utils/html'4 import { childrenToString } from './components'5-import type { FC, Child } from './index'5+import { DOM_RENDERER, DOM_STASH } from './constants'6+import { Suspense as SuspenseDomRenderer } from './dom/components'7+import { buildDataStack } from './dom/render'8+import type { HasRenderToDom, NodeObject } from './dom/render'9+import type { FC, PropsWithChildren, Child } from '.'10 11 let suspenseCounter = 012 13 /**1 unmodified line15 * `Suspense` is an experimental feature.16 * The API might be changed.17 */18 // eslint-disable-next-line @typescript-eslint/no-explicit-any15-export const Suspense: FC<{ fallback: any }> = async ({ children, fallback }) => {19+export const Suspense: FC<PropsWithChildren<{ fallback: any }>> = async ({20+ children,21+ fallback,22+}) => {23 if (!children) {24 return fallback.toString()25 }26 if (!Array.isArray(children)) {27 children = [children]28 }29 30 let resArray: HtmlEscapedString[] | Promise<HtmlEscapedString[]>[] = []31+32+ // for use() hook33+ const stackNode = { [DOM_STASH]: [0, []] } as unknown as NodeObject34+ const popNodeStack = (value?: unknown) => {35+ buildDataStack.pop()36+ return value37+ }38+39 try {40+ stackNode[DOM_STASH][0] = 041+ buildDataStack.push([[], stackNode])42 resArray = children.map((c) => c.toString()) as HtmlEscapedString[]43 } catch (e) {44 if (e instanceof Promise) {28- resArray = [e.then(() => childrenToString(children as Child[]))] as Promise<29- HtmlEscapedString[]30- >[]45+ resArray = [46+ e.then(() => {47+ stackNode[DOM_STASH][0] = 048+ buildDataStack.push([[], stackNode])49+ return childrenToString(children as Child[]).then(popNodeStack)50+ }),51+ ] as Promise<HtmlEscapedString[]>[]52 } else {53 throw e54 }55+ } finally {56+ popNodeStack()57 }58 59 if (resArray.some((res) => (res as {}) instanceof Promise)) {60 const index = suspenseCounter++43 unmodified lines104 } else {105 return raw(resArray.join(''))106 }107 }108+;(Suspense as HasRenderToDom)[DOM_RENDERER] = SuspenseDomRenderer109 110 const textEncoder = new TextEncoder()111 /**112 * @experimental53 unmodified linesadded:src/jsx/types.ts+11 added
1+/**2+ * All types exported from "hono/jsx" are in this file.3+ */4+import type { Child } from './base'5+6+export type { Child, JSXNode, FC } from './base'7+export type { RefObject } from './hooks'8+export type { Context } from './context'9+10+export type PropsWithChildren<P = unknown> = P & { children?: Child | undefined }11+export type CSSProperties = Hono.CSSPropertiesadded:src/jsx/utils.ts+6 added
1+export const normalizeIntrinsicElementProps = (props: Record<string, unknown>): void => {2+ if (props && 'className' in props) {3+ props['class'] = props['className']4+ delete props['className']5+ }6+}modified:src/middleware/basic-auth/index.ts+1 added-1 removed
6 unmodified lines7 const CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/8 const USER_PASS_REGEXP = /^([^:]*):(.*)$/9 const utf8Decoder = new TextDecoder()10 const auth = (req: HonoRequest) => {11- const match = CREDENTIALS_REGEXP.exec(req.headers.get('Authorization') || '')11+ const match = CREDENTIALS_REGEXP.exec(req.header('Authorization') || '')12 if (!match) {13 return undefined14 }15 49 unmodified linesmodified:src/middleware/compress/index.ts+2 added-2 removed
1 unmodified line2 3 const ENCODING_TYPES = ['gzip', 'deflate'] as const4 5 interface CompressionOptions {6- encoding?: typeof ENCODING_TYPES[number]6+ encoding?: (typeof ENCODING_TYPES)[number]7 }8 9 export const compress = (options?: CompressionOptions): MiddlewareHandler => {10 return async function compress(ctx, next) {11 await next()12- const accepted = ctx.req.headers.get('Accept-Encoding')12+ const accepted = ctx.req.header('Accept-Encoding')13 const encoding =14 options?.encoding ?? ENCODING_TYPES.find((encoding) => accepted?.includes(encoding))15 if (!encoding || !ctx.res.body) {16 return9 unmodified linesmodified:src/middleware/jsx-renderer/index.test.tsx+93 added-16 removed
11 unmodified lines12 return html`${c.req.url}`13 }14 15 describe('JSX renderer', () => {16- it('with layout', async () => {16+ it('basic', async () => {17 const app = new Hono()18 app.use(19 '*',20 jsxRenderer(({ children, title }) => (10 unmodified lines31 </h1>,32 { title: 'Title' }33 )34 )35+36+ const app2 = new Hono()37+ app2.use(38+ '*',39+ jsxRenderer(({ children }) => <div class='nested'>{children}</div>)40+ )41+ app2.get('/', (c) => c.render(<h1>http://localhost/nested</h1>, { title: 'Title' }))42+ app.route('/nested', app2)43+35- const res = await app.request('http://localhost/')44+ let res = await app.request('http://localhost/')45 expect(res).not.toBeNull()46 expect(res.status).toBe(200)47 expect(await res.text()).toBe(39- '<html><head>Title</head><body><h1>http://localhost/</h1></body></html>'48+ '<!DOCTYPE html><html><head>Title</head><body><h1>http://localhost/</h1></body></html>'49 )50+51+ res = await app.request('http://localhost/nested')52+ expect(res).not.toBeNull()53+ expect(res.status).toBe(200)54+ expect(await res.text()).toBe(55+ '<!DOCTYPE html><div class="nested"><h1>http://localhost/nested</h1></div>'56+ )57 })58 43- it('without layout', async () => {59+ it('nested layout with Layout', async () => {60 const app = new Hono()45- app.use('*', jsxRenderer())46- app.get('/', (c) =>47- c.render(48- <h1>49- <RequestUrl />50- </h1>,51- { title: 'Title' }52- )61+ app.use(62+ '*',63+ jsxRenderer(({ children, title, Layout }) => (64+ <Layout>65+ <html>66+ <head>{title}</head>67+ <body>{children}</body>68+ </html>69+ </Layout>70+ ))71 )54- const res = await app.request('http://localhost/')72+73+ const app2 = new Hono()74+ app2.use(75+ '*',76+ jsxRenderer(({ children, Layout, title }) => (77+ <Layout title={title}>78+ <div class='nested'>{children}</div>79+ </Layout>80+ ))81+ )82+ app2.get('/', (c) => c.render(<h1>http://localhost/nested</h1>, { title: 'Nested' }))83+84+ const app3 = new Hono()85+ app3.use(86+ '*',87+ jsxRenderer(({ children, Layout, title }) => (88+ <Layout title={title}>89+ <div class='nested2'>{children}</div>90+ </Layout>91+ ))92+ )93+ app3.get('/', (c) => c.render(<h1>http://localhost/nested</h1>, { title: 'Nested2' }))94+ app2.route('/nested2', app3)95+96+ app.route('/nested', app2)97+98+ let res = await app.request('http://localhost/nested')99 expect(res).not.toBeNull()100 expect(res.status).toBe(200)57- expect(await res.text()).toBe('<h1>http://localhost/</h1>')101+ expect(await res.text()).toBe(102+ '<!DOCTYPE html><html><head>Nested</head><body><div class="nested"><h1>http://localhost/nested</h1></div></body></html>'103+ )104+105+ res = await app.request('http://localhost/nested/nested2')106+ expect(res).not.toBeNull()107+ expect(res.status).toBe(200)108+ expect(await res.text()).toBe(109+ '<!DOCTYPE html><html><head>Nested2</head><body><div class="nested"><div class="nested2"><h1>http://localhost/nested</h1></div></div></body></html>'110+ )111 })112 113 it('Should return a default doctype', async () => {114 const app = new Hono()16 unmodified lines131 expect(res.status).toBe(200)132 expect(await res.text()).toBe('<!DOCTYPE html><html><body><h1>Hello</h1></body></html>')133 })134 135+ it('Should return a non includes doctype', async () => {136+ const app = new Hono()137+ app.use(138+ '*',139+ jsxRenderer(140+ ({ children }) => {141+ return (142+ <html>143+ <body>{children}</body>144+ </html>145+ )146+ },147+ { docType: false }148+ )149+ )150+ app.get('/', (c) => c.render(<h1>Hello</h1>, { title: 'Title' }))151+ const res = await app.request('/')152+ expect(res).not.toBeNull()153+ expect(res.status).toBe(200)154+ expect(await res.text()).toBe('<html><body><h1>Hello</h1></body></html>')155+ })156+157 it('Should return a custom doctype', async () => {158 const app = new Hono()159 app.use(160 '*',83 unmodified lines244 </script>`,245 ])246 })247 248+ // this test relies upon 'Should return as streaming content with default headers'249+ // this should be refactored to prevent tests depending on each other250 it('Should return as streaming content with custom headers', async () => {251 const app = new Hono()252 app.use(253 '*',8 unmodified lines262 {263 docType: true,264 stream: {265 'Transfer-Encoding': 'chunked',189- 'Content-Type': 'text/html'266+ 'Content-Type': 'text/html',267 },268 }269 )270 )83 unmodified lines354 })355 const res = await app.request('http://localhost/', undefined, { bar: 'barValue' })356 expect(res).not.toBeNull()357 expect(res.status).toBe(200)281- expect(await res.text()).toBe('<h1>fooValue</h1><p>barValue</p>')358+ expect(await res.text()).toBe('<!DOCTYPE html><h1>fooValue</h1><p>barValue</p>')359 })360 })modified:src/middleware/jsx-renderer/index.ts+32 added-13 removed
1+/* eslint-disable @typescript-eslint/no-explicit-any */2 import type { Context, Renderer } from '../../context'2-// eslint-disable-next-line @typescript-eslint/no-unused-vars3 import { html, raw } from '../../helper/html'4-import { jsx, createContext, useContext } from '../../jsx'5-import type { FC, JSXNode } from '../../jsx'4+import { jsx, createContext, useContext, Fragment } from '../../jsx'5+import type { FC, PropsWithChildren, JSXNode } from '../../jsx'6 import { renderToReadableStream } from '../../jsx/streaming'7 import type { Env, Input, MiddlewareHandler } from '../../types'8 9 export const RequestContext = createContext<Context | null>(null)10 11-type PropsForRenderer = [...Required<Parameters<Renderer>>] extends [unknown, infer Props]11+export type PropsForRenderer = [...Required<Parameters<Renderer>>] extends [unknown, infer Props]12 ? Props13 : unknown14 15 type RendererOptions = {1 unmodified line17 stream?: boolean | Record<string, string>18 }19 20 const createRenderer =21- (c: Context, component?: FC<PropsForRenderer>, options?: RendererOptions) =>21+ (22+ c: Context,23+ Layout: FC,24+ component?: FC<PropsForRenderer & { Layout: FC }>,25+ options?: RendererOptions26+ ) =>27 (children: JSXNode, props: PropsForRenderer) => {28 const docType =29 typeof options?.docType === 'string'30 ? options.docType26- : options?.docType === true27- ? '<!DOCTYPE html>'28- : ''29- /* eslint-disable @typescript-eslint/no-explicit-any */31+ : options?.docType === false32+ ? ''33+ : '<!DOCTYPE html>'34+35+ const currentLayout = component36+ ? component({37+ children,38+ // eslint-disable-next-line @typescript-eslint/no-explicit-any39+ ...{ Layout, ...(props as any) },40+ })41+ : children42+43 const body = html`${raw(docType)}${jsx(44 RequestContext.Provider,45 { value: c },33- (component ? component({ children, ...(props || {}) }) : children) as any46+ // eslint-disable-next-line @typescript-eslint/no-explicit-any47+ currentLayout as any48 )}`49 50 if (options?.stream) {51 return c.body(renderToReadableStream(body), {10 unmodified lines62 }63 }64 65 export const jsxRenderer = (52- component?: FC<PropsForRenderer>,66+ component?: FC<PropsWithChildren<PropsForRenderer & { Layout: FC }>>,67 options?: RendererOptions68 ): MiddlewareHandler =>69 function jsxRenderer(c, next) {56- /* eslint-disable @typescript-eslint/no-explicit-any */57- c.setRenderer(createRenderer(c, component, options) as any)70+ const Layout = (c.getLayout() ?? Fragment) as FC71+ if (component) {72+ c.setLayout((props) => {73+ return component({ ...props, Layout })74+ })75+ }76+ c.setRenderer(createRenderer(c, Layout, component, options) as any)77 return next()78 }79 80 export const useRequestContext = <10 unmodified linesmodified:src/middleware/jwt/index.ts+3 added-2 removed
1 import type { Context } from '../../context'2+import { getCookie } from '../../helper'3 import { HTTPException } from '../../http-exception'4 import type { MiddlewareHandler } from '../../types'5 import { Jwt } from '../../utils/jwt'6 import type { AlgorithmTypes } from '../../utils/jwt/types'19 unmodified lines26 throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.')27 }28 29 return async function jwt(ctx, next) {29- const credentials = ctx.req.headers.get('Authorization')30+ const credentials = ctx.req.raw.headers.get('Authorization')31 let token32 if (credentials) {33 const parts = credentials.split(/\s+/)34 if (parts.length !== 2) {7 unmodified lines42 } else {43 token = parts[1]44 }45 } else if (options.cookie) {45- token = ctx.req.cookie(options.cookie)46+ token = getCookie(ctx)[options.cookie]47 }48 49 if (!token) {50 throw new HTTPException(401, {50 unmodified linesmodified:src/preset/quick.ts+2 added-2 removed
1 unmodified line2 import type { HonoOptions } from '../hono-base'3 import { LinearRouter } from '../router/linear-router'4 import { SmartRouter } from '../router/smart-router'5 import { TrieRouter } from '../router/trie-router'6-import type { Env, Schema } from '../types'6+import type { BlankSchema, Env, Schema } from '../types'7 8 export class Hono<9 E extends Env = Env,10- S extends Schema = {},10+ S extends Schema = BlankSchema,11 BasePath extends string = '/'12 > extends HonoBase<E, S, BasePath> {13 constructor(options: HonoOptions<E> = {}) {14 super(options)5 unmodified linesmodified:src/preset/tiny.ts+2 added-2 removed
1 import { HonoBase } from '../hono-base'2 import type { HonoOptions } from '../hono-base'3 import { PatternRouter } from '../router/pattern-router'4-import type { Env, Schema } from '../types'4+import type { BlankSchema, Env, Schema } from '../types'5 6 export class Hono<7 E extends Env = Env,8- S extends Schema = {},8+ S extends Schema = BlankSchema,9 BasePath extends string = '/'10 > extends HonoBase<E, S, BasePath> {11 constructor(options: HonoOptions<E> = {}) {12 super(options)3 unmodified linesmodified:src/router/linear-router/router.ts+3 added-3 removed
18 unmodified lines19 }20 21 match(method: string, path: string): Result<T> {22 const handlers: [T, Params][] = []23- ROUTES_LOOP: for (let i = 0; i < this.routes.length; i++) {23+ ROUTES_LOOP: for (let i = 0, len = this.routes.length; i < len; i++) {24 const [routeMethod, routePath, handler] = this.routes[i]25 if (routeMethod !== method && routeMethod !== METHOD_NAME_ALL) {26 continue27 }12 unmodified lines40 const endsWithStar = routePath.charCodeAt(routePath.length - 1) === 4241 const parts = (endsWithStar ? routePath.slice(0, -2) : routePath).split(splitByStarRe)42 43 const lastIndex = parts.length - 144- for (let j = 0, pos = 0; j < parts.length; j++) {44+ for (let j = 0, pos = 0, len = parts.length; j < len; j++) {45 const part = parts[j]46 const index = path.indexOf(part, pos)47 if (index !== pos) {48 continue ROUTES_LOOP20 unmodified lines69 const params: Record<string, string> = {}70 const parts = routePath.match(splitPathRe) as string[]71 72 const lastIndex = parts.length - 173- for (let j = 0, pos = 0; j < parts.length; j++) {73+ for (let j = 0, pos = 0, len = parts.length; j < len; j++) {74 if (pos === -1 || pos >= path.length) {75 continue ROUTES_LOOP76 }77 55 unmodified linesmodified:src/utils/jwt/types.ts-6 removed
3 unmodified lines4 this.name = 'JwtAlgorithmNotImplemented'5 }6 }7 8-/**9- * Export for backward compatibility10- * @deprecated Use JwtAlgorithmNotImplemented instead11- **/12-export const JwtAlorithmNotImplemented = JwtAlgorithmNotImplemented13-8 export class JwtTokenInvalid extends Error {9 constructor(token: string) {10 super(`invalid JWT token: ${token}`)11 this.name = 'JwtTokenInvalid'36 unmodified linesmodified:src/utils/body.ts+3 added-2 removed
1-import type { HonoRequest } from '../request'1+import { HonoRequest } from '../request'2 3 export type BodyData = Record<string, string | File | (string | File)[]>4 export type ParseBodyOptions = {5 /**19 unmodified lines25 export const parseBody = async <T extends BodyData = BodyData>(26 request: HonoRequest | Request,27 options: ParseBodyOptions = { all: false }28 ): Promise<T> => {29+ const headers = request instanceof HonoRequest ? request.raw.headers : request.headers29- const contentType = request.headers.get('Content-Type')30+ const contentType = headers.get('Content-Type')31 32 if (isFormDataContent(contentType)) {33 return parseFormData<T>(request, options)34 }68 unmodified linesmodified:src/utils/cookie.ts+1 added-1 removed
34 unmodified lines35 ): Promise<boolean> => {36 try {37 const signatureBinStr = atob(base64Signature)38 const signature = new Uint8Array(signatureBinStr.length)39- for (let i = 0; i < signatureBinStr.length; i++) {39+ for (let i = 0, len = signatureBinStr.length; i < len; i++) {40 signature[i] = signatureBinStr.charCodeAt(i)41 }42 return await crypto.subtle.verify(algorithm, secret, signature, new TextEncoder().encode(value))43 } catch (e) {122 unmodified linesmodified:src/utils/encode.test.ts+1 added-1 removed
4 unmodified lines5 base64String.replace(/\+|\//g, (m) => ({ '+': '-', '/': '_' }[m] ?? m))6 7 const str2UInt8Array = (s: string): Uint8Array => {8 const buffer = new Uint8Array(new ArrayBuffer(s.length))9- for (let i = 0; i < buffer.byteLength; i++) {9+ for (let i = 0, len = buffer.byteLength; i < len; i++) {10 buffer[i] = s.charCodeAt(i)11 }12 return buffer13 }49 unmodified linesmodified:src/utils/encode.ts+1 added-1 removed
8 unmodified lines9 // btoa does not support utf-8 characters. So we need a little bit hack.10 export const encodeBase64 = (buf: ArrayBufferLike): string => {11 let binary = ''12 const bytes = new Uint8Array(buf)13- for (let i = 0; i < bytes.length; i++) {13+ for (let i = 0, len = bytes.length; i < len; i++) {14 binary += String.fromCharCode(bytes[i])15 }16 return btoa(binary)17 }12 unmodified linesmodified:src/utils/html.ts+2 added-2 removed
3 unmodified lines4 Stream: 3,5 } as const6 type HtmlEscapedCallbackOpts = {7 buffer?: [string]8- phase: typeof HtmlEscapedCallbackPhase[keyof typeof HtmlEscapedCallbackPhase]8+ phase: (typeof HtmlEscapedCallbackPhase)[keyof typeof HtmlEscapedCallbackPhase]9 context: object // An object unique to each JSX tree. This object is used as the WeakMap key.10 }11 export type HtmlEscapedCallback = (opts: HtmlEscapedCallbackOpts) => Promise<string> | undefined12 export type HtmlEscaped = {104 unmodified lines117 }118 119 export const resolveCallback = async (120 str: string | HtmlEscapedString,121- phase: typeof HtmlEscapedCallbackPhase[keyof typeof HtmlEscapedCallbackPhase],121+ phase: (typeof HtmlEscapedCallbackPhase)[keyof typeof HtmlEscapedCallbackPhase],122 preserveCallbacks: boolean,123 context: object,124 buffer?: [string]125 ): Promise<string> => {25 unmodified linesmodified:src/utils/http-status.ts+57 added-1 removed
1+export type InfoStatusCode = 100 | 101 | 102 | 1032+export type SuccessStatusCode = 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 2263+export type DeprecatedStatusCode = 305 | 3064+export type RedirectStatusCode = 300 | 301 | 302 | 303 | 304 | DeprecatedStatusCode | 307 | 3085+export type ClientErrorStatusCode =6+ | 4007+ | 4018+ | 4029+ | 40310+ | 40411+ | 40512+ | 40613+ | 40714+ | 40815+ | 40916+ | 41017+ | 41118+ | 41219+ | 41320+ | 41421+ | 41522+ | 41623+ | 41724+ | 41825+ | 42126+ | 42227+ | 42328+ | 42429+ | 42530+ | 42631+ | 42832+ | 42933+ | 43134+ | 45135+export type ServerErrorStatusCode = 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 51136+/**37+ * `UnOfficalStatusCode` can be used to specify an informal status code.38+ * @example39+ *40+ * ```ts41+ * app.get('/', (c) => {42+ * return c.text("hono is cool", 666 as UnOfficalStatusCode)43+ * })44+ * ```45+ */46+export type UnOfficalStatusCode = -147+48+/**49+ * If you want to use an unofficial status, use `UnOfficalStatusCode`.50+ */1-export type StatusCode = number51+export type StatusCode =52+ | InfoStatusCode53+ | SuccessStatusCode54+ | RedirectStatusCode55+ | ClientErrorStatusCode56+ | ServerErrorStatusCode57+ | UnOfficalStatusCodemodified:src/utils/mime.test.ts+29 added-1 removed
1-import { getMimeType } from './mime'1+import { getMimeType, getExtension } from './mime'2 3+const mime = {4+ m3u8: 'application/vnd.apple.mpegurl',5+ ts: 'video/mp2t',6+}7+8 describe('mime', () => {9 it('getMimeType', () => {10 expect(getMimeType('hello.txt')).toBe('text/plain; charset=utf-8')11 expect(getMimeType('hello.html')).toBe('text/html; charset=utf-8')2 unmodified lines14 expect(getMimeType('good.morning.hello.gif')).toBe('image/gif')15 expect(getMimeType('goodmorninghellogif')).toBeUndefined()16 expect(getMimeType('indexjs.abcd')).toBeUndefined()17 })18+19+ it('getMimeType with custom mime', () => {20+ expect(getMimeType('morning-routine.m3u8', mime)).toBe('application/vnd.apple.mpegurl')21+ expect(getMimeType('morning-routine1.ts', mime)).toBe('video/mp2t')22+ expect(getMimeType('readme.txt', mime)).toBeUndefined()23+ })24+25+ it('getExtension', () => {26+ expect(getExtension('audio/aac')).toBe('aac')27+ expect(getExtension('video/x-msvideo')).toBe('avi')28+ expect(getExtension('image/avif')).toBe('avif')29+ expect(getExtension('text/css')).toBe('css')30+ expect(getExtension('text/html')).toBe('htm')31+ expect(getExtension('image/jpeg')).toBe('jpeg')32+ expect(getExtension('text/javascript')).toBe('js')33+ expect(getExtension('application/json')).toBe('json')34+ expect(getExtension('audio/mpeg')).toBe('mp3')35+ expect(getExtension('video/mp4')).toBe('mp4')36+ expect(getExtension('application/pdf')).toBe('pdf')37+ expect(getExtension('image/png')).toBe('png')38+ expect(getExtension('application/zip')).toBe('zip')39+ expect(getExtension('non/existent')).toBeUndefined()40+ })41 })modified:src/utils/mime.ts+10 added-26 removed
1-export const getMimeType = (filename: string): string | undefined => {1+export const getMimeType = (filename: string, mimes = baseMimes): string | undefined => {2 const regexp = /\.([a-zA-Z0-9]+?)$/3 const match = filename.match(regexp)4 if (!match) {5 return4 unmodified lines10 }11 return mimeType12 }13 14+export const getExtension = (mimeType: string): string | undefined => {15+ for (const ext in baseMimes) {16+ if (baseMimes[ext] === mimeType) {17+ return ext18+ }19+ }20+}21+14-const mimes: Record<string, string> = {22+const baseMimes: Record<string, string> = {23 aac: 'audio/aac',16- abw: 'application/x-abiword',17- arc: 'application/x-freearc',24 avi: 'video/x-msvideo',25 avif: 'image/avif',26 av1: 'video/av1',21- azw: 'application/vnd.amazon.ebook',27 bin: 'application/octet-stream',28 bmp: 'image/bmp',24- bz: 'application/x-bzip',25- bz2: 'application/x-bzip2',26- csh: 'application/x-csh',29 css: 'text/css',30 csv: 'text/csv',29- doc: 'application/msword',30- docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',31 eot: 'application/vnd.ms-fontobject',32 epub: 'application/epub+zip',33 gif: 'image/gif',34 gz: 'application/gzip',35 htm: 'text/html',36 html: 'text/html',37 ico: 'image/x-icon',38 ics: 'text/calendar',39- jar: 'application/java-archive',39 jpeg: 'image/jpeg',40 jpg: 'image/jpeg',41 js: 'text/javascript',42 json: 'application/json',4 unmodified lines47 mjs: 'text/javascript',48 mp3: 'audio/mpeg',49 mp4: 'video/mp4',50 mpeg: 'video/mpeg',52- mpkg: 'application/vnd.apple.installer+xml',53- odp: 'application/vnd.oasis.opendocument.presentation',54- ods: 'application/vnd.oasis.opendocument.spreadsheet',55- odt: 'application/vnd.oasis.opendocument.text',51 oga: 'audio/ogg',52 ogv: 'video/ogg',53 ogx: 'application/ogg',54 opus: 'audio/opus',55 otf: 'font/otf',56 pdf: 'application/pdf',62- php: 'application/php',57 png: 'image/png',64- ppt: 'application/vnd.ms-powerpoint',65- pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',58 rtf: 'application/rtf',67- sh: 'application/x-sh',59 svg: 'image/svg+xml',69- swf: 'application/x-shockwave-flash',70- tar: 'application/x-tar',60 tif: 'image/tiff',61 tiff: 'image/tiff',62 ts: 'video/mp2t',63 ttf: 'font/ttf',64 txt: 'text/plain',76- vsd: 'application/vnd.visio',65 wasm: 'application/wasm',66 webm: 'video/webm',67 weba: 'audio/webm',68 webp: 'image/webp',69 woff: 'font/woff',70 woff2: 'font/woff2',71 xhtml: 'application/xhtml+xml',84- xls: 'application/vnd.ms-excel',85- xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',72 xml: 'application/xml',87- xul: 'application/vnd.mozilla.xul+xml',73 zip: 'application/zip',74 '3gp': 'video/3gpp',75 '3g2': 'video/3gpp2',91- '7z': 'application/x-7z-compressed',76 gltf: 'model/gltf+json',77 glb: 'model/gltf-binary',78 }modified:src/utils/types.ts+2 added-4 removed
17 unmodified lines18 : never19 20 export type IfAnyThenEmptyObject<T> = 0 extends 1 & T ? {} : T21 22-export type IntersectNonAnyTypes<T extends any[]> = T extends [infer Head, ...infer Rest]23- ? IfAnyThenEmptyObject<Head> & IntersectNonAnyTypes<Rest>24- : {}25-22 export type JSONPrimitive = string | boolean | number | null | undefined23 export type JSONArray = (JSONPrimitive | JSONObject | JSONArray)[]24 export type JSONObject = { [key: string]: JSONPrimitive | JSONArray | JSONObject | object }25 export type JSONValue = JSONObject | JSONArray | JSONPrimitive21 unmodified lines47 48 export type HasRequiredKeys<BaseType extends object> = RequiredKeysOf<BaseType> extends never49 ? false50 : true51+52+export type IsAny<T> = boolean extends (T extends never ? true : false) ? true : falsemodified:src/validator/validator.test.ts+50 added-34 removed
1 /* eslint-disable @typescript-eslint/no-unused-vars */2 import type { ZodSchema } from 'zod'3 import { z } from 'zod'4 import { Hono } from '../hono'5+import { HTTPException } from '../http-exception'5-import type { ExtractSchema, MiddlewareHandler, ValidationTargets } from '../types'6+import type { ErrorHandler, ExtractSchema, MiddlewareHandler, ValidationTargets } from '../types'7 import type { Equal, Expect } from '../utils/types'8 import type { ValidationFunction } from './validator'9 import { validator } from './validator'10 64 unmodified lines75 expect(res.status).toBe(200)76 })77 })78 79+const onErrorHandler: ErrorHandler = (e, c) => {80+ if (e instanceof HTTPException) {81+ return c.json({ message: e.message, success: false }, e.status)82+ }83+ return c.json({ message: e.message }, 500)84+}85+86 describe('Malformed JSON', () => {87 const app = new Hono()80-88 app.post(89 '/post',90 validator('json', (value, c) => {}),91 (c) => {92 return c.text('Valid!')93 }94 )95+ app.onError(onErrorHandler)96 97 it('Should return 400 response', async () => {98 const res = await app.request('http://localhost/post', {99 method: 'POST',40 unmodified lines140 (c) => {141 return c.text('Valid!')142 }143 )144+ app.onError(onErrorHandler)145 146 it('Should return 400 response, for unsupported content type header', async () => {147 const res = await app.request('http://localhost/post', {148 method: 'POST',239 unmodified lines388 expect(await res.text()).toBe('Invalid!')389 })390 })391 383-describe('Validator middleware with Zod validates queries params - with `queries` will be obsolete in v4', () => {384- const app = new Hono()385-386- const schema = z.object({387- tags: z.array(z.string()),388- })389-390- app.get('/posts', zodValidator('queries', schema), (c) => {391- const res = c.req.valid('queries')392- return c.json({393- tags: res.tags,394- })395- })396-397- it('Should validate queries params and return 200 response', async () => {398- const res = await app.request('http://localhost/posts?tags=book&tags=movie')399- expect(res.status).toBe(200)400- expect(await res.json()).toEqual({401- tags: ['book', 'movie'],402- })403- })404-405- it('Should validate queries params and return 400 response', async () => {406- const res = await app.request('http://localhost/posts')407- expect(res.status).toBe(400)408- expect(await res.text()).toBe('Invalid!')409- })410-})411-392 describe('Validator middleware with Zod validates param', () => {393 const app = new Hono()394 395 const schema = z.object({205 unmodified lines601 '/posts/:id': {602 $put: {603 input: {604 form: {625- title: string605+ title: string | File606 }607 } & {608 param: {609 id: string35 unmodified lines645 '/purge': {646 $purge: {647 input: {648 form: {669- tag: string649+ tag: string | File650 }651 } & {652 query: {673- q: string653+ q: string | string[]654 }655 }656 output: {657 success: boolean175 unmodified lines833 }834 )835 })836 })837+838+describe('Transform', () => {839+ it('Should be number when the type is transformed', () => {840+ const route = new Hono().get(841+ '/',842+ validator('query', async () => {843+ return {844+ page: 1,845+ }846+ }),847+ (c) => {848+ const { page } = c.req.valid('query')849+ expectTypeOf(page).toEqualTypeOf<number>()850+ return c.json({ page })851+ }852+ )853+854+ type Expected = {855+ '/': {856+ $get: {857+ input: {858+ query: {859+ page: string | string[]860+ }861+ }862+ output: {863+ page: number864+ }865+ }866+ }867+ }868+869+ type Actual = ExtractSchema<typeof route>870+ type verify = Expect<Equal<Expected, Actual>>871+ })872+})modified:src/validator/validator.ts+18 added-31 removed
1 import type { Context } from '../context'2 import { getCookie } from '../helper/cookie'3+import { HTTPException } from '../http-exception'4 import type { Env, ValidationTargets, MiddlewareHandler, TypedResponse } from '../types'5 import type { BodyData } from '../utils/body'6 import { bufferToFormData } from '../utils/buffer'7 20 unmodified lines28 P extends string,29 M extends string,30 U extends ValidationTargetByMethod<M>,31 OutputType = ValidationTargets[U],32+ OutputTypeExcludeResponseType = ExcludeResponseType<OutputType>,33 P2 extends string = P,34 V extends {33- in: { [K in U]: unknown extends InputType ? OutputType : InputType }34- out: { [K in U]: ExcludeResponseType<OutputType> }35+ in: {36+ [K in U]: K extends 'json'37+ ? InputType38+ : { [K2 in keyof OutputTypeExcludeResponseType]: ValidationTargets[K][K2] }39+ }40+ out: { [K in U]: OutputTypeExcludeResponseType }41 } = {36- in: { [K in U]: unknown extends InputType ? OutputType : InputType }37- out: { [K in U]: ExcludeResponseType<OutputType> }42+ in: {43+ [K in U]: K extends 'json'44+ ? InputType45+ : { [K2 in keyof OutputTypeExcludeResponseType]: ValidationTargets[K][K2] }46+ }47+ out: { [K in U]: OutputTypeExcludeResponseType }48 },49 // eslint-disable-next-line @typescript-eslint/no-explicit-any50 E extends Env = any51 >(12 unmodified lines64 switch (target) {65 case 'json':66 if (!contentType || !contentType.startsWith('application/json')) {67 const message = `Invalid HTTP header: Content-Type=${contentType}`58- console.error(message)59- return c.json(60- {61- success: false,62- message,63- },64- 40065- )68+ throw new HTTPException(400, { message })69 }70 /**71 * Get the arrayBuffer first, create JSON object via Response,72 * and cache the arrayBuffer in the c.req.bodyCache.3 unmodified lines76 value = await new Response(arrayBuffer).json()77 c.req.bodyCache.json = value78 c.req.bodyCache.arrayBuffer = arrayBuffer79 } catch {77- console.error('Error: Malformed JSON in request body')78- return c.json(79- {80- success: false,81- message: 'Malformed JSON in request body',82- },83- 40084- )80+ const message = 'Malformed JSON in request body'81+ throw new HTTPException(400, { message })82 }83 break84 case 'form': {85 try {11 unmodified lines97 }98 } catch (e) {99 let message = 'Malformed FormData request.'100 message += e instanceof Error ? ` ${e.message}` : ` ${String(e)}`104- return c.json(105- {106- success: false,107- message,108- },109- 400110- )101+ throw new HTTPException(400, { message })102 }103 break104 }105 case 'query':2 unmodified lines108 return v.length === 1 ? [k, v[0]] : [k, v]109 })110 )111 break121- case 'queries':122- value = c.req.queries()123- console.log('Warnings: Validate type `queries` is deprecated. Use `query` instead.')124- break112 case 'param':113 value = c.req.param() as Record<string, string>114 break115 case 'header':18 unmodified linesmodified:src/context.test.ts-69 removed
179 unmodified lines180 const res = c.text('foo')181 expect(res.headers.get('foo')).not.toBeNull()182 expect(res.headers.get('foo')).toBe('bar')183 })184-185- // The `c.runtime()` will be removed in v4.186- it('returns current runtime (node)', async () => {187- c = new Context(req)188- expect(c.runtime).toBe('node')189- })184 })185 186 describe('Context header', () => {187 const req = new HonoRequest(new Request('http://localhost/'))84 unmodified lines272 const res = await c.html('<h1>foo</h1>', originalResponse)273 expect(res.headers.get('content-type')).toMatch(/^text\/html/)274 expect(await res.text()).toBe('<h1>foo</h1>')275 })282-283- it('c.streamText()', async () => {284- const res = c.streamText(async (stream) => {285- for (let i = 0; i < 3; i++) {286- await stream.write(`${i}`)287- await stream.sleep(1)288- }289- })290-291- expect(res.status).toBe(200)292- expect(res.headers.get('content-type')).toMatch(/^text\/plain/)293- expect(res.headers.get('x-content-type-options')).toBe('nosniff')294- expect(res.headers.get('transfer-encoding')).toBe('chunked')295-296- if (!res.body) {297- throw new Error('Body is null')298- }299- const reader = res.body.getReader()300- const decoder = new TextDecoder()301- for (let i = 0; i < 3; i++) {302- const { value } = await reader.read()303- expect(decoder.decode(value)).toEqual(`${i}`)304- }305- })306-307- it('c.stream()', async () => {308- const res = c.stream(async (stream) => {309- for (let i = 0; i < 3; i++) {310- await stream.write(new Uint8Array([i]))311- await stream.sleep(1)312- }313- })314- if (!res.body) {315- throw new Error('Body is null')316- }317- const reader = res.body.getReader()318- for (let i = 0; i < 3; i++) {319- const { value } = await reader.read()320- expect(value).toEqual(new Uint8Array([i]))321- }322- })276 })277 278 declare module './context' {279 interface ContextRenderer {23 unmodified lines303 const res = await c.render('<h1>content</h1>', { title: 'title' })304 expect(res.headers.get('foo')).toBe('bar')305 expect(await res.text()).toBe('<html><head>title</head><body><h1>content</h1></body></html>')306 })354-355- it('c.stream() - with aborted during writing', async () => {356- let aborted = false357- const res = c.stream(async (stream) => {358- stream.onAbort(() => {359- aborted = true360- })361- for (let i = 0; i < 3; i++) {362- await stream.write(new Uint8Array([i]))363- await stream.sleep(1)364- }365- })366- if (!res.body) {367- throw new Error('Body is null')368- }369- const reader = res.body.getReader()370- for (let i = 0; i < 2; i++) {371- await reader.read()372- await reader.cancel()373- }374- expect(aborted).toBe(true)375- })307 })modified:src/context.ts+186 added-125 removed
1-import type { Runtime } from './helper/adapter'1+import type { FC } from './jsx'2+import type { PropsForRenderer } from './middleware/jsx-renderer'3 import type { HonoRequest } from './request'4 import type { Env, FetchEventLike, NotFoundHandler, Input, TypedResponse } from './types'4-import type { CookieOptions } from './utils/cookie'5-import { serialize } from './utils/cookie'5 import { resolveCallback, HtmlEscapedCallbackPhase } from './utils/html'7-import type { StatusCode } from './utils/http-status'8-import { StreamingApi } from './utils/stream'9-import type { JSONValue, InterfaceToType, JSONParsed } from './utils/types'6+import type { RedirectStatusCode, StatusCode } from './utils/http-status'7+import type { JSONValue, InterfaceToType, JSONParsed, IsAny } from './utils/types'8 9 type HeaderRecord = Record<string, string | string[]>10 type Data = string | ArrayBuffer | ReadableStream11 82 unmodified lines94 // eslint-disable-next-line @typescript-eslint/no-explicit-any95 P extends string = any,96 I extends Input = {}97 > {98+ /**99+ * `.req` is the instance of {@link HonoRequest}.100+ */101 req: HonoRequest<P, I['out']>102+ /**103+ * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.104+ * @example105+ * ```ts106+ * // Environment object for Cloudflare Workers107+ * app.get('*', async c => {108+ * const counter = c.env.COUNTER109+ * })110+ * ```111+ * @see https://hono.dev/api/context#env112+ */113 env: E['Bindings'] = {}114 private _var: E['Variables'] = {}115 finalized: boolean = false116+ /**117+ * `.error` can get the error object from the middleware if the Handler throws an error.118+ * @example119+ * ```ts120+ * app.use('*', async (c, next) => {121+ * await next()122+ * if (c.error) {123+ * // do something...124+ * }125+ * })126+ * ```127+ * @see https://hono.dev/api/context#error128+ */129 error: Error | undefined = undefined130 131 #status: StatusCode = 200132 #executionCtx: FetchEventLike | ExecutionContext | undefined133 #headers: Headers | undefined = undefined134 #preparedHeaders: Record<string, string> | undefined = undefined135 #res: Response | undefined136 #isFresh = true137+ private layout: FC<PropsForRenderer & { Layout: FC }> | undefined = undefined138 private renderer: Renderer = (content: string | Promise<string>) => this.html(content)139 private notFoundHandler: NotFoundHandler<E> = () => new Response()140 141 constructor(req: HonoRequest<P, I['out']>, options?: ContextOptions<E>) {6 unmodified lines148 }149 }150 }151 152+ /**153+ * @see https://hono.dev/api/context#event154+ */155 get event(): FetchEventLike {156 if (this.#executionCtx && 'respondWith' in this.#executionCtx) {157 return this.#executionCtx158 } else {159 throw Error('This context has no FetchEvent')160 }161 }162 163+ /**164+ * @see https://hono.dev/api/context#executionctx165+ */166 get executionCtx(): ExecutionContext {167 if (this.#executionCtx) {168 return this.#executionCtx as ExecutionContext169 } else {170 throw Error('This context has no ExecutionContext')171 }172 }173 174+ /**175+ * @see https://hono.dev/api/context#res176+ */177 get res(): Response {178 this.#isFresh = false179 return (this.#res ||= new Response('404 Not Found', { status: 404 }))180 }17 unmodified lines198 this.#res = _res199 this.finalized = true200 }201 202+ /**203+ * `.render()` can create a response within a layout.204+ * @example205+ * ```ts206+ * app.get('/', (c) => {207+ * return c.render('Hello!')208+ * })209+ * ```210+ * @see https://hono.dev/api/context#render-setrenderer211+ */212 // eslint-disable-next-line @typescript-eslint/ban-ts-comment213 // @ts-ignore214 // eslint-disable-next-line @typescript-eslint/no-explicit-any215 render: Renderer = (...args: any[]) => this.renderer(...args)216 217+ /**218+ * `.setRenderer()` can set the layout in the custom middleware.219+ * @example220+ * ```tsx221+ * app.use('*', async (c, next) => {222+ * c.setRenderer((content) => {223+ * return c.html(224+ * <html>225+ * <body>226+ * <p>{content}</p>227+ * </body>228+ * </html>229+ * )230+ * })231+ * await next()232+ * })233+ * ```234+ * @see https://hono.dev/api/context#render-setrenderer235+ */236+ // @ts-expect-error It is unknown how many arguments the renderer will receive.237+ // eslint-disable-next-line @typescript-eslint/no-explicit-any238+ render: Renderer = (...args: any[]) => this.renderer(...args)239+240+ setLayout = (layout: FC<PropsForRenderer & { Layout: FC }>) => (this.layout = layout)241+ getLayout = () => this.layout242+243 setRenderer = (renderer: Renderer) => {244 this.renderer = renderer245 }246 247+ /**248+ * `.header()` can set headers.249+ * @example250+ * ```ts251+ * app.get('/welcome', (c) => {252+ * // Set headers253+ * c.header('X-Message', 'Hello!')254+ * c.header('Content-Type', 'text/plain')255+ *256+ * return c.body('Thank you for coming')257+ * })258+ * ```259+ * @see https://hono.dev/api/context#body260+ */261 header = (name: string, value: string | undefined, options?: { append?: boolean }): void => {262 // Clear the header263 if (value === undefined) {264 if (this.#headers) {36 unmodified lines301 this.#isFresh = false302 this.#status = status303 }304 305+ /**306+ * `.set()` can set the value specified by the key.307+ * @example308+ * ```ts309+ * app.use('*', async (c, next) => {310+ * c.set('message', 'Hono is cool!!')311+ * await next()312+ * })313+ * ```314+ * @see https://hono.dev/api/context#set-get315+```316+ */317 set: Set<E> = (key: string, value: unknown) => {318 this._var ??= {}319 this._var[key as string] = value320 }321 322+ /**323+ * `.get()` can use the value specified by the key.324+ * @example325+ * ```ts326+ * app.get('/', (c) => {327+ * const message = c.get('message')328+ * return c.text(`The message is "${message}"`)329+ * })330+ * ```331+ * @see https://hono.dev/api/context#set-get332+ */333 get: Get<E> = (key: string) => {334 return this._var ? this._var[key] : undefined335 }336 337+ /**338+ * `.var` can access the value of a variable.339+ * @example340+ * ```ts341+ * const result = c.var.client.oneMethod()342+ * ```343+ * @see https://hono.dev/api/context#var344+ */345 // c.var.propName is a read-only230- get var(): Readonly<E['Variables'] & ContextVariableMap> {346+ get var(): Readonly<347+ // eslint-disable-next-line @typescript-eslint/no-explicit-any348+ ContextVariableMap & (IsAny<E['Variables']> extends true ? Record<string, any> : E['Variables'])349+ > {350 return { ...this._var } as never351 }352 353 newResponse: NewResponse = (46 unmodified lines400 headers: this.#headers,401 })402 }403 404+ /**405+ * `.body()` can return the HTTP response.406+ * You can set headers with `.header()` and set HTTP status code with `.status`.407+ * This can also be set in `.text()`, `.json()` and so on.408+ * @example409+ * ```ts410+ * app.get('/welcome', (c) => {411+ * // Set headers412+ * c.header('X-Message', 'Hello!')413+ * c.header('Content-Type', 'text/plain')414+ * // Set HTTP status code415+ * c.status(201)416+ *417+ * // Return the response body418+ * return c.body('Thank you for coming')419+ * })420+ * ```421+ * @see https://hono.dev/api/context#body422+ */423 body: BodyRespond = (424 data: Data | null,425 arg?: StatusCode | ResponseInit,426 headers?: HeaderRecord2 unmodified lines429 ? this.newResponse(data, arg, headers)430 : this.newResponse(data, arg)431 }432 433+ /**434+ * `.text()` can render text as `Content-Type:text/plain`.435+ * @example436+ * ```ts437+ * app.get('/say', (c) => {438+ * return c.text('Hello!')439+ * })440+ * ```441+ * @see https://hono.dev/api/context#text442+ */443 text: TextRespond = (444 text: string,445 arg?: StatusCode | ResponseInit,446 headers?: HeaderRecord11 unmodified lines458 ? this.newResponse(text, arg, headers)459 : this.newResponse(text, arg)460 }461 462+ /**463+ * `.json()` can render JSON as `Content-Type:application/json`.464+ * @example465+ * ```ts466+ * app.get('/api', (c) => {467+ * return c.json({ message: 'Hello!' })468+ * })469+ * ```470+ * @see https://hono.dev/api/context#json471+ */472 json: JSONRespond = <T>(473 object: InterfaceToType<T> extends JSONValue ? T : JSONValue,474 arg?: StatusCode | ResponseInit,475 headers?: HeaderRecord13 unmodified lines489 typeof arg === 'number' ? this.newResponse(body, arg, headers) : this.newResponse(body, arg)490 ) as any491 }492 335- /**336- * @deprecated337- * `c.jsonT()` will be removed in v4.338- * Use `c.json()` instead of `c.jsonT()`.339- * `c.json()` now returns data type, so you can just replace `c.jsonT()` to `c.json()`.340- */341- jsonT: JSONRespond = <T>(342- object: InterfaceToType<T> extends JSONValue ? T : JSONValue,343- arg?: StatusCode | ResponseInit,344- headers?: HeaderRecord345- ): Response &346- TypedResponse<347- InterfaceToType<T> extends JSONValue348- ? JSONValue extends InterfaceToType<T>349- ? never350- : T351- : never352- > => {353- // eslint-disable-next-line @typescript-eslint/no-explicit-any354- return this.json(object, arg as any, headers) as any355- }356-493 html: HTMLRespond = (494 html: string | Promise<string>,495 arg?: StatusCode | ResponseInit,496 headers?: HeaderRecord20 unmodified lines517 ? this.newResponse(html as string, arg, headers)518 : this.newResponse(html as string, arg)519 }520 521+ /**522+ * `.redirect()` can Redirect, default status code is 302.523+ * @example524+ * ```ts525+ * app.get('/redirect', (c) => {526+ * return c.redirect('/')527+ * })528+ * app.get('/redirect-permanently', (c) => {529+ * return c.redirect('/', 301)530+ * })531+ * ```532+ * @see https://hono.dev/api/context#redirect533+ */385- redirect = (location: string, status: StatusCode = 302): Response => {534+ redirect = (location: string, status: RedirectStatusCode = 302): Response => {535 this.#headers ??= new Headers()536 this.#headers.set('Location', location)537 return this.newResponse(null, status)538 }539 391- /** @deprecated392- * Use `streamText()` in `hono/streaming` instead of `c.streamText()`. The `c.streamText()` will be removed in v4.393- */394- streamText = (395- cb: (stream: StreamingApi) => Promise<void>,396- arg?: StatusCode | ResponseInit,397- headers?: HeaderRecord398- ): Response => {399- headers ??= {}400- this.header('content-type', TEXT_PLAIN)401- this.header('x-content-type-options', 'nosniff')402- this.header('transfer-encoding', 'chunked')403- return this.stream(cb, arg, headers)404- }405-406- /** @deprecated407- * Use `stream()` in `hono/streaming` instead of `c.stream()`. The `c.stream()` will be removed in v4.408- */409- stream = (410- cb: (stream: StreamingApi) => Promise<void>,411- arg?: StatusCode | ResponseInit,412- headers?: HeaderRecord413- ): Response => {414- const { readable, writable } = new TransformStream()415- const stream = new StreamingApi(writable, readable)416- cb(stream).finally(() => stream.close())417-418- return typeof arg === 'number'419- ? this.newResponse(stream.responseReadable, arg, headers)420- : this.newResponse(stream.responseReadable, arg)421- }422-423- /** @deprecated424- * Use Cookie Middleware instead of `c.cookie()`. The `c.cookie()` will be removed in v4.425- *540+ /**541+ * `.notFound()` can return the Not Found Response.542 * @example427- *428- * import { setCookie } from 'hono/cookie'429- * // ...430- * app.get('/', (c) => {431- * setCookie(c, 'key', 'value')432- * //...543+ * ```ts544+ * app.get('/notfound', (c) => {545+ * return c.notFound()546 * })547+ * ```548+ * @see https://hono.dev/api/context#notfound549 */435- cookie = (name: string, value: string, opt?: CookieOptions): void => {436- const cookie = serialize(name, value, opt)437- this.header('set-cookie', cookie, { append: true })438- }439-550 notFound = (): Response | Promise<Response> => {441- // eslint-disable-next-line @typescript-eslint/ban-ts-comment442- // @ts-ignore551 return this.notFoundHandler(this)552 }445-446- /** @deprecated447- * Use `getRuntimeKey()` exported from `hono/adapter` instead of `c.runtime()`. The `c.runtime()` will be removed in v4.448- *449- * @example450- *451- * import { getRuntimeKey } from 'hono/adapter'452- * // ...453- * app.get('/', (c) => {454- * const key = getRuntimeKey()455- * //...456- * })457- */458- get runtime(): Runtime {459- // eslint-disable-next-line @typescript-eslint/no-explicit-any460- const global = globalThis as any461-462- if (global?.Deno !== undefined) {463- return 'deno'464- }465-466- if (global?.Bun !== undefined) {467- return 'bun'468- }469-470- if (typeof global?.WebSocketPair === 'function') {471- return 'workerd'472- }473-474- if (typeof global?.EdgeRuntime === 'string') {475- return 'edge-light'476- }477-478- if (global?.fastly !== undefined) {479- return 'fastly'480- }481-482- if (global?.__lagon__ !== undefined) {483- return 'lagon'484- }485-486- if (global?.process?.release?.name === 'node') {487- return 'node'488- }489-490- return 'other'491- }553 }modified:src/helper.ts+2 added
1 // This file is for Deno to import helpers from `hono/helper.ts`.2+export * from './helper/accepts'3 export * from './helper/adapter'4 export * from './helper/cookie'5 export * from './helper/css'6 export * from './helper/factory'7 export * from './helper/html'8 export * from './helper/streaming'9 export * from './helper/testing'10 export * from './helper/dev'11+export * from './adapter/deno/ssg'modified:src/hono-base.ts+94 added-59 removed
23 unmodified lines24 import { getPath, getPathNoStrict, getQueryStrings, mergePath } from './utils/url'25 26 export const COMPOSED_HANDLER = Symbol('composedHandler')27 28-type Methods = typeof METHODS[number] | typeof METHOD_NAME_ALL_LOWERCASE28+type Methods = (typeof METHODS)[number] | typeof METHOD_NAME_ALL_LOWERCASE29 30 function defineDynamicClass(): {31 new <E extends Env = Env, S extends Schema = {}, BasePath extends string = '/'>(): {32 [M in Methods]: HandlerInterface<E, M, S, BasePath>14 unmodified lines47 if (err instanceof HTTPException) {48 return err.getResponse()49 }50 console.error(err)51- const message = 'Internal Server Error'52- return c.text(message, 500)51+ return c.text('Internal Server Error', 500)52 }53 54 type GetPath<E extends Env> = (request: Request, options?: { env?: E['Bindings'] }) => string55 56 export type HonoOptions<E extends Env> = {57+ /**58+ * `strict` option specifies whether to distinguish whether the last path is a directory or not.59+ * @default true60+ * @see https://hono.dev/api/hono#strict-mode61+ */62 strict?: boolean63+ /**64+ * `router` option specifices which router to use.65+ * ```ts66+ * const app = new Hono({ router: new RegExpRouter() })67+ * ```68+ * @see https://hono.dev/api/hono#router-option69+ */70 router?: Router<[H, RouterRoute]>71+ /**72+ * `getPath` can handle the host header value.73+ * @example74+ * ```ts75+ * const app = new Hono({76+ * getPath: (req) =>77+ * '/' + req.headers.get('host') + req.url.replace(/^https?:\/\/[^/]+(\/[^?]*)/, '$1'),78+ * })79+ *80+ * app.get('/www1.example.com/hello', () => c.text('hello www1'))81+ *82+ * // A following request will match the route:83+ * // new Request('http://www1.example.com/hello', {84+ * // headers: { host: 'www1.example.com' },85+ * // })86+ * ```87+ * @see https://hono.dev/api/routing#routing-with-host-header-value88+ */89 getPath?: GetPath<E>90 }91 92 class Hono<35 unmodified lines128 }129 })130 131 // Implementation of app.on(method, path, ...handlers[])103- this.on = (method: string | string[], path: string, ...handlers: H[]) => {132+ this.on = (method: string | string[], path: string | string[], ...handlers: H[]) => {133 if (!method) {134 return this135 }136+ for (const p of [path].flat()) {107- this.#path = path108- for (const m of [method].flat()) {109- handlers.map((handler) => {110- this.addRoute(m.toUpperCase(), this.#path, handler)111- })137+ this.#path = p138+ for (const m of [method].flat()) {139+ handlers.map((handler) => {140+ this.addRoute(m.toUpperCase(), this.#path, handler)141+ })142+ }143 }144 // eslint-disable-next-line @typescript-eslint/no-explicit-any145 return this as any146 }3 unmodified lines150 this.use = (arg1: string | MiddlewareHandler<any>, ...handlers: MiddlewareHandler<any>[]) => {151 if (typeof arg1 === 'string') {152 this.#path = arg1153 } else {154+ this.#path = '*'155 handlers.unshift(arg1)156 }157 handlers.map((handler) => {158 this.addRoute(METHOD_NAME_ALL, this.#path, handler)50 unmodified lines209 })210 return this211 }212 213+ /**214+ * `.basePath()` allows base paths to be specified.215+ * @example216+ * ```ts217+ * const api = new Hono().basePath('/api')218+ * ```219+ * @see https://hono.dev/api/routing#base-path220+ */221 basePath<SubPath extends string>(path: SubPath): Hono<E, S, MergePath<BasePath, SubPath>> {222 const subApp = this.clone()223 subApp._basePath = mergePath(this._basePath, path)224 return subApp225 }226 227+ /**228+ * `.onError()` handles an error and returns a customized Response.229+ * ```ts230+ * app.onError((err, c) => {231+ * console.error(`${err}`)232+ * return c.text('Custom Error Message', 500)233+ * })234+ * ```235+ */236 onError = (handler: ErrorHandler<E>) => {237 this.errorHandler = handler238 return this239 }240 241+ /**242+ * `.notFound()` allows you to customize a Not Found Response.243+ * ```ts244+ * app.notFound((c) => {245+ * return c.text('Custom 404 Message', 404)246+ * })247+ * ```248+ * @see https://hono.dev/api/hono#not-found249+ */250 notFound = (handler: NotFoundHandler<E>) => {251 this.notFoundHandler = handler252 return this253 }254 197- /**198- * @deprecated199- * Use `showRoutes()` utility methods provided by 'hono/dev' instead of `app.showRoutes()`.200- * `app.showRoutes()` will be removed in v4.201- * @example202- * You could rewrite `app.showRoutes()` as follows203- * import { showRoutes } from 'hono/dev'204- * showRoutes(app)205- */206- showRoutes() {207- const length = 8208- this.routes.map((route) => {209- console.log(210- `\x1b[32m${route.method}\x1b[0m ${' '.repeat(length - route.method.length)} ${route.path}`211- )212- })213- }214-255 mount(256 path: string,257 // eslint-disable-next-line @typescript-eslint/no-explicit-any258 applicationHandler: (request: Request, ...args: any) => Response | Promise<Response>,28 unmodified lines287 this.addRoute(METHOD_NAME_ALL, mergePath(path, '*'), handler)288 return this289 }290 251- /**252- * @deprecated253- * `app.routerName()` will be removed in v4.254- * Use `getRouterName()` in `hono/dev` instead of `app.routerName()`.255- */256- get routerName() {257- this.matchRoute('GET', '/')258- return this.router.name259- }260-261- /**262- * @deprecated263- * `app.head()` is no longer used.264- * `app.get()` implicitly handles the HEAD method.265- */266- head = () => {267- console.warn('`app.head()` is no longer used. `app.get()` implicitly handles the HEAD method.')268- return this269- }270-291 private addRoute(method: string, path: string, handler: H) {292 method = method.toUpperCase()293 path = mergePath(this._basePath, path)294 const r: RouterRoute = { path: path, method: method, handler: handler }36 unmodified lines331 // Do not `compose` if it has only one handler332 if (matchResult[0].length === 1) {333 let res: ReturnType<H>334 try {315- res = matchResult[0][0][0][0](c, async () => {316- c.res = await this.notFoundHandler(c)317- })335+ res = matchResult[0][0][0][0](c, async () => {})336+ if (!res) {337+ return this.notFoundHandler(c)338+ }339 } catch (err) {340 return this.handleError(err, c)341 }342 16 unmodified lines359 throw new Error(360 'Context is not finalized. You may forget returning Response object or `await next()`'361 )362 }363+364 return context.res365 } catch (err) {366 return this.handleError(err, c)367 }368 })()369 }370 371 /**350- * @deprecated351- * `app.handleEvent()` will be removed in v4.352- * Use `app.fetch()` instead of `app.handleEvent()`.372+ * `.fetch()` will be entry point of your app.373+ * @see https://hono.dev/api/hono#fetch374 */354- handleEvent = (event: FetchEventLike) => {355- return this.dispatch(event.request, event, undefined, event.request.method)356- }357-375 fetch = (request: Request, Env?: E['Bindings'] | {}, executionCtx?: ExecutionContext) => {376 return this.dispatch(request, executionCtx, Env, request.method)377 }378 379+ /**380+ * `.request()` is a useful method for testing.381+ * You can pass a URL or pathname to send a GET request.382+ * app will return a Response object.383+ * ```ts384+ * test('GET /hello is ok', async () => {385+ * const res = await app.request('/hello')386+ * expect(res.status).toBe(200)387+ * })388+ * ```389+ * @see https://hono.dev/api/hono#request390+ */391 request = (392 input: RequestInfo | URL,393 requestInit?: RequestInit,394 Env?: E['Bindings'] | {},10 unmodified lines405 const req = new Request(path, requestInit)406 return this.fetch(req, Env, executionCtx)407 }408 409+ /**410+ * `.fire()` automatically adds a global fetch event listener.411+ * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.412+ * @see https://hono.dev/api/hono#fire413+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API414+ * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/415+ */416 fire = () => {381- // eslint-disable-next-line @typescript-eslint/ban-ts-comment382- // @ts-ignore417+ // @ts-expect-error `event` is not the type expected by addEventListener418 addEventListener('fetch', (event: FetchEventLike): void => {419 event.respondWith(this.dispatch(event.request, event, undefined, event.request.method))420 })421 }3 unmodified linesmodified:src/hono.test.ts+43 added-126 removed
1 /* eslint-disable @typescript-eslint/no-unused-vars */2 /* eslint-disable @typescript-eslint/ban-ts-comment */3-import { expectTypeOf, vi } from 'vitest'3+import { expectTypeOf } from 'vitest'4 import { hc } from './client'5 import type { Context } from './context'6 import { Hono } from './hono'7 import { HTTPException } from './http-exception'1411 unmodified lines1419 'Handle the error in middleware with async, original message is Error message'1420 )1421 })1422 1423+ describe('Default route app.use', () => {1424+ const app = new Hono()1425+ app1426+ .use(async (c, next) => {1427+ c.header('x-default-use', 'abc')1428+ await next()1429+ })1430+ .get('/multiple/abc', (c) => {1431+ return c.text('GET multiple')1432+ })1433+ it('GET /multiple/abc', async () => {1434+ const res = await app.request('http://localhost/multiple/abc')1435+ expect(res.status).toBe(200)1436+ expect(await res.text()).toBe('GET multiple')1437+ expect(res.headers.get('x-default-use')).toBe('abc')1438+ })1439+ })1440+1441 describe('Error in `notFound()`', () => {1442 const app = new Hono()1443 1444 app.use('*', async () => {})452 unmodified lines1897 expect(res.status).toBe(404)1898 })1899 })1900 1901+describe('Multiple paths with one handler', () => {1902+ const app = new Hono()1903+1904+ const paths = ['/hello', '/ja/hello', '/en/hello']1905+ app.on('GET', paths, (c) => {1906+ return c.json({1907+ path: c.req.path,1908+ routePath: c.req.routePath,1909+ })1910+ })1911+1912+ it('Should handle multiple paths', async () => {1913+ paths.map(async (path) => {1914+ const res = await app.request(path)1915+ expect(res.status).toBe(200)1916+ const data = await res.json()1917+ expect(data).toEqual({1918+ path,1919+ routePath: path,1920+ })1921+ })1922+ })1923+})1924+1925 describe('Multiple handler', () => {1926 describe('handler + handler', () => {1927 const app = new Hono()1928 31 unmodified lines1960 const res = await app.request('/car/good-car')1961 expect(res.ok).toBe(true)1962 expect(await res.text()).toBe('type: car, url: good-car')1963 })1922-1964 it('Should return a correct param - GET /foo/food/good-food', async () => {1965 const res = await app.request('/foo/food/good-food')1966 expect(res.ok).toBe(true)1967 expect(await res.text()).toBe('foo type: food, url: good-food')120 unmodified lines2088 expect(await res.text()).toMatch(/^Context is not finalized/)2089 })2090 })2091 2051-describe('Cookie', () => {2052- describe('Parse cookie', () => {2053- const apps: Record<string, Hono> = {}2054- apps['get by name'] = (() => {2055- const app = new Hono()2056-2057- app.get('/cookie', (c) => {2058- const yummyCookie = c.req.cookie('yummy_cookie')2059- const tastyCookie = c.req.cookie('tasty_cookie')2060- const res = new Response('Good cookie')2061- if (yummyCookie && tastyCookie) {2062- res.headers.set('Yummy-Cookie', yummyCookie)2063- res.headers.set('Tasty-Cookie', tastyCookie)2064- }2065- return res2066- })2067-2068- return app2069- })()2070-2071- apps['get all as an object'] = (() => {2072- const app = new Hono()2073-2074- app.get('/cookie', (c) => {2075- const { yummy_cookie: yummyCookie, tasty_cookie: tastyCookie } = c.req.cookie()2076- const res = new Response('Good cookie')2077- res.headers.set('Yummy-Cookie', yummyCookie)2078- res.headers.set('Tasty-Cookie', tastyCookie)2079- return res2080- })2081-2082- return app2083- })()2084-2085- describe.each(Object.keys(apps))('%s', (name) => {2086- const app = apps[name]2087- it('Parse cookie on c.req.cookie', async () => {2088- const req = new Request('http://localhost/cookie')2089- const cookieString = 'yummy_cookie=choco; tasty_cookie = strawberry '2090- req.headers.set('Cookie', cookieString)2091- const res = await app.request(req)2092-2093- expect(res.headers.get('Yummy-Cookie')).toBe('choco')2094- expect(res.headers.get('Tasty-Cookie')).toBe('strawberry')2095- })2096- })2097- })2098-2099- describe('Set cookie', () => {2100- const app = new Hono()2101-2102- app.get('/set-cookie', (c) => {2103- c.cookie('delicious_cookie', 'macha')2104- return c.text('Give cookie')2105- })2106-2107- it('Set cookie on c.cookie', async () => {2108- const res = await app.request('http://localhost/set-cookie')2109- expect(res.status).toBe(200)2110- const header = res.headers.get('Set-Cookie')2111- expect(header).toBe('delicious_cookie=macha')2112- })2113-2114- app.get('/set-cookie-complex', (c) => {2115- c.cookie('great_cookie', 'banana', {2116- path: '/',2117- secure: true,2118- domain: 'example.com',2119- httpOnly: true,2120- maxAge: 1000,2121- expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)),2122- sameSite: 'Strict',2123- })2124- return c.text('Give cookie')2125- })2126-2127- it('Complex pattern', async () => {2128- const res = await app.request('http://localhost/set-cookie-complex')2129- expect(res.status).toBe(200)2130- const header = res.headers.get('Set-Cookie')2131- expect(header).toBe(2132- 'great_cookie=banana; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict'2133- )2134- })2135-2136- app.get('/set-cookie-multiple', (c) => {2137- c.cookie('delicious_cookie', 'macha')2138- c.cookie('delicious_cookie', 'choco')2139- return c.text('Give cookie')2140- })2141-2142- it('Multiple values', async () => {2143- const res = await app.request('http://localhost/set-cookie-multiple')2144- expect(res.status).toBe(200)2145- const header = res.headers.get('Set-Cookie')2146- expect(header).toBe('delicious_cookie=macha, delicious_cookie=choco')2147- })2148- })2149-})2150-2092 describe('Parse Body', () => {2093 const app = new Hono()2094 2095 app.post('/json', async (c) => {161 unmodified lines2257 expect(await res.text()).toBe('Post id is 123')2258 })2259 })2260 2320-describe('Show routes', () => {2321- const app = new Hono()2322- vi.spyOn(console, 'log')2323- it('Should call `console.log()` with `app.showRoutes()`', async () => {2324- app.get('/', (c) => c.text('/'))2325- app.get('/foo', (c) => c.text('/'))2326- app.showRoutes()2327- expect(console.log).toBeCalled()2328- })2329-})2330-2261 describe('json', () => {2262 const api = new Hono()2263 2264 api.get('/message', (c) => {290 unmodified lines2555 })2556 })2557 })2558 2629-describe('Router Name', () => {2630- it('Should return the correct router name', async () => {2631- const app = new Hono({2632- router: new RegExpRouter(),2633- })2634- app.get('/router-name', (c) => {2635- return c.text(app.routerName ?? 'N/A')2636- })2637- const res = await app.request('/router-name')2638- expect(await res.text()).toBe('RegExpRouter')2639- })2640-})2641-2559 describe('HEAD method', () => {2560 const app = new Hono()2561 2562 app.get('/page', (c) => {805 unmodified linesmodified:src/hono.ts+2 added-2 removed
1 unmodified line2 import type { HonoOptions } from './hono-base'3 import { RegExpRouter } from './router/reg-exp-router'4 import { SmartRouter } from './router/smart-router'5 import { TrieRouter } from './router/trie-router'6-import type { Env, Schema } from './types'6+import type { BlankSchema, Env, Schema } from './types'7 8 export class Hono<9 E extends Env = Env,10- S extends Schema = {},10+ S extends Schema = BlankSchema,11 BasePath extends string = '/'12 > extends HonoBase<E, S, BasePath> {13 constructor(options: HonoOptions<E> = {}) {14 super(options)7 unmodified linesmodified:src/http-exception.ts+18 added
3 unmodified lines4 res?: Response5 message?: string6 }7 8+/**9+ * `HTTPException` must be used when a fatal error such as authentication failure occurs.10+ * @example11+ * ```ts12+ * import { HTTPException } from 'hono/http-exception'13+ *14+ * // ...15+ *16+ * app.post('/auth', async (c, next) => {17+ * // authentication18+ * if (authorized === false) {19+ * throw new HTTPException(401, { message: 'Custom error message' })20+ * }21+ * await next()22+ * })23+ * ```24+ * @see https://hono.dev/api/exception25+ */26 export class HTTPException extends Error {27 readonly res?: Response28 readonly status: StatusCode29 constructor(status: StatusCode = 500, options?: HTTPExceptionOptions) {13 unmodified linesmodified:src/middleware.ts-2 removed
1 // This file is for Deno to import middleware from `hono/middleware.ts`.2 export * from './middleware/basic-auth'3 export * from './middleware/bearer-auth'4 export * from './middleware/cache'5-export * from './helper/cookie' // will be moved to helper.ts in v45 export * from './middleware/compress'6 export * from './middleware/cors'7 export * from './middleware/csrf'8 export * from './middleware/etag'10-export * from './helper/html' // will be moved to helper.ts in v49 export * from './jsx'10 export * from './middleware/jsx-renderer'11 export { jwt } from './middleware/jwt'12 export * from './middleware/logger'5 unmodified linesmodified:src/request.ts+158 added-91 removed
10 unmodified lines11 RouterRoute,12 } from './types'13 import { parseBody } from './utils/body'14 import type { BodyData, ParseBodyOptions } from './utils/body'15-import type { Cookie } from './utils/cookie'16-import { parse } from './utils/cookie'15 import type { UnionToIntersection } from './utils/types'16 import { getQueryParam, getQueryParams, decodeURIComponent_ } from './utils/url'17 18 type Body = {5 unmodified lines24 }25 type BodyCache = Partial<Body & { parsedBody: BodyData }>26 27 export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {28+ /**29+ * `.raw` can get the raw Request object.30+ * @example31+ * ```ts32+ * // For Cloudflare Workers33+ * app.post('/', async (c) => {34+ * const metadata = c.req.raw.cf?.hostMetadata?35+ * ...36+ * })37+ * ```38+ * @see https://hono.dev/api/request#raw39+ */40 raw: Request41 42 #validatedData: { [K in keyof ValidationTargets]?: {} } // Short name of validatedData43 #matchResult: Result<[unknown, RouterRoute]>44 routeIndex: number = 045+ /**46+ * `.path` can get the pathname of the request.47+ * @example48+ * ```ts49+ * app.get('/about/me', (c) => {50+ * const pathname = c.req.path // `/about/me`51+ * })52+ * ```53+ * @see https://hono.dev/api/request#path54+ */55 path: string56 bodyCache: BodyCache = {}57 58 constructor(6 unmodified lines65 this.#matchResult = matchResult66 this.#validatedData = {}67 }68 69+ /**70+ * `.req.param()` gets the path parameters.71+ * @example72+ * ```ts73+ * const name = c.req.param('name')74+ * // or all parameters at once75+ * const { id, comment_id } = c.req.param()76+ * ```77+ * @see https://hono.dev/api/routing#path-parameter78+ */79 param<P2 extends string = P>(80 key: RemoveQuestion<ParamKeys<P2>>81 ): UndefinedIfHavingQuestion<ParamKeys<P2>>82 param<P2 extends string = P>(): UnionToIntersection<ParamKeyToRecord<ParamKeys<P2>>>25 unmodified lines108 private getParamValue(paramKey: any): string | undefined {109 return this.#matchResult[1] ? this.#matchResult[1][paramKey as any] : paramKey110 }111 112+ /**113+ * `.query()` can get querystring parameters.114+ * @example115+ * ```ts116+ * // Query params117+ * app.get('/search', (c) => {118+ * const query = c.req.query('q')119+ * })120+ *121+ * // Get all params at once122+ * app.get('/search', (c) => {123+ * const { q, limit, offset } = c.req.query()124+ * })125+ * ```126+ * @see https://hono.dev/api/request#query127+ */128 query(key: string): string | undefined129 query(): Record<string, string>130 query(key?: string) {131 return getQueryParam(this.url, key)132 }133 134+ /**135+ * `.queries()` can get multiple querystring parameter values, e.g. /search?tags=A&tags=B136+ * @example137+ * ```ts138+ * app.get('/search', (c) => {139+ * // tags will be string[]140+ * const tags = c.req.queries('tags')141+ * })142+ * ```143+ * @see https://hono.dev/api/request#queries144+ */145 queries(key: string): string[] | undefined146 queries(): Record<string, string[]>147 queries(key?: string) {148 return getQueryParams(this.url, key)149 }150 151+ /**152+ * `.header()` can get the request header value.153+ * @example154+ * ```ts155+ * app.get('/', (c) => {156+ * const userAgent = c.req.header('User-Agent')157+ * })158+ * ```159+ * @see https://hono.dev/api/request#header160+ */161 header(name: string): string | undefined162 header(): Record<string, string>163 header(name?: string) {164 if (name) {6 unmodified lines171 })172 return headerData173 }174 108- /** @deprecated109- * Use Cookie Middleware instead of `c.req.cookie()`. The `c.req.cookie()` will be removed in v4.110- *175+ /**176+ * `.parseBody()` can parse Request body of type `multipart/form-data` or `application/x-www-form-urlencoded`177 * @example112- *113- * import { getCookie } from 'hono/cookie'114- * // ...115- * app.get('/', (c) => c.text(getCookie(c, 'cookie-name')))178+ * ```ts179+ * app.post('/entry', async (c) => {180+ * const body = await c.req.parseBody()181+ * })182+ * ```183+ * @see https://hono.dev/api/request#parsebody184 */117- cookie(key: string): string | undefined118-119- /** @deprecated120- * Use Cookie Middleware instead of `c.req.cookie()`. The `c.req.cookie()` will be removed in v4.121- *122- * @example123- *124- * import { getCookie } from 'hono/cookie'125- * // ...126- * app.get('/', (c) => c.json(getCookie(c)))127- */128- cookie(): Cookie129-130- cookie(key?: string) {131- const cookie = this.raw.headers.get('Cookie')132- if (!cookie) {133- return134- }135- const obj = parse(cookie)136- if (key) {137- const value = obj[key]138- return value139- } else {140- return obj141- }142- }143-185 async parseBody<T extends BodyData = BodyData>(options?: ParseBodyOptions): Promise<T> {186 if (this.bodyCache.parsedBody) {187 return this.bodyCache.parsedBody as T188 }19 unmodified lines208 }209 return (bodyCache[key] = raw[key]())210 }211 212+ /**213+ * `.json()` can parse Request body of type `application/json`214+ * @example215+ * ```ts216+ * app.post('/entry', async (c) => {217+ * const body = await c.req.json()218+ * })219+ * ```220+ * @see https://hono.dev/api/request#json221+ */222 json<T = any>(): Promise<T> {223 return this.cachedBody('json')224 }225 226+ /**227+ * `.text()` can parse Request body of type `text/plain`228+ * @example229+ * ```ts230+ * app.post('/entry', async (c) => {231+ * const body = await c.req.text()232+ * })233+ * ```234+ * @see https://hono.dev/api/request#text235+ */236 text(): Promise<string> {237 return this.cachedBody('text')238 }239 240+ /**241+ * `.arrayBuffer()` parse Request body as an `ArrayBuffer`242+ * @example243+ * ```ts244+ * app.post('/entry', async (c) => {245+ * const body = await c.req.arrayBuffer()246+ * })247+ * ```248+ * @see https://hono.dev/api/request#arraybuffer249+ */250 arrayBuffer(): Promise<ArrayBuffer> {251 return this.cachedBody('arrayBuffer')252 }253 13 unmodified lines267 valid(target: keyof ValidationTargets) {268 return this.#validatedData[target] as unknown269 }270 271+ /**272+ * `.url()` can get the request url strings.273+ * @example274+ * ```ts275+ * app.get('/about/me', (c) => {276+ * const url = c.req.url // `http://localhost:8787/about/me`277+ * ...278+ * })279+ * ```280+ * @see https://hono.dev/api/request#url281+ */282 get url() {283 return this.raw.url284 }285 286+ /**287+ * `.method()` can get the method name of the request.288+ * @example289+ * ```ts290+ * app.get('/about/me', (c) => {291+ * const method = c.req.method // `GET`292+ * })293+ * ```294+ * @see https://hono.dev/api/request#method295+ */296 get method() {297 return this.raw.method298 }299 300+ /**301+ * `.matchedRoutes()` can return a matched route in the handler302+ * @example303+ * ```ts304+ * app.use('*', async function logger(c, next) {305+ * await next()306+ * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {307+ * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')308+ * console.log(309+ * method,310+ * ' ',311+ * path,312+ * ' '.repeat(Math.max(10 - path.length, 0)),313+ * name,314+ * i === c.req.routeIndex ? '<- respond from here' : ''315+ * )316+ * })317+ * })318+ * ```319+ * @see https://hono.dev/api/request#matchedroutes320+ */321 get matchedRoutes(): RouterRoute[] {322 return this.#matchResult[0].map(([[, route]]) => route)323 }324 212- get routePath(): string {213- return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path214- }215-216- /** @deprecated217- * Use `c.req.raw.headers` instead of `c.req.headers`. The `c.req.headers` will be removed in v4.218- * Or you can get the header values with using `c.req.header`.325+ /**326+ * `routePath()` can retrieve the path registered within the handler327 * @example220- *221- * app.get('/', (c) => {222- * const userAgent = c.req.header('User-Agent')223- * //...328+ * ```ts329+ * app.get('/posts/:id', (c) => {330+ * return c.json({ path: c.req.routePath })331 * })332+ * ```333+ * @see https://hono.dev/api/request#routepath334 */226- get headers() {227- return this.raw.headers335+ get routePath(): string {336+ return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path337 }229-230- /** @deprecated231- * Use `c.req.raw.body` instead of `c.req.body`. The `c.req.body` will be removed in v4.232- */233- get body() {234- return this.raw.body235- }236-237- /** @deprecated238- * Use `c.req.raw.bodyUsed` instead of `c.req.bodyUsed`. The `c.req.bodyUsed` will be removed in v4.239- */240- get bodyUsed() {241- return this.raw.bodyUsed242- }243-244- /** @deprecated245- * Use `c.req.raw.integrity` instead of `c.req.integrity`. The `c.req.integrity` will be removed in v4.246- */247- get integrity() {248- return this.raw.integrity249- }250-251- /** @deprecated252- * Use `c.req.raw.keepalive` instead of `c.req.keepalive`. The `c.req.keepalive` will be removed in v4.253- */254- get keepalive() {255- return this.raw.keepalive256- }257-258- /** @deprecated259- * Use `c.req.raw.referrer` instead of `c.req.referrer`. The `c.req.referrer` will be removed in v4.260- */261- get referrer() {262- return this.raw.referrer263- }264-265- /** @deprecated266- * Use `c.req.raw.signal` instead of `c.req.signal`. The `c.req.signal` will be removed in v4.267- */268- get signal() {269- return this.raw.signal270- }338 }modified:src/types.test.ts+387 added-100 removed
955 unmodified lines956 bar8: number957 bar9: number958 }>()959 960- return c.jsonT(0)961- })962-963- // app.get('/', handler...)964-965- new Hono().get('/', mw1).get('/', (c) => {966- expectTypeOf(c.var.foo1).toEqualTypeOf<string>()960 return c.json(0)961 })962 970- new Hono().get('/', mw1, mw2).get('/', (c) => {971- expectTypeOf(c.var.foo1).toEqualTypeOf<string>()972- expectTypeOf(c.var.foo2).toEqualTypeOf<string>()973- return c.json(0)974- })975-976- new Hono().get('/', mw1, mw2, mw3).get('/', (c) => {977- expectTypeOf(c.var.foo1).toEqualTypeOf<string>()978- expectTypeOf(c.var.foo2).toEqualTypeOf<string>()979- expectTypeOf(c.var.foo3).toEqualTypeOf<string>()980- return c.json(0)981- })982-983- new Hono().get('/', mw1, mw2, mw3, mw4).get('/', (c) => {984- expectTypeOf(c.var.foo1).toEqualTypeOf<string>()985- expectTypeOf(c.var.foo2).toEqualTypeOf<string>()986- expectTypeOf(c.var.foo3).toEqualTypeOf<string>()987- expectTypeOf(c.var.foo4).toEqualTypeOf<string>()988- return c.json(0)989- })990-991- new Hono().get('/', mw1, mw2, mw3, mw4, mw5).get('/', (c) => {992- expectTypeOf(c.var.foo1).toEqualTypeOf<string>()993- expectTypeOf(c.var.foo2).toEqualTypeOf<string>()994- expectTypeOf(c.var.foo3).toEqualTypeOf<string>()995- expectTypeOf(c.var.foo4).toEqualTypeOf<string>()996- expectTypeOf(c.var.foo5).toEqualTypeOf<string>()997- return c.json(0)998- })999-1000- new Hono().get('/', mw1, mw2, mw3, mw4, mw5, mw6).get('/', (c) => {1001- expectTypeOf(c.var.foo1).toEqualTypeOf<string>()1002- expectTypeOf(c.var.foo2).toEqualTypeOf<string>()1003- expectTypeOf(c.var.foo3).toEqualTypeOf<string>()1004- expectTypeOf(c.var.foo4).toEqualTypeOf<string>()1005- expectTypeOf(c.var.foo5).toEqualTypeOf<string>()1006- expectTypeOf(c.var.foo6).toEqualTypeOf<string>()1007- return c.json(0)1008- })1009-1010- new Hono().get('/', mw1, mw2, mw3, mw4, mw5, mw6, mw7).get('/', (c) => {1011- expectTypeOf(c.var.foo1).toEqualTypeOf<string>()1012- expectTypeOf(c.var.foo2).toEqualTypeOf<string>()1013- expectTypeOf(c.var.foo3).toEqualTypeOf<string>()1014- expectTypeOf(c.var.foo4).toEqualTypeOf<string>()1015- expectTypeOf(c.var.foo5).toEqualTypeOf<string>()1016- expectTypeOf(c.var.foo6).toEqualTypeOf<string>()1017- expectTypeOf(c.var.foo7).toEqualTypeOf<string>()1018- return c.json(0)1019- })1020-1021- new Hono().get('/', mw1, mw2, mw3, mw4, mw5, mw6, mw7, mw8).get('/', (c) => {1022- expectTypeOf(c.var.foo1).toEqualTypeOf<string>()1023- expectTypeOf(c.var.foo2).toEqualTypeOf<string>()1024- expectTypeOf(c.var.foo3).toEqualTypeOf<string>()1025- expectTypeOf(c.var.foo4).toEqualTypeOf<string>()1026- expectTypeOf(c.var.foo5).toEqualTypeOf<string>()1027- expectTypeOf(c.var.foo6).toEqualTypeOf<string>()1028- expectTypeOf(c.var.foo7).toEqualTypeOf<string>()1029- expectTypeOf(c.var.foo8).toEqualTypeOf<string>()1030- return c.json(0)1031- })1032-1033- new Hono().get('/', mw1, mw2, mw3, mw4, mw5, mw6, mw7, mw8, mw9).get('/', (c) => {1034- expectTypeOf(c.var.foo1).toEqualTypeOf<string>()1035- expectTypeOf(c.var.foo2).toEqualTypeOf<string>()1036- expectTypeOf(c.var.foo3).toEqualTypeOf<string>()1037- expectTypeOf(c.var.foo4).toEqualTypeOf<string>()1038- expectTypeOf(c.var.foo5).toEqualTypeOf<string>()1039- expectTypeOf(c.var.foo6).toEqualTypeOf<string>()1040- expectTypeOf(c.var.foo7).toEqualTypeOf<string>()1041- expectTypeOf(c.var.foo8).toEqualTypeOf<string>()1042- expectTypeOf(c.var.foo9).toEqualTypeOf<string>()1043- return c.json(0)1044- })1045-1046- new Hono().get('/', mw1, mw2, mw3, mw4, mw5, mw6, mw7, mw8, mw9, mw10).get('/', (c) => {1047- expectTypeOf(c.var.foo1).toEqualTypeOf<string>()1048- expectTypeOf(c.var.foo2).toEqualTypeOf<string>()1049- expectTypeOf(c.var.foo3).toEqualTypeOf<string>()1050- expectTypeOf(c.var.foo4).toEqualTypeOf<string>()1051- expectTypeOf(c.var.foo5).toEqualTypeOf<string>()1052- expectTypeOf(c.var.foo6).toEqualTypeOf<string>()1053- expectTypeOf(c.var.foo7).toEqualTypeOf<string>()1054- expectTypeOf(c.var.foo8).toEqualTypeOf<string>()1055- expectTypeOf(c.var.foo9).toEqualTypeOf<string>()1056- expectTypeOf(c.var.foo10).toEqualTypeOf<string>()1057- return c.json(0)1058- })1059-963 new Hono().get('/', mw1, mw2, mw3, mw4, mw5, mw6, mw7, mw8, mw9, (c) => {964 expectTypeOf(c.req.valid('query')).toMatchTypeOf<{965 bar1: number966 bar2: number5 unmodified lines972 bar8: number973 bar9: number974 }>()975 1073- return c.jsonT(0)976+ return c.json(0)977 })978+979+ type Env = {980+ Variables: {981+ init: number982+ }983+ }984+985+ new Hono<Env>()986+ .get('/', mw1, (c) => {987+ expectTypeOf(c.get('init')).toEqualTypeOf<number>()988+ expectTypeOf(c.var.init).toEqualTypeOf<number>()989+ expectTypeOf(c.get('foo1')).toEqualTypeOf<string>()990+ expectTypeOf(c.var.foo1).toEqualTypeOf<string>()991+ return c.json(0)992+ })993+ .get('/', (c) => {994+ expectTypeOf(c.get('init')).toEqualTypeOf<number>()995+ expectTypeOf(c.var.init).toEqualTypeOf<number>()996+ // @ts-expect-error foo1 is not typed997+ c.get('foo1')998+ // @ts-expect-error foo1 is not typed999+ c.var.foo11000+ return c.json(0)1001+ })1002+1003+ new Hono<Env>()1004+ .get('/', mw1, mw2, (c) => {1005+ expectTypeOf(c.get('init')).toEqualTypeOf<number>()1006+ expectTypeOf(c.var.init).toEqualTypeOf<number>()1007+ expectTypeOf(c.get('foo1')).toEqualTypeOf<string>()1008+ expectTypeOf(c.var.foo1).toEqualTypeOf<string>()1009+ expectTypeOf(c.get('foo2')).toEqualTypeOf<string>()1010+ expectTypeOf(c.var.foo2).toEqualTypeOf<string>()1011+ return c.json(0)1012+ })1013+ .get('/', (c) => {1014+ expectTypeOf(c.get('init')).toEqualTypeOf<number>()1015+ expectTypeOf(c.var.init).toEqualTypeOf<number>()1016+ // @ts-expect-error foo1 is not typed1017+ c.get('foo1')1018+ // @ts-expect-error foo1 is not typed1019+ c.var.foo11020+ // @ts-expect-error foo2 is not typed1021+ c.get('foo2')1022+ // @ts-expect-error foo2 is not typed1023+ c.var.foo21024+ return c.json(0)1025+ })1026+1027+ new Hono<Env>()1028+ .get('/', mw1, mw2, mw3, (c) => {1029+ expectTypeOf(c.get('init')).toEqualTypeOf<number>()1030+ expectTypeOf(c.var.init).toEqualTypeOf<number>()1031+ expectTypeOf(c.get('foo1')).toEqualTypeOf<string>()1032+ expectTypeOf(c.var.foo1).toEqualTypeOf<string>()1033+ expectTypeOf(c.get('foo2')).toEqualTypeOf<string>()1034+ expectTypeOf(c.var.foo2).toEqualTypeOf<string>()1035+ expectTypeOf(c.get('foo3')).toEqualTypeOf<string>()1036+ expectTypeOf(c.var.foo3).toEqualTypeOf<string>()1037+ return c.json(0)1038+ })1039+ .get('/', (c) => {1040+ expectTypeOf(c.get('init')).toEqualTypeOf<number>()1041+ expectTypeOf(c.var.init).toEqualTypeOf<number>()1042+ // @ts-expect-error foo1 is not typed1043+ c.get('foo1')1044+ // @ts-expect-error foo1 is not typed1045+ c.var.foo11046+ // @ts-expect-error foo2 is not typed1047+ c.get('foo2')1048+ // @ts-expect-error foo2 is not typed1049+ c.var.foo21050+ // @ts-expect-error foo3 is not typed1051+ c.get('foo3')1052+ // @ts-expect-error foo3 is not typed1053+ c.var.foo31054+ return c.json(0)1055+ })1056+1057+ new Hono<Env>()1058+ .get('/', mw1, mw2, mw3, mw4, (c) => {1059+ expectTypeOf(c.get('init')).toEqualTypeOf<number>()1060+ expectTypeOf(c.var.init).toEqualTypeOf<number>()1061+ expectTypeOf(c.get('foo1')).toEqualTypeOf<string>()1062+ expectTypeOf(c.var.foo1).toEqualTypeOf<string>()1063+ expectTypeOf(c.get('foo2')).toEqualTypeOf<string>()1064+ expectTypeOf(c.var.foo2).toEqualTypeOf<string>()1065+ expectTypeOf(c.get('foo3')).toEqualTypeOf<string>()1066+ expectTypeOf(c.var.foo3).toEqualTypeOf<string>()1067+ expectTypeOf(c.get('foo4')).toEqualTypeOf<string>()1068+ expectTypeOf(c.var.foo4).toEqualTypeOf<string>()1069+ return c.json(0)1070+ })1071+ .get('/', (c) => {1072+ expectTypeOf(c.get('init')).toEqualTypeOf<number>()1073+ expectTypeOf(c.var.init).toEqualTypeOf<number>()1074+ // @ts-expect-error foo1 is not typed1075+ c.get('foo1')1076+ // @ts-expect-error foo1 is not typed1077+ c.var.foo11078+ // @ts-expect-error foo2 is not typed1079+ c.get('foo2')1080+ // @ts-expect-error foo2 is not typed1081+ c.var.foo21082+ // @ts-expect-error foo3 is not typed1083+ c.get('foo3')1084+ // @ts-expect-error foo3 is not typed1085+ c.var.foo31086+ // @ts-expect-error foo4 is not typed1087+ c.get('foo4')1088+ // @ts-expect-error foo4 is not typed1089+ c.var.foo41090+ return c.json(0)1091+ })1092+1093+ new Hono<Env>()1094+ .get('/', mw1, mw2, mw3, mw4, mw5, (c) => {1095+ expectTypeOf(c.get('init')).toEqualTypeOf<number>()1096+ expectTypeOf(c.var.init).toEqualTypeOf<number>()1097+ expectTypeOf(c.get('foo1')).toEqualTypeOf<string>()1098+ expectTypeOf(c.var.foo1).toEqualTypeOf<string>()1099+ expectTypeOf(c.get('foo2')).toEqualTypeOf<string>()1100+ expectTypeOf(c.var.foo2).toEqualTypeOf<string>()1101+ expectTypeOf(c.get('foo3')).toEqualTypeOf<string>()1102+ expectTypeOf(c.var.foo3).toEqualTypeOf<string>()1103+ expectTypeOf(c.get('foo4')).toEqualTypeOf<string>()1104+ expectTypeOf(c.var.foo4).toEqualTypeOf<string>()1105+ expectTypeOf(c.get('foo5')).toEqualTypeOf<string>()1106+ expectTypeOf(c.var.foo5).toEqualTypeOf<string>()1107+ return c.json(0)1108+ })1109+ .get('/', (c) => {1110+ expectTypeOf(c.get('init')).toEqualTypeOf<number>()1111+ expectTypeOf(c.var.init).toEqualTypeOf<number>()1112+ // @ts-expect-error foo1 is not typed1113+ c.get('foo1')1114+ // @ts-expect-error foo1 is not typed1115+ c.var.foo11116+ // @ts-expect-error foo2 is not typed1117+ c.get('foo2')1118+ // @ts-expect-error foo2 is not typed1119+ c.var.foo21120+ // @ts-expect-error foo3 is not typed1121+ c.get('foo3')1122+ // @ts-expect-error foo3 is not typed1123+ c.var.foo31124+ // @ts-expect-error foo4 is not typed1125+ c.get('foo4')1126+ // @ts-expect-error foo4 is not typed1127+ c.var.foo41128+ // @ts-expect-error foo5 is not typed1129+ c.get('foo5')1130+ // @ts-expect-error foo5 is not typed1131+ c.var.foo51132+ return c.json(0)1133+ })1134+1135+ new Hono<Env>()1136+ .get('/', mw1, mw2, mw3, mw4, mw5, mw6, (c) => {1137+ expectTypeOf(c.get('init')).toEqualTypeOf<number>()1138+ expectTypeOf(c.var.init).toEqualTypeOf<number>()1139+ expectTypeOf(c.get('foo1')).toEqualTypeOf<string>()1140+ expectTypeOf(c.var.foo1).toEqualTypeOf<string>()1141+ expectTypeOf(c.get('foo2')).toEqualTypeOf<string>()1142+ expectTypeOf(c.var.foo2).toEqualTypeOf<string>()1143+ expectTypeOf(c.get('foo3')).toEqualTypeOf<string>()1144+ expectTypeOf(c.var.foo3).toEqualTypeOf<string>()1145+ expectTypeOf(c.get('foo4')).toEqualTypeOf<string>()1146+ expectTypeOf(c.var.foo4).toEqualTypeOf<string>()1147+ expectTypeOf(c.get('foo5')).toEqualTypeOf<string>()1148+ expectTypeOf(c.var.foo5).toEqualTypeOf<string>()1149+ expectTypeOf(c.get('foo6')).toEqualTypeOf<string>()1150+ expectTypeOf(c.var.foo6).toEqualTypeOf<string>()1151+ return c.json(0)1152+ })1153+ .get('/', (c) => {1154+ expectTypeOf(c.get('init')).toEqualTypeOf<number>()1155+ expectTypeOf(c.var.init).toEqualTypeOf<number>()1156+ // @ts-expect-error foo1 is not typed1157+ c.get('foo1')1158+ // @ts-expect-error foo1 is not typed1159+ c.var.foo11160+ // @ts-expect-error foo2 is not typed1161+ c.get('foo2')1162+ // @ts-expect-error foo2 is not typed1163+ c.var.foo21164+ // @ts-expect-error foo3 is not typed1165+ c.get('foo3')1166+ // @ts-expect-error foo3 is not typed1167+ c.var.foo31168+ // @ts-expect-error foo4 is not typed1169+ c.get('foo4')1170+ // @ts-expect-error foo4 is not typed1171+ c.var.foo41172+ // @ts-expect-error foo5 is not typed1173+ c.get('foo5')1174+ // @ts-expect-error foo5 is not typed1175+ c.var.foo51176+ // @ts-expect-error foo6 is not typed1177+ c.get('foo6')1178+ // @ts-expect-error foo6 is not typed1179+ c.var.foo61180+ return c.json(0)1181+ })1182+1183+ new Hono<Env>()1184+ .get('/', mw1, mw2, mw3, mw4, mw5, mw6, mw7, (c) => {1185+ expectTypeOf(c.get('init')).toEqualTypeOf<number>()1186+ expectTypeOf(c.var.init).toEqualTypeOf<number>()1187+ expectTypeOf(c.get('foo1')).toEqualTypeOf<string>()1188+ expectTypeOf(c.var.foo1).toEqualTypeOf<string>()1189+ expectTypeOf(c.get('foo2')).toEqualTypeOf<string>()1190+ expectTypeOf(c.var.foo2).toEqualTypeOf<string>()1191+ expectTypeOf(c.get('foo3')).toEqualTypeOf<string>()1192+ expectTypeOf(c.var.foo3).toEqualTypeOf<string>()1193+ expectTypeOf(c.get('foo4')).toEqualTypeOf<string>()1194+ expectTypeOf(c.var.foo4).toEqualTypeOf<string>()1195+ expectTypeOf(c.get('foo5')).toEqualTypeOf<string>()1196+ expectTypeOf(c.var.foo5).toEqualTypeOf<string>()1197+ expectTypeOf(c.get('foo6')).toEqualTypeOf<string>()1198+ expectTypeOf(c.var.foo6).toEqualTypeOf<string>()1199+ expectTypeOf(c.get('foo7')).toEqualTypeOf<string>()1200+ expectTypeOf(c.var.foo7).toEqualTypeOf<string>()1201+ return c.json(0)1202+ })1203+ .get('/', (c) => {1204+ expectTypeOf(c.get('init')).toEqualTypeOf<number>()1205+ expectTypeOf(c.var.init).toEqualTypeOf<number>()1206+ // @ts-expect-error foo1 is not typed1207+ c.get('foo1')1208+ // @ts-expect-error foo1 is not typed1209+ c.var.foo11210+ // @ts-expect-error foo2 is not typed1211+ c.get('foo2')1212+ // @ts-expect-error foo2 is not typed1213+ c.var.foo21214+ // @ts-expect-error foo3 is not typed1215+ c.get('foo3')1216+ // @ts-expect-error foo3 is not typed1217+ c.var.foo31218+ // @ts-expect-error foo4 is not typed1219+ c.get('foo4')1220+ // @ts-expect-error foo4 is not typed1221+ c.var.foo41222+ // @ts-expect-error foo5 is not typed1223+ c.get('foo5')1224+ // @ts-expect-error foo5 is not typed1225+ c.var.foo51226+ // @ts-expect-error foo6 is not typed1227+ c.get('foo6')1228+ // @ts-expect-error foo6 is not typed1229+ c.var.foo61230+ // @ts-expect-error foo7 is not typed1231+ c.get('foo7')1232+ // @ts-expect-error foo7 is not typed1233+ c.var.foo71234+ return c.json(0)1235+ })1236+1237+ new Hono<Env>()1238+ .get('/', mw1, mw2, mw3, mw4, mw5, mw6, mw7, mw8, (c) => {1239+ expectTypeOf(c.get('init')).toEqualTypeOf<number>()1240+ expectTypeOf(c.var.init).toEqualTypeOf<number>()1241+ expectTypeOf(c.get('foo1')).toEqualTypeOf<string>()1242+ expectTypeOf(c.var.foo1).toEqualTypeOf<string>()1243+ expectTypeOf(c.get('foo2')).toEqualTypeOf<string>()1244+ expectTypeOf(c.var.foo2).toEqualTypeOf<string>()1245+ expectTypeOf(c.get('foo3')).toEqualTypeOf<string>()1246+ expectTypeOf(c.var.foo3).toEqualTypeOf<string>()1247+ expectTypeOf(c.get('foo4')).toEqualTypeOf<string>()1248+ expectTypeOf(c.var.foo4).toEqualTypeOf<string>()1249+ expectTypeOf(c.get('foo5')).toEqualTypeOf<string>()1250+ expectTypeOf(c.var.foo5).toEqualTypeOf<string>()1251+ expectTypeOf(c.get('foo6')).toEqualTypeOf<string>()1252+ expectTypeOf(c.var.foo6).toEqualTypeOf<string>()1253+ expectTypeOf(c.get('foo7')).toEqualTypeOf<string>()1254+ expectTypeOf(c.var.foo7).toEqualTypeOf<string>()1255+ expectTypeOf(c.get('foo8')).toEqualTypeOf<string>()1256+ expectTypeOf(c.var.foo8).toEqualTypeOf<string>()1257+ return c.json(0)1258+ })1259+ .get('/', (c) => {1260+ expectTypeOf(c.get('init')).toEqualTypeOf<number>()1261+ expectTypeOf(c.var.init).toEqualTypeOf<number>()1262+ // @ts-expect-error foo1 is not typed1263+ c.get('foo1')1264+ // @ts-expect-error foo1 is not typed1265+ c.var.foo11266+ // @ts-expect-error foo2 is not typed1267+ c.get('foo2')1268+ // @ts-expect-error foo2 is not typed1269+ c.var.foo21270+ // @ts-expect-error foo3 is not typed1271+ c.get('foo3')1272+ // @ts-expect-error foo3 is not typed1273+ c.var.foo31274+ // @ts-expect-error foo4 is not typed1275+ c.get('foo4')1276+ // @ts-expect-error foo4 is not typed1277+ c.var.foo41278+ // @ts-expect-error foo5 is not typed1279+ c.get('foo5')1280+ // @ts-expect-error foo5 is not typed1281+ c.var.foo51282+ // @ts-expect-error foo6 is not typed1283+ c.get('foo6')1284+ // @ts-expect-error foo6 is not typed1285+ c.var.foo61286+ // @ts-expect-error foo7 is not typed1287+ c.get('foo7')1288+ // @ts-expect-error foo7 is not typed1289+ c.var.foo71290+ // @ts-expect-error foo8 is not typed1291+ c.get('foo8')1292+ // @ts-expect-error foo8 is not typed1293+ c.var.foo81294+ return c.json(0)1295+ })1296+1297+ new Hono<Env>()1298+ .get('/', mw1, mw2, mw3, mw4, mw5, mw6, mw7, mw8, mw9, (c) => {1299+ expectTypeOf(c.get('init')).toEqualTypeOf<number>()1300+ expectTypeOf(c.var.init).toEqualTypeOf<number>()1301+ expectTypeOf(c.get('foo1')).toEqualTypeOf<string>()1302+ expectTypeOf(c.var.foo1).toEqualTypeOf<string>()1303+ expectTypeOf(c.get('foo2')).toEqualTypeOf<string>()1304+ expectTypeOf(c.var.foo2).toEqualTypeOf<string>()1305+ expectTypeOf(c.get('foo3')).toEqualTypeOf<string>()1306+ expectTypeOf(c.var.foo3).toEqualTypeOf<string>()1307+ expectTypeOf(c.get('foo4')).toEqualTypeOf<string>()1308+ expectTypeOf(c.var.foo4).toEqualTypeOf<string>()1309+ expectTypeOf(c.get('foo5')).toEqualTypeOf<string>()1310+ expectTypeOf(c.var.foo5).toEqualTypeOf<string>()1311+ expectTypeOf(c.get('foo6')).toEqualTypeOf<string>()1312+ expectTypeOf(c.var.foo6).toEqualTypeOf<string>()1313+ expectTypeOf(c.get('foo7')).toEqualTypeOf<string>()1314+ expectTypeOf(c.var.foo7).toEqualTypeOf<string>()1315+ expectTypeOf(c.get('foo8')).toEqualTypeOf<string>()1316+ expectTypeOf(c.var.foo8).toEqualTypeOf<string>()1317+ expectTypeOf(c.get('foo9')).toEqualTypeOf<string>()1318+ expectTypeOf(c.var.foo9).toEqualTypeOf<string>()1319+ return c.json(0)1320+ })1321+ .get('/', (c) => {1322+ expectTypeOf(c.get('init')).toEqualTypeOf<number>()1323+ expectTypeOf(c.var.init).toEqualTypeOf<number>()1324+ // @ts-expect-error foo1 is not typed1325+ c.get('foo1')1326+ // @ts-expect-error foo1 is not typed1327+ c.var.foo11328+ // @ts-expect-error foo2 is not typed1329+ c.get('foo2')1330+ // @ts-expect-error foo2 is not typed1331+ c.var.foo21332+ // @ts-expect-error foo3 is not typed1333+ c.get('foo3')1334+ // @ts-expect-error foo3 is not typed1335+ c.var.foo31336+ // @ts-expect-error foo4 is not typed1337+ c.get('foo4')1338+ // @ts-expect-error foo4 is not typed1339+ c.var.foo41340+ // @ts-expect-error foo5 is not typed1341+ c.get('foo5')1342+ // @ts-expect-error foo5 is not typed1343+ c.var.foo51344+ // @ts-expect-error foo6 is not typed1345+ c.get('foo6')1346+ // @ts-expect-error foo6 is not typed1347+ c.var.foo61348+ // @ts-expect-error foo7 is not typed1349+ c.get('foo7')1350+ // @ts-expect-error foo7 is not typed1351+ c.var.foo71352+ // @ts-expect-error foo8 is not typed1353+ c.get('foo8')1354+ // @ts-expect-error foo8 is not typed1355+ c.var.foo81356+ // @ts-expect-error foo9 is not typed1357+ c.get('foo9')1358+ // @ts-expect-error foo9 is not typed1359+ c.var.foo91360+ return c.json(0)1361+ })1362 })1363 })1364 1365 /**30 unmodified lines1396 '/',1397 validator('json', (v) => v),1398 async (c) => {1399 expectTypeOf(c.get('testVar')).toEqualTypeOf<string>()1113- return c.jsonT({ success: true })1400+ return c.json({ success: true })1401 }1402 )1403 .patch(1404 '/',1405 validator('json', (v) => v),1406 async (c) => {1407 expectTypeOf(c.get('testVar')).toEqualTypeOf<string>()1121- return c.jsonT({ success: true })1408+ return c.json({ success: true })1409 }1410 )1411 })1412 })23 unmodified linesmodified:src/types.ts+70 added-92 removed
1 unmodified line2 /* eslint-disable @typescript-eslint/no-explicit-any */3 /* eslint-disable @typescript-eslint/ban-types */4 import type { Context } from './context'5 import type { Hono } from './hono'6-import type { IntersectNonAnyTypes, RemoveBlankRecord, UnionToIntersection } from './utils/types'6+import type { IfAnyThenEmptyObject, RemoveBlankRecord, UnionToIntersection } from './utils/types'7 8 ////////////////////////////////////////9 ////// //////10 ////// Values //////14 unmodified lines25 in?: Partial<ValidationTargets>26 out?: Partial<{ [K in keyof ValidationTargets]: unknown }>27 }28 29+export type BlankSchema = {}30+export type BlankInput = {}31+32 ////////////////////////////////////////33 ////// //////34 ////// Routes //////35 ////// //////15 unmodified lines51 52 export type Handler<53 E extends Env = any,54 P extends string = any,52- I extends Input = Input,55+ I extends Input = BlankInput,56 R extends HandlerResponse<any> = any57 > = (c: Context<E, P, I>, next: Next) => R58 59 export type MiddlewareHandler<4 unmodified lines64 65 export type H<66 E extends Env = any,67 P extends string = any,65- I extends Input = {},68+ I extends Input = BlankInput,69 R extends HandlerResponse<any> = any70 > = Handler<E, P, I, R> | MiddlewareHandler<E, P, I>71 72 export type NotFoundHandler<E extends Env = any> = (c: Context<E>) => Response | Promise<Response>18 unmodified lines91 92 // app.get(handler)93 <94 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,92- I extends Input = {},95+ I extends Input = BlankInput,96 R extends HandlerResponse<any> = any,97 E2 extends Env = E98 >(99 handler: H<E2, P, I, R>5 unmodified lines105 106 // app.get(handler x2)107 <108 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,106- I extends Input = {},109+ I extends Input = BlankInput,110 I2 extends Input = I,111 R extends HandlerResponse<any> = any,112 E2 extends Env = E,113 E3 extends Env = IntersectNonAnyTypes<[E, E2]>8 unmodified lines122 // app.get(handler x 3)123 <124 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,125 R extends HandlerResponse<any> = any,123- I extends Input = {},126+ I extends Input = BlankInput,127 I2 extends Input = I,128 I3 extends Input = I & I2,129 E2 extends Env = E,130 E3 extends Env = E,9 unmodified lines140 // app.get(handler x 4)141 <142 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,143 R extends HandlerResponse<any> = any,141- I extends Input = {},144+ I extends Input = BlankInput,145 I2 extends Input = I,146 I3 extends Input = I & I2,147 I4 extends Input = I & I2 & I3,148 E2 extends Env = E,11 unmodified lines160 // app.get(handler x 5)161 <162 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,163 R extends HandlerResponse<any> = any,161- I extends Input = {},164+ I extends Input = BlankInput,165 I2 extends Input = I,166 I3 extends Input = I & I2,167 I4 extends Input = I & I2 & I3,168 I5 extends Input = I & I2 & I3 & I4,13 unmodified lines182 // app.get(handler x 6)183 <184 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,185 R extends HandlerResponse<any> = any,183- I extends Input = {},186+ I extends Input = BlankInput,187 I2 extends Input = I,188 I3 extends Input = I & I2,189 I4 extends Input = I & I2 & I3,190 I5 extends Input = I & I2 & I3 & I4,22 unmodified lines213 // app.get(handler x 7)214 <215 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,216 R extends HandlerResponse<any> = any,214- I extends Input = {},217+ I extends Input = BlankInput,218 I2 extends Input = I,219 I3 extends Input = I & I2,220 I4 extends Input = I & I2 & I3,221 I5 extends Input = I & I2 & I3 & I4,25 unmodified lines247 // app.get(handler x 8)248 <249 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,250 R extends HandlerResponse<any> = any,248- I extends Input = {},251+ I extends Input = BlankInput,252 I2 extends Input = I,253 I3 extends Input = I & I2,254 I4 extends Input = I & I2 & I3,255 I5 extends Input = I & I2 & I3 & I4,28 unmodified lines284 // app.get(handler x 9)285 <286 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,287 R extends HandlerResponse<any> = any,285- I extends Input = {},288+ I extends Input = BlankInput,289 I2 extends Input = I,290 I3 extends Input = I & I2,291 I4 extends Input = I & I2 & I3,292 I5 extends Input = I & I2 & I3 & I4,31 unmodified lines324 // app.get(handler x 10)325 <326 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,327 R extends HandlerResponse<any> = any,325- I extends Input = {},328+ I extends Input = BlankInput,329 I2 extends Input = I,330 I3 extends Input = I & I2,331 I4 extends Input = I & I2 & I3,332 I5 extends Input = I & I2 & I3 & I4,33 unmodified lines366 367 // app.get(...handlers[])368 <369 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,367- I extends Input = {},370+ I extends Input = BlankInput,371 R extends HandlerResponse<any> = any372 >(373 ...handlers: H<E, P, I, R>[]374 ): Hono<E, S & ToSchema<M, P, I['in'], MergeTypedResponseData<R>>, BasePath>13 unmodified lines388 <389 P extends string,390 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,391 R extends HandlerResponse<any> = any,389- I extends Input = {},392+ I extends Input = BlankInput,393 E2 extends Env = E394 >(395 path: P,396 handler: H<E2, MergedPath, I, R>394- ): Hono<395- IntersectNonAnyTypes<[E, E2]>,396- S & ToSchema<M, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>,397- BasePath398- >397+ ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>, BasePath>398 399 // app.get(path, handler x2)400 <401 P extends string,402 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,403 R extends HandlerResponse<any> = any,405- I extends Input = {},404+ I extends Input = BlankInput,405 I2 extends Input = I,406 E2 extends Env = E,407 E3 extends Env = IntersectNonAnyTypes<[E, E2]>408 >(409 path: P,410 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2, R>]412- ): Hono<413- IntersectNonAnyTypes<[E, E2, E3]>,414- S & ToSchema<M, MergePath<BasePath, P>, I2['in'], MergeTypedResponseData<R>>,415- BasePath416- >411+ ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I2['in'], MergeTypedResponseData<R>>, BasePath>412 413 // app.get(path, handler x3)414 <415 P extends string,416 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,417 R extends HandlerResponse<any> = any,423- I extends Input = {},418+ I extends Input = BlankInput,419 I2 extends Input = I,420 I3 extends Input = I & I2,421 E2 extends Env = E,422 E3 extends Env = E,423 E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>424 >(425 path: P,426 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2>, H<E4, MergedPath, I3, R>]432- ): Hono<433- IntersectNonAnyTypes<[E, E2, E3, E4]>,434- S & ToSchema<M, MergePath<BasePath, P>, I3['in'], MergeTypedResponseData<R>>,435- BasePath436- >427+ ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I3['in'], MergeTypedResponseData<R>>, BasePath>428 429 // app.get(path, handler x4)430 <431 P extends string,432 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,433 R extends HandlerResponse<any> = any,443- I extends Input = {},434+ I extends Input = BlankInput,435 I2 extends Input = I,436 I3 extends Input = I & I2,437 I4 extends Input = I & I2 & I3,438 E2 extends Env = E,7 unmodified lines446 H<E3, MergedPath, I2>,447 H<E4, MergedPath, I3>,448 H<E5, MergedPath, I4, R>449 ]459- ): Hono<460- IntersectNonAnyTypes<[E, E2, E3, E4, E5]>,461- S & ToSchema<M, MergePath<BasePath, P>, I4['in'], MergeTypedResponseData<R>>,462- BasePath463- >450+ ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I4['in'], MergeTypedResponseData<R>>, BasePath>451 452 // app.get(path, handler x5)453 <454 P extends string,455 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,456 R extends HandlerResponse<any> = any,470- I extends Input = {},457+ I extends Input = BlankInput,458 I2 extends Input = I,459 I3 extends Input = I & I2,460 I4 extends Input = I & I2 & I3,461 I5 extends Input = I & I2 & I3 & I4,10 unmodified lines472 H<E4, MergedPath, I3>,473 H<E5, MergedPath, I4>,474 H<E6, MergedPath, I5, R>475 ]489- ): Hono<490- IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>,491- S & ToSchema<M, MergePath<BasePath, P>, I5['in'], MergeTypedResponseData<R>>,492- BasePath493- >476+ ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I5['in'], MergeTypedResponseData<R>>, BasePath>477 478 // app.get(path, handler x6)479 <480 P extends string,481 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,482 R extends HandlerResponse<any> = any,500- I extends Input = {},483+ I extends Input = BlankInput,484 I2 extends Input = I,485 I3 extends Input = I & I2,486 I4 extends Input = I & I2 & I3,487 I5 extends Input = I & I2 & I3 & I4,13 unmodified lines501 H<E5, MergedPath, I4>,502 H<E6, MergedPath, I5>,503 H<E7, MergedPath, I6, R>504 ]522- ): Hono<523- IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>,524- S & ToSchema<M, MergePath<BasePath, P>, I6['in'], MergeTypedResponseData<R>>,525- BasePath526- >505+ ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I6['in'], MergeTypedResponseData<R>>, BasePath>506 507 // app.get(path, handler x7)508 <509 P extends string,510 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,511 R extends HandlerResponse<any> = any,533- I extends Input = {},512+ I extends Input = BlankInput,513 I2 extends Input = I,514 I3 extends Input = I & I2,515 I4 extends Input = I & I2 & I3,516 I5 extends Input = I & I2 & I3 & I4,16 unmodified lines533 H<E6, MergedPath, I5>,534 H<E7, MergedPath, I6>,535 H<E8, MergedPath, I7, R>536 ]558- ): Hono<559- IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>,560- S & ToSchema<M, MergePath<BasePath, P>, I7['in'], MergeTypedResponseData<R>>,561- BasePath562- >537+ ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I7['in'], MergeTypedResponseData<R>>, BasePath>538 539 // app.get(path, handler x8)540 <541 P extends string,542 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,543 R extends HandlerResponse<any> = any,569- I extends Input = {},544+ I extends Input = BlankInput,545 I2 extends Input = I,546 I3 extends Input = I & I2,547 I4 extends Input = I & I2 & I3,548 I5 extends Input = I & I2 & I3 & I4,19 unmodified lines568 H<E7, MergedPath, I6>,569 H<E8, MergedPath, I7>,570 H<E9, MergedPath, I8, R>571 ]597- ): Hono<598- IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>,599- S & ToSchema<M, MergePath<BasePath, P>, I8['in'], MergeTypedResponseData<R>>,600- BasePath601- >572+ ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I8['in'], MergeTypedResponseData<R>>, BasePath>573 574 // app.get(path, handler x9)575 <576 P extends string,577 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,578 R extends HandlerResponse<any> = any,608- I extends Input = {},579+ I extends Input = BlankInput,580 I2 extends Input = I,581 I3 extends Input = I & I2,582 I4 extends Input = I & I2 & I3,583 I5 extends Input = I & I2 & I3 & I4,22 unmodified lines606 H<E8, MergedPath, I7>,607 H<E9, MergedPath, I8>,608 H<E10, MergedPath, I9, R>609 ]639- ): Hono<640- IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>,641- S & ToSchema<M, MergePath<BasePath, P>, I9['in'], MergeTypedResponseData<R>>,642- BasePath643- >610+ ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I9['in'], MergeTypedResponseData<R>>, BasePath>611 612 // app.get(path, handler x10)613 <614 P extends string,615 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,616 R extends HandlerResponse<any> = any,650- I extends Input = {},617+ I extends Input = BlankInput,618 I2 extends Input = I,619 I3 extends Input = I & I2,620 I4 extends Input = I & I2 & I3,621 I5 extends Input = I & I2 & I3 & I4,26 unmodified lines648 H<E10, MergedPath, I9>,649 H<E11, MergedPath, I10, R>650 ]651 ): Hono<685- IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11]>,652+ E,653 S & ToSchema<M, MergePath<BasePath, P>, I10['in'], MergeTypedResponseData<R>>,654 BasePath655 >656 657 // app.get(path, ...handlers[])691- <P extends string, I extends Input = {}, R extends HandlerResponse<any> = any>(658+ <P extends string, I extends Input = BlankInput, R extends HandlerResponse<any> = any>(659 path: P,660 ...handlers: H<E, MergePath<BasePath, P>, I, R>[]661 ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>, BasePath>662 }217 unmodified lines880 M extends string,881 P extends string,882 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,883 R extends HandlerResponse<any> = any,917- I extends Input = {},884+ I extends Input = BlankInput,885 E2 extends Env = E886 >(887 method: M,888 path: P,9 unmodified lines898 M extends string,899 P extends string,900 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,901 R extends HandlerResponse<any> = any,935- I extends Input = {},902+ I extends Input = BlankInput,903 I2 extends Input = I,904 E2 extends Env = E,905 E3 extends Env = IntersectNonAnyTypes<[E, E2]>906 >(11 unmodified lines918 M extends string,919 P extends string,920 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,921 R extends HandlerResponse<any> = any,955- I extends Input = {},922+ I extends Input = BlankInput,923 I2 extends Input = I,924 I3 extends Input = I & I2,925 E2 extends Env = E,926 E3 extends Env = E,13 unmodified lines940 M extends string,941 P extends string,942 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,943 R extends HandlerResponse<any> = any,977- I extends Input = {},944+ I extends Input = BlankInput,945 I2 extends Input = I,946 I3 extends Input = I & I2,947 I4 extends Input = I & I2 & I3,948 E2 extends Env = E,20 unmodified lines969 M extends string,970 P extends string,971 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,972 R extends HandlerResponse<any> = any,1006- I extends Input = {},973+ I extends Input = BlankInput,974 I2 extends Input = I,975 I3 extends Input = I & I2,976 I4 extends Input = I & I2 & I3,977 I5 extends Input = I & I2 & I3 & I4,23 unmodified lines1001 M extends string,1002 P extends string,1003 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1004 R extends HandlerResponse<any> = any,1038- I extends Input = {},1005+ I extends Input = BlankInput,1006 I2 extends Input = I,1007 I3 extends Input = I & I2,1008 I4 extends Input = I & I2 & I3,1009 I5 extends Input = I & I2 & I3 & I4,26 unmodified lines1036 M extends string,1037 P extends string,1038 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1039 R extends HandlerResponse<any> = any,1073- I extends Input = {},1040+ I extends Input = BlankInput,1041 I2 extends Input = I,1042 I3 extends Input = I & I2,1043 I4 extends Input = I & I2 & I3,1044 I5 extends Input = I & I2 & I3 & I4,29 unmodified lines1074 M extends string,1075 P extends string,1076 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1077 R extends HandlerResponse<any> = any,1111- I extends Input = {},1078+ I extends Input = BlankInput,1079 I2 extends Input = I,1080 I3 extends Input = I & I2,1081 I4 extends Input = I & I2 & I3,1082 I5 extends Input = I & I2 & I3 & I4,32 unmodified lines1115 M extends string,1116 P extends string,1117 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1118 R extends HandlerResponse<any> = any,1152- I extends Input = {},1119+ I extends Input = BlankInput,1120 I2 extends Input = I,1121 I3 extends Input = I & I2,1122 I4 extends Input = I & I2 & I3,1123 I5 extends Input = I & I2 & I3 & I4,34 unmodified lines1158 <1159 M extends string,1160 P extends string,1161 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1195- I extends Input = {},1162+ I extends Input = BlankInput,1163 I2 extends Input = I,1164 I3 extends Input = I & I2,1165 I4 extends Input = I & I2 & I3,1166 I5 extends Input = I & I2 & I3 & I4,46 unmodified lines1213 Ms extends string[],1214 P extends string,1215 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1216 R extends HandlerResponse<any> = any,1250- I extends Input = {},1217+ I extends Input = BlankInput,1218 E2 extends Env = E1219 >(1220 methods: Ms,1221 path: P,9 unmodified lines1231 Ms extends string[],1232 P extends string,1233 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1234 R extends HandlerResponse<any> = any,1268- I extends Input = {},1235+ I extends Input = BlankInput,1236 I2 extends Input = I,1237 E2 extends Env = E,1238 E3 extends Env = IntersectNonAnyTypes<[E, E2]>1239 >(11 unmodified lines1251 Ms extends string[],1252 P extends string,1253 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1254 R extends HandlerResponse<any> = any,1288- I extends Input = {},1255+ I extends Input = BlankInput,1256 I2 extends Input = I,1257 I3 extends Input = I & I2,1258 E2 extends Env = E,1259 E3 extends Env = E,13 unmodified lines1273 Ms extends string[],1274 P extends string,1275 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1276 R extends HandlerResponse<any> = any,1310- I extends Input = {},1277+ I extends Input = BlankInput,1278 I2 extends Input = I,1279 I3 extends Input = I & I2,1280 I4 extends Input = I & I2 & I3,1281 E2 extends Env = E,20 unmodified lines1302 Ms extends string[],1303 P extends string,1304 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1305 R extends HandlerResponse<any> = any,1339- I extends Input = {},1306+ I extends Input = BlankInput,1307 I2 extends Input = I,1308 I3 extends Input = I & I2,1309 I4 extends Input = I & I2 & I3,1310 I5 extends Input = I & I2 & I3 & I4,23 unmodified lines1334 Ms extends string[],1335 P extends string,1336 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1337 R extends HandlerResponse<any> = any,1371- I extends Input = {},1338+ I extends Input = BlankInput,1339 I2 extends Input = I,1340 I3 extends Input = I & I2,1341 I4 extends Input = I & I2 & I3,1342 I5 extends Input = I & I2 & I3 & I4,26 unmodified lines1369 Ms extends string[],1370 P extends string,1371 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1372 R extends HandlerResponse<any> = any,1406- I extends Input = {},1373+ I extends Input = BlankInput,1374 I2 extends Input = I,1375 I3 extends Input = I & I2,1376 I4 extends Input = I & I2 & I3,1377 I5 extends Input = I & I2 & I3 & I4,29 unmodified lines1407 Ms extends string[],1408 P extends string,1409 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1410 R extends HandlerResponse<any> = any,1444- I extends Input = {},1411+ I extends Input = BlankInput,1412 I2 extends Input = I,1413 I3 extends Input = I & I2,1414 I4 extends Input = I & I2 & I3,1415 I5 extends Input = I & I2 & I3 & I4,31 unmodified lines1447 <1448 Ms extends string[],1449 P extends string,1450 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1484- I extends Input = {},1451+ I extends Input = BlankInput,1452 I2 extends Input = I,1453 I3 extends Input = I & I2,1454 I4 extends Input = I & I2 & I3,1455 I5 extends Input = I & I2 & I3 & I4,40 unmodified lines1496 <1497 Ms extends string[],1498 P extends string,1499 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1533- I extends Input = {},1500+ I extends Input = BlankInput,1501 I2 extends Input = I,1502 I3 extends Input = I & I2,1503 I4 extends Input = I & I2 & I3,1504 I5 extends Input = I & I2 & I3 & I4,48 unmodified lines1553 E,1554 S & ToSchema<string, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>,1555 BasePath1556 >1557+1558+ // app.on(method | method[], path[], ...handlers[])1559+ <I extends Input = BlankInput, R extends HandlerResponse<any> = any>(1560+ methods: string | string[],1561+ paths: string[],1562+ ...handlers: H<E, any, I, R>[]1563+ ): Hono<E, S & ToSchema<string, string, I['in'], MergeTypedResponseData<R>>, BasePath>1564 }1565 1566 type ExtractKey<S> = S extends Record<infer Key, unknown>1567 ? Key extends string109 unmodified lines1677 export type ValidationTargets = {1678 json: any1679 form: Record<string, string | File>1680 query: Record<string, string | string[]>1707- queries: Record<string, string[]> // Deprecated. Will be obsolete in v4.1681 param: Record<string, string>1682 header: Record<string, string>1683 cookie: Record<string, string>1684 }50 unmodified lines1735 export type ExtractSchema<T> = UnionToIntersection<1736 T extends Hono<infer _, infer S, any> ? S : never1737 >1738 1739+type EnvOrEmpty<T> = T extends Env ? (Env extends T ? {} : T) : T1740+type IntersectNonAnyTypes<T extends any[]> = T extends [infer Head, ...infer Rest]1741+ ? IfAnyThenEmptyObject<EnvOrEmpty<Head>> & IntersectNonAnyTypes<Rest>1742+ : {}1743+1744 ////////////////////////////////////////1745 ////// //////1746 ////// FetchEvent //////1747 ////// //////8 unmodified linesmodified:.gitignore-3 removed
3 unmodified lines4 # Cloudflare Workers5 worker6 .wrangler7 8-# Bun9-bun.lockb10-8 # Logs9 logs10 *.log11 npm-debug.log*125 unmodified linesadded:bun.lockbbinary
A binary file, added.
added:bunfig.toml+2 added
1+[install.lockfile]2+print = "yarn"modified:package.json+59 added-28 removed
1 {2 "name": "hono",3- "version": "3.12.12",3+ "version": "4.0.0-rc.4",4 "description": "Ultrafast web framework for the Edges",5 "main": "dist/cjs/index.js",6 "type": "module",7 "module": "dist/index.js",1 unmodified line9 "files": [10 "dist"11 ],12 "scripts": {13- "test": "tsc --noEmit && vitest --run",13+ "test": "tsc --noEmit && vitest --run && vitest -c .vitest.config/jsx-runtime-default.ts --run && vitest -c .vitest.config/jsx-runtime-dom.ts --run",14 "test:watch": "vitest --watch",15- "test:deno": "deno test --allow-read --allow-env runtime_tests/deno && deno test --no-lock -c runtime_tests/deno-jsx/deno.precompile.json runtime_tests/deno-jsx && deno test --no-lock -c runtime_tests/deno-jsx/deno.react-jsx.json runtime_tests/deno-jsx",15+ "test:deno": "deno test --allow-read --allow-env --allow-write -c runtime_tests/deno/deno.json runtime_tests/deno && deno test --no-lock -c runtime_tests/deno-jsx/deno.precompile.json runtime_tests/deno-jsx && deno test --no-lock -c runtime_tests/deno-jsx/deno.react-jsx.json runtime_tests/deno-jsx",16 "test:bun": "bun test --jsx-import-source ../../src/jsx runtime_tests/bun/index.test.tsx",17 "test:fastly": "vitest --run --config ./runtime_tests/fastly/vitest.config.ts",18- "test:lagon": "start-server-and-test \"lagon dev runtime_tests/lagon/index.ts -e runtime_tests/lagon/.env.lagon\" http://127.0.0.1:1234 \"yarn vitest --run runtime_tests/lagon/index.test.ts --config runtime_tests/lagon/vitest.config.ts\"",18 "test:node": "vitest --run --config ./runtime_tests/node/vitest.config.ts",19 "test:wrangler": "vitest --run --config ./runtime_tests/wrangler/vitest.config.ts",20 "test:lambda": "vitest --run --config ./runtime_tests/lambda/vitest.config.ts",21 "test:lambda-edge": "vitest --run --config ./runtime_tests/lambda-edge/vitest.config.ts",23- "test:all": "yarn test && yarn test:deno && yarn test:bun && yarn test:fastly && yarn test:lagon && yarn test:node && yarn test:wrangler && yarn test:lambda && yarn test:lambda-edge",24- "lint": "eslint --ext js,ts src runtime_tests",25- "lint:fix": "eslint --ext js,ts src runtime_tests --fix",26- "format": "prettier --check \"src/**/*.{js,ts}\" \"runtime_tests/**/*.{js,ts}\"",27- "format:fix": "prettier --write \"src/**/*.{js,ts}\" \"runtime_tests/**/*.{js,ts}\"",22+ "test:all": "bun run test && bun test:deno && bun test:bun && bun test:fastly && bun test:node && bun test:wrangler && bun test:lambda && bun test:lambda-edge",23+ "lint": "eslint --ext js,ts,tsx src runtime_tests",24+ "lint:fix": "eslint --ext js,ts,tsx src runtime_tests --fix",25+ "format": "prettier --check \"src/**/*.{js,ts,tsx}\" \"runtime_tests/**/*.{js,ts,tsx}\"",26+ "format:fix": "prettier --write \"src/**/*.{js,ts,tsx}\" \"runtime_tests/**/*.{js,ts,tsx}\"",27 "denoify": "rimraf deno_dist && denoify && rimraf \"deno_dist/**/*.test.{ts,tsx}\"",28 "copy:package.cjs.json": "cp ./package.cjs.json ./dist/cjs/package.json && cp ./package.cjs.json ./dist/types/package.json ",30- "build": "rimraf dist && tsx ./build.ts && yarn copy:package.cjs.json",29+ "build": "rimraf dist && tsx ./build.ts && bun run copy:package.cjs.json",30 "postbuild": "publint",32- "watch": "rimraf dist && tsx ./build.ts --watch && yarn copy:package.cjs.json",31+ "watch": "rimraf dist && tsx ./build.ts --watch && bun run copy:package.cjs.json",32 "coverage": "vitest --run --coverage",34- "prerelease": "yarn denoify && yarn test:deno && yarn build",33+ "prerelease": "bun denoify && bun test:deno && bun run build",34 "release": "np"35 },36 "exports": {37 ".": {45 unmodified lines83 "types": "./dist/types/helper/cookie/index.d.ts",84 "import": "./dist/helper/cookie/index.js",85 "require": "./dist/cjs/helper/cookie/index.js"86 },87+ "./accepts": {88+ "types": "./dist/types/helper/accepts/index.d.ts",89+ "import": "./dist/helper/accepts/index.js",90+ "require": "./dist/cjs/helper/accepts/index.js"91+ },92 "./compress": {93 "types": "./dist/types/middleware/compress/index.d.ts",94 "import": "./dist/middleware/compress/index.js",95 "require": "./dist/cjs/middleware/compress/index.js"47 unmodified lines143 "types": "./dist/types/middleware/jsx-renderer/index.d.ts",144 "import": "./dist/middleware/jsx-renderer/index.js",145 "require": "./dist/cjs/middleware/jsx-renderer/index.js"146 },147+ "./jsx/dom": {148+ "types": "./dist/types/jsx/dom/index.d.ts",149+ "import": "./dist/jsx/dom/index.js",150+ "require": "./dist/cjs/jsx/dom/index.js"151+ },152+ "./jsx/dom/jsx-dev-runtime": {153+ "types": "./dist/types/jsx/dom/jsx-dev-runtime.d.ts",154+ "import": "./dist/jsx/dom/jsx-dev-runtime.js",155+ "require": "./dist/cjs/jsx/dom/jsx-dev-runtime.js"156+ },157+ "./jsx/dom/jsx-runtime": {158+ "types": "./dist/types/jsx/dom/jsx-runtime.d.ts",159+ "import": "./dist/jsx/dom/jsx-runtime.js",160+ "require": "./dist/cjs/jsx/dom/jsx-runtime.js"161+ },162+ "./jsx/dom/css": {163+ "types": "./dist/types/jsx/dom/css.d.ts",164+ "import": "./dist/jsx/dom/css.js",165+ "require": "./dist/cjs/jsx/dom/css.js"166+ },167 "./jwt": {168 "types": "./dist/types/middleware/jwt/index.d.ts",169 "import": "./dist/middleware/jwt/index.js",170 "require": "./dist/cjs/middleware/jwt/index.js"22 unmodified lines193 "types": "./dist/types/middleware/secure-headers/index.d.ts",194 "import": "./dist/middleware/secure-headers/index.js",195 "require": "./dist/cjs/middleware/secure-headers/index.js"196 },197+ "./ssg": {198+ "types": "./dist/types/helper/ssg/index.d.ts",199+ "import": "./dist/helper/ssg/index.js",200+ "require": "./dist/cjs/helper/ssg/index.js"201+ },202 "./streaming": {203 "types": "./dist/types/helper/streaming/index.d.ts",204 "import": "./dist/helper/streaming/index.js",205 "require": "./dist/cjs/helper/streaming/index.js"77 unmodified lines283 "types": "./dist/types/adapter/bun/index.d.ts",284 "import": "./dist/adapter/bun/index.js",285 "require": "./dist/cjs/adapter/bun/index.js"286 },258- "./nextjs": {259- "types": "./dist/types/adapter/nextjs/index.d.ts",260- "import": "./dist/adapter/nextjs/index.js",261- "require": "./dist/cjs/adapter/nextjs/index.js"262- },287 "./aws-lambda": {288 "types": "./dist/types/adapter/aws-lambda/index.d.ts",289 "import": "./dist/adapter/aws-lambda/index.js",290 "require": "./dist/cjs/adapter/aws-lambda/index.js"52 unmodified lines343 ],344 "cookie": [345 "./dist/types/helper/cookie"346 ],347+ "accepts": [348+ "./dist/types/helper/accepts"349+ ],350 "compress": [351 "./dist/types/middleware/compress"352 ],353 "cors": [25 unmodified lines379 ],380 "jsx-renderer": [381 "./dist/types/middleware/jsx-renderer"382 ],383+ "jsx/dom": [384+ "./dist/types/jsx/dom"385+ ],386+ "jsx/dom/css": [387+ "./dist/types/jsx/dom/css.d.ts"388+ ],389 "jwt": [390 "./dist/types/middleware/jwt"391 ],392 "timing": [10 unmodified lines403 ],404 "streaming": [405 "./dist/types/helper/streaming"406 ],407+ "ssg": [408+ "./dist/types/helper/ssg"409+ ],410 "secure-headers": [411 "./dist/types/middleware/secure-headers"412 ],413 "validator": [87 unmodified lines501 "fastly",502 "compute@edge",503 "deno",504 "bun",469- "lagon",505 "lambda",506 "nodejs"507 ],508 "devDependencies": {2 unmodified lines511 "@hono/node-server": "^1.3.3",512 "@types/crypto-js": "^4.1.1",513 "@types/glob": "^8.0.0",514 "@types/jsdom": "^21.1.4",480- "@types/node": "^20.8.2",481- "@types/node-fetch": "^2.6.2",515+ "@types/node": "20.11.4",516 "@types/supertest": "^2.0.12",517 "@vitest/coverage-v8": "^1.1.0",518 "arg": "^5.0.2",519 "crypto-js": "^4.1.1",520 "denoify": "^1.6.6",521 "esbuild": "^0.15.12",522 "eslint": "^8.55.0",489- "form-data": "^4.0.0",523 "jsdom": "^22.1.0",491- "msw": "^1.0.0",492- "node-fetch": "2",493- "np": "^7.7.0",524+ "msw": "1.3.2",525+ "np": "7.7.0",526 "prettier": "^2.6.2",527 "publint": "^0.1.8",528 "rimraf": "^3.0.2",497- "start-server-and-test": "^1.15.2",529 "supertest": "^6.3.3",499- "tsx": "^3.11.0",530+ "tsx": "^4.7.0",531 "typescript": "^5.3.3",532 "vite-plugin-fastly-js-compute": "^0.4.2",502- "vitest": "^1.1.0",533+ "vitest": "^1.2.2",534 "wrangler": "3.17.1",535 "zod": "^3.20.2"536 },537 "engines": {538 "node": ">=16.0.0"539 }509-}540+}modified:README.md+2 added-2 removed
24 unmodified lines25 [](https://doc.deno.land/https/deno.land/x/hono/mod.ts)26 [](https://discord.gg/KMh2eNSdxV)27 28 Hono - _**\[炎\] means flame🔥 in Japanese**_ - is a small, simple, and ultrafast web framework for the Edges.29-It works on any JavaScript runtime: Cloudflare Workers, Fastly Compute, Deno, Bun, Vercel, Lagon, AWS Lambda, Lambda@Edge, and Node.js.29+It works on any JavaScript runtime: Cloudflare Workers, Fastly Compute, Deno, Bun, Vercel, AWS Lambda, Lambda@Edge, and Node.js.30 31 Fast, but not only fast.32 33 ```ts14 unmodified lines48 ## Features49 50 - **Ultrafast** 🚀 - The router `RegExpRouter` is really fast. Not using linear loops. Fast.51 - **Lightweight** 🪶 - The `hono/tiny` preset is under 14kB. Hono has zero dependencies and uses only the Web Standard API.52-- **Multi-runtime** 🌍 - Works on Cloudflare Workers, Fastly Compute, Deno, Bun, Lagon, AWS Lambda, Lambda@Edge, or Node.js. The same code runs on all platforms.52+- **Multi-runtime** 🌍 - Works on Cloudflare Workers, Fastly Compute, Deno, Bun, AWS Lambda, Lambda@Edge, or Node.js. The same code runs on all platforms.53 - **Batteries Included** 🔋 - Hono has built-in middleware, custom middleware, and third-party middleware. Batteries included.54 - **Delightful DX** 😃 - Super clean APIs. First-class TypeScript support. Now, we've got "Types".55 56 ## Benchmarks49 unmodified linesmodified:vitest.config.ts+1 added
9 unmodified lines10 coverage: {11 provider: 'v8',12 reporter: ['text'],13 },14+ pool: 'forks',15 },16 })modified:yarn.locknot shown
Its text is not shown, modified.