Skip to content
Myr

context.ts

This file

Path

src/context.ts

846 lines 路 22.8 KiB 路 TypeScript

Last changed by

feat(context): allow URL object on `c.redirect()` (#3609)Hyeseong Kimbefore adoption01277aa

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 { RedirectStatusCode, StatusCode } from './utils/http-status'15import type { BaseMime } from './utils/mime'16import type {17  InvalidJSONValue,18  IsAny,19  JSONParsed,20  JSONValue,21  SimplifyDeepArray,22} from './utils/types'2324type HeaderRecord =25  | Record<'Content-Type', BaseMime>26  | Record<ResponseHeader, string | string[]>27  | Record<string, string | string[]>2829/**30 * Data type can be a string, ArrayBuffer, or ReadableStream.31 */32export type Data = string | ArrayBuffer | ReadableStream3334/**35 * Interface for the execution context in a web worker or similar environment.36 */37export interface ExecutionContext {38  /**39   * Extends the lifetime of the event callback until the promise is settled.40   *41   * @param promise - A promise to wait for.42   */43  waitUntil(promise: Promise<unknown>): void44  /**45   * Allows the event to be passed through to subsequent event listeners.46   */47  passThroughOnException(): void48}4950/**51 * Interface for context variable mapping.52 */53export interface ContextVariableMap {}5455/**56 * Interface for context renderer.57 */58export interface ContextRenderer {}5960/**61 * Interface representing a renderer for content.62 *63 * @interface DefaultRenderer64 * @param {string | Promise<string>} content - The content to be rendered, which can be either a string or a Promise resolving to a string.65 * @returns {Response | Promise<Response>} - The response after rendering the content, which can be either a Response or a Promise resolving to a Response.66 */67interface DefaultRenderer {68  (content: string | Promise<string>): Response | Promise<Response>69}7071/**72 * Renderer type which can either be a ContextRenderer or DefaultRenderer.73 */74export type Renderer = ContextRenderer extends Function ? ContextRenderer : DefaultRenderer7576/**77 * Extracts the props for the renderer.78 */79export type PropsForRenderer = [...Required<Parameters<Renderer>>] extends [unknown, infer Props]80  ? Props81  : unknown8283// eslint-disable-next-line @typescript-eslint/no-explicit-any84export type Layout<T = Record<string, any>> = (props: T) => any8586/**87 * Interface for getting context variables.88 *89 * @template E - Environment type.90 */91interface Get<E extends Env> {92  <Key extends keyof E['Variables']>(key: Key): E['Variables'][Key]93  <Key extends keyof ContextVariableMap>(key: Key): ContextVariableMap[Key]94}9596/**97 * Interface for setting context variables.98 *99 * @template E - Environment type.100 */101interface Set<E extends Env> {102  <Key extends keyof E['Variables']>(key: Key, value: E['Variables'][Key]): void103  <Key extends keyof ContextVariableMap>(key: Key, value: ContextVariableMap[Key]): void104}105106/**107 * Interface for creating a new response.108 */109interface NewResponse {110  (data: Data | null, status?: StatusCode, headers?: HeaderRecord): Response111  (data: Data | null, init?: ResponseInit): Response112}113114/**115 * Interface for responding with a body.116 */117interface BodyRespond extends NewResponse {}118119/**120 * Interface for responding with text.121 *122 * @interface TextRespond123 * @template T - The type of the text content.124 * @template U - The type of the status code.125 *126 * @param {T} text - The text content to be included in the response.127 * @param {U} [status] - An optional status code for the response.128 * @param {HeaderRecord} [headers] - An optional record of headers to include in the response.129 *130 * @returns {Response & TypedResponse<T, U, 'text'>} - The response after rendering the text content, typed with the provided text and status code types.131 */132interface TextRespond {133  <T extends string, U extends StatusCode = StatusCode>(134    text: T,135    status?: U,136    headers?: HeaderRecord137  ): Response & TypedResponse<T, U, 'text'>138  <T extends string, U extends StatusCode = StatusCode>(text: T, init?: ResponseInit): Response &139    TypedResponse<T, U, 'text'>140}141142/**143 * Interface for responding with JSON.144 *145 * @interface JSONRespond146 * @template T - The type of the JSON value or simplified unknown type.147 * @template U - The type of the status code.148 *149 * @param {T} object - The JSON object to be included in the response.150 * @param {U} [status] - An optional status code for the response.151 * @param {HeaderRecord} [headers] - An optional record of headers to include in the response.152 *153 * @returns {JSONRespondReturn<T, U>} - The response after rendering the JSON object, typed with the provided object and status code types.154 */155interface JSONRespond {156  <157    T extends JSONValue | SimplifyDeepArray<unknown> | InvalidJSONValue,158    U extends StatusCode = StatusCode159  >(160    object: T,161    status?: U,162    headers?: HeaderRecord163  ): JSONRespondReturn<T, U>164  <165    T extends JSONValue | SimplifyDeepArray<unknown> | InvalidJSONValue,166    U extends StatusCode = StatusCode167  >(168    object: T,169    init?: ResponseInit170  ): JSONRespondReturn<T, U>171}172173/**174 * @template T - The type of the JSON value or simplified unknown type.175 * @template U - The type of the status code.176 *177 * @returns {Response & TypedResponse<SimplifyDeepArray<T> extends JSONValue ? (JSONValue extends SimplifyDeepArray<T> ? never : JSONParsed<T>) : never, U, 'json'>} - The response after rendering the JSON object, typed with the provided object and status code types.178 */179type JSONRespondReturn<180  T extends JSONValue | SimplifyDeepArray<unknown> | InvalidJSONValue,181  U extends StatusCode182> = Response &183  TypedResponse<184    SimplifyDeepArray<T> extends JSONValue185      ? JSONValue extends SimplifyDeepArray<T>186        ? never187        : JSONParsed<T>188      : never,189    U,190    'json'191  >192193/**194 * Interface representing a function that responds with HTML content.195 *196 * @param html - The HTML content to respond with, which can be a string or a Promise that resolves to a string.197 * @param status - (Optional) The HTTP status code for the response.198 * @param headers - (Optional) A record of headers to include in the response.199 * @param init - (Optional) The response initialization object.200 *201 * @returns A Response object or a Promise that resolves to a Response object.202 */203interface HTMLRespond {204  <T extends string | Promise<string>>(205    html: T,206    status?: StatusCode,207    headers?: HeaderRecord208  ): T extends string ? Response : Promise<Response>209  <T extends string | Promise<string>>(html: T, init?: ResponseInit): T extends string210    ? Response211    : Promise<Response>212}213214/**215 * Options for configuring the context.216 *217 * @template E - Environment type.218 */219type ContextOptions<E extends Env> = {220  /**221   * Bindings for the environment.222   */223  env: E['Bindings']224  /**225   * Execution context for the request.226   */227  executionCtx?: FetchEventLike | ExecutionContext | undefined228  /**229   * Handler for not found responses.230   */231  notFoundHandler?: NotFoundHandler<E>232  matchResult?: Result<[H, RouterRoute]>233  path?: string234}235236interface SetHeadersOptions {237  append?: boolean238}239240interface SetHeaders {241  (name: 'Content-Type', value?: BaseMime, options?: SetHeadersOptions): void242  (name: ResponseHeader, value?: string, options?: SetHeadersOptions): void243  (name: string, value?: string, options?: SetHeadersOptions): void244}245246type ResponseHeadersInit =247  | [string, string][]248  | Record<'Content-Type', BaseMime>249  | Record<ResponseHeader, string>250  | Record<string, string>251  | Headers252253interface ResponseInit {254  headers?: ResponseHeadersInit255  status?: number256  statusText?: string257}258259export const TEXT_PLAIN = 'text/plain; charset=UTF-8'260261/**262 * Sets the headers of a response.263 *264 * @param headers - The Headers object to set the headers on.265 * @param map - A record of header key-value pairs to set.266 * @returns The updated Headers object.267 */268const setHeaders = (headers: Headers, map: Record<string, string> = {}) => {269  for (const key of Object.keys(map)) {270    headers.set(key, map[key])271  }272  return headers273}274275export class Context<276  // eslint-disable-next-line @typescript-eslint/no-explicit-any277  E extends Env = any,278  // eslint-disable-next-line @typescript-eslint/no-explicit-any279  P extends string = any,280  I extends Input = {}281> {282  #rawRequest: Request283  #req: HonoRequest<P, I['out']> | undefined284  /**285   * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.286   *287   * @see {@link https://hono.dev/docs/api/context#env}288   *289   * @example290   * ```ts291   * // Environment object for Cloudflare Workers292   * app.get('*', async c => {293   *   const counter = c.env.COUNTER294   * })295   * ```296   */297  env: E['Bindings'] = {}298  #var: Map<unknown, unknown> | undefined299  finalized: boolean = false300  /**301   * `.error` can get the error object from the middleware if the Handler throws an error.302   *303   * @see {@link https://hono.dev/docs/api/context#error}304   *305   * @example306   * ```ts307   * app.use('*', async (c, next) => {308   *   await next()309   *   if (c.error) {310   *     // do something...311   *   }312   * })313   * ```314   */315  error: Error | undefined316317  #status: StatusCode = 200318  #executionCtx: FetchEventLike | ExecutionContext | undefined319  #headers: Headers | undefined320  #preparedHeaders: Record<string, string> | undefined321  #res: Response | undefined322  #isFresh = true323  #layout: Layout<PropsForRenderer & { Layout: Layout }> | undefined324  #renderer: Renderer | undefined325  #notFoundHandler: NotFoundHandler<E> | undefined326327  #matchResult: Result<[H, RouterRoute]> | undefined328  #path: string | undefined329330  /**331   * Creates an instance of the Context class.332   *333   * @param req - The Request object.334   * @param options - Optional configuration options for the context.335   */336  constructor(req: Request, options?: ContextOptions<E>) {337    this.#rawRequest = req338    if (options) {339      this.#executionCtx = options.executionCtx340      this.env = options.env341      this.#notFoundHandler = options.notFoundHandler342      this.#path = options.path343      this.#matchResult = options.matchResult344    }345  }346347  /**348   * `.req` is the instance of {@link HonoRequest}.349   */350  get req(): HonoRequest<P, I['out']> {351    this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult)352    return this.#req353  }354355  /**356   * @see {@link https://hono.dev/docs/api/context#event}357   * The FetchEvent associated with the current request.358   *359   * @throws Will throw an error if the context does not have a FetchEvent.360   */361  get event(): FetchEventLike {362    if (this.#executionCtx && 'respondWith' in this.#executionCtx) {363      return this.#executionCtx364    } else {365      throw Error('This context has no FetchEvent')366    }367  }368369  /**370   * @see {@link https://hono.dev/docs/api/context#executionctx}371   * The ExecutionContext associated with the current request.372   *373   * @throws Will throw an error if the context does not have an ExecutionContext.374   */375  get executionCtx(): ExecutionContext {376    if (this.#executionCtx) {377      return this.#executionCtx as ExecutionContext378    } else {379      throw Error('This context has no ExecutionContext')380    }381  }382383  /**384   * @see {@link https://hono.dev/docs/api/context#res}385   * The Response object for the current request.386   */387  get res(): Response {388    this.#isFresh = false389    return (this.#res ||= new Response('404 Not Found', { status: 404 }))390  }391392  /**393   * Sets the Response object for the current request.394   *395   * @param _res - The Response object to set.396   */397  set res(_res: Response | undefined) {398    this.#isFresh = false399    if (this.#res && _res) {400      try {401        for (const [k, v] of this.#res.headers.entries()) {402          if (k === 'content-type') {403            continue404          }405          if (k === 'set-cookie') {406            const cookies = this.#res.headers.getSetCookie()407            _res.headers.delete('set-cookie')408            for (const cookie of cookies) {409              _res.headers.append('set-cookie', cookie)410            }411          } else {412            _res.headers.set(k, v)413          }414        }415      } catch (e) {416        if (e instanceof TypeError && e.message.includes('immutable')) {417          // `_res` is immutable (probably a response from a fetch API), so retry with a new response.418          this.res = new Response(_res.body, {419            headers: _res.headers,420            status: _res.status,421          })422          return423        } else {424          throw e425        }426      }427    }428    this.#res = _res429    this.finalized = true430  }431432  /**433   * `.render()` can create a response within a layout.434   *435   * @see {@link https://hono.dev/docs/api/context#render-setrenderer}436   *437   * @example438   * ```ts439   * app.get('/', (c) => {440   *   return c.render('Hello!')441   * })442   * ```443   */444  render: Renderer = (...args) => {445    this.#renderer ??= (content: string | Promise<string>) => this.html(content)446    return this.#renderer(...args)447  }448449  /**450   * Sets the layout for the response.451   *452   * @param layout - The layout to set.453   * @returns The layout function.454   */455  setLayout = (456    layout: Layout<PropsForRenderer & { Layout: Layout }>457  ): Layout<458    PropsForRenderer & {459      Layout: Layout460    }461  > => (this.#layout = layout)462463  /**464   * Gets the current layout for the response.465   *466   * @returns The current layout function.467   */468  getLayout = (): Layout<PropsForRenderer & { Layout: Layout }> | undefined => this.#layout469470  /**471   * `.setRenderer()` can set the layout in the custom middleware.472   *473   * @see {@link https://hono.dev/docs/api/context#render-setrenderer}474   *475   * @example476   * ```tsx477   * app.use('*', async (c, next) => {478   *   c.setRenderer((content) => {479   *     return c.html(480   *       <html>481   *         <body>482   *           <p>{content}</p>483   *         </body>484   *       </html>485   *     )486   *   })487   *   await next()488   * })489   * ```490   */491  setRenderer = (renderer: Renderer): void => {492    this.#renderer = renderer493  }494495  /**496   * `.header()` can set headers.497   *498   * @see {@link https://hono.dev/docs/api/context#body}499   *500   * @example501   * ```ts502   * app.get('/welcome', (c) => {503   *   // Set headers504   *   c.header('X-Message', 'Hello!')505   *   c.header('Content-Type', 'text/plain')506   *507   *   return c.body('Thank you for coming')508   * })509   * ```510   */511  header: SetHeaders = (name, value, options): void => {512    // Clear the header513    if (value === undefined) {514      if (this.#headers) {515        this.#headers.delete(name)516      } else if (this.#preparedHeaders) {517        delete this.#preparedHeaders[name.toLocaleLowerCase()]518      }519      if (this.finalized) {520        this.res.headers.delete(name)521      }522      return523    }524525    if (options?.append) {526      if (!this.#headers) {527        this.#isFresh = false528        this.#headers = new Headers(this.#preparedHeaders)529        this.#preparedHeaders = {}530      }531      this.#headers.append(name, value)532    } else {533      if (this.#headers) {534        this.#headers.set(name, value)535      } else {536        this.#preparedHeaders ??= {}537        this.#preparedHeaders[name.toLowerCase()] = value538      }539    }540541    if (this.finalized) {542      if (options?.append) {543        this.res.headers.append(name, value)544      } else {545        this.res.headers.set(name, value)546      }547    }548  }549550  status = (status: StatusCode): void => {551    this.#isFresh = false552    this.#status = status553  }554555  /**556   * `.set()` can set the value specified by the key.557   *558   * @see {@link https://hono.dev/docs/api/context#set-get}559   *560   * @example561   * ```ts562   * app.use('*', async (c, next) => {563   *   c.set('message', 'Hono is cool!!')564   *   await next()565   * })566   * ```567   */568  set: Set<569    IsAny<E> extends true570      ? {571          // eslint-disable-next-line @typescript-eslint/no-explicit-any572          Variables: ContextVariableMap & Record<string, any>573        }574      : E575  > = (key: string, value: unknown) => {576    this.#var ??= new Map()577    this.#var.set(key, value)578  }579580  /**581   * `.get()` can use the value specified by the key.582   *583   * @see {@link https://hono.dev/docs/api/context#set-get}584   *585   * @example586   * ```ts587   * app.get('/', (c) => {588   *   const message = c.get('message')589   *   return c.text(`The message is "${message}"`)590   * })591   * ```592   */593  get: Get<594    IsAny<E> extends true595      ? {596          // eslint-disable-next-line @typescript-eslint/no-explicit-any597          Variables: ContextVariableMap & Record<string, any>598        }599      : E600  > = (key: string) => {601    return this.#var ? this.#var.get(key) : undefined602  }603604  /**605   * `.var` can access the value of a variable.606   *607   * @see {@link https://hono.dev/docs/api/context#var}608   *609   * @example610   * ```ts611   * const result = c.var.client.oneMethod()612   * ```613   */614  // c.var.propName is a read-only615  get var(): Readonly<616    // eslint-disable-next-line @typescript-eslint/no-explicit-any617    ContextVariableMap & (IsAny<E['Variables']> extends true ? Record<string, any> : E['Variables'])618  > {619    if (!this.#var) {620      // eslint-disable-next-line @typescript-eslint/no-explicit-any621      return {} as any622    }623    return Object.fromEntries(this.#var)624  }625626  newResponse: NewResponse = (627    data: Data | null,628    arg?: StatusCode | ResponseInit,629    headers?: HeaderRecord630  ): Response => {631    // Optimized632    if (this.#isFresh && !headers && !arg && this.#status === 200) {633      return new Response(data, {634        headers: this.#preparedHeaders,635      })636    }637638    if (arg && typeof arg !== 'number') {639      const header = new Headers(arg.headers)640      if (this.#headers) {641        // If the header is set by c.header() and arg.headers, c.header() will be prioritized.642        this.#headers.forEach((v, k) => {643          if (k === 'set-cookie') {644            header.append(k, v)645          } else {646            header.set(k, v)647          }648        })649      }650      const headers = setHeaders(header, this.#preparedHeaders)651      return new Response(data, {652        headers,653        status: arg.status ?? this.#status,654      })655    }656657    const status = typeof arg === 'number' ? arg : this.#status658    this.#preparedHeaders ??= {}659660    this.#headers ??= new Headers()661    setHeaders(this.#headers, this.#preparedHeaders)662663    if (this.#res) {664      this.#res.headers.forEach((v, k) => {665        if (k === 'set-cookie') {666          this.#headers?.append(k, v)667        } else {668          this.#headers?.set(k, v)669        }670      })671      setHeaders(this.#headers, this.#preparedHeaders)672    }673674    headers ??= {}675    for (const [k, v] of Object.entries(headers)) {676      if (typeof v === 'string') {677        this.#headers.set(k, v)678      } else {679        this.#headers.delete(k)680        for (const v2 of v) {681          this.#headers.append(k, v2)682        }683      }684    }685686    return new Response(data, {687      status,688      headers: this.#headers,689    })690  }691692  /**693   * `.body()` can return the HTTP response.694   * You can set headers with `.header()` and set HTTP status code with `.status`.695   * This can also be set in `.text()`, `.json()` and so on.696   *697   * @see {@link https://hono.dev/docs/api/context#body}698   *699   * @example700   * ```ts701   * app.get('/welcome', (c) => {702   *   // Set headers703   *   c.header('X-Message', 'Hello!')704   *   c.header('Content-Type', 'text/plain')705   *   // Set HTTP status code706   *   c.status(201)707   *708   *   // Return the response body709   *   return c.body('Thank you for coming')710   * })711   * ```712   */713  body: BodyRespond = (714    data: Data | null,715    arg?: StatusCode | ResponseInit,716    headers?: HeaderRecord717  ): Response => {718    return typeof arg === 'number'719      ? this.newResponse(data, arg, headers)720      : this.newResponse(data, arg)721  }722723  /**724   * `.text()` can render text as `Content-Type:text/plain`.725   *726   * @see {@link https://hono.dev/docs/api/context#text}727   *728   * @example729   * ```ts730   * app.get('/say', (c) => {731   *   return c.text('Hello!')732   * })733   * ```734   */735  text: TextRespond = (736    text: string,737    arg?: StatusCode | ResponseInit,738    headers?: HeaderRecord739  ): ReturnType<TextRespond> => {740    // If the header is empty, return Response immediately.741    // Content-Type will be added automatically as `text/plain`.742    if (!this.#preparedHeaders) {743      if (this.#isFresh && !headers && !arg) {744        // @ts-expect-error `Response` due to missing some types-only keys745        return new Response(text)746      }747      this.#preparedHeaders = {}748    }749    this.#preparedHeaders['content-type'] = TEXT_PLAIN750    // @ts-expect-error `Response` due to missing some types-only keys751    return typeof arg === 'number'752      ? this.newResponse(text, arg, headers)753      : this.newResponse(text, arg)754  }755756  /**757   * `.json()` can render JSON as `Content-Type:application/json`.758   *759   * @see {@link https://hono.dev/docs/api/context#json}760   *761   * @example762   * ```ts763   * app.get('/api', (c) => {764   *   return c.json({ message: 'Hello!' })765   * })766   * ```767   */768  json: JSONRespond = <769    T extends JSONValue | SimplifyDeepArray<unknown> | InvalidJSONValue,770    U extends StatusCode = StatusCode771  >(772    object: T,773    arg?: U | ResponseInit,774    headers?: HeaderRecord775  ): JSONRespondReturn<T, U> => {776    const body = JSON.stringify(object)777    this.#preparedHeaders ??= {}778    this.#preparedHeaders['content-type'] = 'application/json; charset=UTF-8'779    /* eslint-disable @typescript-eslint/no-explicit-any */780    return (781      typeof arg === 'number' ? this.newResponse(body, arg, headers) : this.newResponse(body, arg)782    ) as any783  }784785  html: HTMLRespond = (786    html: string | Promise<string>,787    arg?: StatusCode | ResponseInit,788    headers?: HeaderRecord789  ): Response | Promise<Response> => {790    this.#preparedHeaders ??= {}791    this.#preparedHeaders['content-type'] = 'text/html; charset=UTF-8'792793    if (typeof html === 'object') {794      return resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then((html) => {795        return typeof arg === 'number'796          ? this.newResponse(html, arg, headers)797          : this.newResponse(html, arg)798      })799    }800801    return typeof arg === 'number'802      ? this.newResponse(html as string, arg, headers)803      : this.newResponse(html as string, arg)804  }805806  /**807   * `.redirect()` can Redirect, default status code is 302.808   *809   * @see {@link https://hono.dev/docs/api/context#redirect}810   *811   * @example812   * ```ts813   * app.get('/redirect', (c) => {814   *   return c.redirect('/')815   * })816   * app.get('/redirect-permanently', (c) => {817   *   return c.redirect('/', 301)818   * })819   * ```820   */821  redirect = <T extends RedirectStatusCode = 302>(822    location: string | URL,823    status?: T824  ): Response & TypedResponse<undefined, T, 'redirect'> => {825    this.#headers ??= new Headers()826    this.#headers.set('Location', String(location))827    return this.newResponse(null, status ?? 302) as any828  }829830  /**831   * `.notFound()` can return the Not Found Response.832   *833   * @see {@link https://hono.dev/docs/api/context#notfound}834   *835   * @example836   * ```ts837   * app.get('/notfound', (c) => {838   *   return c.notFound()839   * })840   * ```841   */842  notFound = (): Response | Promise<Response> => {843    this.#notFoundHandler ??= () => new Response()844    return this.#notFoundHandler(this)845  }846}