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

The walk stopped after 200 commits: lines older than 7ee829b point at it.

perf(context): improve initializing `Context` (#3046)Yusuke Wadabefore adoptionae3a67b

lines 1–11why, one step back
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'

feat(header): suggest name of header and combine in one file (#3577)EdamAmexbefore adoptione7732a5

line 12why, one step back
12import type { ResponseHeader } from './utils/headers'

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 13–14why, one step back
13import { HtmlEscapedCallbackPhase, resolveCallback } from './utils/html'
14import type { RedirectStatusCode, StatusCode } from './utils/http-status'

chore(lint): ESLint v9 (#3393)Yusuke Wadabefore adoption5f78e4e

line 15why, one step back
15import type { BaseMime } from './utils/mime'

feat(types): improve JSONParsed (#3074)m-shakabefore adoption2a4f257

lines 16–22why, one step back
16import type {
17 InvalidJSONValue,18 IsAny,19 JSONParsed,20 JSONValue,21 SimplifyDeepArray,22} from './utils/types'

v4.4.7Yusuke Wadabefore adoption7ee829b

line 23why, one step back
23

feat(context): add Context-Type types to `c.header` (#3255)Shotaro Nakamurabefore adoptionac069d1

lines 24–27why, one step back
24type HeaderRecord =
25 | Record<'Content-Type', BaseMime>26 | Record<ResponseHeader, string | string[]>27 | Record<string, string | string[]>

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 28–155why, one step back
28
29/**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 {

feat(types): improve JSONParsed (#3074)m-shakabefore adoption2a4f257

lines 156–159why, one step back
156 <
157 T extends JSONValue | SimplifyDeepArray<unknown> | InvalidJSONValue,158 U extends StatusCode = StatusCode159 >(

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 160–163why, one step back
160 object: T,
161 status?: U,162 headers?: HeaderRecord163 ): JSONRespondReturn<T, U>

feat(types): improve JSONParsed (#3074)m-shakabefore adoption2a4f257

lines 164–167why, one step back
164 <
165 T extends JSONValue | SimplifyDeepArray<unknown> | InvalidJSONValue,166 U extends StatusCode = StatusCode167 >(

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 168–179why, one step back
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<

feat(types): improve JSONParsed (#3074)m-shakabefore adoption2a4f257

line 180why, one step back
180 T extends JSONValue | SimplifyDeepArray<unknown> | InvalidJSONValue,

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 181–187why, one step back
181 U extends StatusCode
182> = Response &183 TypedResponse<184 SimplifyDeepArray<T> extends JSONValue185 ? JSONValue extends SimplifyDeepArray<T>186 ? never187 : JSONParsed<T>

fix(type): degradation of generic type handling (#3138)m-shakabefore adoption8dc9e48

line 188why, one step back
188 : never,

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 189–231why, one step back
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>

perf(context): improve initializing `Context` (#3046)Yusuke Wadabefore adoptionae3a67b

lines 232–233why, one step back
232 matchResult?: Result<[H, RouterRoute]>
233 path?: string

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 234–235why, one step back
234}
235

feat(context): Add types for `c.header` (#3221)Shotaro Nakamurabefore adoption7cd0248

lines 236–240why, one step back
236interface SetHeadersOptions {
237 append?: boolean238}239240interface SetHeaders {

feat(context): add Context-Type types to `c.header` (#3255)Shotaro Nakamurabefore adoptionac069d1

line 241why, one step back
241 (name: 'Content-Type', value?: BaseMime, options?: SetHeadersOptions): void

feat(context): Add types for `c.header` (#3221)Shotaro Nakamurabefore adoption7cd0248

lines 242–247why, one step back
242 (name: ResponseHeader, value?: string, options?: SetHeadersOptions): void
243 (name: string, value?: string, options?: SetHeadersOptions): void244}245246type ResponseHeadersInit =247 | [string, string][]

feat(context): add Context-Type types to `c.header` (#3255)Shotaro Nakamurabefore adoptionac069d1

line 248why, one step back
248 | Record<'Content-Type', BaseMime>

feat(context): Add types for `c.header` (#3221)Shotaro Nakamurabefore adoption7cd0248

line 249why, one step back
249 | Record<ResponseHeader, string>

feat(context): add Context-Type types to `c.header` (#3255)Shotaro Nakamurabefore adoptionac069d1

line 250why, one step back
250 | Record<string, string>

feat(context): Add types for `c.header` (#3221)Shotaro Nakamurabefore adoption7cd0248

lines 251–258why, one step back
251 | Headers
252253interface ResponseInit {254 headers?: ResponseHeadersInit255 status?: number256 statusText?: string257}258

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 259–268why, one step back
259export 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> = {}) => {

refactor(context): use simple for-of syntax (#3598)Taku Amanobefore adoption224ec36

line 269why, one step back
269 for (const key of Object.keys(map)) {

perf(context): improve performance of context (setHeaders) (#3592)EdamAmexbefore adoption4dd8b2b

lines 270–271why, one step back
270 headers.set(key, map[key])
271 }

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 272–281why, one step back
272 return headers
273}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> {

perf(context): improve initializing `Context` (#3046)Yusuke Wadabefore adoptionae3a67b

lines 282–283why, one step back
282 #rawRequest: Request
283 #req: HonoRequest<P, I['out']> | undefined

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 284–286why, one step back
284 /**
285 * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.286 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 287why, one step back
287 * @see {@link https://hono.dev/docs/api/context#env}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 288–297why, one step back
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'] = {}

Merge pull request #3144 from honojs/nextYusuke Wadabefore adoption2f4bb3e

line 298why, one step back
298 #var: Map<unknown, unknown> | undefined

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 299–302why, one step back
299 finalized: boolean = false
300 /**301 * `.error` can get the error object from the middleware if the Handler throws an error.302 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 303why, one step back
303 * @see {@link https://hono.dev/docs/api/context#error}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 304–314why, one step back
304 *
305 * @example306 * ```ts307 * app.use('*', async (c, next) => {308 * await next()309 * if (c.error) {310 * // do something...311 * }312 * })313 * ```314 */

perf(context): improve initializing `Context` (#3046)Yusuke Wadabefore adoptionae3a67b

line 315why, one step back
315 error: Error | undefined

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 316–318why, one step back
316
317 #status: StatusCode = 200318 #executionCtx: FetchEventLike | ExecutionContext | undefined

perf(context): improve initializing `Context` (#3046)Yusuke Wadabefore adoptionae3a67b

lines 319–320why, one step back
319 #headers: Headers | undefined
320 #preparedHeaders: Record<string, string> | undefined

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 321–322why, one step back
321 #res: Response | undefined
322 #isFresh = true

perf(context): improve initializing `Context` (#3046)Yusuke Wadabefore adoptionae3a67b

lines 323–325why, one step back
323 #layout: Layout<PropsForRenderer & { Layout: Layout }> | undefined
324 #renderer: Renderer | undefined325 #notFoundHandler: NotFoundHandler<E> | undefined

v4.4.7Yusuke Wadabefore adoption7ee829b

line 326why, one step back
326

perf(context): improve initializing `Context` (#3046)Yusuke Wadabefore adoptionae3a67b

lines 327–329why, one step back
327 #matchResult: Result<[H, RouterRoute]> | undefined
328 #path: string | undefined329

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 330–332why, one step back
330 /**
331 * Creates an instance of the Context class.332 *

perf(context): improve initializing `Context` (#3046)Yusuke Wadabefore adoptionae3a67b

line 333why, one step back
333 * @param req - The Request object.

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 334–335why, one step back
334 * @param options - Optional configuration options for the context.
335 */

perf(context): improve initializing `Context` (#3046)Yusuke Wadabefore adoptionae3a67b

lines 336–337why, one step back
336 constructor(req: Request, options?: ContextOptions<E>) {
337 this.#rawRequest = req

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 338–340why, one step back
338 if (options) {
339 this.#executionCtx = options.executionCtx340 this.env = options.env

perf(context): improve initializing `Context` (#3046)Yusuke Wadabefore adoptionae3a67b

lines 341–343why, one step back
341 this.#notFoundHandler = options.notFoundHandler
342 this.#path = options.path343 this.#matchResult = options.matchResult

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 344–347why, one step back
344 }
345 }346347 /**

perf(context): improve initializing `Context` (#3046)Yusuke Wadabefore adoptionae3a67b

lines 348–355why, one step back
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 /**

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 356why, one step back
356 * @see {@link https://hono.dev/docs/api/context#event}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 357–369why, one step back
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 /**

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 370why, one step back
370 * @see {@link https://hono.dev/docs/api/context#executionctx}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 371–383why, one step back
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 /**

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 384why, one step back
384 * @see {@link https://hono.dev/docs/api/context#res}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 385–399why, one step back
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) {

Merge pull request #3394 from honojs/nextYusuke Wadabefore adoption2da003b

lines 400–403why, one step back
400 try {
401 for (const [k, v] of this.#res.headers.entries()) {402 if (k === 'content-type') {403 continue

v4.4.7Yusuke Wadabefore adoption7ee829b

line 404why, one step back
404 }

Merge pull request #3394 from honojs/nextYusuke Wadabefore adoption2da003b

lines 405–422why, one step back
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 return

v4.4.7Yusuke Wadabefore adoption7ee829b

line 423why, one step back
423 } else {

Merge pull request #3394 from honojs/nextYusuke Wadabefore adoption2da003b

line 424why, one step back
424 throw e

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 425–434why, one step back
425 }
426 }427 }428 this.#res = _res429 this.finalized = true430 }431432 /**433 * `.render()` can create a response within a layout.434 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 435why, one step back
435 * @see {@link https://hono.dev/docs/api/context#render-setrenderer}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 436–443why, one step back
436 *
437 * @example438 * ```ts439 * app.get('/', (c) => {440 * return c.render('Hello!')441 * })442 * ```443 */

perf(context): improve initializing `Context` (#3046)Yusuke Wadabefore adoptionae3a67b

lines 444–447why, one step back
444 render: Renderer = (...args) => {
445 this.#renderer ??= (content: string | Promise<string>) => this.html(content)446 return this.#renderer(...args)447 }

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 448–460why, one step back
448
449 /**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 }

perf(context): improve initializing `Context` (#3046)Yusuke Wadabefore adoptionae3a67b

line 461why, one step back
461 > => (this.#layout = layout)

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 462–467why, one step back
462
463 /**464 * Gets the current layout for the response.465 *466 * @returns The current layout function.467 */

perf(context): improve initializing `Context` (#3046)Yusuke Wadabefore adoptionae3a67b

line 468why, one step back
468 getLayout = (): Layout<PropsForRenderer & { Layout: Layout }> | undefined => this.#layout

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 469–472why, one step back
469
470 /**471 * `.setRenderer()` can set the layout in the custom middleware.472 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 473why, one step back
473 * @see {@link https://hono.dev/docs/api/context#render-setrenderer}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 474–491why, one step back
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 => {

perf(context): improve initializing `Context` (#3046)Yusuke Wadabefore adoptionae3a67b

line 492why, one step back
492 this.#renderer = renderer

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 493–497why, one step back
493 }
494495 /**496 * `.header()` can set headers.497 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 498why, one step back
498 * @see {@link https://hono.dev/docs/api/context#body}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 499–510why, one step back
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 */

feat(context): Add types for `c.header` (#3221)Shotaro Nakamurabefore adoption7cd0248

line 511why, one step back
511 header: SetHeaders = (name, value, options): void => {

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 512–557why, one step back
512 // Clear the header
513 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 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 558why, one step back
558 * @see {@link https://hono.dev/docs/api/context#set-get}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 559–567why, one step back
559 *
560 * @example561 * ```ts562 * app.use('*', async (c, next) => {563 * c.set('message', 'Hono is cool!!')564 * await next()565 * })566 * ```567 */

Merge pull request #3144 from honojs/nextYusuke Wadabefore adoption2f4bb3e

lines 568–577why, one step back
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)

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 578–582why, one step back
578 }
579580 /**581 * `.get()` can use the value specified by the key.582 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 583why, one step back
583 * @see {@link https://hono.dev/docs/api/context#set-get}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 584–592why, one step back
584 *
585 * @example586 * ```ts587 * app.get('/', (c) => {588 * const message = c.get('message')589 * return c.text(`The message is "${message}"`)590 * })591 * ```592 */

Merge pull request #3144 from honojs/nextYusuke Wadabefore adoption2f4bb3e

lines 593–601why, one step back
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) : undefined

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 602–606why, one step back
602 }
603604 /**605 * `.var` can access the value of a variable.606 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 607why, one step back
607 * @see {@link https://hono.dev/docs/api/context#var}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 608–618why, one step back
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 > {

Merge pull request #3144 from honojs/nextYusuke Wadabefore adoption2f4bb3e

lines 619–623why, one step back
619 if (!this.#var) {
620 // eslint-disable-next-line @typescript-eslint/no-explicit-any621 return {} as any622 }623 return Object.fromEntries(this.#var)

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 624–696why, one step back
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 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 697why, one step back
697 * @see {@link https://hono.dev/docs/api/context#body}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 698–725why, one step back
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 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 726why, one step back
726 * @see {@link https://hono.dev/docs/api/context#text}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 727–758why, one step back
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 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 759why, one step back
759 * @see {@link https://hono.dev/docs/api/context#json}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 760–768why, one step back
760 *
761 * @example762 * ```ts763 * app.get('/api', (c) => {764 * return c.json({ message: 'Hello!' })765 * })766 * ```767 */768 json: JSONRespond = <

feat(types): improve JSONParsed (#3074)m-shakabefore adoption2a4f257

line 769why, one step back
769 T extends JSONValue | SimplifyDeepArray<unknown> | InvalidJSONValue,

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 770–793why, one step back
770 U extends StatusCode = StatusCode
771 >(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') {

Merge pull request #3394 from honojs/nextYusuke Wadabefore adoption2da003b

lines 794–798why, one step back
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 })

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 799–808why, one step back
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 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 809why, one step back
809 * @see {@link https://hono.dev/docs/api/context#redirect}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 810–821why, one step back
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>(

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

line 822why, one step back
822 location: string | URL,

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 823–825why, one step back
823 status?: T
824 ): Response & TypedResponse<undefined, T, 'redirect'> => {825 this.#headers ??= new Headers()

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

line 826why, one step back
826 this.#headers.set('Location', String(location))

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 827–832why, one step back
827 return this.newResponse(null, status ?? 302) as any
828 }829830 /**831 * `.notFound()` can return the Not Found Response.832 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 833why, one step back
833 * @see {@link https://hono.dev/docs/api/context#notfound}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 834–842why, one step back
834 *
835 * @example836 * ```ts837 * app.get('/notfound', (c) => {838 * return c.notFound()839 * })840 * ```841 */842 notFound = (): Response | Promise<Response> => {

perf(context): improve initializing `Context` (#3046)Yusuke Wadabefore adoptionae3a67b

lines 843–844why, one step back
843 this.#notFoundHandler ??= () => new Response()
844 return this.#notFoundHandler(this)

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 845–846why, one step back
845 }
846}