perf(types): add type annotations (#2663)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat(jsr): reduce slow types (#2369) * feat(jsr): reduce slow types * fix: use allow function * chore: format code * chore: denoify * use `fn = () => {}` syntax for backwards compatible * add type annotations and denoify * add type annotations for helpers and denoify * tweak ---------
authored by Yusuke Wada · committed by GitHub · parent 6db1cc6 · Browse files · 50 files·+228 added−114 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Shotaro Nakamura <79000684+nakasyou@users.noreply.github.com>
Diff stats
50 files+228 added−114 removed
- other:+228 added−114 removed
Provenance
- Commit
e5975ed- Tree
4fb940c- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
6db1cc6
50 files changed+228 added−114 removed
modified:deno_dist/helper/accepts/accepts.ts+3 added-3 removed
23 unmodified lines242526272828293031328 unmodified lines4142434445454647484910 unmodified lines606162636464656667685 unmodified lines23 unmodified linesexport interface acceptsOptions extends acceptsConfig { match?: (accepts: Accept[], config: acceptsConfig) => string}
export const parseAccept = (acceptHeader: string) => {export const parseAccept = (acceptHeader: string): Accept[] => { // Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 const accepts = acceptHeader.split(',') // ['text/html', 'application/xhtml+xml', 'application/xml;q=0.9', 'image/webp', '*/*;q=0.8'] return accepts.map((accept) => { const [type, ...params] = accept.trim().split(';') // ['application/xml', 'q=0.9']8 unmodified lines } })}
export const defaultMatch = (accepts: Accept[], config: acceptsConfig) => {export const defaultMatch = (accepts: Accept[], config: acceptsConfig): string => { const { supports, default: defaultSupport } = config const accept = accepts.sort((a, b) => b.q - a.q).find((accept) => supports.includes(accept.type)) return accept ? accept.type : defaultSupport}10 unmodified lines * }) * }) * ``` */export const accepts = (c: Context, options: acceptsOptions) => {export const accepts = (c: Context, options: acceptsOptions): string => { const acceptHeader = c.req.header(options.header) if (!acceptHeader) { return options.default }5 unmodified linesmodified:deno_dist/helper/adapter/index.ts+1 added-1 removed
28 unmodified lines2930313233333435363720 unmodified lines28 unmodified lines
return runtimeEnvHandlers[runtime]()}
export const getRuntimeKey = () => {export const getRuntimeKey = (): Runtime => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const global = globalThis as any
if (global?.Deno !== undefined) {20 unmodified linesmodified:deno_dist/helper/cookie/index.ts+1 added-1 removed
116 unmodified lines117 }118 c.header('set-cookie', cookie, { append: true })119 }120 121-export const deleteCookie = (c: Context, name: string, opt?: CookieOptions) => {121+export const deleteCookie = (c: Context, name: string, opt?: CookieOptions): string | undefined => {122 const deletedCookie = getCookie(c, name)123 setCookie(c, name, '', { ...opt, maxAge: 0 })124 return deletedCookie125 }modified:deno_dist/helper/css/common.ts+8 added-8 removed
1 unmodified line2 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()6+export const SELECTOR: unique symbol = Symbol()7+export const CLASS_NAME: unique symbol = Symbol()8+export const STYLE_STRING: unique symbol = Symbol()9+export const SELECTORS: unique symbol = Symbol()10+export const EXTERNAL_CLASS_NAMES: unique symbol = Symbol()11+const CSS_ESCAPED: unique symbol = Symbol()12 13 export interface CssClassName {14 [SELECTOR]: string15 [CLASS_NAME]: string32 unmodified lines48 }49 return 'css-' + out50 }51 52-const cssStringReStr = [52+const cssStringReStr: string = [53 '"(?:(?:\\\\[\\s\\S]|[^"\\\\])*)"', // double quoted string54 // eslint-disable-next-line quotes55 "'(?:(?:\\\\[\\s\\S]|[^'\\\\])*)'", // single quoted string56 ].join('|')57-const minifyCssRe = new RegExp(57+const minifyCssRe: RegExp = new RegExp(58 [59 '(' + cssStringReStr + ')', // $1: quoted string60 61 '(?:' +182 unmodified linesmodified:deno_dist/helper/css/index.ts+40 added-13 removed
22 unmodified lines23 Record<string, string>, // class name to add24 Record<string, true> // class name already added25 ]26 27+interface CssType {28+ (strings: TemplateStringsArray, ...values: CssVariableType[]): Promise<string>29+}30+31+interface CxType {32+ (33+ ...args: (CssClassName | Promise<string> | string | boolean | null | undefined)[]34+ ): Promise<string>35+}36+37+interface KeyframesType {38+ (strings: TemplateStringsArray, ...values: CssVariableType[]): CssClassNameCommon39+}40+41+interface ViewTransitionType {42+ (strings: TemplateStringsArray, ...values: CssVariableType[]): Promise<string>43+ (content: Promise<string>): Promise<string>44+ (): Promise<string>45+}46+47+interface StyleType {48+ (args?: { children?: Promise<string> }): HtmlEscapedString49+}50+51 /**52 * @experimental53 * `createCssContext` is an experimental feature.54 * The API might be changed.55 */32-export const createCssContext = ({ id }: { id: Readonly<string> }) => {56+export const createCssContext = ({ id }: { id: Readonly<string> }): DefaultContextType => {57 const [cssJsxDomObject, StyleRenderToDom] = createCssJsxDomObjects({ id })58 59 const contextMap: WeakMap<object, usedClassNameData> = new WeakMap()60 68 unmodified lines129 promise.toString = cssJsxDomObject.toString130 return promise131 }132 109- const css = (strings: TemplateStringsArray, ...values: CssVariableType[]): Promise<string> => {133+ const css: CssType = (strings, ...values) => {134 return newCssClassNameObject(cssCommon(strings, values))135 }136 113- const cx = (114- ...args: (CssClassName | Promise<string> | string | boolean | null | undefined)[]115- ): Promise<string> => {137+ const cx: CxType = (...args) => {138 // eslint-disable-next-line @typescript-eslint/no-explicit-any139 args = cxCommon(args as any) as any140 // eslint-disable-next-line @typescript-eslint/no-explicit-any141 return css(Array(args.length).fill('') as any, ...args)142 }143 144 const keyframes = keyframesCommon145 124- type ViewTransitionType = {125- (strings: TemplateStringsArray, ...values: CssVariableType[]): Promise<string>126- (content: Promise<string>): Promise<string>127- (): Promise<string>128- }146 const viewTransition: ViewTransitionType = ((147 strings: TemplateStringsArray | Promise<string> | undefined,148 ...values: CssVariableType[]132- ): Promise<string> => {149+ ) => {150 // eslint-disable-next-line @typescript-eslint/no-explicit-any151 return newCssClassNameObject(viewTransitionCommon(strings as any, values))152 }) as ViewTransitionType153 137- const Style = ({ children }: { children?: Promise<string> } = {}) =>154+ const Style: StyleType = ({ children } = {}) =>155 children156 ? raw(`<style id="${id}">${(children as unknown as CssClassName)[STYLE_STRING]}</style>`)157 : raw(`<style id="${id}"></style>`)158 // eslint-disable-next-line @typescript-eslint/no-explicit-any7 unmodified lines166 Style,167 }168 }169 153-const defaultContext = createCssContext({ id: DEFAULT_STYLE_ID })170+interface DefaultContextType {171+ css: CssType172+ cx: CxType173+ keyframes: KeyframesType174+ viewTransition: ViewTransitionType175+ Style: StyleType176+}177 178+const defaultContext: DefaultContextType = createCssContext({179+ id: DEFAULT_STYLE_ID,180+})181+182 /**183 * @experimental184 * `css` is an experimental feature.185 * The API might be changed.30 unmodified linesmodified:deno_dist/helper/dev/index.ts+2 added-2 removed
13 unmodified lines14 name: string15 isMiddleware: boolean16 }17 18-const handlerName = (handler: Function) => {18+const handlerName = (handler: Function): string => {19 return handler.name || (isMiddleware(handler) ? '[middleware]' : '[handler]')20 }21 22 export const inspectRoutes = <E extends Env>(hono: Hono<E>): RouteData[] => {44 unmodified lines67 })68 })69 }70 71-export const getRouterName = <E extends Env>(app: Hono<E>) => {71+export const getRouterName = <E extends Env>(app: Hono<E>): string => {72 app.router.match('GET', '/')73 return app.router.name74 }modified:deno_dist/helper/factory/index.ts+3 added-3 removed
214 unmodified lines215 /**216 * @experimental217 * `createApp` is an experimental feature.218 */219- createApp = () => {219+ createApp = (): Hono<E> => {220 const app = new Hono<E>()221 if (this.initApp) {222 this.initApp(app)223 }9 unmodified lines233 }234 235 export const createFactory = <E extends Env = any, P extends string = any>(init?: {236 initApp?: InitApp<E>237-}) => new Factory<E, P>(init)237+}): Factory<E, P> => new Factory<E, P>(init)238 239 export const createMiddleware = <E extends Env = any, P extends string = any, I extends Input = {}>(240 middleware: MiddlewareHandler<E, P, I>241-) => createFactory<E, P>().createMiddleware<I>(middleware)241+): MiddlewareHandler<E, P, I> => createFactory<E, P>().createMiddleware<I>(middleware)modified:deno_dist/helper/streaming/sse.ts+1 added-1 removed
60 unmodified lines61 export const streamSSE = (62 c: Context,63 cb: (stream: SSEStreamingApi) => Promise<void>,64 onError?: (e: Error, stream: SSEStreamingApi) => Promise<void>65-) => {65+): Response => {66 const { readable, writable } = new TransformStream()67 const stream = new SSEStreamingApi(writable, readable)68 69 c.header('Transfer-Encoding', 'chunked')8 unmodified linesmodified:deno_dist/helper/testing/index.ts+3 added-1 removed
1 import { hc } from '../../client/index.ts'2+import type { Client } from '../../client/types.ts'3 import type { ExecutionContext } from '../../context.ts'4 import type { Hono } from '../../hono.ts'5+import type { UnionToIntersection } from '../../utils/types.ts'6 7 // eslint-disable-next-line @typescript-eslint/no-explicit-any8 type ExtractEnv<T> = T extends Hono<infer E, any, any> ? E : never9 1 unmodified line11 export const testClient = <T extends Hono<any, any, any>>(12 app: T,13 Env?: ExtractEnv<T>['Bindings'] | {},14 executionCtx?: ExecutionContext13-) => {15+): UnionToIntersection<Client<T>> => {16 const customFetch = (input: RequestInfo | URL, init?: RequestInit) => {17 return app.request(input, init, Env, executionCtx)18 }19 2 unmodified linesmodified:deno_dist/jsx/dom/context.ts+1 added-1 removed
3 unmodified lines4 import { globalContexts } from '../context.ts'5 import { Fragment } from './jsx-runtime.ts'6 import { setInternalTagFlag } from './utils.ts'7 8-export const createContextProviderFunction = <T>(values: T[]) =>8+export const createContextProviderFunction = <T>(values: T[]): Function =>9 setInternalTagFlag(({ value, children }: { value: T; children: Child[] }) => {10 if (!children) {11 return undefined12 }42 unmodified linesmodified:deno_dist/jsx/dom/css.ts+10 added-1 removed
54 unmodified lines55 }56 return result57 }58 59+interface CreateCssJsxDomObjectsType {60+ (args: { id: Readonly<string> }): readonly [61+ {62+ toString(this: CssClassName): string63+ },64+ FC<PropsWithChildren<void>>65+ ]66+}67+59-export const createCssJsxDomObjects = ({ id }: { id: Readonly<string> }) => {68+export const createCssJsxDomObjects: CreateCssJsxDomObjectsType = ({ id }) => {69 let styleSheet: CSSStyleSheet | null | undefined = undefined70 const findStyleSheet = (): [CSSStyleSheet, Set<string>] | [] => {71 if (!styleSheet) {72 styleSheet = document.querySelector<HTMLStyleElement>(`style#${id}`)148 unmodified linesmodified:deno_dist/jsx/dom/jsx-dev-runtime.ts+1 added-1 removed
26 unmodified lines27 JSXNodeCompatPrototype28 ) as JSXNode29 }30 31-export const Fragment = (props: Record<string, unknown>) => jsxDEV('', props, undefined)31+export const Fragment = (props: Record<string, unknown>): JSXNode => jsxDEV('', props, undefined)modified:deno_dist/jsx/dom/utils.ts+1 added-1 removed
1 import { DOM_INTERNAL_TAG } from '../constants.ts'2 3-export const setInternalTagFlag = (fn: Function) => {3+export const setInternalTagFlag = (fn: Function): Function => {4 // eslint-disable-next-line @typescript-eslint/no-explicit-any5 ;(fn as any)[DOM_INTERNAL_TAG] = true6 return fn7 }modified:deno_dist/jsx/hooks/index.ts+4 added-1 removed
16 unmodified lines17 (() => void) | undefined, // cleanup18 (() => void) | undefined // effect19 ]20 21-const resolvedPromiseValueMap = new WeakMap<Promise<unknown>, unknown>()21+const resolvedPromiseValueMap: WeakMap<Promise<unknown>, unknown> = new WeakMap<22+ Promise<unknown>,23+ unknown24+>()25 26 const isDepsChanged = (27 prevDeps: readonly unknown[] | undefined,28 deps: readonly unknown[] | undefined394 unmodified linesmodified:deno_dist/jsx/jsx-runtime.ts+5 added-1 removed
1 export { jsxDEV as jsx, Fragment } from './jsx-dev-runtime.ts'2 export { jsxDEV as jsxs } from './jsx-dev-runtime.ts'3 4 import { raw, html } from '../helper/html/index.ts'5+import type { HtmlEscapedString } from '../utils/html.ts'6 export { html as jsxTemplate }6-export const jsxAttr = (name: string, value: string | Promise<string>) =>7+export const jsxAttr = (8+ name: string,9+ value: string | Promise<string>10+): HtmlEscapedString | Promise<HtmlEscapedString> =>11 typeof value === 'string' ? raw(name + '="' + html`${value}` + '"') : html`${name}="${value}"`12 export const jsxEscape = (value: string) => valuemodified:deno_dist/middleware/jsx-renderer/index.ts+3 added-1 removed
1 unmodified line2 import type { Context, PropsForRenderer } from '../../context.ts'3 import { html, raw } from '../../helper/html/index.ts'4 import { jsx, createContext, useContext, Fragment } from '../../jsx/index.ts'5 import type { FC, PropsWithChildren, JSXNode } from '../../jsx/index.ts'6+import type { Context as JSXContext } from '../../jsx/index.ts'7 import { renderToReadableStream } from '../../jsx/streaming.ts'8 import type { Env, Input, MiddlewareHandler } from '../../types.ts'9 import type { HtmlEscapedString } from '../../utils/html.ts'10 10-export const RequestContext = createContext<Context | null>(null)11+export const RequestContext: JSXContext<Context<any, any, {}> | null> =12+ createContext<Context | null>(null)13 14 type RendererOptions = {15 docType?: boolean | string16 stream?: boolean | Record<string, string>79 unmodified linesmodified:deno_dist/middleware/timing/index.ts+1 added-1 removed
22 unmodified lines23 autoEnd: boolean24 crossOrigin: boolean | string | ((c: Context) => boolean | string)25 }26 27-const getTime = () => {27+const getTime = (): number => {28 try {29 return performance.now()30 } catch {}31 return Date.now()108 unmodified linesmodified:deno_dist/router/smart-router/router.ts+1 added-1 removed
57 unmodified lines58 59 return res as Result<T>60 }61 62- get activeRouter() {62+ get activeRouter(): Router<T> {63 if (this.routes || this.routers.length !== 1) {64 throw new Error('No active router has been determined yet.')65 }66 3 unmodified linesmodified:deno_dist/utils/jwt/utf8.ts+2 added-2 removed
1-export const utf8Encoder = new TextEncoder()2-export const utf8Decoder = new TextDecoder()1+export const utf8Encoder: TextEncoder = new TextEncoder()2+export const utf8Decoder: TextDecoder = new TextDecoder()modified:deno_dist/utils/buffer.ts+4 added-1 removed
46 unmodified lines47 }48 return buffer49 }50 51-export const bufferToFormData = (arrayBuffer: ArrayBuffer, contentType: string) => {51+export const bufferToFormData = (52+ arrayBuffer: ArrayBuffer,53+ contentType: string54+): Promise<FormData> => {55 const response = new Response(arrayBuffer, {56 headers: {57 'Content-Type': contentType,58 },3 unmodified linesmodified:deno_dist/utils/color.ts+1 added-1 removed
1-export function getColorEnabled() {1+export function getColorEnabled(): boolean {2 // eslint-disable-next-line @typescript-eslint/no-explicit-any3 const { process, Deno } = globalThis as any4 5 const isNoColor =9 unmodified linesmodified:deno_dist/utils/stream.ts+3 added-3 removed
28 unmodified lines29 },30 })31 }32 33- async write(input: Uint8Array | string) {33+ async write(input: Uint8Array | string): Promise<StreamingApi> {34 try {35 if (typeof input === 'string') {36 input = this.encoder.encode(input)37 }3 unmodified lines41 }42 return this43 }44 45- async writeln(input: string) {45+ async writeln(input: string): Promise<StreamingApi> {46 await this.write(input + '\n')47 return this48 }49 50- sleep(ms: number) {50+ sleep(ms: number): Promise<unknown> {51 return new Promise((res) => setTimeout(res, ms))52 }53 54 async close() {17 unmodified linesmodified:deno_dist/context.ts+10 added-3 removed
1 import type { HonoRequest } from './request.ts'2-import type { Env, FetchEventLike, NotFoundHandler, Input, TypedResponse } from './types.ts'3-import { resolveCallback, HtmlEscapedCallbackPhase } from './utils/html.ts'2+import type { Env, FetchEventLike, Input, NotFoundHandler, TypedResponse } from './types.ts'3+import { HtmlEscapedCallbackPhase, resolveCallback } from './utils/html.ts'4 import type { RedirectStatusCode, StatusCode } from './utils/http-status.ts'5 import type { JSONValue, JSONParsed, IsAny, Simplify } from './utils/types.ts'6 7 type HeaderRecord = Record<string, string | string[]>215 unmodified lines223 * @see https://hono.dev/api/context#render-setrenderer224 */225 render: Renderer = (...args) => this.renderer(...args)226 227- setLayout = (layout: Layout<PropsForRenderer & { Layout: Layout }>) => (this.layout = layout)227+ setLayout = (228+ layout: Layout<PropsForRenderer & { Layout: Layout }>229+ ): Layout<230+ PropsForRenderer & {231+ Layout: Layout232+ }233+ > => (this.layout = layout)234+235 getLayout = () => this.layout236 237 /**238 * `.setRenderer()` can set the layout in the custom middleware.334 unmodified linesmodified:deno_dist/hono-base.ts+3 added-3 removed
231 unmodified lines232 * return c.text('Custom Error Message', 500)233 * })234 * ```235 */236- onError = (handler: ErrorHandler<E>) => {236+ onError = (handler: ErrorHandler<E>): Hono<E, S, BasePath> => {237 this.errorHandler = handler238 return this239 }240 5 unmodified lines246 * })247 * ```248 * @see https://hono.dev/api/hono#not-found249 */250- notFound = (handler: NotFoundHandler<E>) => {250+ notFound = (handler: NotFoundHandler<E>): Hono<E, S, BasePath> => {251 this.notFoundHandler = handler252 return this253 }254 140 unmodified lines395 input: RequestInfo | URL,396 requestInit?: RequestInit,397 Env?: E['Bindings'] | {},398 executionCtx?: ExecutionContext399- ) => {399+ ): Response | Promise<Response> => {400 if (input instanceof Request) {401 if (requestInit !== undefined) {402 input = new Request(input, requestInit)403 }24 unmodified linesmodified:deno_dist/request.ts+2 added-2 removed
287 unmodified lines288 * })289 * ```290 * @see https://hono.dev/api/request#url291 */292- get url() {292+ get url(): string {293 return this.raw.url294 }295 296 /**5 unmodified lines302 * })303 * ```304 * @see https://hono.dev/api/request#method305 */306- get method() {306+ get method(): string {307 return this.raw.method308 }309 310 /**38 unmodified linesmodified:src/helper/accepts/accepts.ts+3 added-3 removed
23 unmodified lines24 export interface acceptsOptions extends acceptsConfig {25 match?: (accepts: Accept[], config: acceptsConfig) => string26 }27 28-export const parseAccept = (acceptHeader: string) => {28+export const parseAccept = (acceptHeader: string): Accept[] => {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']8 unmodified lines41 }42 })43 }44 45-export const defaultMatch = (accepts: Accept[], config: acceptsConfig) => {45+export const defaultMatch = (accepts: Accept[], config: acceptsConfig): string => {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 }10 unmodified lines60 * })61 * })62 * ```63 */64-export const accepts = (c: Context, options: acceptsOptions) => {64+export const accepts = (c: Context, options: acceptsOptions): string => {65 const acceptHeader = c.req.header(options.header)66 if (!acceptHeader) {67 return options.default68 }5 unmodified linesmodified:src/helper/adapter/index.ts+1 added-1 removed
28 unmodified lines29 30 return runtimeEnvHandlers[runtime]()31 }32 33-export const getRuntimeKey = () => {33+export const getRuntimeKey = (): Runtime => {34 // eslint-disable-next-line @typescript-eslint/no-explicit-any35 const global = globalThis as any36 37 if (global?.Deno !== undefined) {20 unmodified linesmodified:src/helper/cookie/index.ts+1 added-1 removed
116 unmodified lines117 }118 c.header('set-cookie', cookie, { append: true })119 }120 121-export const deleteCookie = (c: Context, name: string, opt?: CookieOptions) => {121+export const deleteCookie = (c: Context, name: string, opt?: CookieOptions): string | undefined => {122 const deletedCookie = getCookie(c, name)123 setCookie(c, name, '', { ...opt, maxAge: 0 })124 return deletedCookie125 }modified:src/helper/css/common.ts+8 added-8 removed
1 unmodified line2 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()6+export const SELECTOR: unique symbol = Symbol()7+export const CLASS_NAME: unique symbol = Symbol()8+export const STYLE_STRING: unique symbol = Symbol()9+export const SELECTORS: unique symbol = Symbol()10+export const EXTERNAL_CLASS_NAMES: unique symbol = Symbol()11+const CSS_ESCAPED: unique symbol = Symbol()12 13 export interface CssClassName {14 [SELECTOR]: string15 [CLASS_NAME]: string32 unmodified lines48 }49 return 'css-' + out50 }51 52-const cssStringReStr = [52+const cssStringReStr: string = [53 '"(?:(?:\\\\[\\s\\S]|[^"\\\\])*)"', // double quoted string54 // eslint-disable-next-line quotes55 "'(?:(?:\\\\[\\s\\S]|[^'\\\\])*)'", // single quoted string56 ].join('|')57-const minifyCssRe = new RegExp(57+const minifyCssRe: RegExp = new RegExp(58 [59 '(' + cssStringReStr + ')', // $1: quoted string60 61 '(?:' +182 unmodified linesmodified:src/helper/css/index.ts+40 added-13 removed
22 unmodified lines23 Record<string, string>, // class name to add24 Record<string, true> // class name already added25 ]26 27+interface CssType {28+ (strings: TemplateStringsArray, ...values: CssVariableType[]): Promise<string>29+}30+31+interface CxType {32+ (33+ ...args: (CssClassName | Promise<string> | string | boolean | null | undefined)[]34+ ): Promise<string>35+}36+37+interface KeyframesType {38+ (strings: TemplateStringsArray, ...values: CssVariableType[]): CssClassNameCommon39+}40+41+interface ViewTransitionType {42+ (strings: TemplateStringsArray, ...values: CssVariableType[]): Promise<string>43+ (content: Promise<string>): Promise<string>44+ (): Promise<string>45+}46+47+interface StyleType {48+ (args?: { children?: Promise<string> }): HtmlEscapedString49+}50+51 /**52 * @experimental53 * `createCssContext` is an experimental feature.54 * The API might be changed.55 */32-export const createCssContext = ({ id }: { id: Readonly<string> }) => {56+export const createCssContext = ({ id }: { id: Readonly<string> }): DefaultContextType => {57 const [cssJsxDomObject, StyleRenderToDom] = createCssJsxDomObjects({ id })58 59 const contextMap: WeakMap<object, usedClassNameData> = new WeakMap()60 68 unmodified lines129 promise.toString = cssJsxDomObject.toString130 return promise131 }132 109- const css = (strings: TemplateStringsArray, ...values: CssVariableType[]): Promise<string> => {133+ const css: CssType = (strings, ...values) => {134 return newCssClassNameObject(cssCommon(strings, values))135 }136 113- const cx = (114- ...args: (CssClassName | Promise<string> | string | boolean | null | undefined)[]115- ): Promise<string> => {137+ const cx: CxType = (...args) => {138 // eslint-disable-next-line @typescript-eslint/no-explicit-any139 args = cxCommon(args as any) as any140 // eslint-disable-next-line @typescript-eslint/no-explicit-any141 return css(Array(args.length).fill('') as any, ...args)142 }143 144 const keyframes = keyframesCommon145 124- type ViewTransitionType = {125- (strings: TemplateStringsArray, ...values: CssVariableType[]): Promise<string>126- (content: Promise<string>): Promise<string>127- (): Promise<string>128- }146 const viewTransition: ViewTransitionType = ((147 strings: TemplateStringsArray | Promise<string> | undefined,148 ...values: CssVariableType[]132- ): Promise<string> => {149+ ) => {150 // eslint-disable-next-line @typescript-eslint/no-explicit-any151 return newCssClassNameObject(viewTransitionCommon(strings as any, values))152 }) as ViewTransitionType153 137- const Style = ({ children }: { children?: Promise<string> } = {}) =>154+ const Style: StyleType = ({ children } = {}) =>155 children156 ? raw(`<style id="${id}">${(children as unknown as CssClassName)[STYLE_STRING]}</style>`)157 : raw(`<style id="${id}"></style>`)158 // eslint-disable-next-line @typescript-eslint/no-explicit-any7 unmodified lines166 Style,167 }168 }169 153-const defaultContext = createCssContext({ id: DEFAULT_STYLE_ID })170+interface DefaultContextType {171+ css: CssType172+ cx: CxType173+ keyframes: KeyframesType174+ viewTransition: ViewTransitionType175+ Style: StyleType176+}177 178+const defaultContext: DefaultContextType = createCssContext({179+ id: DEFAULT_STYLE_ID,180+})181+182 /**183 * @experimental184 * `css` is an experimental feature.185 * The API might be changed.30 unmodified linesmodified:src/helper/dev/index.ts+2 added-2 removed
13 unmodified lines14 name: string15 isMiddleware: boolean16 }17 18-const handlerName = (handler: Function) => {18+const handlerName = (handler: Function): string => {19 return handler.name || (isMiddleware(handler) ? '[middleware]' : '[handler]')20 }21 22 export const inspectRoutes = <E extends Env>(hono: Hono<E>): RouteData[] => {44 unmodified lines67 })68 })69 }70 71-export const getRouterName = <E extends Env>(app: Hono<E>) => {71+export const getRouterName = <E extends Env>(app: Hono<E>): string => {72 app.router.match('GET', '/')73 return app.router.name74 }modified:src/helper/factory/index.ts+3 added-3 removed
214 unmodified lines215 /**216 * @experimental217 * `createApp` is an experimental feature.218 */219- createApp = () => {219+ createApp = (): Hono<E> => {220 const app = new Hono<E>()221 if (this.initApp) {222 this.initApp(app)223 }9 unmodified lines233 }234 235 export const createFactory = <E extends Env = any, P extends string = any>(init?: {236 initApp?: InitApp<E>237-}) => new Factory<E, P>(init)237+}): Factory<E, P> => new Factory<E, P>(init)238 239 export const createMiddleware = <E extends Env = any, P extends string = any, I extends Input = {}>(240 middleware: MiddlewareHandler<E, P, I>241-) => createFactory<E, P>().createMiddleware<I>(middleware)241+): MiddlewareHandler<E, P, I> => createFactory<E, P>().createMiddleware<I>(middleware)modified:src/helper/streaming/sse.ts+1 added-1 removed
60 unmodified lines61 export const streamSSE = (62 c: Context,63 cb: (stream: SSEStreamingApi) => Promise<void>,64 onError?: (e: Error, stream: SSEStreamingApi) => Promise<void>65-) => {65+): Response => {66 const { readable, writable } = new TransformStream()67 const stream = new SSEStreamingApi(writable, readable)68 69 c.header('Transfer-Encoding', 'chunked')8 unmodified linesmodified:src/helper/testing/index.ts+3 added-1 removed
1 import { hc } from '../../client'2+import type { Client } from '../../client/types'3 import type { ExecutionContext } from '../../context'4 import type { Hono } from '../../hono'5+import type { UnionToIntersection } from '../../utils/types'6 7 // eslint-disable-next-line @typescript-eslint/no-explicit-any8 type ExtractEnv<T> = T extends Hono<infer E, any, any> ? E : never9 1 unmodified line11 export const testClient = <T extends Hono<any, any, any>>(12 app: T,13 Env?: ExtractEnv<T>['Bindings'] | {},14 executionCtx?: ExecutionContext13-) => {15+): UnionToIntersection<Client<T>> => {16 const customFetch = (input: RequestInfo | URL, init?: RequestInit) => {17 return app.request(input, init, Env, executionCtx)18 }19 2 unmodified linesmodified:src/jsx/dom/context.ts+1 added-1 removed
3 unmodified lines4 import { globalContexts } from '../context'5 import { Fragment } from './jsx-runtime'6 import { setInternalTagFlag } from './utils'7 8-export const createContextProviderFunction = <T>(values: T[]) =>8+export const createContextProviderFunction = <T>(values: T[]): Function =>9 setInternalTagFlag(({ value, children }: { value: T; children: Child[] }) => {10 if (!children) {11 return undefined12 }42 unmodified linesmodified:src/jsx/dom/css.ts+10 added-1 removed
54 unmodified lines55 }56 return result57 }58 59+interface CreateCssJsxDomObjectsType {60+ (args: { id: Readonly<string> }): readonly [61+ {62+ toString(this: CssClassName): string63+ },64+ FC<PropsWithChildren<void>>65+ ]66+}67+59-export const createCssJsxDomObjects = ({ id }: { id: Readonly<string> }) => {68+export const createCssJsxDomObjects: CreateCssJsxDomObjectsType = ({ id }) => {69 let styleSheet: CSSStyleSheet | null | undefined = undefined70 const findStyleSheet = (): [CSSStyleSheet, Set<string>] | [] => {71 if (!styleSheet) {72 styleSheet = document.querySelector<HTMLStyleElement>(`style#${id}`)148 unmodified linesmodified:src/jsx/dom/jsx-dev-runtime.ts+1 added-1 removed
26 unmodified lines27 JSXNodeCompatPrototype28 ) as JSXNode29 }30 31-export const Fragment = (props: Record<string, unknown>) => jsxDEV('', props, undefined)31+export const Fragment = (props: Record<string, unknown>): JSXNode => jsxDEV('', props, undefined)modified:src/jsx/dom/utils.ts+1 added-1 removed
1 import { DOM_INTERNAL_TAG } from '../constants'2 3-export const setInternalTagFlag = (fn: Function) => {3+export const setInternalTagFlag = (fn: Function): Function => {4 // eslint-disable-next-line @typescript-eslint/no-explicit-any5 ;(fn as any)[DOM_INTERNAL_TAG] = true6 return fn7 }modified:src/jsx/hooks/index.ts+4 added-1 removed
16 unmodified lines17 (() => void) | undefined, // cleanup18 (() => void) | undefined // effect19 ]20 21-const resolvedPromiseValueMap = new WeakMap<Promise<unknown>, unknown>()21+const resolvedPromiseValueMap: WeakMap<Promise<unknown>, unknown> = new WeakMap<22+ Promise<unknown>,23+ unknown24+>()25 26 const isDepsChanged = (27 prevDeps: readonly unknown[] | undefined,28 deps: readonly unknown[] | undefined394 unmodified linesmodified:src/jsx/jsx-runtime.ts+5 added-1 removed
1 export { jsxDEV as jsx, Fragment } from './jsx-dev-runtime'2 export { jsxDEV as jsxs } from './jsx-dev-runtime'3 4 import { raw, html } from '../helper/html'5+import type { HtmlEscapedString } from '../utils/html'6 export { html as jsxTemplate }6-export const jsxAttr = (name: string, value: string | Promise<string>) =>7+export const jsxAttr = (8+ name: string,9+ value: string | Promise<string>10+): HtmlEscapedString | Promise<HtmlEscapedString> =>11 typeof value === 'string' ? raw(name + '="' + html`${value}` + '"') : html`${name}="${value}"`12 export const jsxEscape = (value: string) => valuemodified:src/middleware/jsx-renderer/index.ts+3 added-1 removed
1 unmodified line2 import type { Context, PropsForRenderer } from '../../context'3 import { html, raw } from '../../helper/html'4 import { jsx, createContext, useContext, Fragment } from '../../jsx'5 import type { FC, PropsWithChildren, JSXNode } from '../../jsx'6+import type { Context as JSXContext } from '../../jsx'7 import { renderToReadableStream } from '../../jsx/streaming'8 import type { Env, Input, MiddlewareHandler } from '../../types'9 import type { HtmlEscapedString } from '../../utils/html'10 10-export const RequestContext = createContext<Context | null>(null)11+export const RequestContext: JSXContext<Context<any, any, {}> | null> =12+ createContext<Context | null>(null)13 14 type RendererOptions = {15 docType?: boolean | string16 stream?: boolean | Record<string, string>79 unmodified linesmodified:src/middleware/timing/index.ts+1 added-1 removed
22 unmodified lines23 autoEnd: boolean24 crossOrigin: boolean | string | ((c: Context) => boolean | string)25 }26 27-const getTime = () => {27+const getTime = (): number => {28 try {29 return performance.now()30 } catch {}31 return Date.now()108 unmodified linesmodified:src/router/smart-router/router.ts+1 added-1 removed
57 unmodified lines58 59 return res as Result<T>60 }61 62- get activeRouter() {62+ get activeRouter(): Router<T> {63 if (this.routes || this.routers.length !== 1) {64 throw new Error('No active router has been determined yet.')65 }66 3 unmodified linesmodified:src/utils/jwt/utf8.ts+2 added-2 removed
1-export const utf8Encoder = new TextEncoder()2-export const utf8Decoder = new TextDecoder()1+export const utf8Encoder: TextEncoder = new TextEncoder()2+export const utf8Decoder: TextDecoder = new TextDecoder()modified:src/utils/buffer.ts+4 added-1 removed
46 unmodified lines47 }48 return buffer49 }50 51-export const bufferToFormData = (arrayBuffer: ArrayBuffer, contentType: string) => {51+export const bufferToFormData = (52+ arrayBuffer: ArrayBuffer,53+ contentType: string54+): Promise<FormData> => {55 const response = new Response(arrayBuffer, {56 headers: {57 'Content-Type': contentType,58 },3 unmodified linesmodified:src/utils/color.ts+1 added-1 removed
1-export function getColorEnabled() {1+export function getColorEnabled(): boolean {2 // eslint-disable-next-line @typescript-eslint/no-explicit-any3 const { process, Deno } = globalThis as any4 5 const isNoColor =9 unmodified linesmodified:src/utils/stream.ts+3 added-3 removed
28 unmodified lines29 },30 })31 }32 33- async write(input: Uint8Array | string) {33+ async write(input: Uint8Array | string): Promise<StreamingApi> {34 try {35 if (typeof input === 'string') {36 input = this.encoder.encode(input)37 }3 unmodified lines41 }42 return this43 }44 45- async writeln(input: string) {45+ async writeln(input: string): Promise<StreamingApi> {46 await this.write(input + '\n')47 return this48 }49 50- sleep(ms: number) {50+ sleep(ms: number): Promise<unknown> {51 return new Promise((res) => setTimeout(res, ms))52 }53 54 async close() {17 unmodified linesmodified:src/context.ts+10 added-3 removed
1 import type { HonoRequest } from './request'2-import type { Env, FetchEventLike, NotFoundHandler, Input, TypedResponse } from './types'3-import { resolveCallback, HtmlEscapedCallbackPhase } from './utils/html'2+import type { Env, FetchEventLike, Input, NotFoundHandler, TypedResponse } from './types'3+import { HtmlEscapedCallbackPhase, resolveCallback } from './utils/html'4 import type { RedirectStatusCode, StatusCode } from './utils/http-status'5 import type { JSONValue, JSONParsed, IsAny, Simplify } from './utils/types'6 7 type HeaderRecord = Record<string, string | string[]>215 unmodified lines223 * @see https://hono.dev/api/context#render-setrenderer224 */225 render: Renderer = (...args) => this.renderer(...args)226 227- setLayout = (layout: Layout<PropsForRenderer & { Layout: Layout }>) => (this.layout = layout)227+ setLayout = (228+ layout: Layout<PropsForRenderer & { Layout: Layout }>229+ ): Layout<230+ PropsForRenderer & {231+ Layout: Layout232+ }233+ > => (this.layout = layout)234+235 getLayout = () => this.layout236 237 /**238 * `.setRenderer()` can set the layout in the custom middleware.334 unmodified linesmodified:src/hono-base.ts+3 added-3 removed
231 unmodified lines232 * return c.text('Custom Error Message', 500)233 * })234 * ```235 */236- onError = (handler: ErrorHandler<E>) => {236+ onError = (handler: ErrorHandler<E>): Hono<E, S, BasePath> => {237 this.errorHandler = handler238 return this239 }240 5 unmodified lines246 * })247 * ```248 * @see https://hono.dev/api/hono#not-found249 */250- notFound = (handler: NotFoundHandler<E>) => {250+ notFound = (handler: NotFoundHandler<E>): Hono<E, S, BasePath> => {251 this.notFoundHandler = handler252 return this253 }254 140 unmodified lines395 input: RequestInfo | URL,396 requestInit?: RequestInit,397 Env?: E['Bindings'] | {},398 executionCtx?: ExecutionContext399- ) => {399+ ): Response | Promise<Response> => {400 if (input instanceof Request) {401 if (requestInit !== undefined) {402 input = new Request(input, requestInit)403 }24 unmodified linesmodified:src/request.ts+2 added-2 removed
287 unmodified lines288 * })289 * ```290 * @see https://hono.dev/api/request#url291 */292- get url() {292+ get url(): string {293 return this.raw.url294 }295 296 /**5 unmodified lines302 * })303 * ```304 * @see https://hono.dev/api/request#method305 */306- get method() {306+ get method(): string {307 return this.raw.method308 }309 310 /**38 unmodified lines