Skip to content
Myr

context.ts

This file

Path

src/context.ts

550 lines 路 15.1 KiB 路 TypeScript

Last changed by

refactor(context): skip jsx type import (#2248)Taku Amanobefore adoption0b59827

History of this file

Take it

1import type { HonoRequest } from './request'2import type { Env, FetchEventLike, NotFoundHandler, Input, TypedResponse } from './types'3import { resolveCallback, HtmlEscapedCallbackPhase } from './utils/html'4import type { RedirectStatusCode, StatusCode } from './utils/http-status'5import type { JSONValue, InterfaceToType, JSONParsed, IsAny } from './utils/types'67type HeaderRecord = Record<string, string | string[]>8type Data = string | ArrayBuffer | ReadableStream910export interface ExecutionContext {11  waitUntil(promise: Promise<unknown>): void12  passThroughOnException(): void13}1415export interface ContextVariableMap {}1617export interface ContextRenderer {}18interface DefaultRenderer {19  (content: string | Promise<string>): Response | Promise<Response>20}2122export type Renderer = ContextRenderer extends Function ? ContextRenderer : DefaultRenderer23export type PropsForRenderer = [...Required<Parameters<Renderer>>] extends [unknown, infer Props]24  ? Props25  : unknown2627// eslint-disable-next-line @typescript-eslint/no-explicit-any28export type Layout<T = Record<string, any>> = (props: T) => any2930interface Get<E extends Env> {31  <Key extends keyof ContextVariableMap>(key: Key): ContextVariableMap[Key]32  <Key extends keyof E['Variables']>(key: Key): E['Variables'][Key]33}3435interface Set<E extends Env> {36  <Key extends keyof ContextVariableMap>(key: Key, value: ContextVariableMap[Key]): void37  <Key extends keyof E['Variables']>(key: Key, value: E['Variables'][Key]): void38}3940interface NewResponse {41  (data: Data | null, status?: StatusCode, headers?: HeaderRecord): Response42  (data: Data | null, init?: ResponseInit): Response43}4445interface BodyRespond extends NewResponse {}4647interface TextRespond {48  (text: string, status?: StatusCode, headers?: HeaderRecord): Response49  (text: string, init?: ResponseInit): Response50}5152interface JSONRespond {53  <T>(54    object: InterfaceToType<T> extends JSONValue ? T : JSONValue,55    status?: StatusCode,56    headers?: HeaderRecord57  ): Response &58    TypedResponse<59      InterfaceToType<T> extends JSONValue60        ? JSONValue extends InterfaceToType<T>61          ? never62          : JSONParsed<T>63        : never64    >65  <T>(object: InterfaceToType<T> extends JSONValue ? T : JSONValue, init?: ResponseInit): Response &66    TypedResponse<67      InterfaceToType<T> extends JSONValue68        ? JSONValue extends InterfaceToType<T>69          ? never70          : JSONParsed<T>71        : never72    >73}7475interface HTMLRespond {76  (html: string | Promise<string>, status?: StatusCode, headers?: HeaderRecord):77    | Response78    | Promise<Response>79  (html: string | Promise<string>, init?: ResponseInit): Response | Promise<Response>80}8182type ContextOptions<E extends Env> = {83  env: E['Bindings']84  executionCtx?: FetchEventLike | ExecutionContext | undefined85  notFoundHandler?: NotFoundHandler<E>86}8788export const TEXT_PLAIN = 'text/plain; charset=UTF-8'8990const setHeaders = (headers: Headers, map: Record<string, string> = {}) => {91  Object.entries(map).forEach(([key, value]) => headers.set(key, value))92  return headers93}9495export class Context<96  // eslint-disable-next-line @typescript-eslint/no-explicit-any97  E extends Env = any,98  // eslint-disable-next-line @typescript-eslint/no-explicit-any99  P extends string = any,100  I extends Input = {}101> {102  /**103   * `.req` is the instance of {@link HonoRequest}.104   */105  req: HonoRequest<P, I['out']>106  /**107   * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.108   * @example109   * ```ts110   * // Environment object for Cloudflare Workers111   * app.get('*', async c => {112   *   const counter = c.env.COUNTER113   * })114   * ```115   * @see https://hono.dev/api/context#env116   */117  env: E['Bindings'] = {}118  private _var: E['Variables'] = {}119  finalized: boolean = false120  /**121   * `.error` can get the error object from the middleware if the Handler throws an error.122   * @example123   * ```ts124   * app.use('*', async (c, next) => {125   *   await next()126   *   if (c.error) {127   *     // do something...128   *   }129   * })130   * ```131   * @see https://hono.dev/api/context#error132   */133  error: Error | undefined = undefined134135  #status: StatusCode = 200136  #executionCtx: FetchEventLike | ExecutionContext | undefined137  #headers: Headers | undefined = undefined138  #preparedHeaders: Record<string, string> | undefined = undefined139  #res: Response | undefined140  #isFresh = true141  private layout: Layout<PropsForRenderer & { Layout: Layout }> | undefined = undefined142  private renderer: Renderer = (content: string | Promise<string>) => this.html(content)143  private notFoundHandler: NotFoundHandler<E> = () => new Response()144145  constructor(req: HonoRequest<P, I['out']>, options?: ContextOptions<E>) {146    this.req = req147    if (options) {148      this.#executionCtx = options.executionCtx149      this.env = options.env150      if (options.notFoundHandler) {151        this.notFoundHandler = options.notFoundHandler152      }153    }154  }155156  /**157   * @see https://hono.dev/api/context#event158   */159  get event(): FetchEventLike {160    if (this.#executionCtx && 'respondWith' in this.#executionCtx) {161      return this.#executionCtx162    } else {163      throw Error('This context has no FetchEvent')164    }165  }166167  /**168   * @see https://hono.dev/api/context#executionctx169   */170  get executionCtx(): ExecutionContext {171    if (this.#executionCtx) {172      return this.#executionCtx as ExecutionContext173    } else {174      throw Error('This context has no ExecutionContext')175    }176  }177178  /**179   * @see https://hono.dev/api/context#res180   */181  get res(): Response {182    this.#isFresh = false183    return (this.#res ||= new Response('404 Not Found', { status: 404 }))184  }185186  set res(_res: Response | undefined) {187    this.#isFresh = false188    if (this.#res && _res) {189      this.#res.headers.delete('content-type')190      for (const [k, v] of this.#res.headers.entries()) {191        if (k === 'set-cookie') {192          const cookies = this.#res.headers.getSetCookie()193          _res.headers.delete('set-cookie')194          for (const cookie of cookies) {195            _res.headers.append('set-cookie', cookie)196          }197        } else {198          _res.headers.set(k, v)199        }200      }201    }202    this.#res = _res203    this.finalized = true204  }205206  /**207   * `.render()` can create a response within a layout.208   * @example209   * ```ts210   * app.get('/', (c) => {211   *   return c.render('Hello!')212   * })213   * ```214   * @see https://hono.dev/api/context#render-setrenderer215   */216  render: Renderer = (...args) => this.renderer(...args)217218  setLayout = (layout: Layout<PropsForRenderer & { Layout: Layout }>) => (this.layout = layout)219  getLayout = () => this.layout220221  /**222   * `.setRenderer()` can set the layout in the custom middleware.223   * @example224   * ```tsx225   * app.use('*', async (c, next) => {226   *   c.setRenderer((content) => {227   *     return c.html(228   *       <html>229   *         <body>230   *           <p>{content}</p>231   *         </body>232   *       </html>233   *     )234   *   })235   *   await next()236   * })237   * ```238   * @see https://hono.dev/api/context#render-setrenderer239   */240  setRenderer = (renderer: Renderer) => {241    this.renderer = renderer242  }243244  /**245   * `.header()` can set headers.246   * @example247   * ```ts248   * app.get('/welcome', (c) => {249   *   // Set headers250   *   c.header('X-Message', 'Hello!')251   *   c.header('Content-Type', 'text/plain')252   *253   *   return c.body('Thank you for coming')254   * })255   * ```256   * @see https://hono.dev/api/context#body257   */258  header = (name: string, value: string | undefined, options?: { append?: boolean }): void => {259    // Clear the header260    if (value === undefined) {261      if (this.#headers) {262        this.#headers.delete(name)263      } else if (this.#preparedHeaders) {264        delete this.#preparedHeaders[name.toLocaleLowerCase()]265      }266      if (this.finalized) {267        this.res.headers.delete(name)268      }269      return270    }271272    if (options?.append) {273      if (!this.#headers) {274        this.#isFresh = false275        this.#headers = new Headers(this.#preparedHeaders)276        this.#preparedHeaders = {}277      }278      this.#headers.append(name, value)279    } else {280      if (this.#headers) {281        this.#headers.set(name, value)282      } else {283        this.#preparedHeaders ??= {}284        this.#preparedHeaders[name.toLowerCase()] = value285      }286    }287288    if (this.finalized) {289      if (options?.append) {290        this.res.headers.append(name, value)291      } else {292        this.res.headers.set(name, value)293      }294    }295  }296297  status = (status: StatusCode): void => {298    this.#isFresh = false299    this.#status = status300  }301302  /**303   * `.set()` can set the value specified by the key.304   * @example305   * ```ts306   * app.use('*', async (c, next) => {307   *   c.set('message', 'Hono is cool!!')308   *   await next()309   * })310   * ```311   * @see https://hono.dev/api/context#set-get312```313   */314  set: Set<E> = (key: string, value: unknown) => {315    this._var ??= {}316    this._var[key as string] = value317  }318319  /**320   * `.get()` can use the value specified by the key.321   * @example322   * ```ts323   * app.get('/', (c) => {324   *   const message = c.get('message')325   *   return c.text(`The message is "${message}"`)326   * })327   * ```328   * @see https://hono.dev/api/context#set-get329   */330  get: Get<E> = (key: string) => {331    return this._var ? this._var[key] : undefined332  }333334  /**335   * `.var` can access the value of a variable.336   * @example337   * ```ts338   * const result = c.var.client.oneMethod()339   * ```340   * @see https://hono.dev/api/context#var341   */342  // c.var.propName is a read-only343  get var(): Readonly<344    // eslint-disable-next-line @typescript-eslint/no-explicit-any345    ContextVariableMap & (IsAny<E['Variables']> extends true ? Record<string, any> : E['Variables'])346  > {347    return { ...this._var } as never348  }349350  newResponse: NewResponse = (351    data: Data | null,352    arg?: StatusCode | ResponseInit,353    headers?: HeaderRecord354  ): Response => {355    // Optimized356    if (this.#isFresh && !headers && !arg && this.#status === 200) {357      return new Response(data, {358        headers: this.#preparedHeaders,359      })360    }361362    if (arg && typeof arg !== 'number') {363      const headers = setHeaders(new Headers(arg.headers), this.#preparedHeaders)364      return new Response(data, {365        headers,366        status: arg.status ?? this.#status,367      })368    }369370    const status = typeof arg === 'number' ? arg : this.#status371    this.#preparedHeaders ??= {}372373    this.#headers ??= new Headers()374    setHeaders(this.#headers, this.#preparedHeaders)375376    if (this.#res) {377      this.#res.headers.forEach((v, k) => {378        this.#headers?.set(k, v)379      })380      setHeaders(this.#headers, this.#preparedHeaders)381    }382383    headers ??= {}384    for (const [k, v] of Object.entries(headers)) {385      if (typeof v === 'string') {386        this.#headers.set(k, v)387      } else {388        this.#headers.delete(k)389        for (const v2 of v) {390          this.#headers.append(k, v2)391        }392      }393    }394395    return new Response(data, {396      status,397      headers: this.#headers,398    })399  }400401  /**402   * `.body()` can return the HTTP response.403   * You can set headers with `.header()` and set HTTP status code with `.status`.404   * This can also be set in `.text()`, `.json()` and so on.405   * @example406   * ```ts407   * app.get('/welcome', (c) => {408   *   // Set headers409   *   c.header('X-Message', 'Hello!')410   *   c.header('Content-Type', 'text/plain')411   *   // Set HTTP status code412   *   c.status(201)413   *414   *   // Return the response body415   *   return c.body('Thank you for coming')416   * })417   * ```418   * @see https://hono.dev/api/context#body419   */420  body: BodyRespond = (421    data: Data | null,422    arg?: StatusCode | ResponseInit,423    headers?: HeaderRecord424  ): Response => {425    return typeof arg === 'number'426      ? this.newResponse(data, arg, headers)427      : this.newResponse(data, arg)428  }429430  /**431   * `.text()` can render text as `Content-Type:text/plain`.432   * @example433   * ```ts434   * app.get('/say', (c) => {435   *   return c.text('Hello!')436   * })437   * ```438   * @see https://hono.dev/api/context#text439   */440  text: TextRespond = (441    text: string,442    arg?: StatusCode | ResponseInit,443    headers?: HeaderRecord444  ): Response => {445    // If the header is empty, return Response immediately.446    // Content-Type will be added automatically as `text/plain`.447    if (!this.#preparedHeaders) {448      if (this.#isFresh && !headers && !arg) {449        return new Response(text)450      }451      this.#preparedHeaders = {}452    }453    this.#preparedHeaders['content-type'] = TEXT_PLAIN454    return typeof arg === 'number'455      ? this.newResponse(text, arg, headers)456      : this.newResponse(text, arg)457  }458459  /**460   * `.json()` can render JSON as `Content-Type:application/json`.461   * @example462   * ```ts463   * app.get('/api', (c) => {464   *   return c.json({ message: 'Hello!' })465   * })466   * ```467   * @see https://hono.dev/api/context#json468   */469  json: JSONRespond = <T>(470    object: InterfaceToType<T> extends JSONValue ? T : JSONValue,471    arg?: StatusCode | ResponseInit,472    headers?: HeaderRecord473  ): Response &474    TypedResponse<475      InterfaceToType<T> extends JSONValue476        ? JSONValue extends InterfaceToType<T>477          ? never478          : JSONParsed<T>479        : never480    > => {481    const body = JSON.stringify(object)482    this.#preparedHeaders ??= {}483    this.#preparedHeaders['content-type'] = 'application/json; charset=UTF-8'484    /* eslint-disable @typescript-eslint/no-explicit-any */485    return (486      typeof arg === 'number' ? this.newResponse(body, arg, headers) : this.newResponse(body, arg)487    ) as any488  }489490  html: HTMLRespond = (491    html: string | Promise<string>,492    arg?: StatusCode | ResponseInit,493    headers?: HeaderRecord494  ): Response | Promise<Response> => {495    this.#preparedHeaders ??= {}496    this.#preparedHeaders['content-type'] = 'text/html; charset=UTF-8'497498    if (typeof html === 'object') {499      if (!(html instanceof Promise)) {500        html = (html as string).toString() // HtmlEscapedString object to string501      }502      if ((html as string | Promise<string>) instanceof Promise) {503        return (html as unknown as Promise<string>)504          .then((html) => resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}))505          .then((html) => {506            return typeof arg === 'number'507              ? this.newResponse(html, arg, headers)508              : this.newResponse(html, arg)509          })510      }511    }512513    return typeof arg === 'number'514      ? this.newResponse(html as string, arg, headers)515      : this.newResponse(html as string, arg)516  }517518  /**519   * `.redirect()` can Redirect, default status code is 302.520   * @example521   * ```ts522   * app.get('/redirect', (c) => {523   *   return c.redirect('/')524   * })525   * app.get('/redirect-permanently', (c) => {526   *   return c.redirect('/', 301)527   * })528   * ```529   * @see https://hono.dev/api/context#redirect530   */531  redirect = (location: string, status: RedirectStatusCode = 302): Response => {532    this.#headers ??= new Headers()533    this.#headers.set('Location', location)534    return this.newResponse(null, status)535  }536537  /**538   * `.notFound()` can return the Not Found Response.539   * @example540   * ```ts541   * app.get('/notfound', (c) => {542   *   return c.notFound()543   * })544   * ```545   * @see https://hono.dev/api/context#notfound546   */547  notFound = (): Response | Promise<Response> => {548    return this.notFoundHandler(this)549  }550}