Skip to content
Myr

Merge pull request #1489 from honojs/next

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Yusuke Wada · committed by GitHub · parents d6478aa, 6c37462 · Browse files · 28 files+601 added−51 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

28 files+601 added−51 removed

  • tests:+255 added−13 removed
  • other:+346 added−38 removed

28 files+601 added−51 removed

modified:benchmarks/routers/src/bench.mts+2 added
modified:benchmarks/routers/src/hono.mts+1 added-1 removed
added:benchmarks/routers/src/memoirist.mts+17 added
modified:benchmarks/routers/package.json+1 added
modified:deno_dist/client/client.ts+14 added-1 removed
1import type { Hono } from '../hono.ts'2import type { ValidationTargets } from '../types.ts'3import { serialize } from '../utils/cookie.ts'4import type { UnionToIntersection } from '../utils/types.ts'5import type { Callback, Client, ClientRequestOptions } from './types.ts'6import { deepMerge, mergePath, removeIndexString, replaceUrlParam } from './utils.ts'7
78 unmodified lines
8687 let methodUpperCase = this.method.toUpperCase()88 let setBody = !(methodUpperCase === 'GET' || methodUpperCase === 'HEAD')8989 const headerValues: Record<string, string> = opt?.headers ? opt.headers : {}90 const headerValues: Record<string, string> = {91 ...(args?.header ?? {}),92 ...(opt?.headers ? opt.headers : {}),93 }9495 if (args?.cookie) {96 const cookies: string[] = []97 for (const [key, value] of Object.entries(args.cookie)) {98 cookies.push(serialize(key, value, { path: '/' }))99 }100 headerValues['Cookie'] = cookies.join(',')101 }102103 if (this.cType) headerValues['Content-Type'] = this.cType104105 const headers = new Headers(headerValues ?? undefined)106 let url = this.url
49 unmodified lines
modified:deno_dist/client/types.ts+26 added-11 removed
2 unmodified lines
3import type { RemoveBlankRecord } from '../utils/types.ts'45type HonoRequest = typeof Hono.prototype['request']67export type ClientRequestOptions<T = unknown> = keyof T extends never7export type ClientRequestOptions = {8 headers?: Record<string, string>9 fetch?: typeof fetch | HonoRequest10}8 ? {9 headers?: Record<string, string>10 fetch?: typeof fetch | HonoRequest11 }12 : {13 headers: T14 fetch?: typeof fetch | HonoRequest15 }1617type ClientRequest<S extends Schema> = {18 [M in keyof S]: S[M] extends { input: infer R; output: infer O }19 ? RemoveBlankRecord<R> extends never20 ? (args?: {}, options?: ClientRequestOptions) => Promise<ClientResponse<O>>16 : (17 // Client does not support `header` and `cookie`18 args: Omit<R, 'header' | 'cookie'>,19 options?: ClientRequestOptions20 ) => Promise<ClientResponse<O>>21 : (args: R, options?: ClientRequestOptions) => Promise<ClientResponse<O>>22 : never23} & {24 $url: () => URL25}
27 unmodified lines
53) => Promise<ClientResponse<InferResponseType<T>>>5455export type InferResponseType<T> = T extends (56 // eslint-disable-next-line @typescript-eslint/no-explicit-any56 args: any | undefined57 args: any | undefined,58 // eslint-disable-next-line @typescript-eslint/no-explicit-any59 options: any | undefined60) => Promise<ClientResponse<infer O>>61 ? O62 : never6361export type InferRequestType<T> = T extends (args: infer R) => Promise<ClientResponse<unknown>>64export type InferRequestType<T> = T extends (65 args: infer R,66 // eslint-disable-next-line @typescript-eslint/no-explicit-any67 options: any | undefined68) => Promise<ClientResponse<unknown>>69 ? NonNullable<R>70 : never7172export type InferRequestOptionsType<T> = T extends (73 // eslint-disable-next-line @typescript-eslint/no-explicit-any74 args: any,75 options: infer R76) => Promise<ClientResponse<unknown>>77 ? NonNullable<R>78 : never7980type PathToChain<81 Path extends string,82 E extends Schema,83 Original extends string = ''
30 unmodified lines
added:deno_dist/helper/testing/index.ts+18 added
modified:deno_dist/middleware/jwt/index.ts+4 added
75 unmodified lines
7677 await next()78 }79}8081export const verify = Jwt.verify82export const decode = Jwt.decode83export const sign = Jwt.sign
modified:deno_dist/utils/body.ts+12 added-2 removed
1import type { HonoRequest } from '../request.ts'23export type BodyData = Record<string, string | File>3export type BodyData = Record<string, string | string[] | File>45export const parseBody = async <T extends BodyData = BodyData>(6 request: HonoRequest | Request7): Promise<T> => {
8 unmodified lines
16 const formData = await request.formData()17 if (formData) {18 const form: BodyData = {}19 formData.forEach((value, key) => {20 if (key.slice(-2) === '[]') {21 if (!form[key]) {22 form[key] = [value.toString()]23 } else {24 if (Array.isArray(form[key])) {25 ;(form[key] as string[]).push(value.toString())26 }27 }28 } else {20 form[key] = value29 form[key] = value30 }31 })32 body = form33 }34 }
2 unmodified lines
modified:deno_dist/utils/cookie.ts+8 added-3 removed
9 unmodified lines
10 path?: string11 secure?: boolean12 signingSecret?: string13 sameSite?: 'Strict' | 'Lax' | 'None'14 partitioned?: boolean15}1617const algorithm = { name: 'HMAC', hash: 'SHA-256' }18
85 unmodified lines
104 cookie += `; Max-Age=${Math.floor(opt.maxAge)}`105 }106107 if (opt.domain) {107 cookie += '; Domain=' + opt.domain108 cookie += `; Domain=${opt.domain}`109 }110111 if (opt.path) {111 cookie += '; Path=' + opt.path112 cookie += `; Path=${opt.path}`113 }114115 if (opt.expires) {115 cookie += '; Expires=' + opt.expires.toUTCString()116 cookie += `; Expires=${opt.expires.toUTCString()}`117 }118119 if (opt.httpOnly) {120 cookie += '; HttpOnly'
6 unmodified lines
127 if (opt.sameSite) {128 cookie += `; SameSite=${opt.sameSite}`129 }130131 if (opt.partitioned) {132 cookie += '; Partitioned'133 }134135 return cookie136}137138export const serialize = (name: string, value: string, opt: CookieOptions = {}): string => {
15 unmodified lines
added:deno_dist/utils/stream.ts+46 added
1export class StreamingApi {2 private writer: WritableStreamDefaultWriter<Uint8Array>3 private encoder: TextEncoder4 private writable: WritableStream56 constructor(writable: WritableStream) {7 this.writable = writable8 this.writer = writable.getWriter()9 this.encoder = new TextEncoder()10 }1112 async write(input: Uint8Array | string) {13 try {14 if (typeof input === 'string') {15 input = this.encoder.encode(input)16 }17 await this.writer.write(input)18 } catch (e) {19 // Do nothing. If you want to handle errors, create a stream by yourself.20 }21 return this22 }2324 async writeln(input: string) {25 await this.write(input + '\n')26 return this27 }2829 sleep(ms: number) {30 return new Promise((res) => setTimeout(res, ms))31 }3233 async close() {34 try {35 await this.writer.close()36 } catch (e) {37 // Do nothing. If you want to handle errors, create a stream by yourself.38 }39 }4041 async pipe(body: ReadableStream) {42 this.writer.releaseLock()43 await body.pipeTo(this.writable, { preventClose: true })44 this.writer = this.writable.getWriter()45 }46}
modified:deno_dist/context.ts+30 added-1 removed
2 unmodified lines
3import type { Env, NotFoundHandler, Input, TypedResponse } from './types.ts'4import type { CookieOptions } from './utils/cookie.ts'5import { serialize } from './utils/cookie.ts'6import type { StatusCode } from './utils/http-status.ts'7import { StreamingApi } from './utils/stream.ts'8import type { JSONValue, InterfaceToType } from './utils/types.ts'910type Runtime = 'node' | 'deno' | 'bun' | 'workerd' | 'fastly' | 'edge-light' | 'lagon' | 'other'11type HeaderRecord = Record<string, string | string[]>
73 unmodified lines
85 executionCtx?: FetchEventLike | ExecutionContext | undefined86 notFoundHandler?: NotFoundHandler<E>87}8889const TEXT_PLAIN = 'text/plain; charset=UTF-8'9091export class Context<92 // eslint-disable-next-line @typescript-eslint/no-explicit-any93 E extends Env = any,94 // eslint-disable-next-line @typescript-eslint/no-explicit-any
217 unmodified lines
312 }313 // If Content-Type is not set, we don't have to set `text/plain`.314 // Fewer the header values, it will be faster.315 if (this._pH['content-type']) {313 this._pH['content-type'] = 'text/plain; charset=UTF-8'316 this._pH['content-type'] = TEXT_PLAIN317 }318 return typeof arg === 'number'319 ? this.newResponse(text, arg, headers)320 : this.newResponse(text, arg)
52 unmodified lines
373 this._h.set('Location', location)374 return this.newResponse(null, status)375 }376377 streamText = (378 cb: (stream: StreamingApi) => Promise<void>,379 arg?: StatusCode | ResponseInit,380 headers?: HeaderRecord381 ): Response => {382 headers ??= {}383 this.header('content-type', TEXT_PLAIN)384 this.header('x-content-type-options', 'nosniff')385 this.header('transfer-encoding', 'chunked')386 return this.stream(cb, arg, headers)387 }388389 stream = (390 cb: (stream: StreamingApi) => Promise<void>,391 arg?: StatusCode | ResponseInit,392 headers?: HeaderRecord393 ): Response => {394 const { readable, writable } = new TransformStream()395 const stream = new StreamingApi(writable)396 cb(stream).finally(() => stream.close())397398 return typeof arg === 'number'399 ? this.newResponse(readable, arg, headers)400 : this.newResponse(readable, arg)401 }402403 /** @deprecated404 * Use Cookie Middleware instead of `c.cookie()`. The `c.cookie()` will be removed in v4.405 *406 * @example
66 unmodified lines
modified:src/client/client.test.ts+102 added-9 removed
5 unmodified lines
6import { setupServer } from 'msw/node'7import _fetch, { Request as NodeFetchRequest } from 'node-fetch'8import { vi } from 'vitest'9import { Hono } from '../hono'10import { parse, serialize } from '../utils/cookie'11import type { Equal, Expect } from '../utils/types'12import { validator } from '../validator'13import { hc } from './client'13import type { InferRequestType, InferResponseType } from './types'14import type { InferRequestOptionsType, InferRequestType, InferResponseType } from './types'1516// @ts-ignore17global.fetch = _fetch18// @ts-ignore
6 unmodified lines
2526 const route = app27 .post(28 '/posts',28 // Client does not support `cookie`29 validator('cookie', () => {30 return {} as {31 debug: string32 }33 }),34 // Client does not support `header`34 validator('header', () => {35 return {} as {37 'x-request-id': string36 'x-message': string37 }38 }),39 validator('json', () => {40 return {} as {
54 unmodified lines
95 it('Should get 200 response', async () => {96 const res = await client.posts.$post(97 {98 json: payload,100 },101 {102 headers: {99 header: {100 'x-message': 'foobar',101 },105 }102 cookie: {103 debug: 'true',104 },105 },106 {}107 )108109 expect(res.ok).toBe(true)110 const data = await res.json()
10 unmodified lines
121 expect(res.status).toBe(404)122 })123})124124describe('Basic - query, queries, form, and path params', () => {125describe('Basic - query, queries, form, path params, header and cookie', () => {126 const app = new Hono()127128 const route = app129 .get(
32 unmodified lines
162 const data = c.req.valid('form')163 return c.jsonT(data)164 }165 )166 .get(167 '/header',168 validator('header', () => {169 return {170 'x-message-id': 'Hello',171 }172 }),173 (c) => {174 const data = c.req.valid('header')175 return c.jsonT(data)176 }177 )178 .get(179 '/cookie',180 validator('cookie', () => {181 return {182 hello: 'world',183 }184 }),185 (c) => {186 const data = c.req.valid('cookie')187 return c.jsonT(data)188 }189 )190191 const server = setupServer(192 rest.get('http://localhost/api/search', (req, res, ctx) => {193 const url = new URL(req.url)
23 unmodified lines
217 const buffer = await req.arrayBuffer()218 // @ts-ignore219 const string = String.fromCharCode.apply('', new Uint8Array(buffer))220 return res(ctx.status(200), ctx.text(string))221 }),222 rest.get('http://localhost/api/header', async (req, res, ctx) => {223 const message = await req.headers.get('x-message-id')224 return res(ctx.status(200), ctx.json({ 'x-message-id': message }))225 }),226227 rest.get('http://localhost/api/cookie', async (req, res, ctx) => {228 const obj = parse(req.headers.get('cookie') || '')229 const value = obj['hello']230 return res(ctx.status(200), ctx.json({ hello: value }))231 })232 )233234 beforeAll(() => server.listen())
47 unmodified lines
282283 expect(res.status).toBe(200)284 expect(await res.text()).toMatch('Good Night')285 })286287 it('Should get 200 response - header', async () => {288 const header = {289 'x-message-id': 'Hello',290 }291 const res = await client.header.$get({292 header,293 })294295 expect(res.status).toBe(200)296 expect(await res.json()).toEqual(header)297 })298299 it('Should get 200 response - cookie', async () => {300 const cookie = {301 hello: 'world',302 }303 const res = await client.cookie.$get({304 cookie,305 })306307 expect(res.status).toBe(200)308 expect(await res.json()).toEqual(cookie)309 })310})311312describe('Infer the response/request type', () => {313 const app = new Hono()
4 unmodified lines
318 name: 'dummy',319 age: 'dummy',320 }321 }),322 validator('header', () => {323 return {324 'x-request-id': 'dummy',325 }326 }),327 validator('cookie', () => {328 return {329 name: 'dummy',330 }331 }),332 (c) =>333 c.jsonT({334 id: 123,335 title: 'Morning!',
25 unmodified lines
361 }362 type verify = Expect<Equal<Expected, Actual['query']>>363 })364365 it('Should infer request header type the type correctly', () => {366 const client = hc<AppType>('/')367 const req = client.index.$get368 type c = typeof req369370 type Actual = InferRequestType<c>371 type Expected = {372 'x-request-id': string373 }374 type verify = Expect<Equal<Expected, Actual['header']>>375 })376377 it('Should infer request cookie type the type correctly', () => {378 const client = hc<AppType>('/')379 const req = client.index.$get380 type c = typeof req381382 type Actual = InferRequestType<c>383 type Expected = {384 name: string385 }386 type verify = Expect<Equal<Expected, Actual['cookie']>>387 })388389 describe('Without input', () => {390 const route = app.get('/', (c) => c.jsonT({ ok: true }))391 type AppType = typeof route392
183 unmodified lines
modified:src/client/client.ts+14 added-1 removed
1import type { Hono } from '../hono'2import type { ValidationTargets } from '../types'3import { serialize } from '../utils/cookie'4import type { UnionToIntersection } from '../utils/types'5import type { Callback, Client, ClientRequestOptions } from './types'6import { deepMerge, mergePath, removeIndexString, replaceUrlParam } from './utils'7
78 unmodified lines
8687 let methodUpperCase = this.method.toUpperCase()88 let setBody = !(methodUpperCase === 'GET' || methodUpperCase === 'HEAD')8989 const headerValues: Record<string, string> = opt?.headers ? opt.headers : {}90 const headerValues: Record<string, string> = {91 ...(args?.header ?? {}),92 ...(opt?.headers ? opt.headers : {}),93 }9495 if (args?.cookie) {96 const cookies: string[] = []97 for (const [key, value] of Object.entries(args.cookie)) {98 cookies.push(serialize(key, value, { path: '/' }))99 }100 headerValues['Cookie'] = cookies.join(',')101 }102103 if (this.cType) headerValues['Content-Type'] = this.cType104105 const headers = new Headers(headerValues ?? undefined)106 let url = this.url
49 unmodified lines
modified:src/client/types.ts+26 added-11 removed
2 unmodified lines
3import type { RemoveBlankRecord } from '../utils/types'45type HonoRequest = typeof Hono.prototype['request']67export type ClientRequestOptions<T = unknown> = keyof T extends never7export type ClientRequestOptions = {8 headers?: Record<string, string>9 fetch?: typeof fetch | HonoRequest10}8 ? {9 headers?: Record<string, string>10 fetch?: typeof fetch | HonoRequest11 }12 : {13 headers: T14 fetch?: typeof fetch | HonoRequest15 }1617type ClientRequest<S extends Schema> = {18 [M in keyof S]: S[M] extends { input: infer R; output: infer O }19 ? RemoveBlankRecord<R> extends never20 ? (args?: {}, options?: ClientRequestOptions) => Promise<ClientResponse<O>>16 : (17 // Client does not support `header` and `cookie`18 args: Omit<R, 'header' | 'cookie'>,19 options?: ClientRequestOptions20 ) => Promise<ClientResponse<O>>21 : (args: R, options?: ClientRequestOptions) => Promise<ClientResponse<O>>22 : never23} & {24 $url: () => URL25}
27 unmodified lines
53) => Promise<ClientResponse<InferResponseType<T>>>5455export type InferResponseType<T> = T extends (56 // eslint-disable-next-line @typescript-eslint/no-explicit-any56 args: any | undefined57 args: any | undefined,58 // eslint-disable-next-line @typescript-eslint/no-explicit-any59 options: any | undefined60) => Promise<ClientResponse<infer O>>61 ? O62 : never6361export type InferRequestType<T> = T extends (args: infer R) => Promise<ClientResponse<unknown>>64export type InferRequestType<T> = T extends (65 args: infer R,66 // eslint-disable-next-line @typescript-eslint/no-explicit-any67 options: any | undefined68) => Promise<ClientResponse<unknown>>69 ? NonNullable<R>70 : never7172export type InferRequestOptionsType<T> = T extends (73 // eslint-disable-next-line @typescript-eslint/no-explicit-any74 args: any,75 options: infer R76) => Promise<ClientResponse<unknown>>77 ? NonNullable<R>78 : never7980type PathToChain<81 Path extends string,82 E extends Schema,83 Original extends string = ''
30 unmodified lines
modified:src/helper/cookie/index.test.ts+1 added-1 removed
242 unmodified lines
243 deleteCookie(c, 'delicious_cookie2')244 return c.text('Give cookie')245 })246247 it('Delete multile cookies', async () => {247 it('Delete multiple cookies', async () => {248 const res2 = await app.request('http://localhost/delete-cookie-multiple')249 expect(res2.status).toBe(200)250 const header2 = res2.headers.get('Set-Cookie')251 expect(header2).toBe('delicious_cookie=; Max-Age=0, delicious_cookie2=; Max-Age=0')
19 unmodified lines
added:src/helper/testing/index.test.ts+19 added
1import { Hono } from '../../hono'2import { testClient } from '.'34describe('hono testClinet', () => {5 it('should return the correct search result', async () => {6 const app = new Hono().get('/search', (c) => c.jsonT({ hello: 'world' }))7 const res = await testClient(app).search.$get()8 expect(await res.json()).toEqual({ hello: 'world' })9 })1011 it('should return the correct environment variables value', async () => {12 type Bindings = { hello: string }13 const app = new Hono<{ Bindings: Bindings }>().get('/search', (c) => {14 return c.jsonT({ hello: c.env.hello })15 })16 const res = await testClient(app, { hello: 'world' }).search.$get()17 expect(await res.json()).toEqual({ hello: 'world' })18 })19})
added:src/helper/testing/index.ts+18 added
1import { hc } from '../../client'2import type { Hono } from '../../hono'34// eslint-disable-next-line @typescript-eslint/no-explicit-any5type ExtractEnv<T> = T extends Hono<infer E, any, any> ? E : never67// eslint-disable-next-line @typescript-eslint/no-explicit-any8export const testClient = <T extends Hono<any, any, any>>(9 app: T,10 Env?: ExtractEnv<T>['Bindings'] | {},11 executionCtx?: ExecutionContext12) => {13 const customFetch = (input: RequestInfo | URL, init?: RequestInit) => {14 return app.request(input, init, Env, executionCtx)15 }1617 return hc<typeof app>('', { fetch: customFetch })18}
modified:src/middleware/jwt/index.ts+4 added
75 unmodified lines
7677 await next()78 }79}8081export const verify = Jwt.verify82export const decode = Jwt.decode83export const sign = Jwt.sign
modified:src/utils/body.test.ts+3 added-1 removed
2 unmodified lines
3describe('Parse Body Util', () => {4 it('should parse `multipart/form-data`', async () => {5 const data = new FormData()6 data.append('message', 'hello')7 data.append('multi[]', 'foo')8 data.append('multi[]', 'bar')9 const req = new Request('https://localhost/form', {10 method: 'POST',11 body: data,12 // `Content-Type` header must not be set.13 })12 expect(await parseBody(req)).toEqual({ message: 'hello' })14 expect(await parseBody(req)).toEqual({ message: 'hello', 'multi[]': ['foo', 'bar'] })15 })1617 it('should parse `x-www-form-urlencoded`', async () => {18 const searchParams = new URLSearchParams()
21 unmodified lines
modified:src/utils/body.ts+12 added-2 removed
1import type { HonoRequest } from '../request'23export type BodyData = Record<string, string | File>3export type BodyData = Record<string, string | string[] | File>45export const parseBody = async <T extends BodyData = BodyData>(6 request: HonoRequest | Request7): Promise<T> => {
8 unmodified lines
16 const formData = await request.formData()17 if (formData) {18 const form: BodyData = {}19 formData.forEach((value, key) => {20 if (key.slice(-2) === '[]') {21 if (!form[key]) {22 form[key] = [value.toString()]23 } else {24 if (Array.isArray(form[key])) {25 ;(form[key] as string[]).push(value.toString())26 }27 }28 } else {20 form[key] = value29 form[key] = value30 }31 })32 body = form33 }34 }
2 unmodified lines
modified:src/utils/cookie.test.ts+4 added-2 removed
160 unmodified lines
161 httpOnly: true,162 maxAge: 1000,163 expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)),164 sameSite: 'Strict',165 partitioned: true,166 })167 expect(serialized).toBe(167 'great_cookie=banana; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict'168 'great_cookie=banana; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict; Partitioned'169 )170 })171172 it('Should serialize a signed cookie', async () => {
13 unmodified lines
186 httpOnly: true,187 maxAge: 1000,188 expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)),189 sameSite: 'Strict',190 partitioned: true,191 })192 expect(serialized).toBe(191 'great_cookie=banana.hSo6gB7YT2db0WBiEAakEmh7dtwEL0DSp76G23WvHuQ%3D; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict'193 'great_cookie=banana.hSo6gB7YT2db0WBiEAakEmh7dtwEL0DSp76G23WvHuQ%3D; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict; Partitioned'194 )195 })196197 it('Should serialize cookie with maxAge is 0', () => {
13 unmodified lines
modified:src/utils/cookie.ts+8 added-3 removed
9 unmodified lines
10 path?: string11 secure?: boolean12 signingSecret?: string13 sameSite?: 'Strict' | 'Lax' | 'None'14 partitioned?: boolean15}1617const algorithm = { name: 'HMAC', hash: 'SHA-256' }18
85 unmodified lines
104 cookie += `; Max-Age=${Math.floor(opt.maxAge)}`105 }106107 if (opt.domain) {107 cookie += '; Domain=' + opt.domain108 cookie += `; Domain=${opt.domain}`109 }110111 if (opt.path) {111 cookie += '; Path=' + opt.path112 cookie += `; Path=${opt.path}`113 }114115 if (opt.expires) {115 cookie += '; Expires=' + opt.expires.toUTCString()116 cookie += `; Expires=${opt.expires.toUTCString()}`117 }118119 if (opt.httpOnly) {120 cookie += '; HttpOnly'
6 unmodified lines
127 if (opt.sameSite) {128 cookie += `; SameSite=${opt.sameSite}`129 }130131 if (opt.partitioned) {132 cookie += '; Partitioned'133 }134135 return cookie136}137138export const serialize = (name: string, value: string, opt: CookieOptions = {}): string => {
15 unmodified lines
added:src/utils/stream.test.ts+85 added
1import { StreamingApi } from './stream'23describe('StreamingApi', () => {4 it('write(string)', async () => {5 const { readable, writable } = new TransformStream()6 const api = new StreamingApi(writable)7 const reader = readable.getReader()8 api.write('foo')9 expect((await reader.read()).value).toEqual(new TextEncoder().encode('foo'))10 api.write('bar')11 expect((await reader.read()).value).toEqual(new TextEncoder().encode('bar'))12 })1314 it('write(Uint8Array)', async () => {15 const { readable, writable } = new TransformStream()16 const api = new StreamingApi(writable)17 const reader = readable.getReader()18 api.write(new Uint8Array([1, 2, 3]))19 expect((await reader.read()).value).toEqual(new Uint8Array([1, 2, 3]))20 api.write(new Uint8Array([4, 5, 6]))21 expect((await reader.read()).value).toEqual(new Uint8Array([4, 5, 6]))22 })2324 it('writeln(string)', async () => {25 const { readable, writable } = new TransformStream()26 const api = new StreamingApi(writable)27 const reader = readable.getReader()28 api.writeln('foo')29 expect((await reader.read()).value).toEqual(new TextEncoder().encode('foo\n'))30 api.writeln('bar')31 expect((await reader.read()).value).toEqual(new TextEncoder().encode('bar\n'))32 })3334 it('pipe()', async () => {35 const { readable: senderReadable, writable: senderWritable } = new TransformStream()3637 // send data to readable in other scope38 ;(async () => {39 const writer = senderWritable.getWriter()40 await writer.write(new TextEncoder().encode('foo'))41 await writer.write(new TextEncoder().encode('bar'))42 // await writer.close()43 })()4445 const { readable: receiverReadable, writable: receiverWritable } = new TransformStream()4647 const api = new StreamingApi(receiverWritable)4849 // pipe readable to api in other scope50 ;(async () => {51 await api.pipe(senderReadable)52 })()5354 // read data from api55 const reader = receiverReadable.getReader()56 expect((await reader.read()).value).toEqual(new TextEncoder().encode('foo'))57 expect((await reader.read()).value).toEqual(new TextEncoder().encode('bar'))58 })5960 it('close()', async () => {61 const { readable, writable } = new TransformStream()62 const api = new StreamingApi(writable)63 const reader = readable.getReader()64 await api.close()65 expect((await reader.read()).done).toBe(true)66 })6768 it('should not throw an error in write()', async () => {69 const { writable } = new TransformStream()70 const api = new StreamingApi(writable)71 await api.close()72 const write = () => api.write('foo')73 expect(write).not.toThrow()74 })7576 it('should not throw an error in close()', async () => {77 const { writable } = new TransformStream()78 const api = new StreamingApi(writable)79 const close = async () => {80 await api.close()81 await api.close()82 }83 expect(close).not.toThrow()84 })85})
added:src/utils/stream.ts+46 added
1export class StreamingApi {2 private writer: WritableStreamDefaultWriter<Uint8Array>3 private encoder: TextEncoder4 private writable: WritableStream56 constructor(writable: WritableStream) {7 this.writable = writable8 this.writer = writable.getWriter()9 this.encoder = new TextEncoder()10 }1112 async write(input: Uint8Array | string) {13 try {14 if (typeof input === 'string') {15 input = this.encoder.encode(input)16 }17 await this.writer.write(input)18 } catch (e) {19 // Do nothing. If you want to handle errors, create a stream by yourself.20 }21 return this22 }2324 async writeln(input: string) {25 await this.write(input + '\n')26 return this27 }2829 sleep(ms: number) {30 return new Promise((res) => setTimeout(res, ms))31 }3233 async close() {34 try {35 await this.writer.close()36 } catch (e) {37 // Do nothing. If you want to handle errors, create a stream by yourself.38 }39 }4041 async pipe(body: ReadableStream) {42 this.writer.releaseLock()43 await body.pipeTo(this.writable, { preventClose: true })44 this.writer = this.writable.getWriter()45 }46}
modified:src/context.test.ts+41 added
259 unmodified lines
260 const res = c.html('<h1>foo</h1>', originalResponse)261 expect(res.headers.get('content-type')).toMatch(/^text\/html/)262 expect(await res.text()).toBe('<h1>foo</h1>')263 })264265 it('c.streamText()', async () => {266 const res = c.streamText(async (stream) => {267 for (let i = 0; i < 3; i++) {268 await stream.write(`${i}`)269 await stream.sleep(1)270 }271 })272273 expect(res.status).toBe(200)274 expect(res.headers.get('content-type')).toMatch(/^text\/plain/)275 expect(res.headers.get('x-content-type-options')).toBe('nosniff')276 expect(res.headers.get('transfer-encoding')).toBe('chunked')277278 if (!res.body) {279 throw new Error('Body is null')280 }281 const reader = res.body.getReader()282 const decoder = new TextDecoder()283 for (let i = 0; i < 3; i++) {284 const { value } = await reader.read()285 expect(decoder.decode(value)).toEqual(`${i}`)286 }287 })288289 it('c.stream()', async () => {290 const res = c.stream(async (stream) => {291 for (let i = 0; i < 3; i++) {292 await stream.write(new Uint8Array([i]))293 await stream.sleep(1)294 }295 })296 if (!res.body) {297 throw new Error('Body is null')298 }299 const reader = res.body.getReader()300 for (let i = 0; i < 3; i++) {301 const { value } = await reader.read()302 expect(value).toEqual(new Uint8Array([i]))303 }304 })305})306307declare module './context' {308 interface ContextRenderer {
28 unmodified lines
modified:src/context.ts+30 added-1 removed
2 unmodified lines
3import type { Env, NotFoundHandler, Input, TypedResponse } from './types'4import type { CookieOptions } from './utils/cookie'5import { serialize } from './utils/cookie'6import type { StatusCode } from './utils/http-status'7import { StreamingApi } from './utils/stream'8import type { JSONValue, InterfaceToType } from './utils/types'910type Runtime = 'node' | 'deno' | 'bun' | 'workerd' | 'fastly' | 'edge-light' | 'lagon' | 'other'11type HeaderRecord = Record<string, string | string[]>
73 unmodified lines
85 executionCtx?: FetchEventLike | ExecutionContext | undefined86 notFoundHandler?: NotFoundHandler<E>87}8889const TEXT_PLAIN = 'text/plain; charset=UTF-8'9091export class Context<92 // eslint-disable-next-line @typescript-eslint/no-explicit-any93 E extends Env = any,94 // eslint-disable-next-line @typescript-eslint/no-explicit-any
217 unmodified lines
312 }313 // If Content-Type is not set, we don't have to set `text/plain`.314 // Fewer the header values, it will be faster.315 if (this._pH['content-type']) {313 this._pH['content-type'] = 'text/plain; charset=UTF-8'316 this._pH['content-type'] = TEXT_PLAIN317 }318 return typeof arg === 'number'319 ? this.newResponse(text, arg, headers)320 : this.newResponse(text, arg)
52 unmodified lines
373 this._h.set('Location', location)374 return this.newResponse(null, status)375 }376377 streamText = (378 cb: (stream: StreamingApi) => Promise<void>,379 arg?: StatusCode | ResponseInit,380 headers?: HeaderRecord381 ): Response => {382 headers ??= {}383 this.header('content-type', TEXT_PLAIN)384 this.header('x-content-type-options', 'nosniff')385 this.header('transfer-encoding', 'chunked')386 return this.stream(cb, arg, headers)387 }388389 stream = (390 cb: (stream: StreamingApi) => Promise<void>,391 arg?: StatusCode | ResponseInit,392 headers?: HeaderRecord393 ): Response => {394 const { readable, writable } = new TransformStream()395 const stream = new StreamingApi(writable)396 cb(stream).finally(() => stream.close())397398 return typeof arg === 'number'399 ? this.newResponse(readable, arg, headers)400 : this.newResponse(readable, arg)401 }402403 /** @deprecated404 * Use Cookie Middleware instead of `c.cookie()`. The `c.cookie()` will be removed in v4.405 *406 * @example
66 unmodified lines
modified:package.json+9 added-1 removed
1{2 "name": "hono",3 "version": "3.6.3",3 "version": "3.7.0-rc.1",4 "description": "Ultrafast web framework for the Edges",5 "main": "dist/cjs/index.js",6 "type": "module",7 "module": "dist/index.js",
224 unmodified lines
232 "./lambda-edge": {233 "types": "./dist/types/adapter/lambda-edge/index.d.ts",234 "import": "./dist/adapter/lambda-edge/index.js",235 "require": "./dist/cjs/adapter/lambda-edge/index.js"236 },237 "./testing": {238 "types": "./dist/types/helper/testing/index.d.ts",239 "import": "./dist/helper/testing/index.js",240 "require": "./dist/cjs/helper/testing/index.js"241 }242 },243 "typesVersions": {244 "*": {
112 unmodified lines
357 "./dist/types/adapter/vercel"358 ],359 "lambda-edge": [360 "./dist/types/adapter/lambda-edge"361 ],362 "testing": [363 "./dist/types/helper/testing"364 ]365 }366 },367 "author": "Yusuke Wada <yusuke@kamawada.com> (https://github.com/yusukebe)",
75 unmodified lines