Skip to content
Myr

context.ts

This file

Path

src/context.ts

797 lines 路 22.2 KiB 路 TypeScript

Last changed by

fix(types): allow returning a Blob as a response body (#5446)Yusuke Wadabefore adoption90d02fb

History of this file

Take it

1import { HonoRequest } from './request'2import type { Result } from './router'3import type {4  Env,5  FetchEventLike,6  H,7  Input,8  NotFoundHandler,9  RouterRoute,10  TypedResponse,11} from './types'12import type { ResponseHeader } from './utils/headers'13import { HtmlEscapedCallbackPhase, resolveCallback } from './utils/html'14import type { ContentfulStatusCode, RedirectStatusCode, StatusCode } from './utils/http-status'15import type { BaseMime } from './utils/mime'16import type { InvalidJSONValue, IsAny, JSONParsed, JSONValue } from './utils/types'1718type HeaderRecord =19  | Record<'Content-Type', BaseMime>20  | Record<ResponseHeader, string | string[]>21  | Record<string, string | string[]>2223/**24 * Data type can be a string, ArrayBuffer, Blob, Uint8Array (buffer), or ReadableStream.25 */26export type Data = string | ArrayBuffer | Blob | ReadableStream | Uint8Array<ArrayBuffer>2728/**29 * Interface for the execution context in a web worker or similar environment.30 */31export interface ExecutionContext {32  /**33   * Extends the lifetime of the event callback until the promise is settled.34   *35   * @param promise - A promise to wait for.36   */37  waitUntil(promise: Promise<unknown>): void38  /**39   * Allows the event to be passed through to subsequent event listeners.40   */41  passThroughOnException(): void42  /**43   * For compatibility with Wrangler 4.x.44   */45  // eslint-disable-next-line @typescript-eslint/no-explicit-any46  props: any47  /**48   * For compatibility with Wrangler 4.x.49   */50  // eslint-disable-next-line @typescript-eslint/no-explicit-any51  exports?: any52}5354/**55 * Interface for context variable mapping.56 */57export interface ContextVariableMap {}5859/**60 * Interface for context renderer.61 */62export interface ContextRenderer {}6364/**65 * Interface representing a renderer for content.66 *67 * @interface DefaultRenderer68 * @param {string | Promise<string>} content - The content to be rendered, which can be either a string or a Promise resolving to a string.69 * @returns {Response | Promise<Response>} - The response after rendering the content, which can be either a Response or a Promise resolving to a Response.70 */71interface DefaultRenderer {72  (content: string | Promise<string>): Response | Promise<Response>73}7475/**76 * Renderer type which can either be a ContextRenderer or DefaultRenderer.77 */78export type Renderer = ContextRenderer extends Function ? ContextRenderer : DefaultRenderer7980/**81 * Extracts the props for the renderer.82 */83export type PropsForRenderer = [...Required<Parameters<Renderer>>] extends [unknown, infer Props]84  ? Props85  : unknown8687// eslint-disable-next-line @typescript-eslint/no-explicit-any88export type Layout<T = Record<string, any>> = (props: T) => any8990/**91 * Interface for getting context variables.92 *93 * @template E - Environment type.94 */95interface Get<E extends Env> {96  <Key extends keyof E['Variables']>(key: Key): E['Variables'][Key]97  <Key extends keyof ContextVariableMap>(key: Key): ContextVariableMap[Key]98}99100/**101 * Interface for setting context variables.102 *103 * @template E - Environment type.104 */105interface Set<E extends Env> {106  <Key extends keyof E['Variables']>(key: Key, value: E['Variables'][Key]): void107  <Key extends keyof ContextVariableMap>(key: Key, value: ContextVariableMap[Key]): void108}109110/**111 * Interface for creating a new response.112 */113interface NewResponse {114  (data: Data | null, status?: StatusCode, headers?: HeaderRecord): Response115  (data: Data | null, init?: ResponseOrInit): Response116}117118/**119 * Interface for responding with a body.120 */121interface BodyRespond {122  // if we return content, only allow the status codes that allow for returning the body123  <T extends Data, U extends ContentfulStatusCode>(124    data: T,125    status?: U,126    headers?: HeaderRecord127  ): Response & TypedResponse<T, U, 'body'>128  <T extends Data, U extends ContentfulStatusCode>(129    data: T,130    init?: ResponseOrInit<U>131  ): Response & TypedResponse<T, U, 'body'>132  <T extends null, U extends StatusCode>(133    data: T,134    status?: U,135    headers?: HeaderRecord136  ): Response & TypedResponse<null, U, 'body'>137  <T extends null, U extends StatusCode>(138    data: T,139    init?: ResponseOrInit<U>140  ): Response & TypedResponse<null, U, 'body'>141}142143/**144 * Interface for responding with text.145 *146 * @interface TextRespond147 * @template T - The type of the text content.148 * @template U - The type of the status code.149 *150 * @param {T} text - The text content to be included in the response.151 * @param {U} [status] - An optional status code for the response.152 * @param {HeaderRecord} [headers] - An optional record of headers to include in the response.153 *154 * @returns {Response & TypedResponse<T, U, 'text'>} - The response after rendering the text content, typed with the provided text and status code types.155 */156interface TextRespond {157  <T extends string, U extends ContentfulStatusCode = ContentfulStatusCode>(158    text: T,159    status?: U,160    headers?: HeaderRecord161  ): Response & TypedResponse<T, U, 'text'>162  <T extends string, U extends ContentfulStatusCode = ContentfulStatusCode>(163    text: T,164    init?: ResponseOrInit<U>165  ): Response & TypedResponse<T, U, 'text'>166}167168/**169 * Interface for responding with JSON.170 *171 * @interface JSONRespond172 * @template T - The type of the JSON value or simplified unknown type.173 * @template U - The type of the status code.174 *175 * @param {T} object - The JSON object to be included in the response.176 * @param {U} [status] - An optional status code for the response.177 * @param {HeaderRecord} [headers] - An optional record of headers to include in the response.178 *179 * @returns {JSONRespondReturn<T, U>} - The response after rendering the JSON object, typed with the provided object and status code types.180 */181interface JSONRespond {182  <183    T extends JSONValue | {} | InvalidJSONValue,184    U extends ContentfulStatusCode = ContentfulStatusCode,185  >(186    object: T,187    status?: U,188    headers?: HeaderRecord189  ): JSONRespondReturn<T, U>190  <191    T extends JSONValue | {} | InvalidJSONValue,192    U extends ContentfulStatusCode = ContentfulStatusCode,193  >(194    object: T,195    init?: ResponseOrInit<U>196  ): JSONRespondReturn<T, U>197}198199/**200 * @template T - The type of the JSON value or simplified unknown type.201 * @template U - The type of the status code.202 *203 * @returns {Response & TypedResponse<JSONParsed<T>, U, 'json'>} - The response after rendering the JSON object, typed with the provided object and status code types.204 */205type JSONRespondReturn<206  T extends JSONValue | {} | InvalidJSONValue,207  U extends ContentfulStatusCode,208> = Response & TypedResponse<JSONParsed<T>, U, 'json'>209210/**211 * Interface representing a function that responds with HTML content.212 *213 * @param html - The HTML content to respond with, which can be a string or a Promise that resolves to a string.214 * @param status - (Optional) The HTTP status code for the response.215 * @param headers - (Optional) A record of headers to include in the response.216 * @param init - (Optional) The response initialization object.217 *218 * @returns A Response object or a Promise that resolves to a Response object.219 */220interface HTMLRespond {221  <T extends string | Promise<string>>(222    html: T,223    status?: ContentfulStatusCode,224    headers?: HeaderRecord225  ): T extends string ? Response : Promise<Response>226  <T extends string | Promise<string>>(227    html: T,228    init?: ResponseOrInit<ContentfulStatusCode>229  ): T extends string ? Response : Promise<Response>230}231232/**233 * Options for configuring the context.234 *235 * @template E - Environment type.236 */237type ContextOptions<E extends Env> = {238  /**239   * Bindings for the environment.240   */241  env: E['Bindings']242  /**243   * Execution context for the request.244   */245  executionCtx?: FetchEventLike | ExecutionContext | undefined246  /**247   * Handler for not found responses.248   */249  notFoundHandler?: NotFoundHandler<E>250  matchResult?: Result<[H, RouterRoute]>251  path?: string252}253254interface SetHeadersOptions {255  append?: boolean256}257258interface SetHeaders {259  (name: 'Content-Type', value?: BaseMime, options?: SetHeadersOptions): void260  (name: ResponseHeader, value?: string, options?: SetHeadersOptions): void261  (name: string, value?: string, options?: SetHeadersOptions): void262}263264type ResponseHeadersInit =265  | [string, string][]266  | Record<'Content-Type', BaseMime>267  | Record<ResponseHeader, string>268  | Record<string, string>269  | Headers270271interface ResponseInit<T extends StatusCode = StatusCode> {272  headers?: ResponseHeadersInit273  status?: T274  statusText?: string275}276277type ResponseOrInit<T extends StatusCode = StatusCode> = ResponseInit<T> | Response278279export const TEXT_PLAIN = 'text/plain; charset=UTF-8'280281const setDefaultContentType = (contentType: string, headers?: HeaderRecord): HeaderRecord => {282  return {283    'Content-Type': contentType,284    ...headers,285  }286}287288const createResponseInstance = (289  body?: BodyInit | null | undefined,290  init?: globalThis.ResponseInit291): Response => new Response(body, init)292293export class Context<294  // eslint-disable-next-line @typescript-eslint/no-explicit-any295  E extends Env = any,296  // eslint-disable-next-line @typescript-eslint/no-explicit-any297  P extends string = any,298  I extends Input = {},299> {300  #rawRequest: Request301  #req: HonoRequest<P, I['out']> | undefined302  /**303   * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.304   *305   * @see {@link https://hono.dev/docs/api/context#env}306   *307   * @example308   * ```ts309   * // Environment object for Cloudflare Workers310   * app.get('*', async c => {311   *   const counter = c.env.COUNTER312   * })313   * ```314   */315  env: E['Bindings'] = {}316  #var: Map<unknown, unknown> | undefined317  finalized: boolean = false318  /**319   * `.error` can get the error object from the middleware if the Handler throws an error.320   *321   * @see {@link https://hono.dev/docs/api/context#error}322   *323   * @example324   * ```ts325   * app.use('*', async (c, next) => {326   *   await next()327   *   if (c.error) {328   *     // do something...329   *   }330   * })331   * ```332   */333  error: Error | undefined334335  #status: StatusCode | undefined336  #executionCtx: FetchEventLike | ExecutionContext | undefined337  #res: Response | undefined338  #layout: Layout<PropsForRenderer & { Layout: Layout }> | undefined339  #renderer: Renderer | undefined340  #notFoundHandler: NotFoundHandler<E> | undefined341  #preparedHeaders: Headers | undefined342343  #matchResult: Result<[H, RouterRoute]> | undefined344  #path: string | undefined345346  /**347   * Creates an instance of the Context class.348   *349   * @param req - The Request object.350   * @param options - Optional configuration options for the context.351   */352  constructor(req: Request, options?: ContextOptions<E>) {353    this.#rawRequest = req354    if (options) {355      this.#executionCtx = options.executionCtx356      this.env = options.env357      this.#notFoundHandler = options.notFoundHandler358      this.#path = options.path359      this.#matchResult = options.matchResult360    }361  }362363  /**364   * `.req` is the instance of {@link HonoRequest}.365   */366  get req(): HonoRequest<P, I['out']> {367    this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult)368    return this.#req369  }370371  /**372   * @see {@link https://hono.dev/docs/api/context#event}373   * The FetchEvent associated with the current request.374   *375   * @throws Will throw an error if the context does not have a FetchEvent.376   */377  get event(): FetchEventLike {378    if (this.#executionCtx && 'respondWith' in this.#executionCtx) {379      return this.#executionCtx380    } else {381      throw Error('This context has no FetchEvent')382    }383  }384385  /**386   * @see {@link https://hono.dev/docs/api/context#executionctx}387   * The ExecutionContext associated with the current request.388   *389   * @throws Will throw an error if the context does not have an ExecutionContext.390   */391  get executionCtx(): ExecutionContext {392    if (this.#executionCtx) {393      return this.#executionCtx as ExecutionContext394    } else {395      throw Error('This context has no ExecutionContext')396    }397  }398399  /**400   * @see {@link https://hono.dev/docs/api/context#res}401   * The Response object for the current request.402   */403  get res(): Response {404    return (this.#res ||= createResponseInstance(null, {405      headers: (this.#preparedHeaders ??= new Headers()),406    }))407  }408409  /**410   * Sets the Response object for the current request.411   *412   * @param _res - The Response object to set.413   */414  set res(_res: Response | undefined) {415    if (this.#res && _res) {416      _res = createResponseInstance(_res.body, _res)417      for (const [k, v] of this.#res.headers.entries()) {418        if (k === 'content-type') {419          continue420        }421        if (k === 'set-cookie') {422          const cookies = this.#res.headers.getSetCookie()423          _res.headers.delete('set-cookie')424          for (const cookie of cookies) {425            _res.headers.append('set-cookie', cookie)426          }427        } else {428          _res.headers.set(k, v)429        }430      }431    }432    this.#res = _res433    this.finalized = true434  }435436  /**437   * `.render()` can create a response within a layout.438   *439   * @see {@link https://hono.dev/docs/api/context#render-setrenderer}440   *441   * @example442   * ```ts443   * app.get('/', (c) => {444   *   return c.render('Hello!')445   * })446   * ```447   */448  render: Renderer = (...args) => {449    this.#renderer ??= (content: string | Promise<string>) => this.html(content)450    return this.#renderer(...args)451  }452453  /**454   * Sets the layout for the response.455   *456   * @param layout - The layout to set.457   * @returns The layout function.458   */459  setLayout = (460    layout: Layout<PropsForRenderer & { Layout: Layout }>461  ): Layout<462    PropsForRenderer & {463      Layout: Layout464    }465  > => (this.#layout = layout)466467  /**468   * Gets the current layout for the response.469   *470   * @returns The current layout function.471   */472  getLayout = (): Layout<PropsForRenderer & { Layout: Layout }> | undefined => this.#layout473474  /**475   * `.setRenderer()` can set the layout in the custom middleware.476   *477   * @see {@link https://hono.dev/docs/api/context#render-setrenderer}478   *479   * @example480   * ```tsx481   * app.use('*', async (c, next) => {482   *   c.setRenderer((content) => {483   *     return c.html(484   *       <html>485   *         <body>486   *           <p>{content}</p>487   *         </body>488   *       </html>489   *     )490   *   })491   *   await next()492   * })493   * ```494   */495  setRenderer = (renderer: Renderer): void => {496    this.#renderer = renderer497  }498499  /**500   * `.header()` can set headers.501   *502   * @see {@link https://hono.dev/docs/api/context#header}503   *504   * @example505   * ```ts506   * app.get('/welcome', (c) => {507   *   // Set headers508   *   c.header('X-Message', 'Hello!')509   *   c.header('Content-Type', 'text/plain')510   *511   *   // Append multiple headers using the append option (e.g. Vary)512   *   c.header('Vary', 'Accept-Encoding', { append: true })513   *   c.header('Vary', 'User-Agent', { append: true })514   *515   *   return c.body('Thank you for coming')516   * })517   * ```518   */519  header: SetHeaders = (name, value, options): void => {520    if (this.finalized) {521      this.#res = createResponseInstance((this.#res as Response).body, this.#res)522    }523    const headers = this.#res ? this.#res.headers : (this.#preparedHeaders ??= new Headers())524    if (value === undefined) {525      headers.delete(name)526    } else if (options?.append) {527      headers.append(name, value)528    } else {529      headers.set(name, value)530    }531  }532533  status = (status: StatusCode): void => {534    this.#status = status535  }536537  /**538   * `.set()` can set the value specified by the key.539   *540   * @see {@link https://hono.dev/docs/api/context#set-get}541   *542   * @example543   * ```ts544   * app.use('*', async (c, next) => {545   *   c.set('message', 'Hono is hot!!')546   *   await next()547   * })548   * ```549   */550  set: Set<551    IsAny<E> extends true552      ? {553          // eslint-disable-next-line @typescript-eslint/no-explicit-any554          Variables: ContextVariableMap & Record<PropertyKey, any>555        }556      : E557  > = (key: PropertyKey, value: unknown) => {558    this.#var ??= new Map()559    this.#var.set(key, value)560  }561562  /**563   * `.get()` can use the value specified by the key.564   *565   * @see {@link https://hono.dev/docs/api/context#set-get}566   *567   * @example568   * ```ts569   * app.get('/', (c) => {570   *   const message = c.get('message')571   *   return c.text(`The message is "${message}"`)572   * })573   * ```574   */575  get: Get<576    IsAny<E> extends true577      ? {578          // eslint-disable-next-line @typescript-eslint/no-explicit-any579          Variables: ContextVariableMap & Record<PropertyKey, any>580        }581      : E582  > = (key: PropertyKey) => {583    return this.#var ? this.#var.get(key) : undefined584  }585586  /**587   * `.var` can access the value of a variable.588   *589   * @see {@link https://hono.dev/docs/api/context#var}590   *591   * @example592   * ```ts593   * const result = c.var.client.oneMethod()594   * ```595   */596  // c.var.propName is a read-only597  get var(): Readonly<598    // eslint-disable-next-line @typescript-eslint/no-explicit-any599    ContextVariableMap & (IsAny<E['Variables']> extends true ? Record<string, any> : E['Variables'])600  > {601    if (!this.#var) {602      // eslint-disable-next-line @typescript-eslint/no-explicit-any603      return {} as any604    }605    return Object.fromEntries(this.#var)606  }607608  #newResponse(609    data: Data | null,610    arg?: StatusCode | ResponseOrInit,611    headers?: HeaderRecord612  ): Response {613    let responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders614615    if (typeof arg === 'object' && arg.headers) {616      responseHeaders ??= new Headers()617      for (const [key, value] of new Headers(arg.headers)) {618        if (key === 'set-cookie') {619          responseHeaders.append(key, value)620        } else {621          responseHeaders.set(key, value)622        }623      }624    }625626    if (headers) {627      if (!responseHeaders) {628        let count = 0629        for (const k in headers) {630          if (++count > 1 || typeof headers[k as keyof HeaderRecord] !== 'string') {631            responseHeaders = new Headers()632            break633          }634        }635      }636      if (responseHeaders) {637        for (const k in headers) {638          const v = headers[k as keyof HeaderRecord]639          if (typeof v === 'string') {640            responseHeaders.set(k, v)641          } else {642            responseHeaders.delete(k)643            for (const v2 of v) {644              responseHeaders.append(k, v2)645            }646          }647        }648      }649    }650651    const status = typeof arg === 'number' ? arg : (arg?.status ?? this.#status)652    return createResponseInstance(data, {653      status,654      headers: responseHeaders ?? (headers as Record<string, string> | undefined),655    })656  }657658  newResponse: NewResponse = (...args) => this.#newResponse(...(args as Parameters<NewResponse>))659660  /**661   * `.body()` can return the HTTP response.662   * You can set headers with `.header()` and set HTTP status code with `.status`.663   * This can also be set in `.text()`, `.json()` and so on.664   *665   * @see {@link https://hono.dev/docs/api/context#body}666   *667   * @example668   * ```ts669   * app.get('/welcome', (c) => {670   *   // Set headers671   *   c.header('X-Message', 'Hello!')672   *   c.header('Content-Type', 'text/plain')673   *   // Set HTTP status code674   *   c.status(201)675   *676   *   // Return the response body677   *   return c.body('Thank you for coming')678   * })679   * ```680   */681  body: BodyRespond = (682    data: Data | null,683    arg?: StatusCode | RequestInit,684    headers?: HeaderRecord685  ): ReturnType<BodyRespond> => this.#newResponse(data, arg, headers) as ReturnType<BodyRespond>686687  /**688   * `.text()` can render text as `Content-Type:text/plain`.689   *690   * @see {@link https://hono.dev/docs/api/context#text}691   *692   * @example693   * ```ts694   * app.get('/say', (c) => {695   *   return c.text('Hello!')696   * })697   * ```698   */699  text: TextRespond = (700    text: string,701    arg?: ContentfulStatusCode | ResponseOrInit,702    headers?: HeaderRecord703  ): ReturnType<TextRespond> => {704    return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized705      ? (new Response(text) as ReturnType<TextRespond>)706      : (this.#newResponse(707          text,708          arg,709          setDefaultContentType(TEXT_PLAIN, headers)710        ) as ReturnType<TextRespond>)711  }712713  /**714   * `.json()` can render JSON as `Content-Type:application/json`.715   *716   * @see {@link https://hono.dev/docs/api/context#json}717   *718   * @example719   * ```ts720   * app.get('/api', (c) => {721   *   return c.json({ message: 'Hello!' })722   * })723   * ```724   */725  json: JSONRespond = <726    T extends JSONValue | {} | InvalidJSONValue,727    U extends ContentfulStatusCode = ContentfulStatusCode,728  >(729    object: T,730    arg?: U | ResponseOrInit<U>,731    headers?: HeaderRecord732  ): JSONRespondReturn<T, U> => {733    return this.#newResponse(734      JSON.stringify(object),735      arg,736      setDefaultContentType('application/json', headers)737    ) /* eslint-disable @typescript-eslint/no-explicit-any */ as any738  }739740  html: HTMLRespond = (741    html: string | Promise<string>,742    arg?: ContentfulStatusCode | ResponseOrInit<ContentfulStatusCode>,743    headers?: HeaderRecord744  ): Response | Promise<Response> => {745    const res = (html: string) =>746      this.#newResponse(html, arg, setDefaultContentType('text/html; charset=UTF-8', headers))747    return typeof html === 'object'748      ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res)749      : res(html)750  }751752  /**753   * `.redirect()` can Redirect, default status code is 302.754   *755   * @see {@link https://hono.dev/docs/api/context#redirect}756   *757   * @example758   * ```ts759   * app.get('/redirect', (c) => {760   *   return c.redirect('/')761   * })762   * app.get('/redirect-permanently', (c) => {763   *   return c.redirect('/', 301)764   * })765   * ```766   */767  redirect = <T extends RedirectStatusCode = 302>(768    location: string | URL,769    status?: T770  ): Response & TypedResponse<undefined, T, 'redirect'> => {771    const locationString = String(location)772    this.header(773      'Location',774      // Multibytes should be encoded775      // eslint-disable-next-line no-control-regex776      !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString)777    )778    return this.newResponse(null, status ?? 302) as any779  }780781  /**782   * `.notFound()` can return the Not Found Response.783   *784   * @see {@link https://hono.dev/docs/api/context#notfound}785   *786   * @example787   * ```ts788   * app.get('/notfound', (c) => {789   *   return c.notFound()790   * })791   * ```792   */793  notFound = (): ReturnType<NotFoundHandler> => {794    this.#notFoundHandler ??= () => createResponseInstance()795    return this.#notFoundHandler(this)796  }797}