Skip to content
Myr

Merge branch 'main' into next

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

authored by Yusuke Wada · committed by Yusuke Wada · parents 61d50f6, d21f8eb · Browse files · 23 files+326 added−70 removed
This commit

State

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

Diff stats

23 files+326 added−70 removed

  • tests:+166 added−14 removed
  • other:+160 added−56 removed

23 files+326 added−70 removed

modified:.github/workflows/ci.yml+8 added-4 removed
added:runtime_tests/lambda/stream-mock.ts+43 added
added:runtime_tests/lambda/stream.test.ts+75 added
1import { streamHandle } from '../../src/adapter/aws-lambda/handler'2import type { LambdaEvent } from '../../src/adapter/aws-lambda/handler'3import type {4 ApiGatewayRequestContext,5 ApiGatewayRequestContextV2,6 LambdaContext,7} from '../../src/adapter/aws-lambda/types'8import { Hono } from '../../src/hono'9import './stream-mock'1011type Bindings = {12 event: LambdaEvent13 lambdaContext: LambdaContext14 requestContext: ApiGatewayRequestContext | ApiGatewayRequestContextV215}1617const testApiGatewayRequestContextV2 = {18 accountId: '123456789012',19 apiId: 'urlid',20 authentication: null,21 authorizer: {22 iam: {23 accessKey: 'AKIA...',24 accountId: '111122223333',25 callerId: 'AIDA...',26 cognitoIdentity: null,27 principalOrgId: null,28 userArn: 'arn:aws:iam::111122223333:user/example-user',29 userId: 'AIDA...',30 },31 },32 domainName: 'example.com',33 domainPrefix: '<url-id>',34 http: {35 method: 'GET',36 path: '/my/path',37 protocol: 'HTTP/1.1',38 sourceIp: '123.123.123.123',39 userAgent: 'agent',40 },41 requestId: 'id',42 routeKey: '$default',43 stage: '$default',44 time: '12/Mar/2020:19:03:58 +0000',45 timeEpoch: 1583348638390,46 customProperty: 'customValue',47}4849describe('streamHandle function', () => {50 const app = new Hono<{ Bindings: Bindings }>()5152 app.get('/cookies', async (c) => {53 c.res.headers.append('Set-Cookie', 'cookie1=value1')54 c.res.headers.append('Set-Cookie', 'cookie2=value2')55 return c.text('Cookies Set')56 })5758 const handler = streamHandle(app)5960 it('to write multiple cookies into the headers', async () => {61 const event = {62 headers: { 'content-type': 'text/plain' },63 rawPath: '/cookies',64 rawQueryString: '',65 body: null,66 isBase64Encoded: false,67 requestContext: testApiGatewayRequestContextV2,68 }6970 const stream = await handler(event)7172 const metadata = JSON.parse(stream.chunks[0].toString())73 expect(metadata.cookies).toEqual(['cookie1=value1', 'cookie2=value2'])74 })75})
modified:runtime_tests/lambda/vitest.config.ts+5 added-1 removed
7 unmodified lines
8 NAME: 'Node',9 },10 globals: true,11 include: ['**/runtime_tests/lambda/**/*.+(ts|tsx|js)'],12 exclude: ['**/runtime_tests/lambda/vitest.config.ts', '**/runtime_tests/lambda/mock.ts'],12 exclude: [13 '**/runtime_tests/lambda/vitest.config.ts',14 '**/runtime_tests/lambda/mock.ts',15 '**/runtime_tests/lambda/stream-mock.ts',16 ],17 coverage: {18 ...config.test?.coverage,19 reportsDirectory: './coverage/raw/runtime-lambda',20 },
2 unmodified lines
modified:src/adapter/aws-lambda/handler.ts+12 added-1 removed
124 unmodified lines
125 requestContext,126 context,127 })128129 const headers: Record<string, string> = {}130 const cookies: string[] = []131 res.headers.forEach((value, name) => {132 if (name === 'set-cookie') {133 cookies.push(value)134 } else {135 headers[name] = value136 }137 })138139 // Check content type140 const httpResponseMetadata = {141 statusCode: res.status,132 headers: Object.fromEntries(res.headers.entries()),142 headers,143 cookies,144 }145146 // Update response stream147 // @ts-expect-error awslambda is not a standard API
340 unmodified lines
modified:src/adapter/deno/deno.d.ts+5 added-1 removed
15 unmodified lines
16 * @returns A promise that resolves when the file is written.17 */18 export function writeFile(path: string, data: Uint8Array): Promise<void>1920 export function upgradeWebSocket(req: Request): {20 export function upgradeWebSocket(21 req: Request,22 // eslint-disable-next-line @typescript-eslint/no-explicit-any23 options: any24 ): {25 response: Response26 socket: WebSocket27 }28}
modified:src/adapter/deno/websocket.test.ts+36 added
37 unmodified lines
38 })39 )40 expect(await messagePromise).toBe(data)41 })4243 it('Should receive data is valid with Options', async () => {44 const messagePromise = new Promise((resolve) =>45 app.get(46 '/ws',47 upgradeWebSocket(48 () => ({49 onMessage: (evt) => resolve(evt.data),50 }),51 {52 idleTimeout: 5000,53 }54 )55 )56 )57 const socket = new EventTarget() as WebSocket58 Deno.upgradeWebSocket = () => {59 return {60 response: new Response(),61 socket,62 }63 }64 await app.request('/ws', {65 headers: {66 upgrade: 'websocket',67 },68 })69 const data = Math.random().toString()70 socket.onmessage &&71 socket.onmessage(72 new MessageEvent('message', {73 data,74 })75 )76 expect(await messagePromise).toBe(data)77 })78})
modified:src/adapter/deno/websocket.ts+46 added-25 removed
1import type { UpgradeWebSocket, WSContext, WSReadyState } from '../../helper/websocket'23export const upgradeWebSocket: UpgradeWebSocket = (createEvents) => async (c, next) => {4 if (c.req.header('upgrade') !== 'websocket') {5 return await next()6 }3export interface UpgradeWebSocketOptions {4 /**5 * Sets the `.protocol` property on the client side web socket to the6 * value provided here, which should be one of the strings specified in the7 * `protocols` parameter when requesting the web socket. This is intended8 * for clients and servers to specify sub-protocols to use to communicate to9 * each other.10 */11 protocol?: string12 /**13 * If the client does not respond to this frame with a14 * `pong` within the timeout specified, the connection is deemed15 * unhealthy and is closed. The `close` and `error` event will be emitted.16 *17 * The unit is seconds, with a default of 30.18 * Set to `0` to disable timeouts.19 */20 idleTimeout?: number21}228 const events = await createEvents(c)9 const { response, socket } = Deno.upgradeWebSocket(c.req.raw)23export const upgradeWebSocket: UpgradeWebSocket<UpgradeWebSocketOptions> =24 (createEvents, options) => async (c, next) => {25 if (c.req.header('upgrade') !== 'websocket') {26 return await next()27 }2811 const wsContext: WSContext = {12 binaryType: 'arraybuffer',13 close: (code, reason) => socket.close(code, reason),14 get protocol() {15 return socket.protocol16 },17 raw: socket,18 get readyState() {19 return socket.readyState as WSReadyState20 },21 url: socket.url ? new URL(socket.url) : null,22 send: (source) => socket.send(source),23 }24 socket.onopen = (evt) => events.onOpen?.(evt, wsContext)25 socket.onmessage = (evt) => events.onMessage?.(evt, wsContext)26 socket.onclose = (evt) => events.onClose?.(evt, wsContext)27 socket.onerror = (evt) => events.onError?.(evt, wsContext)29 const events = await createEvents(c)30 const { response, socket } = Deno.upgradeWebSocket(c.req.raw, options || {})3132 const wsContext: WSContext = {33 binaryType: 'arraybuffer',34 close: (code, reason) => socket.close(code, reason),35 get protocol() {36 return socket.protocol37 },38 raw: socket,39 get readyState() {40 return socket.readyState as WSReadyState41 },42 url: socket.url ? new URL(socket.url) : null,43 send: (source) => socket.send(source),44 }45 socket.onopen = (evt) => events.onOpen?.(evt, wsContext)46 socket.onmessage = (evt) => events.onMessage?.(evt, wsContext)47 socket.onclose = (evt) => events.onClose?.(evt, wsContext)48 socket.onerror = (evt) => events.onError?.(evt, wsContext)4929 return response30}50 return response51 }
modified:src/client/utils.test.ts+1 added-1 removed
95 unmodified lines
9697describe('deepMerge', () => {98 it('should return the source object if the target object is not an object', () => {99 const target = null100 const source = { a: 1 }100 const source = 'not an object' as unknown as Record<string, unknown>101 const result = deepMerge(target, source)102 expect(result).toEqual(source)103 })104
13 unmodified lines
modified:src/helper/accepts/accepts.ts+15 added-7 removed
27 unmodified lines
28export const parseAccept = (acceptHeader: string): Accept[] => {29 // Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.830 const accepts = acceptHeader.split(',') // ['text/html', 'application/xhtml+xml', 'application/xml;q=0.9', 'image/webp', '*/*;q=0.8']31 return accepts.map((accept) => {32 const [type, ...params] = accept.trim().split(';') // ['application/xml', 'q=0.9']33 const q = params.find((param) => param.startsWith('q=')) // 'q=0.9'32 const parts = accept.trim().split(';') // ['text/html', 'q=0.9', 'image/webp']33 const type = parts[0] // text/html34 const params = parts.slice(1) // ['q=0.9', 'image/webp']35 const q = params.find((param) => param.startsWith('q='))3637 const paramsObject = params.reduce((acc, param) => {38 const keyValue = param.split('=')39 const key = keyValue[0].trim()40 const value = keyValue[1].trim()41 acc[key] = value42 return acc43 }, {} as { [key: string]: string })4445 return {35 type,36 params: params.reduce((acc, param) => {37 const [key, value] = param.split('=')38 return { ...acc, [key.trim()]: value.trim() }39 }, {}),46 type: type,47 params: paramsObject,48 q: q ? parseFloat(q.split('=')[1]) : 1,49 }50 })51}
30 unmodified lines
modified:src/helper/conninfo/types.ts+2 added-2 removed
28 unmodified lines
29 | {}30)3132/**33 * HTTP Connection infomation33 * HTTP Connection information34 */35export interface ConnInfo {36 /**37 * Remote infomation37 * Remote information38 */39 remote: NetAddrInfo40}41
4 unmodified lines
modified:src/helper/ssg/ssg.test.tsx-1 removed
1/* eslint-disable @typescript-eslint/unbound-method */2/** @jsxImportSource ../../jsx */3import { beforeEach, describe, expect, it } from 'vitest'3import { Hono } from '../../hono'4import { poweredBy } from '../../middleware/powered-by'5import {6 X_HONO_DISABLE_SSG_HEADER_KEY,
784 unmodified lines
modified:src/helper/websocket/index.ts+3 added-2 removed
18 unmodified lines
1920/**21 * Upgrade WebSocket Type22 */23export type UpgradeWebSocket = (24 createEvents: (c: Context) => WSEvents | Promise<WSEvents>23export type UpgradeWebSocket<T = any> = (24 createEvents: (c: Context) => WSEvents | Promise<WSEvents>,25 options?: T26) => MiddlewareHandler<27 any,28 string,29 {
28 unmodified lines
modified:src/jsx/utils.ts+1 added-1 removed
1const normalizeElementKeyMap = new Map([1const normalizeElementKeyMap: Map<string, string> = new Map([2 ['className', 'class'],3 ['htmlFor', 'for'],4])5export const normalizeIntrinsicElementKey = (key: string): string =>
25 unmodified lines
modified:src/utils/buffer.test.ts+32 added-1 removed
1import { SHA256 as sha256CryptoJS } from 'crypto-js'2import { bufferToFormData, bufferToString, timingSafeEqual } from './buffer'2import { bufferToFormData, bufferToString, equal, timingSafeEqual } from './buffer'34describe('equal', () => {5 it('should return true for identical ArrayBuffers', () => {6 const buffer1 = new ArrayBuffer(1)7 const buffer2 = buffer18 expect(equal(buffer1, buffer2)).toBe(true)9 })1011 it('should return false for ArrayBuffers of different lengths', () => {12 const buffer1 = new ArrayBuffer(1)13 const buffer2 = new ArrayBuffer(2)14 expect(equal(buffer1, buffer2)).toBe(false)15 })1617 it('should return false for ArrayBuffers with different content', () => {18 const buffer1 = new Uint8Array([1, 2, 3, 4]).buffer19 const buffer2 = new Uint8Array([2, 2, 3, 4]).buffer20 expect(equal(buffer1, buffer2)).toBe(false)21 })2223 it('should return true for ArrayBuffers with identical content', () => {24 const buffer1 = new Uint8Array([1, 2, 3, 4]).buffer25 const buffer2 = new Uint8Array([1, 2, 3, 4]).buffer26 expect(equal(buffer1, buffer2)).toBe(true)27 })28})2930describe('buffer', () => {31 it('positive', async () => {32 expect(33 await timingSafeEqual(
34 unmodified lines
68 expect(await timingSafeEqual({ a: 1 }, { a: 1 })).toBe(false)69 expect(await timingSafeEqual({ a: 1 }, { a: 2 })).toBe(false)70 expect(await timingSafeEqual([1, 2], [1, 2])).toBe(false)71 expect(await timingSafeEqual([1, 2], [1, 2, 3])).toBe(false)72 expect(await timingSafeEqual('a', 'b', () => undefined)).toBe(false)73 })74})7576describe('bufferToString', () => {
1 unmodified line
78 const bytes = [227, 129, 130, 227, 129, 132, 227, 129, 134, 227, 129, 136, 227, 129, 138]79 const buffer = Uint8Array.from(bytes).buffer80 expect(bufferToString(buffer)).toBe('あいうえお')81 })82 it('should return the passed arguments as is ', () => {83 const notBuffer = 'あいうえお' as unknown as ArrayBuffer84 expect(bufferToString(notBuffer)).toBe('あいうえお')85 })86})8788describe('bufferToFormData', () => {89 it('Should parse multipart/form-data from ArrayBuffer', async () => {
27 unmodified lines
modified:src/utils/buffer.ts+1 added-2 removed
33 unmodified lines
34 if (!hashFunction) {35 hashFunction = sha25636 }3738 const sa = await hashFunction(a)39 const sb = await hashFunction(b)38 const [sa, sb] = await Promise.all([hashFunction(a), hashFunction(b)])3940 if (!sa || !sb) {41 return false42 }
23 unmodified lines
modified:src/context.test.ts+4 added-3 removed
34 unmodified lines
35 expect(res.headers.get('X-Custom')).toBe('Message')36 })3738 it('c.html()', async () => {39 const res = await c.html('<h1>Hello! Hono!</h1>', 201, { 'X-Custom': 'Message' })39 const res: Response = c.html('<h1>Hello! Hono!</h1>', 201, { 'X-Custom': 'Message' })40 expect(res.status).toBe(201)41 expect(res.headers.get('Content-Type')).toMatch('text/html')42 expect(await res.text()).toBe('<h1>Hello! Hono!</h1>')43 expect(res.headers.get('X-Custom')).toBe('Message')44 })4546 it('c.html() with async', async () => {47 const res = await c.html(48 new Promise((resolve) => setTimeout(() => resolve('<h1>Hello! Hono!</h1>'), 0)),47 const resPromise: Promise<Response> = c.html(48 new Promise<string>((resolve) => setTimeout(() => resolve('<h1>Hello! Hono!</h1>'), 0)),49 201,50 {51 'X-Custom': 'Message',52 }53 )54 const res = await resPromise55 expect(res.status).toBe(201)56 expect(res.headers.get('Content-Type')).toMatch('text/html')57 expect(await res.text()).toBe('<h1>Hello! Hono!</h1>')58 expect(res.headers.get('X-Custom')).toBe('Message')
401 unmodified lines
modified:src/context.ts+10 added-6 removed
67 unmodified lines
68 *69 * @template E - Environment type.70 */71interface Get<E extends Env> {72 <Key extends keyof ContextVariableMap>(key: Key): ContextVariableMap[Key]72 <Key extends keyof E['Variables']>(key: Key): E['Variables'][Key]73 <Key extends keyof ContextVariableMap>(key: Key): ContextVariableMap[Key]74}7576/**77 * Interface for setting context variables.78 *79 * @template E - Environment type.80 */81interface Set<E extends Env> {82 <Key extends keyof ContextVariableMap>(key: Key, value: ContextVariableMap[Key]): void82 <Key extends keyof E['Variables']>(key: Key, value: E['Variables'][Key]): void83 <Key extends keyof ContextVariableMap>(key: Key, value: ContextVariableMap[Key]): void84}8586/**87 * Interface for creating a new response.
86 unmodified lines
174 *175 * @returns A Response object or a Promise that resolves to a Response object.176 */177interface HTMLRespond {178 (html: string | Promise<string>, status?: StatusCode, headers?: HeaderRecord):179 | Response180 | Promise<Response>181 (html: string | Promise<string>, init?: ResponseInit): Response | Promise<Response>178 <T extends string | Promise<string>>(179 html: T,180 status?: StatusCode,181 headers?: HeaderRecord182 ): T extends string ? Response : Promise<Response>183 <T extends string | Promise<string>>(html: T, init?: ResponseInit): T extends string184 ? Response185 : Promise<Response>186}187188/**189 * Options for configuring the context.
566 unmodified lines
modified:src/hono-base.ts+2 added-2 removed
192 unmodified lines
193 * @see {@link https://hono.dev/api/routing#grouping}194 *195 * @param {string} path - base Path196 * @param {Hono} app - other Hono instance197 * @returns {Hono} routed Hono instnace197 * @returns {Hono} routed Hono instance198 *199 * @example200 * ```ts201 * const app = new Hono()
256 unmodified lines
458 * `.fetch()` will be entry point of your app.459 *460 * @see {@link https://hono.dev/api/hono#fetch}461 *462 * @param {Request} request - reuqest Object of request462 * @param {Request} request - request Object of request463 * @param {Env} Env - env Object464 * @param {ExecutionContext} - context of execution465 * @returns {Response | Promise<Response>} response of request466 *
56 unmodified lines
modified:src/request.test.ts-6 removed
174 unmodified lines
175 body: text,176 })177 )178 expect(await req.text()).toEqual(text)179 expect(await req.text()).toEqual(text)179 expect(await req.json()).toEqual(json)180 expect(await req.arrayBuffer()).toEqual(buffer)181 expect(await req.blob()).toEqual(182 new Blob([text], {
9 unmodified lines
192 body: '{"foo":"bar"}',193 })194 )195 expect(await req.json()).toEqual(json)197 expect(await req.json()).toEqual(json)196 expect(await req.text()).toEqual(text)197 expect(await req.arrayBuffer()).toEqual(buffer)198 expect(await req.blob()).toEqual(199 new Blob([text], {
10 unmodified lines
210 body: buffer,211 })212 )213 expect(await req.arrayBuffer()).toEqual(buffer)216 expect(await req.arrayBuffer()).toEqual(buffer)214 expect(await req.text()).toEqual(text)215 expect(await req.json()).toEqual(json)216 expect(await req.blob()).toEqual(217 new Blob([text], {
12 unmodified lines
230 body: blob,231 })232 )233 expect(await req.blob()).toEqual(blob)237 expect(await req.blob()).toEqual(blob)234 expect(await req.text()).toEqual(text)235 expect(await req.json()).toEqual(json)236 expect(await req.arrayBuffer()).toEqual(buffer)237 })
7 unmodified lines
245 body: data,246 })247 )248 expect((await req.formData()).get('foo')).toBe('bar')253 expect((await req.formData()).get('foo')).toBe('bar')249 expect(async () => await req.text()).not.toThrow()250 expect(async () => await req.arrayBuffer()).not.toThrow()251 expect(async () => await req.blob()).not.toThrow()252 })
8 unmodified lines
261 body: data,262 })263 )264 expect((await req.parseBody())['foo']).toBe('bar')270 expect((await req.parseBody())['foo']).toBe('bar')265 expect(async () => await req.text()).not.toThrow()266 expect(async () => await req.arrayBuffer()).not.toThrow()267 expect(async () => await req.blob()).not.toThrow()268 })
47 unmodified lines
modified:src/types.test.ts+18 added-2 removed
1636 unmodified lines
1637 payload: string1638 }1639}16401641describe('c.var with ContextVariableMap - test only types', () => {1642 it('Should no throw a type error', () => {1641describe('ContextVariableMap type tests', () => {1642 it('Should not throw type errors with c.var', () => {1643 new Hono().get((c) => {1644 expectTypeOf(c.get('payload')).toEqualTypeOf<string>()1645 return c.json(0)1646 })
1 unmodified line
1648 expectTypeOf(c.var.payload).toEqualTypeOf<string>()1649 return c.json(0)1650 })1651 })16521653 it('Should override ContextVariableMap with env variables', () => {1654 const middleware = createMiddleware<{1655 Variables: {1656 payload: number1657 }1658 }>(async (c, next) => {1659 c.set('payload', 123)1660 await next()1661 })16621663 new Hono().get(middleware, (c) => {1664 expectTypeOf(c.get('payload')).toEqualTypeOf<number>()1665 return c.json(0)1666 })1667 })1668})16691670/**1671 * It's challenge to test all cases. This is a minimal pattern.
46 unmodified lines
modified:bunfig.toml+6 added-1 removed
1[install.lockfile]2print = "yarn"2print = "yarn"34[test]5coverage = true6coverageReporter = ["text", "lcov"]7coverageDir = "coverage/raw/bun"
modified:package.json+1 added-1 removed
606 unmodified lines
607 },608 "engines": {609 "node": ">=16.0.0"610 }611}611}