feat(adapters): add the seven adapters as workspace packages (#5463)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat(adapters): add the eight adapters as workspace packages * chore(adapters): drop cloudflare-pages, it is obsolete
authored by Yusuke Wada · committed by GitHub · parent 4d9f2a2 · Browse files · 101 files·+4746 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
101 files+4746 added−0 removed
- tests:+2111 added−0 removed
- other:+2635 added−0 removed
Provenance
- Commit
b877827- Tree
50ffd94- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
4d9f2a2
101 files changed+4746 added−0 removed
added:adapters/aws-lambda/src/conninfo.test.ts+118 added
1+import { Context } from 'hono'2+import { getConnInfo } from './conninfo'3+4+describe('getConnInfo', () => {5+ describe('API Gateway v1', () => {6+ it('Should return the client IP from identity.sourceIp', () => {7+ const ip = '203.0.113.42'8+ const c = new Context(new Request('http://localhost/'), {9+ env: {10+ requestContext: {11+ identity: {12+ sourceIp: ip,13+ userAgent: 'test',14+ },15+ accountId: '123',16+ apiId: 'abc',17+ authorizer: {},18+ domainName: 'example.com',19+ domainPrefix: 'api',20+ extendedRequestId: 'xxx',21+ httpMethod: 'GET',22+ path: '/',23+ protocol: 'HTTP/1.1',24+ requestId: 'req-1',25+ requestTime: '',26+ requestTimeEpoch: 0,27+ resourcePath: '/',28+ stage: 'prod',29+ },30+ },31+ })32+33+ const info = getConnInfo(c)34+35+ expect(info.remote.address).toBe(ip)36+ })37+ })38+39+ describe('API Gateway v2', () => {40+ it('Should return the client IP from http.sourceIp', () => {41+ const ip = '198.51.100.23'42+ const c = new Context(new Request('http://localhost/'), {43+ env: {44+ requestContext: {45+ http: {46+ method: 'GET',47+ path: '/',48+ protocol: 'HTTP/1.1',49+ sourceIp: ip,50+ userAgent: 'test',51+ },52+ accountId: '123',53+ apiId: 'abc',54+ authentication: null,55+ authorizer: {},56+ domainName: 'example.com',57+ domainPrefix: 'api',58+ requestId: 'req-1',59+ routeKey: 'GET /',60+ stage: 'prod',61+ time: '',62+ timeEpoch: 0,63+ },64+ },65+ })66+67+ const info = getConnInfo(c)68+69+ expect(info.remote.address).toBe(ip)70+ })71+ })72+73+ describe('ALB', () => {74+ it.each([75+ {76+ description: 'ALB appends real client IP',77+ xff: '10.0.0.1, 192.0.2.50',78+ expected: '192.0.2.50',79+ },80+ {81+ description: 'attacker-controlled first IP',82+ xff: '127.0.0.1, 192.168.1.100',83+ expected: '192.168.1.100',84+ },85+ ])('Should return the last IP from x-forwarded-for ($description)', ({ xff, expected }) => {86+ const req = new Request('http://localhost/', {87+ headers: { 'x-forwarded-for': xff },88+ })89+ const c = new Context(req, {90+ env: {91+ requestContext: {92+ elb: {93+ targetGroupArn: 'arn:aws:elasticloadbalancing:...',94+ },95+ },96+ },97+ })98+ const info = getConnInfo(c)99+ expect(info.remote.address).toBe(expected)100+ })101+102+ it('Should return undefined when no x-forwarded-for header', () => {103+ const c = new Context(new Request('http://localhost/'), {104+ env: {105+ requestContext: {106+ elb: {107+ targetGroupArn: 'arn:aws:elasticloadbalancing:...',108+ },109+ },110+ },111+ })112+113+ const info = getConnInfo(c)114+115+ expect(info.remote.address).toBeUndefined()116+ })117+ })118+})added:adapters/aws-lambda/src/conninfo.ts+73 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273import type { Context } from 'hono'import type { GetConnInfo } from 'hono/conninfo'import type { ApiGatewayRequestContext, ApiGatewayRequestContextV2, ALBRequestContext,} from './types'
type LambdaRequestContext = | ApiGatewayRequestContext | ApiGatewayRequestContextV2 | ALBRequestContext
type Env = { Bindings: { requestContext: LambdaRequestContext }}
/** * Get connection information from AWS Lambda * * Extracts client IP from various Lambda event sources: * - API Gateway v1 (REST API): requestContext.identity.sourceIp * - API Gateway v2 (HTTP API/Function URLs): requestContext.http.sourceIp * - ALB: Falls back to x-forwarded-for header * * @param c - Context * @returns Connection information including remote address * @example * ```ts * import { Hono } from 'hono' * import { handle, getConnInfo } from './index' * * const app = new Hono() * * app.get('/', (c) => { * const info = getConnInfo(c) * return c.text(`Your IP: ${info.remote.address}`) * }) * * export const handler = handle(app) * ``` */export const getConnInfo: GetConnInfo = (c: Context<Env>) => { const requestContext = c.env.requestContext
let address: string | undefined
// API Gateway v1 - has identity object if ('identity' in requestContext && requestContext.identity?.sourceIp) { address = requestContext.identity.sourceIp } // API Gateway v2 - has http object else if ('http' in requestContext && requestContext.http?.sourceIp) { address = requestContext.http.sourceIp } // ALB - use X-Forwarded-For header else { const xff = c.req.header('x-forwarded-for') if (xff) { const ips = xff.split(',') // ALB appends the real client IP to the end of the header address = ips[ips.length - 1].trim() } }
return { remote: { address, }, }}added:adapters/aws-lambda/src/handler.test.ts+678 added
1+import { Hono } from 'hono'2+import { bodyLimit } from 'hono/body-limit'3+import { setCookie } from 'hono/cookie'4+import type { APIGatewayProxyEventV2, LambdaEvent, LatticeProxyEventV2 } from './handler'5+import {6+ getProcessor,7+ handle,8+ isContentEncodingBinary,9+ defaultIsContentTypeBinary,10+} from './handler'11+import type { ApiGatewayRequestContextV2 } from './types'12+13+// Base event objects to reduce duplication14+const baseV1Event: LambdaEvent = {15+ version: '1.0',16+ resource: '/my/path',17+ path: '/my/path',18+ httpMethod: 'GET',19+ headers: {},20+ multiValueHeaders: {},21+ queryStringParameters: {},22+ requestContext: {23+ accountId: '123456789012',24+ apiId: 'id',25+ authorizer: { claims: null, scopes: null },26+ domainName: 'id.execute-api.us-east-1.amazonaws.com',27+ domainPrefix: 'id',28+ extendedRequestId: 'request-id',29+ httpMethod: 'GET',30+ identity: {31+ sourceIp: '192.0.2.1',32+ userAgent: 'user-agent',33+ clientCert: {34+ clientCertPem: 'CERT_CONTENT',35+ subjectDN: 'www.example.com',36+ issuerDN: 'Example issuer',37+ serialNumber: 'a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1',38+ validity: {39+ notBefore: 'May 28 12:30:02 2019 GMT',40+ notAfter: 'Aug 5 09:36:04 2021 GMT',41+ },42+ },43+ },44+ path: '/my/path',45+ protocol: 'HTTP/1.1',46+ requestId: 'id=',47+ requestTime: '04/Mar/2020:19:15:17 +0000',48+ requestTimeEpoch: 1583349317135,49+ resourcePath: '/my/path',50+ stage: '$default',51+ },52+ pathParameters: {},53+ stageVariables: {},54+ body: null,55+ isBase64Encoded: false,56+}57+58+const baseV2Event: LambdaEvent = {59+ version: '2.0',60+ routeKey: '$default',61+ rawPath: '/my/path',62+ rawQueryString: '',63+ cookies: [],64+ headers: {},65+ queryStringParameters: {},66+ requestContext: {67+ accountId: '123456789012',68+ apiId: 'api-id',69+ authentication: null,70+ authorizer: {},71+ domainName: 'id.execute-api.us-east-1.amazonaws.com',72+ domainPrefix: 'id',73+ http: {74+ method: 'POST',75+ path: '/my/path',76+ protocol: 'HTTP/1.1',77+ sourceIp: '192.0.2.1',78+ userAgent: 'agent',79+ },80+ requestId: 'id',81+ routeKey: '$default',82+ stage: '$default',83+ time: '12/Mar/2020:19:03:58 +0000',84+ timeEpoch: 1583348638390,85+ },86+ body: null,87+ pathParameters: {},88+ isBase64Encoded: false,89+ stageVariables: {},90+}91+92+describe('isContentTypeBinary', () => {93+ it.each([94+ ['image/png', true],95+ ['font/woff2', true],96+ ['image/svg+xml', false],97+ ['image/svg+xml; charset=UTF-8', false],98+ ['text/plain', false],99+ ['text/plain; charset=UTF-8', false],100+ ['text/css', false],101+ ['text/javascript', false],102+ ['application/json', false],103+ ['application/ld+json', false],104+ ['application/json', false],105+ ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', true],106+ ['application/msword', true],107+ ['application/epub+zip', true],108+ ['application/ld+json', false],109+ ['application/vnd.oasis.opendocument.text', true],110+ ['application/vnd.apple.installer+xml', true],111+ ['application/vnd.apple.installer+xml; charset=UTF-8', true],112+ ['application/vnd.mozilla.xul+xml', true],113+ ['APPLICATION/VND.APPLE.INSTALLER+XML', true],114+ ['APPLICATION/JSON', false],115+ ['TEXT/PLAIN', false],116+ ])('Should determine whether %s it is binary', (mimeType: string, expected: boolean) => {117+ expect(defaultIsContentTypeBinary(mimeType)).toBe(expected)118+ })119+})120+121+describe('isContentEncodingBinary', () => {122+ it('Should determine whether it is compressed', () => {123+ expect(isContentEncodingBinary('gzip')).toBe(true)124+ expect(isContentEncodingBinary('compress')).toBe(true)125+ expect(isContentEncodingBinary('deflate')).toBe(true)126+ expect(isContentEncodingBinary('br')).toBe(true)127+ expect(isContentEncodingBinary('deflate, gzip')).toBe(true)128+ expect(isContentEncodingBinary('zstd')).toBe(true)129+ expect(isContentEncodingBinary('')).toBe(false)130+ expect(isContentEncodingBinary('identity')).toBe(false)131+ expect(isContentEncodingBinary(null)).toBe(false)132+ })133+})134+135+describe('EventProcessor.createResult with contentTypesAsBinary', () => {136+ const event = baseV1Event137+138+ it('Should encode as base64 when content-type is in contentTypesAsBinary array', async () => {139+ const processor = getProcessor(event)140+ const response = new Response('test content', {141+ headers: { 'content-type': 'application/custom' },142+ })143+144+ const result = await processor.createResult(event, response, {145+ isContentTypeBinary: (contentType: string) => contentType === 'application/custom',146+ })147+148+ expect(result.isBase64Encoded).toBe(true)149+ expect(result.body).toBe('dGVzdCBjb250ZW50')150+ })151+152+ it('Should not encode as base64 when content-type is not in isContentTypeBinary array', async () => {153+ const processor = getProcessor(event)154+ const response = new Response('test content', {155+ headers: { 'content-type': 'application/json' },156+ })157+158+ const result = await processor.createResult(event, response, {159+ isContentTypeBinary: (contentType: string) => contentType === 'application/custom',160+ })161+162+ expect(result.isBase64Encoded).toBe(false)163+ expect(result.body).toBe('test content')164+ })165+166+ it('Should use defaultIsContentTypeBinary when isContentTypeBinary is undefined with binary content', async () => {167+ const processor = getProcessor(event)168+ const response = new Response('test image content', {169+ headers: { 'content-type': 'image/png' },170+ })171+172+ // Pass undefined for isContentTypeBinary to test default behavior173+ const result = await processor.createResult(event, response, {174+ isContentTypeBinary: undefined,175+ })176+177+ expect(result.isBase64Encoded).toBe(true)178+ expect(result.body).toBe('dGVzdCBpbWFnZSBjb250ZW50')179+ })180+181+ it('Should use defaultIsContentTypeBinary when isContentTypeBinary is undefined with non-binary content', async () => {182+ const processor = getProcessor(event)183+ const response = new Response('test text content', {184+ headers: { 'content-type': 'text/plain' },185+ })186+187+ // Pass undefined for isContentTypeBinary to test default behavior188+ const result = await processor.createResult(event, response, {189+ isContentTypeBinary: undefined,190+ })191+192+ expect(result.isBase64Encoded).toBe(false)193+ expect(result.body).toBe('test text content')194+ })195+})196+197+describe('EventProcessor.createRequest', () => {198+ it('Should preserve percent-encoded values in query string for version 1.0', () => {199+ const event: LambdaEvent = {200+ ...baseV1Event,201+ // API Gateway provides decoded values202+ multiValueQueryStringParameters: {203+ path: ['/book/{bookId}/'], // Originally %7BbookId%7D204+ name: ['John Doe'], // Originally John%20Doe205+ tag: ['日本語'], // Originally %E6%97%A5%E6%9C%AC%E8%AA%9E206+ },207+ }208+209+ const processor = getProcessor(event)210+ const request = processor.createRequest(event)211+212+ // URL should contain properly encoded values213+ expect(request.url).toEqual(214+ 'https://id.execute-api.us-east-1.amazonaws.com/my/path?path=%2Fbook%2F%7BbookId%7D%2F&name=John%20Doe&tag=%E6%97%A5%E6%9C%AC%E8%AA%9E'215+ )216+ })217+218+ it('Should handle special characters correctly in queryStringParameters for version 1.0', () => {219+ const event: LambdaEvent = {220+ ...baseV1Event,221+ queryStringParameters: {222+ 'key with spaces': 'value with spaces',223+ 'special!@#$%^&*()': 'chars!@#$%^&*()',224+ equals: 'a=b=c',225+ ampersand: 'a&b&c',226+ },227+ }228+229+ const processor = getProcessor(event)230+ const request = processor.createRequest(event)231+232+ // Verify the URL is properly encoded233+ const url = new URL(request.url)234+ expect(url.searchParams.get('key with spaces')).toBe('value with spaces')235+ expect(url.searchParams.get('special!@#$%^&*()')).toBe('chars!@#$%^&*()')236+ expect(url.searchParams.get('equals')).toBe('a=b=c')237+ expect(url.searchParams.get('ampersand')).toBe('a&b&c')238+ })239+240+ it('Should preserve empty query parameters for version 1.0', () => {241+ const event: LambdaEvent = {242+ ...baseV1Event,243+ queryStringParameters: {244+ empty: '',245+ present: '0',246+ omitted: undefined,247+ },248+ }249+250+ const request = getProcessor(event).createRequest(event)251+252+ expect(request.url).toBe(253+ 'https://id.execute-api.us-east-1.amazonaws.com/my/path?empty=&present=0'254+ )255+ })256+257+ it('Should preserve empty query parameters for ALB events', () => {258+ const event: LambdaEvent = {259+ httpMethod: 'GET',260+ path: '/my/path',261+ headers: { host: 'example.test' },262+ body: null,263+ isBase64Encoded: false,264+ queryStringParameters: {265+ empty: '',266+ present: '0',267+ omitted: undefined,268+ },269+ requestContext: {270+ elb: { targetGroupArn: 'arn:aws:elasticloadbalancing:...' },271+ },272+ }273+274+ const request = getProcessor(event).createRequest(event)275+276+ expect(request.url).toBe('https://example.test/my/path?empty=&present=0')277+ })278+279+ it('Should return valid Request object from version 1.0 API Gateway event', () => {280+ const event: LambdaEvent = {281+ ...baseV1Event,282+ headers: {283+ 'content-type': 'application/json',284+ header1: 'value1',285+ header2: 'value1',286+ },287+ multiValueHeaders: {288+ header1: ['value1'],289+ header2: ['value1', 'value2', 'value3'],290+ },291+ // This value doesn't match multi value's content.292+ // We want to assert handler is using the multi value's content when both are available.293+ queryStringParameters: {294+ parameter2: 'value',295+ },296+ multiValueQueryStringParameters: {297+ parameter1: ['value1', 'value2'],298+ parameter2: ['value'],299+ },300+ }301+302+ const processor = getProcessor(event)303+ const request = processor.createRequest(event)304+305+ expect(request.method).toEqual('GET')306+ // Note: Values are now properly encoded307+ expect(request.url).toEqual(308+ 'https://id.execute-api.us-east-1.amazonaws.com/my/path?parameter1=value1¶meter1=value2¶meter2=value'309+ )310+ expect(Object.fromEntries(request.headers)).toEqual({311+ 'content-type': 'application/json',312+ header1: 'value1',313+ header2: 'value1, value2, value3',314+ })315+ })316+317+ it('Should preserve every repeated header value for version 1.0 API Gateway event', () => {318+ const event: LambdaEvent = {319+ ...baseV1Event,320+ headers: {321+ 'x-forwarded-for': '203.0.113.10',322+ },323+ multiValueHeaders: {324+ 'x-forwarded-for': ['203.0.113.1', '203.0.113.10'],325+ },326+ }327+328+ const processor = getProcessor(event)329+ const request = processor.createRequest(event)330+331+ expect(request.headers.get('x-forwarded-for')).toEqual('203.0.113.1, 203.0.113.10')332+ })333+334+ it('Should return valid Request object from version 2.0 API Gateway event', () => {335+ const event: LambdaEvent = {336+ ...baseV2Event,337+ rawQueryString: 'parameter1=value1¶meter1=value2¶meter2=value',338+ cookies: ['cookie1', 'cookie2'],339+ headers: {340+ 'content-type': 'application/json',341+ header1: 'value1',342+ header2: 'value1,value2',343+ },344+ queryStringParameters: {345+ parameter1: 'value1,value2',346+ parameter2: 'value',347+ },348+ body: 'Hello from Lambda',349+ pathParameters: {350+ parameter1: 'value1',351+ },352+ stageVariables: {353+ stageVariable1: 'value1',354+ stageVariable2: 'value2',355+ },356+ }357+358+ const processor = getProcessor(event)359+ const request = processor.createRequest(event)360+361+ expect(request.method).toEqual('POST')362+ expect(request.url).toEqual(363+ 'https://id.execute-api.us-east-1.amazonaws.com/my/path?parameter1=value1¶meter1=value2¶meter2=value'364+ )365+ expect(Object.fromEntries(request.headers)).toEqual({366+ 'content-length': '17',367+ 'content-type': 'application/json',368+ cookie: 'cookie1; cookie2',369+ header1: 'value1',370+ header2: 'value1,value2',371+ })372+ })373+374+ it('Should return valid Request object from version 2.0 Lattice event', async () => {375+ const event: LatticeProxyEventV2 = {376+ version: '2.0',377+ // query string parameters from the path take precedence over the explicit notation below378+ path: '/my/path?parameter1=value1¶meter1=value2¶meter2=value',379+ method: 'POST',380+ headers: {381+ cookie: ['cookie1=value1; cookie2=value2'],382+ 'content-type': ['application/x-www-form-urlencoded'],383+ header1: ['value1'],384+ header2: ['value1', 'value2'],385+ host: ['my-service-a1b2c3.x1y2z3.vpc-lattice-svcs.us-east-1.on.aws'],386+ },387+ queryStringParameters: {388+ parameter1: ['value1', 'value2'],389+ parameter2: ['value'],390+ },391+ body: 'SGVsbG8gZnJvbSBMYW1iZGE=',392+ isBase64Encoded: true,393+ requestContext: {394+ serviceNetworkArn: '',395+ serviceArn: '',396+ targetGroupArn: '',397+ identity: {},398+ region: 'us-east-1',399+ timeEpoch: '1583348638390123',400+ },401+ }402+403+ const processor = getProcessor(event)404+ const request = processor.createRequest(event)405+406+ expect(await request.text()).toEqual('Hello from Lambda')407+ expect(request.method).toEqual('POST')408+ expect(request.url).toEqual(409+ 'https://my-service-a1b2c3.x1y2z3.vpc-lattice-svcs.us-east-1.on.aws/my/path?parameter1=value1¶meter1=value2¶meter2=value'410+ )411+ expect(Object.fromEntries(request.headers)).toEqual({412+ 'content-length': '17',413+ 'content-type': 'application/x-www-form-urlencoded',414+ cookie: 'cookie1=value1; cookie2=value2',415+ header1: 'value1',416+ header2: 'value1, value2',417+ host: 'my-service-a1b2c3.x1y2z3.vpc-lattice-svcs.us-east-1.on.aws',418+ })419+ })420+421+ it('Should preserve every repeated header value for Lattice event', async () => {422+ const event: LatticeProxyEventV2 = {423+ version: '2.0',424+ path: '/my/path',425+ method: 'GET',426+ headers: {427+ host: ['example.test'],428+ 'x-forwarded-for': ['203.0.113.1', '203.0.113.10'],429+ },430+ queryStringParameters: {},431+ body: null,432+ isBase64Encoded: false,433+ requestContext: {434+ serviceNetworkArn: '',435+ serviceArn: '',436+ targetGroupArn: '',437+ identity: {},438+ region: 'us-east-1',439+ timeEpoch: '1583348638390123',440+ },441+ }442+443+ const processor = getProcessor(event)444+ const request = processor.createRequest(event)445+446+ expect(request.headers.get('x-forwarded-for')).toEqual('203.0.113.1, 203.0.113.10')447+ })448+449+ describe('non-ASCII header value processing', () => {450+ it('Should encode non-ASCII header values with encodeURIComponent', async () => {451+ const event: LambdaEvent = {452+ ...baseV1Event,453+ headers: {454+ 'x-city': '炎', // Non-ASCII character455+ },456+ }457+458+ const processor = getProcessor(event)459+ const request = processor.createRequest(event)460+461+ const xCity = request.headers.get('x-city') ?? ''462+ expect(decodeURIComponent(xCity)).toBe('炎')463+ })464+ })465+})466+467+describe('handle', () => {468+ it('Should route a V1 REST event by its path even when a base path mapping adds rawPath', async () => {469+ const app = new Hono()470+ app.get('/my/path', (c) => c.text('Hello'))471+ const handler = handle(app)472+473+ // A custom domain base path mapping makes API Gateway add a `rawPath` to the474+ // V1 (REST API) event, holding the path before the mapping was stripped. The475+ // event is still V1: it carries `path` and a V1 request context with no `http`.476+ const event: LambdaEvent = {477+ ...baseV1Event,478+ rawPath: '/base/my/path',479+ }480+481+ const result = await handler(event)482+ expect(result.statusCode).toBe(200)483+ expect(result.body).toBe('Hello')484+ })485+486+ it('Should return 400 when request contains invalid header names (v2)', async () => {487+ const app = new Hono()488+ app.get('/my/path', (c) => c.text('Hello'))489+ const handler = handle(app)490+491+ const event: LambdaEvent = {492+ ...baseV2Event,493+ headers: {494+ 'valid-header': 'value',495+ 'a"a': 'invalid header name',496+ },497+ requestContext: {498+ ...baseV2Event.requestContext,499+ http: {500+ method: 'GET',501+ path: '/my/path',502+ protocol: 'HTTP/1.1',503+ sourceIp: '192.0.2.1',504+ userAgent: 'agent',505+ },506+ },507+ }508+509+ const result = await handler(event)510+ expect(result.statusCode).toBe(400)511+ expect(result.body).toBe('Invalid request')512+ })513+514+ it('ALB single-header: emits the first Set-Cookie intact, never comma-joined', async () => {515+ const app = new Hono()516+ app.get('/multi-cookie', (c) => {517+ setCookie(c, 'session', 'abc123', { expires: new Date('2026-06-09T00:00:00Z') })518+ setCookie(c, 'csrf', 'xyz789', { expires: new Date('2026-06-10T00:00:00Z') })519+ return c.text('ok')520+ })521+ const handler = handle(app)522+523+ const event = {524+ httpMethod: 'GET',525+ path: '/multi-cookie',526+ headers: { host: 'app.example.com' },527+ body: null,528+ isBase64Encoded: false,529+ requestContext: { elb: { targetGroupArn: 'arn:aws:elasticloadbalancing:...' } },530+ } as unknown as LambdaEvent531+532+ const result = await handler(event)533+534+ expect(result.headers!['set-cookie']).toBe(535+ 'session=abc123; Path=/; Expires=Tue, 09 Jun 2026 00:00:00 GMT'536+ )537+ })538+539+ it('Lattice v2: emits multiple Set-Cookie as an array', async () => {540+ const app = new Hono()541+ app.get('/multi-cookie', (c) => {542+ setCookie(c, 'session', 'abc123')543+ setCookie(c, 'csrf', 'xyz789')544+ return c.text('ok')545+ })546+ const handler = handle(app)547+548+ const event: LatticeProxyEventV2 = {549+ version: '2.0',550+ path: '/multi-cookie',551+ method: 'GET',552+ headers: { host: ['app.example.com'] },553+ queryStringParameters: {},554+ body: null,555+ isBase64Encoded: false,556+ requestContext: {557+ serviceNetworkArn: '',558+ serviceArn: 'arn:aws:vpc-lattice:us-east-1:123456789012:service/svc-0a40',559+ targetGroupArn: '',560+ identity: {},561+ region: 'us-east-1',562+ timeEpoch: '1583348638390123',563+ },564+ }565+566+ const result = await handler(event)567+568+ expect(result.headers!['set-cookie']).toEqual(['session=abc123; Path=/', 'csrf=xyz789; Path=/'])569+ })570+571+ it('Should return 400 when request contains invalid header names (v1)', async () => {572+ const app = new Hono()573+ app.get('/my/path', (c) => c.text('Hello'))574+ const handler = handle(app)575+576+ const event: LambdaEvent = {577+ ...baseV1Event,578+ headers: {579+ 'a"a': 'invalid header name',580+ },581+ multiValueHeaders: {582+ 'a"a': ['invalid header name'],583+ },584+ }585+586+ const result = await handler(event)587+ expect(result.statusCode).toBe(400)588+ expect(result.body).toBe('Invalid request')589+ })590+591+ it('Should enforce bodyLimit when the client understates Content-Length', async () => {592+ const app = new Hono()593+ app.post(594+ '/upload',595+ bodyLimit({ maxSize: 1024, onError: (c) => c.text('too large', 413) }),596+ async (c) => c.json({ received: (await c.req.text()).length })597+ )598+ const handler = handle(app)599+600+ const event: LambdaEvent = {601+ ...baseV2Event,602+ rawPath: '/upload',603+ headers: { 'content-type': 'text/plain', 'content-length': '1' },604+ body: 'A'.repeat(10000),605+ requestContext: {606+ ...baseV2Event.requestContext,607+ http: {608+ method: 'POST',609+ path: '/upload',610+ protocol: 'HTTP/1.1',611+ sourceIp: '192.0.2.1',612+ userAgent: 'agent',613+ },614+ },615+ }616+617+ const result = await handler(event)618+ expect(result.statusCode).toBe(413)619+ })620+})621+622+describe('V2 request context authorizer', () => {623+ const baseV2RequestContext = baseV2Event.requestContext as ApiGatewayRequestContextV2624+625+ it('Should expose the context of a Lambda (REQUEST) authorizer', async () => {626+ const app = new Hono<{ Bindings: { event: APIGatewayProxyEventV2 } }>()627+ app.get('/my/path', (c) => c.json(c.env.event.requestContext.authorizer.lambda))628+ const handler = handle(app)629+630+ const event: LambdaEvent = {631+ ...baseV2Event,632+ requestContext: {633+ ...baseV2RequestContext,634+ http: { ...baseV2RequestContext.http, method: 'GET' },635+ authorizer: { lambda: { userId: 'user-123', isAdmin: true } },636+ },637+ }638+639+ const result = await handler(event)640+ expect(result.statusCode).toBe(200)641+ expect(JSON.parse(result.body)).toEqual({ userId: 'user-123', isAdmin: true })642+ })643+644+ it('Should expose the claims and scopes of a JWT authorizer', async () => {645+ const app = new Hono<{ Bindings: { event: APIGatewayProxyEventV2 } }>()646+ app.get('/my/path', (c) => c.json(c.env.event.requestContext.authorizer.jwt))647+ const handler = handle(app)648+649+ const event: LambdaEvent = {650+ ...baseV2Event,651+ requestContext: {652+ ...baseV2RequestContext,653+ http: { ...baseV2RequestContext.http, method: 'GET' },654+ authorizer: {655+ jwt: { claims: { sub: 'user-123', email_verified: true }, scopes: ['read'] },656+ },657+ },658+ }659+660+ const result = await handler(event)661+ expect(result.statusCode).toBe(200)662+ expect(JSON.parse(result.body)).toEqual({663+ claims: { sub: 'user-123', email_verified: true },664+ scopes: ['read'],665+ })666+ })667+668+ it('Should type each authorizer variant as optional', () => {669+ const authorizer: ApiGatewayRequestContextV2['authorizer'] = {}670+ expectTypeOf(authorizer.lambda).toEqualTypeOf<Record<string, unknown> | null | undefined>()671+ expectTypeOf(authorizer.jwt).toEqualTypeOf<672+ | { claims: Record<string, string | number | boolean | string[]>; scopes: string[] | null }673+ | undefined674+ >()675+ // A JWT authorizer reports no scopes as `null`.676+ expectTypeOf<null>().toMatchTypeOf<NonNullable<typeof authorizer.jwt>['scopes']>()677+ })678+})added:adapters/aws-lambda/src/handler.ts+682 added
1+import { pipeline } from 'node:stream/promises'2+import type { Hono } from 'hono'3+import type { Env, Schema } from 'hono/types'4+import { decodeBase64, encodeBase64 } from 'hono/utils/encode'5+import type {6+ ALBRequestContext,7+ ApiGatewayRequestContext,8+ ApiGatewayRequestContextV2,9+ Handler,10+ LambdaContext,11+ LatticeRequestContextV2,12+} from './types'13+14+function sanitizeHeaderValue(value: string): string {15+ // Check if the value contains non-ASCII characters (char codes > 127)16+ // eslint-disable-next-line no-control-regex17+ const hasNonAscii = /[^\x00-\x7F]/.test(value)18+ if (!hasNonAscii) {19+ return value20+ }21+ return encodeURIComponent(value)22+}23+24+export type LambdaEvent =25+ | APIGatewayProxyEvent26+ | APIGatewayProxyEventV227+ | ALBProxyEvent28+ | LatticeProxyEventV229+30+export interface LatticeProxyEventV2 {31+ version: string32+ path: string33+ method: string34+ headers: Record<string, string[] | undefined>35+ queryStringParameters: Record<string, string[] | undefined>36+ body: string | null37+ isBase64Encoded: boolean38+ requestContext: LatticeRequestContextV239+}40+41+// When calling HTTP API or Lambda directly through function urls42+export interface APIGatewayProxyEventV2 {43+ version: string44+ routeKey: string45+ headers: Record<string, string | undefined>46+ multiValueHeaders?: undefined47+ cookies?: string[]48+ rawPath: string49+ rawQueryString: string50+ body: string | null51+ isBase64Encoded: boolean52+ requestContext: ApiGatewayRequestContextV253+ queryStringParameters?: {54+ [name: string]: string | undefined55+ }56+ pathParameters?: {57+ [name: string]: string | undefined58+ }59+ stageVariables?: {60+ [name: string]: string | undefined61+ }62+}63+64+// When calling Lambda through an API Gateway65+export interface APIGatewayProxyEvent {66+ version: string67+ httpMethod: string68+ headers: Record<string, string | undefined>69+ multiValueHeaders?: {70+ [headerKey: string]: string[]71+ }72+ path: string73+ body: string | null74+ isBase64Encoded: boolean75+ queryStringParameters?: Record<string, string | undefined>76+ requestContext: ApiGatewayRequestContext77+ resource: string78+ multiValueQueryStringParameters?: {79+ [parameterKey: string]: string[]80+ }81+ pathParameters?: Record<string, string>82+ stageVariables?: Record<string, string>83+}84+85+// When calling Lambda through an Application Load Balancer86+export interface ALBProxyEvent {87+ httpMethod: string88+ headers?: Record<string, string | undefined>89+ multiValueHeaders?: Record<string, string[] | undefined>90+ path: string91+ body: string | null92+ isBase64Encoded: boolean93+ queryStringParameters?: Record<string, string | undefined>94+ multiValueQueryStringParameters?: {95+ [parameterKey: string]: string[]96+ }97+ requestContext: ALBRequestContext98+}99+100+type WithHeaders = {101+ headers: Record<string, string | string[]>102+ multiValueHeaders?: undefined103+}104+type WithMultiValueHeaders = {105+ headers?: undefined106+ multiValueHeaders: Record<string, string[]>107+}108+109+export type APIGatewayProxyResult = {110+ statusCode: number111+ statusDescription?: string112+ body: string113+ cookies?: string[]114+ isBase64Encoded: boolean115+} & (WithHeaders | WithMultiValueHeaders)116+117+const getRequestContext = (118+ event: LambdaEvent119+):120+ | ApiGatewayRequestContext121+ | ApiGatewayRequestContextV2122+ | ALBRequestContext123+ | LatticeRequestContextV2 => {124+ return event.requestContext125+}126+127+async function* readWebStream(128+ reader: ReadableStreamDefaultReader<Uint8Array>129+): AsyncGenerator<Uint8Array> {130+ let readResult = await reader.read()131+ while (!readResult.done) {132+ yield readResult.value133+ readResult = await reader.read()134+ }135+}136+137+const streamToNodeStream = (138+ reader: ReadableStreamDefaultReader<Uint8Array>,139+ writer: NodeJS.WritableStream140+): Promise<void> => pipeline(readWebStream(reader), writer)141+142+export const streamHandle = <143+ E extends Env = Env,144+ S extends Schema = {},145+ BasePath extends string = '/',146+>(147+ app: Hono<E, S, BasePath>148+): Handler => {149+ // @ts-expect-error awslambda is not a standard API150+ return awslambda.streamifyResponse(151+ async (event: LambdaEvent, responseStream: NodeJS.WritableStream, context: LambdaContext) => {152+ const processor = getProcessor(event)153+ try {154+ const req = processor.createRequest(event)155+ const requestContext = getRequestContext(event)156+157+ const res = await app.fetch(req, {158+ event,159+ requestContext,160+ context,161+ })162+163+ const headers: Record<string, string> = {}164+ const cookies: string[] = []165+ res.headers.forEach((value, name) => {166+ if (name === 'set-cookie') {167+ cookies.push(value)168+ } else {169+ headers[name] = value170+ }171+ })172+173+ // Check content type174+ const httpResponseMetadata = {175+ statusCode: res.status,176+ headers,177+ cookies,178+ }179+180+ // Update response stream181+ // @ts-expect-error awslambda is not a standard API182+ responseStream = awslambda.HttpResponseStream.from(responseStream, httpResponseMetadata)183+184+ if (res.body) {185+ await streamToNodeStream(res.body.getReader(), responseStream)186+ } else {187+ responseStream.write('')188+ }189+ } catch (error) {190+ console.error('Error processing request:', error)191+ responseStream.write('Internal Server Error')192+ } finally {193+ responseStream.end()194+ }195+ }196+ )197+}198+199+type HandleOptions = {200+ isContentTypeBinary: ((contentType: string) => boolean) | undefined201+}202+203+/**204+ * Converts a Hono application to an AWS Lambda handler.205+ *206+ * Accepts events from API Gateway (v1 and v2), Application Load Balancer (ALB),207+ * and Lambda Function URLs.208+ *209+ * @param app - The Hono application instance210+ * @param options - Optional configuration211+ * @param options.isContentTypeBinary - A function to determine if the content type is binary.212+ * If not provided, the default function will be used.213+ * @returns Lambda handler function214+ *215+ * @example216+ * ```js217+ * import { Hono } from 'hono'218+ * import { handle } from './index'219+ *220+ * const app = new Hono()221+ *222+ * app.get('/', (c) => c.text('Hello from Lambda'))223+ * app.get('/json', (c) => c.json({ message: 'Hello JSON' }))224+ *225+ * export const handler = handle(app)226+ * ```227+ *228+ * @example229+ * ```js230+ * // With custom binary content type detection231+ * import { handle, defaultIsContentTypeBinary } from './index'232+ * export const handler = handle(app, {233+ * isContentTypeBinary: (contentType) => {234+ * if (defaultIsContentTypeBinary(contentType)) {235+ * // default logic same as prior to v4.8.4236+ * return true237+ * }238+ * return contentType.startsWith('image/') || contentType === 'application/pdf'239+ * }240+ * })241+ * ```242+ */243+export const handle = <E extends Env = Env, S extends Schema = {}, BasePath extends string = '/'>(244+ app: Hono<E, S, BasePath>,245+ { isContentTypeBinary }: HandleOptions = { isContentTypeBinary: undefined }246+): (<L extends LambdaEvent>(247+ event: L,248+ lambdaContext?: LambdaContext249+) => Promise<250+ APIGatewayProxyResult &251+ (L extends { multiValueHeaders: Record<string, string[]> }252+ ? WithMultiValueHeaders253+ : WithHeaders)254+>) => {255+ // @ts-expect-error conditional return type is not inferable256+ return async (event, lambdaContext?) => {257+ const processor = getProcessor(event)258+259+ let req, requestContext260+ try {261+ req = processor.createRequest(event)262+ requestContext = getRequestContext(event)263+ } catch (error) {264+ console.error('Error processing request:', error)265+ const errorResponse =266+ error instanceof TypeError267+ ? new Response('Invalid request', { status: 400 })268+ : new Response('Internal Server Error', { status: 500 })269+ return processor.createResult(event, errorResponse, { isContentTypeBinary })270+ }271+272+ const res = await app.fetch(req, {273+ event,274+ requestContext,275+ lambdaContext,276+ })277+278+ return processor.createResult(event, res, { isContentTypeBinary })279+ }280+}281+282+export abstract class EventProcessor<E extends LambdaEvent> {283+ protected abstract getPath(event: E): string284+285+ protected abstract getMethod(event: E): string286+287+ protected abstract getQueryString(event: E): string288+289+ protected abstract getHeaders(event: E): Headers290+291+ protected abstract getCookies(event: E, headers: Headers): void292+293+ protected abstract setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void294+295+ protected getHeaderValue(headers: E['headers'], key: string): string | undefined {296+ const value = headers297+ ? Array.isArray(headers[key])298+ ? headers[key][0]299+ : headers[key]300+ : undefined301+302+ return value303+ }304+305+ protected getDomainName(event: E): string | undefined {306+ if (event.requestContext && 'domainName' in event.requestContext) {307+ return event.requestContext.domainName308+ }309+310+ const hostFromHeaders = this.getHeaderValue(event.headers, 'host')311+312+ if (hostFromHeaders) {313+ return hostFromHeaders314+ }315+316+ const multiValueHeaders = 'multiValueHeaders' in event ? event.multiValueHeaders : {}317+ const hostFromMultiValueHeaders = this.getHeaderValue(multiValueHeaders, 'host')318+319+ return hostFromMultiValueHeaders320+ }321+322+ createRequest(event: E): Request {323+ const queryString = this.getQueryString(event)324+ const domainName = this.getDomainName(event)325+ const path = this.getPath(event)326+ const urlPath = `https://${domainName}${path}`327+ const url = queryString ? `${urlPath}?${queryString}` : urlPath328+329+ const headers = this.getHeaders(event)330+331+ const method = this.getMethod(event)332+ const requestInit: RequestInit = {333+ headers,334+ method,335+ }336+337+ if (event.body) {338+ const body = event.isBase64Encoded339+ ? decodeBase64(event.body)340+ : new TextEncoder().encode(event.body)341+ requestInit.body = body342+ headers.set('content-length', body.length.toString())343+ }344+345+ return new Request(url, requestInit)346+ }347+348+ async createResult(349+ event: E,350+ res: Response,351+ options: Pick<HandleOptions, 'isContentTypeBinary'>352+ ): Promise<APIGatewayProxyResult> {353+ // determine whether the response body should be base64 encoded354+ const contentType = res.headers.get('content-type')355+ const isContentTypeBinary = options.isContentTypeBinary ?? defaultIsContentTypeBinary // overwrite default function if provided356+ let isBase64Encoded = contentType && isContentTypeBinary(contentType) ? true : false357+358+ if (!isBase64Encoded) {359+ const contentEncoding = res.headers.get('content-encoding')360+ isBase64Encoded = isContentEncodingBinary(contentEncoding)361+ }362+363+ const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()364+365+ const result: APIGatewayProxyResult = {366+ body: body,367+ statusCode: res.status,368+ isBase64Encoded,369+ ...('multiValueHeaders' in event && event.multiValueHeaders370+ ? {371+ multiValueHeaders: {},372+ }373+ : {374+ headers: {},375+ }),376+ }377+378+ this.setCookies(event, res, result)379+ if (result.multiValueHeaders) {380+ res.headers.forEach((value, key) => {381+ result.multiValueHeaders[key] = [value]382+ })383+ } else {384+ res.headers.forEach((value, key) => {385+ result.headers[key] = value386+ })387+ }388+389+ return result390+ }391+392+ setCookies(_event: E, res: Response, result: APIGatewayProxyResult) {393+ if (res.headers.has('set-cookie')) {394+ const cookies = res.headers.getSetCookie395+ ? res.headers.getSetCookie()396+ : Array.from(res.headers.entries())397+ .filter(([k]) => k === 'set-cookie')398+ .map(([, v]) => v)399+400+ if (Array.isArray(cookies)) {401+ this.setCookiesToResult(result, cookies)402+ res.headers.delete('set-cookie')403+ }404+ }405+ }406+}407+408+export class EventV2Processor extends EventProcessor<APIGatewayProxyEventV2> {409+ protected getPath(event: APIGatewayProxyEventV2): string {410+ return event.rawPath411+ }412+413+ protected getMethod(event: APIGatewayProxyEventV2): string {414+ return event.requestContext.http.method415+ }416+417+ protected getQueryString(event: APIGatewayProxyEventV2): string {418+ return event.rawQueryString419+ }420+421+ protected getCookies(event: APIGatewayProxyEventV2, headers: Headers): void {422+ if (Array.isArray(event.cookies)) {423+ headers.set('Cookie', event.cookies.join('; '))424+ }425+ }426+427+ protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {428+ result.cookies = cookies429+ }430+431+ protected getHeaders(event: APIGatewayProxyEventV2): Headers {432+ const headers = new Headers()433+ this.getCookies(event, headers)434+ if (event.headers) {435+ for (const [k, v] of Object.entries(event.headers)) {436+ if (v) {437+ headers.set(k, v)438+ }439+ }440+ }441+ return headers442+ }443+}444+445+const v2Processor: EventV2Processor = new EventV2Processor()446+447+export class EventV1Processor extends EventProcessor<APIGatewayProxyEvent> {448+ protected getPath(event: APIGatewayProxyEvent): string {449+ return event.path450+ }451+452+ protected getMethod(event: APIGatewayProxyEvent): string {453+ return event.httpMethod454+ }455+456+ protected getQueryString(event: APIGatewayProxyEvent): string {457+ // In the case of gateway Integration either queryStringParameters or multiValueQueryStringParameters can be present not both458+ // API Gateway passes decoded values, so we need to re-encode them to preserve the original URL459+ if (event.multiValueQueryStringParameters) {460+ return Object.entries(event.multiValueQueryStringParameters || {})461+ .filter(([, value]) => value)462+ .map(([key, values]) =>463+ values.map((value) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join('&')464+ )465+ .join('&')466+ } else {467+ return Object.entries(event.queryStringParameters || {})468+ .filter(([, value]) => value !== undefined)469+ .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value || '')}`)470+ .join('&')471+ }472+ }473+474+ protected getCookies(_event: APIGatewayProxyEvent, _headers: Headers): void {475+ // nop476+ }477+478+ protected getHeaders(event: APIGatewayProxyEvent): Headers {479+ const headers = new Headers()480+ this.getCookies(event, headers)481+ if (event.multiValueHeaders) {482+ for (const [k, values] of Object.entries(event.multiValueHeaders)) {483+ if (values) {484+ values.forEach((v) => headers.append(k, sanitizeHeaderValue(v)))485+ }486+ }487+ }488+ if (event.headers) {489+ for (const [k, v] of Object.entries(event.headers)) {490+ if (v && !headers.has(k)) {491+ headers.set(k, sanitizeHeaderValue(v))492+ }493+ }494+ }495+ return headers496+ }497+498+ protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {499+ result.multiValueHeaders = {500+ 'set-cookie': cookies,501+ }502+ }503+}504+505+const v1Processor: EventV1Processor = new EventV1Processor()506+507+export class ALBProcessor extends EventProcessor<ALBProxyEvent> {508+ protected getHeaders(event: ALBProxyEvent): Headers {509+ const headers = new Headers()510+ // if multiValueHeaders is present the ALB will use it instead of the headers field511+ // https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html#multi-value-headers512+ if (event.multiValueHeaders) {513+ for (const [key, values] of Object.entries(event.multiValueHeaders)) {514+ if (values && Array.isArray(values)) {515+ // https://www.rfc-editor.org/rfc/rfc9110.html#name-common-rules-for-defining-f516+ const sanitizedValue = sanitizeHeaderValue(values.join('; '))517+ headers.set(key, sanitizedValue)518+ }519+ }520+ } else {521+ for (const [key, value] of Object.entries(event.headers ?? {})) {522+ if (value) {523+ headers.set(key, sanitizeHeaderValue(value))524+ }525+ }526+ }527+ return headers528+ }529+530+ protected getPath(event: ALBProxyEvent): string {531+ return event.path532+ }533+534+ protected getMethod(event: ALBProxyEvent): string {535+ return event.httpMethod536+ }537+538+ protected getQueryString(event: ALBProxyEvent): string {539+ // In the case of ALB Integration either queryStringParameters or multiValueQueryStringParameters can be present not both540+ /*541+ In other cases like when using the serverless framework, the event object does contain both queryStringParameters and multiValueQueryStringParameters:542+ Below is an example event object for this URL: /payment/b8c55e69?select=amount&select=currency543+ {544+ ...545+ queryStringParameters: { select: 'currency' },546+ multiValueQueryStringParameters: { select: [ 'amount', 'currency' ] },547+ }548+ The expected results is for select to be an array with two items. However the pre-fix code is only returning one item ('currency') in the array.549+ A simple fix would be to invert the if statement and check the multiValueQueryStringParameters first.550+ */551+ if (event.multiValueQueryStringParameters) {552+ return Object.entries(event.multiValueQueryStringParameters || {})553+ .filter(([, value]) => value)554+ .map(([key, value]) => `${key}=${value.join(`&${key}=`)}`)555+ .join('&')556+ } else {557+ return Object.entries(event.queryStringParameters || {})558+ .filter(([, value]) => value !== undefined)559+ .map(([key, value]) => `${key}=${value}`)560+ .join('&')561+ }562+ }563+564+ protected getCookies(event: ALBProxyEvent, headers: Headers): void {565+ let cookie566+ if (event.multiValueHeaders) {567+ cookie = event.multiValueHeaders['cookie']?.join('; ')568+ } else {569+ cookie = event.headers ? event.headers['cookie'] : undefined570+ }571+ if (cookie) {572+ headers.append('Cookie', cookie)573+ }574+ }575+576+ protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {577+ // when multi value headers is enabled578+ if (result.multiValueHeaders) {579+ result.multiValueHeaders['set-cookie'] = cookies580+ } else {581+ result.headers['set-cookie'] = cookies[0]582+ }583+ }584+}585+586+const albProcessor: ALBProcessor = new ALBProcessor()587+588+export class LatticeV2Processor extends EventProcessor<LatticeProxyEventV2> {589+ protected getPath(event: LatticeProxyEventV2): string {590+ return event.path591+ }592+593+ protected getMethod(event: LatticeProxyEventV2): string {594+ return event.method595+ }596+597+ protected getQueryString(): string {598+ return ''599+ }600+601+ protected getHeaders(event: LatticeProxyEventV2): Headers {602+ const headers = new Headers()603+604+ if (event.headers) {605+ for (const [k, values] of Object.entries(event.headers)) {606+ if (values) {607+ values.forEach((v) => headers.append(k, sanitizeHeaderValue(v)))608+ }609+ }610+ }611+612+ return headers613+ }614+615+ protected getCookies(): void {616+ // nop617+ }618+619+ protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {620+ result.headers = {621+ ...result.headers,622+ 'set-cookie': cookies,623+ }624+ }625+}626+627+const latticeV2Processor: LatticeV2Processor = new LatticeV2Processor()628+629+export const getProcessor = (event: LambdaEvent): EventProcessor<LambdaEvent> => {630+ if (isProxyEventALB(event)) {631+ return albProcessor632+ }633+ if (isProxyEventV2(event)) {634+ return v2Processor635+ }636+ if (isLatticeEventV2(event)) {637+ return latticeV2Processor638+ }639+640+ return v1Processor641+}642+643+const isProxyEventALB = (event: LambdaEvent): event is ALBProxyEvent => {644+ if (event.requestContext) {645+ return Object.hasOwn(event.requestContext, 'elb')646+ }647+ return false648+}649+650+const isProxyEventV2 = (event: LambdaEvent): event is APIGatewayProxyEventV2 => {651+ // A V1 (REST API) event behind a custom domain base path mapping also carries a652+ // `rawPath`, so `rawPath` alone is not enough to identify a V2 event. Every V2653+ // (HTTP API / function URL) event has an `http` object on its request context.654+ return Object.hasOwn(event, 'rawPath') && Object.hasOwn(event.requestContext ?? {}, 'http')655+}656+657+const isLatticeEventV2 = (event: LambdaEvent): event is LatticeProxyEventV2 => {658+ if (event.requestContext) {659+ return Object.hasOwn(event.requestContext, 'serviceArn')660+ }661+ return false662+}663+664+/**665+ * Check if the given content type is binary.666+ * This is a default function and may be overwritten by the user via `isContentTypeBinary` option in handler().667+ * @param contentType The content type to check.668+ * @returns True if the content type is binary, false otherwise.669+ */670+export const defaultIsContentTypeBinary = (contentType: string): boolean => {671+ if (/^application\/vnd\.(?:apple\.installer|mozilla\.xul)\+xml\s*(?:;|$)/i.test(contentType)) {672+ return true673+ }674+675+ return !/^text\/(?:plain|html|css|javascript|csv)|(?:\/|\+)(?:json|xml)\s*(?:;|$)/i.test(676+ contentType677+ )678+}679+680+export const isContentEncodingBinary = (contentEncoding: string | null) => {681+ return !!contentEncoding && !/^identity$/i.test(contentEncoding)682+}added:adapters/aws-lambda/src/index.ts+14 added
1234567891011121314/** * @module * AWS Lambda Adapter for Hono. */
export { handle, streamHandle, defaultIsContentTypeBinary } from './handler'export { getConnInfo } from './conninfo'export type { APIGatewayProxyResult, LambdaEvent } from './handler'export type { ApiGatewayRequestContext, ApiGatewayRequestContextV2, ALBRequestContext, LambdaContext,} from './types'added:adapters/aws-lambda/src/types.ts+173 added
1+/* eslint-disable @typescript-eslint/no-explicit-any */2+3+export interface CognitoIdentity {4+ cognitoIdentityId: string5+ cognitoIdentityPoolId: string6+}7+8+export interface ClientContext {9+ client: ClientContextClient10+11+ Custom?: any12+ env: ClientContextEnv13+}14+15+export interface ClientContextClient {16+ installationId: string17+ appTitle: string18+ appVersionName: string19+ appVersionCode: string20+ appPackageName: string21+}22+23+export interface ClientContextEnv {24+ platformVersion: string25+ platform: string26+ make: string27+ model: string28+ locale: string29+}30+31+/**32+ * {@link Handler} context parameter.33+ * See {@link https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html AWS documentation}.34+ */35+export interface LambdaContext {36+ callbackWaitsForEmptyEventLoop: boolean37+ functionName: string38+ functionVersion: string39+ invokedFunctionArn: string40+ memoryLimitInMB: string41+ awsRequestId: string42+ logGroupName: string43+ logStreamName: string44+ identity?: CognitoIdentity | undefined45+ clientContext?: ClientContext | undefined46+47+ getRemainingTimeInMillis(): number48+}49+50+type Callback<TResult = any> = (error?: Error | string | null, result?: TResult) => void51+52+export type Handler<TEvent = any, TResult = any> = (53+ event: TEvent,54+ context: LambdaContext,55+ callback: Callback<TResult>56+) => void | Promise<TResult>57+58+interface ClientCert {59+ clientCertPem: string60+ subjectDN: string61+ issuerDN: string62+ serialNumber: string63+ validity: {64+ notBefore: string65+ notAfter: string66+ }67+}68+69+interface Identity {70+ accessKey?: string71+ accountId?: string72+ caller?: string73+ cognitoAuthenticationProvider?: string74+ cognitoAuthenticationType?: string75+ cognitoIdentityId?: string76+ cognitoIdentityPoolId?: string77+ principalOrgId?: string78+ sourceIp: string79+ user?: string80+ userAgent: string81+ userArn?: string82+ clientCert?: ClientCert83+}84+85+export interface ApiGatewayRequestContext {86+ accountId: string87+ apiId: string88+ authorizer: {89+ claims?: unknown90+ scopes?: unknown91+ }92+ domainName: string93+ domainPrefix: string94+ extendedRequestId: string95+ httpMethod: string96+ identity: Identity97+ path: string98+ protocol: string99+ requestId: string100+ requestTime: string101+ requestTimeEpoch: number102+ resourceId?: string103+ resourcePath: string104+ stage: string105+}106+107+interface Authorizer {108+ iam?: {109+ accessKey: string110+ accountId: string111+ callerId: string112+ cognitoIdentity: null113+ principalOrgId: null114+ userArn: string115+ userId: string116+ }117+ jwt?: {118+ claims: Record<string, string | number | boolean | string[]>119+ scopes: string[] | null120+ }121+ /**122+ * The `context` object returned by a Lambda (REQUEST) authorizer.123+ * It is `null` when the authorizer returns no context.124+ */125+ lambda?: Record<string, unknown> | null126+}127+128+export interface ApiGatewayRequestContextV2 {129+ accountId: string130+ apiId: string131+ authentication: null132+ authorizer: Authorizer133+ domainName: string134+ domainPrefix: string135+ http: {136+ method: string137+ path: string138+ protocol: string139+ sourceIp: string140+ userAgent: string141+ }142+ requestId: string143+ routeKey: string144+ stage: string145+ time: string146+ timeEpoch: number147+}148+149+export interface ALBRequestContext {150+ elb: {151+ targetGroupArn: string152+ }153+}154+155+export interface LatticeRequestContextV2 {156+ serviceNetworkArn: string157+ serviceArn: string158+ targetGroupArn: string159+ region: string160+ timeEpoch: string161+ identity: {162+ sourceVpcArn?: string163+ type?: string164+ principal?: string165+ principalOrgID?: string166+ sessionName?: string167+ x509IssuerOu?: string168+ x509SanDns?: string169+ x509SanNameCn?: string170+ x509SanUri?: string171+ x509SubjectCn?: string172+ }173+}added:adapters/aws-lambda/package.json+37 added
12345678910111213141516171819202122232425262728293031323334353637{ "name": "@hono/aws-lambda", "version": "1.0.0", "description": "AWS Lambda adapter for Hono", "type": "module", "types": "./dist/index.d.ts", "files": [ "dist" ], "exports": { ".": { "types": "./dist/index.d.ts", "default": "./dist/index.js" } }, "scripts": { "build": "rm -rf dist && vp pack && publint", "test": "tsc -p tsconfig.json && vp test --run" }, "license": "MIT", "repository": { "type": "git", "url": "git+https://github.com/honojs/hono.git", "directory": "adapters/aws-lambda" }, "homepage": "https://hono.dev", "author": "Yusuke Wada <yusuke@kamawada.com> (https://github.com/yusukebe)", "peerDependencies": { "hono": ">=4.13.9" }, "engines": { "node": ">=16.9.0" }, "devDependencies": { "hono": "workspace:*" }}added:adapters/aws-lambda/README.md+22 added
12345678910111213141516171819202122# @hono/aws-lambda
AWS Lambda adapter for [Hono](https://hono.dev).
```shnpm i @hono/aws-lambda```
## Migrating from `hono/aws-lambda`
The exports are the same. Change the import path:
```diff- import { handle } from 'hono/aws-lambda'+ import { handle } from '@hono/aws-lambda'```
`hono/aws-lambda` is deprecated and will be removed in Hono v5.
## License
MITadded:adapters/aws-lambda/tsconfig.json+16 added
12345678910111213141516{ "extends": "../../tsconfig.base.json", "compilerOptions": { "module": "ES2020", "rootDir": "./src/", "outDir": "./dist/", "types": [ "node", "vitest/globals" ], "noEmit": true }, "include": [ "src/**/*.ts" ]}added:adapters/aws-lambda/vite.config.ts+15 added
123456789101112131415import { defineConfig } from 'vite-plus'
export default defineConfig({ pack: { entry: ['src/**/*.ts', '!src/**/*.test.ts', '!src/**/*.d.ts'], tsconfig: 'tsconfig.json', unbundle: true, format: ['esm'], dts: true, outExtensions: () => ({ js: '.js', dts: '.d.ts' }), }, test: { globals: true, },})added:adapters/cloudflare-workers/src/conninfo.test.ts+19 added
12345678910111213141516171819import { Context } from 'hono'import { getConnInfo } from './conninfo'
describe('getConnInfo', () => { it('Should getConnInfo works', () => { const address = Math.random().toString() const req = new Request('http://localhost/', { headers: { 'cf-connecting-ip': address, }, }) const c = new Context(req)
const info = getConnInfo(c)
expect(info.remote.address).toBe(address) expect(info.remote.addressType).toBeUndefined() })})added:adapters/cloudflare-workers/src/conninfo.ts+7 added
1234567import type { GetConnInfo } from 'hono/conninfo'
export const getConnInfo: GetConnInfo = (c) => ({ remote: { address: c.req.header('cf-connecting-ip'), },})added:adapters/cloudflare-workers/src/index.ts+8 added
1+/**2+ * @module3+ * Cloudflare Workers Adapter for Hono.4+ */5+6+export { serveStatic } from './serve-static-module'7+export { upgradeWebSocket } from './websocket'8+export { getConnInfo } from './conninfo'added:adapters/cloudflare-workers/src/serve-static-module.ts+12 added
1+// For ES module mode2+import type { Env, MiddlewareHandler } from 'hono/types'3+import type { ServeStaticOptions } from './serve-static'4+import { serveStatic } from './serve-static'5+6+const module = <E extends Env = Env>(7+ options: Omit<ServeStaticOptions<E>, 'namespace'>8+): MiddlewareHandler => {9+ return serveStatic<E>(options)10+}11+12+export { module as serveStatic }added:adapters/cloudflare-workers/src/serve-static.test.ts+221 added
1+import type { Context } from 'hono'2+import { Hono } from 'hono'3+import type { Next } from 'hono/types'4+import { serveStatic } from './serve-static'5+6+// Mock7+const store: Record<string, string> = {8+ 'assets/static/plain.abcdef.txt': 'This is plain.txt',9+ 'assets/static/hono.abcdef.html': '<h1>Hono!</h1>',10+ 'assets/static/top/index.abcdef.html': '<h1>Top</h1>',11+ 'static-no-root/plain.abcdef.txt': 'That is plain.txt',12+ 'assets/static/options/foo.abcdef.txt': 'With options',13+ 'assets/.static/plain.abcdef.txt': 'In the dot',14+ 'assets/static/video/morning-routine.abcdef.m3u8': 'Good morning',15+ 'assets/static/video/morning-routine1.abcdef.ts': 'Good',16+ 'assets/static/video/introduction.abcdef.mp4': 'Let me introduce myself',17+ 'assets/static/download': 'download',18+}19+const manifest = JSON.stringify({20+ 'assets/static/plain.txt': 'assets/static/plain.abcdef.txt',21+ 'assets/static/hono.html': 'assets/static/hono.abcdef.html',22+ 'assets/static/top/index.html': 'assets/static/top/index.abcdef.html',23+ 'static-no-root/plain.txt': 'static-no-root/plain.abcdef.txt',24+ 'assets/.static/plain.txt': 'assets/.static/plain.abcdef.txt',25+ 'assets/static/download': 'assets/static/download',26+})27+28+Object.assign(global, { __STATIC_CONTENT_MANIFEST: manifest })29+Object.assign(global, {30+ __STATIC_CONTENT: {31+ get: (path: string) => {32+ return store[path]33+ },34+ },35+})36+37+describe('ServeStatic Middleware', () => {38+ const app = new Hono()39+ const onNotFound = vi.fn(() => {})40+ app.use('/static/*', serveStatic({ root: './assets', onNotFound, manifest }))41+ app.use('/static-no-root/*', serveStatic({ manifest }))42+ app.use(43+ '/dot-static/*',44+ serveStatic({45+ root: './assets',46+ rewriteRequestPath: (path) => path.replace(/^\/dot-static/, '/.static'),47+ manifest,48+ })49+ )50+51+ beforeEach(() => onNotFound.mockClear())52+53+ it('Should return plain.txt', async () => {54+ const res = await app.request('http://localhost/static/plain.txt')55+ expect(res.status).toBe(200)56+ expect(await res.text()).toBe('This is plain.txt')57+ expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')58+ expect(onNotFound).not.toHaveBeenCalled()59+ })60+61+ it('Should return hono.html', async () => {62+ const res = await app.request('http://localhost/static/hono.html')63+ expect(res.status).toBe(200)64+ expect(await res.text()).toBe('<h1>Hono!</h1>')65+ expect(res.headers.get('Content-Type')).toBe('text/html; charset=utf-8')66+ expect(onNotFound).not.toHaveBeenCalled()67+ })68+69+ it('Should return 404 response', async () => {70+ const res = await app.request('http://localhost/static/not-found.html')71+ expect(res.status).toBe(404)72+ expect(onNotFound).toHaveBeenCalledWith('assets/static/not-found.html', expect.anything())73+ })74+75+ it('Should return plan.txt', async () => {76+ const res = await app.request('http://localhost/static-no-root/plain.txt')77+ expect(res.status).toBe(200)78+ expect(await res.text()).toBe('That is plain.txt')79+ expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')80+ })81+82+ // Serve static on Cloudflare Workers cannot determine whether the target path is a directory or not83+ it.skip('Should return index.html', async () => {84+ const res = await app.request('http://localhost/static/top')85+ expect(res.status).toBe(200)86+ expect(await res.text()).toBe('<h1>Top</h1>')87+ expect(res.headers.get('Content-Type')).toBe('text/html; charset=utf-8')88+ })89+90+ it('Should return plain.txt with a rewriteRequestPath option', async () => {91+ const res = await app.request('http://localhost/dot-static/plain.txt')92+ expect(res.status).toBe(200)93+ expect(await res.text()).toBe('In the dot')94+ expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')95+ })96+})97+98+describe('With options', () => {99+ const manifest = {100+ 'assets/static/options/foo.txt': 'assets/static/options/foo.abcdef.txt',101+ }102+103+ const app = new Hono()104+ app.use('/static/*', serveStatic({ root: './assets', manifest: manifest }))105+106+ it('Should return foo.txt', async () => {107+ const res = await app.request('http://localhost/static/options/foo.txt')108+ expect(res.status).toBe(200)109+ expect(await res.text()).toBe('With options')110+ expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')111+ })112+})113+114+describe('With `file` options', () => {115+ const app = new Hono()116+ app.get('/foo/*', serveStatic({ path: './assets/static/hono.html', manifest }))117+ app.get('/bar/*', serveStatic({ path: './static/hono.html', root: './assets', manifest }))118+119+ it('Should return hono.html', async () => {120+ const res = await app.request('http://localhost/foo/fallback')121+ expect(res.status).toBe(200)122+ expect(await res.text()).toBe('<h1>Hono!</h1>')123+ })124+125+ it('Should return hono.html - with `root` option', async () => {126+ const res = await app.request('http://localhost/bar/fallback')127+ expect(res.status).toBe(200)128+ expect(await res.text()).toBe('<h1>Hono!</h1>')129+ })130+})131+132+describe('With `mimes` options', () => {133+ const mimes = {134+ m3u8: 'application/vnd.apple.mpegurl',135+ ts: 'video/mp2t',136+ }137+ const manifest = {138+ 'assets/static/video/morning-routine.m3u8': 'assets/static/video/morning-routine.abcdef.m3u8',139+ 'assets/static/video/morning-routine1.ts': 'assets/static/video/morning-routine1.abcdef.ts',140+ 'assets/static/video/introduction.mp4': 'assets/static/video/introduction.abcdef.mp4',141+ }142+143+ const app = new Hono()144+ app.use('/static/*', serveStatic({ root: './assets', mimes, manifest }))145+146+ it('Should return content-type of m3u8', async () => {147+ const res = await app.request('http://localhost/static/video/morning-routine.m3u8')148+ expect(res.status).toBe(200)149+ expect(res.headers.get('Content-Type')).toBe('application/vnd.apple.mpegurl')150+ })151+ it('Should return content-type of ts', async () => {152+ const res = await app.request('http://localhost/static/video/morning-routine1.ts')153+ expect(res.status).toBe(200)154+ expect(res.headers.get('Content-Type')).toBe('video/mp2t')155+ })156+ it('Should return content-type of default on Hono', async () => {157+ const res = await app.request('http://localhost/static/video/introduction.mp4')158+ expect(res.status).toBe(200)159+ expect(res.headers.get('Content-Type')).toBe('video/mp4')160+ })161+})162+163+describe('With middleware', () => {164+ const app = new Hono()165+ const md1 = async (c: Context, next: Next) => {166+ await next()167+ c.res.headers.append('x-foo', 'bar')168+ }169+ const md2 = async (c: Context, next: Next) => {170+ await next()171+ c.res.headers.append('x-foo2', 'bar2')172+ }173+174+ app.use('/static/*', md1)175+ app.use('/static/*', md2)176+ app.use('/static/*', serveStatic({ root: './assets', manifest }))177+ app.get('/static/foo', (c) => {178+ return c.text('bar')179+ })180+181+ it('Should return plain.txt with correct headers', async () => {182+ const res = await app.request('http://localhost/static/plain.txt')183+ expect(res.status).toBe(200)184+ expect(await res.text()).toBe('This is plain.txt')185+ expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')186+ expect(res.headers.get('x-foo')).toBe('bar')187+ expect(res.headers.get('x-foo2')).toBe('bar2')188+ })189+190+ it('Should return 200 Response', async () => {191+ const res = await app.request('http://localhost/static/foo')192+ expect(res.status).toBe(200)193+ expect(await res.text()).toBe('bar')194+ })195+196+ it('Should handle a file without an extension', async () => {197+ const res = await app.request('http://localhost/static/download')198+ expect(res.status).toBe(200)199+ })200+})201+202+describe('Types of middleware', () => {203+ it('Should pass env type from generics of serveStatic', async () => {204+ type Env = {205+ Bindings: {206+ HOGE: string207+ }208+ }209+ const app = new Hono<Env>()210+ app.use(211+ '/static/*',212+ serveStatic<Env>({213+ root: './assets',214+ onNotFound: (_, c) => {215+ expectTypeOf(c.env).toEqualTypeOf<Env['Bindings']>()216+ },217+ manifest,218+ })219+ )220+ })221+})added:adapters/cloudflare-workers/src/serve-static.ts+42 added
1+import { serveStatic as baseServeStatic } from 'hono/serve-static'2+import type { ServeStaticOptions as BaseServeStaticOptions } from 'hono/serve-static'3+import type { Env, MiddlewareHandler } from 'hono/types'4+import { getContentFromKVAsset } from './utils'5+6+export type ServeStaticOptions<E extends Env = Env> = BaseServeStaticOptions<E> & {7+ // namespace is KVNamespace8+ namespace?: unknown9+ manifest?: object | string10+}11+12+/**13+ * @deprecated14+ * `serveStatic` in the Cloudflare Workers adapter is deprecated.15+ * You can serve static files directly using Cloudflare Static Assets.16+ * @see https://developers.cloudflare.com/workers/static-assets/17+ * Cloudflare Static Assets is currently in open beta. If this doesn't work for you,18+ * please consider using Cloudflare Pages. You can start to create the Cloudflare Pages19+ * application with the `npm create hono@latest` command.20+ */21+export const serveStatic = <E extends Env = Env>(22+ options: ServeStaticOptions<E> = {}23+): MiddlewareHandler => {24+ return async function serveStatic(c, next) {25+ const getContent = async (path: string) => {26+ return getContentFromKVAsset(path, {27+ manifest: options.manifest,28+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment29+ // @ts-ignore30+ namespace: options.namespace31+ ? options.namespace32+ : c.env33+ ? c.env.__STATIC_CONTENT34+ : undefined,35+ })36+ }37+ return baseServeStatic({38+ ...options,39+ getContent,40+ })(c, next)41+ }42+}added:adapters/cloudflare-workers/src/utils.test.ts+33 added
1+import { getContentFromKVAsset } from './utils'2+3+// Mock4+const store: { [key: string]: string } = {5+ 'index.abcdef.html': 'This is index',6+ 'assets/static/plain.abcdef.txt': 'Asset text',7+}8+const manifest = JSON.stringify({9+ 'index.html': 'index.abcdef.html',10+ 'assets/static/plain.txt': 'assets/static/plain.abcdef.txt',11+})12+13+Object.assign(global, { __STATIC_CONTENT_MANIFEST: manifest })14+Object.assign(global, {15+ __STATIC_CONTENT: {16+ get: (path: string) => {17+ return store[path]18+ },19+ },20+})21+22+describe('Utils for Cloudflare Workers', () => {23+ it('getContentFromKVAsset', async () => {24+ let content = await getContentFromKVAsset('not-found.txt')25+ expect(content).toBeFalsy()26+ content = await getContentFromKVAsset('index.html')27+ expect(content).toBeTruthy()28+ expect(content).toBe('This is index')29+ content = await getContentFromKVAsset('assets/static/plain.txt')30+ expect(content).toBeTruthy()31+ expect(content).toBe('Asset text')32+ })33+})added:adapters/cloudflare-workers/src/utils.ts+50 added
1+// __STATIC_CONTENT is KVNamespace2+declare const __STATIC_CONTENT: unknown3+declare const __STATIC_CONTENT_MANIFEST: string4+5+export type KVAssetOptions = {6+ manifest?: object | string7+ // namespace is KVNamespace8+ namespace?: unknown9+}10+11+export const getContentFromKVAsset = async (12+ path: string,13+ options?: KVAssetOptions14+): Promise<ReadableStream | null> => {15+ let ASSET_MANIFEST: Record<string, string>16+17+ if (options && options.manifest) {18+ if (typeof options.manifest === 'string') {19+ ASSET_MANIFEST = JSON.parse(options.manifest)20+ } else {21+ ASSET_MANIFEST = options.manifest as Record<string, string>22+ }23+ } else {24+ if (typeof __STATIC_CONTENT_MANIFEST === 'string') {25+ ASSET_MANIFEST = JSON.parse(__STATIC_CONTENT_MANIFEST)26+ } else {27+ ASSET_MANIFEST = __STATIC_CONTENT_MANIFEST28+ }29+ }30+31+ // ASSET_NAMESPACE is KVNamespace32+ let ASSET_NAMESPACE: unknown33+ if (options && options.namespace) {34+ ASSET_NAMESPACE = options.namespace35+ } else {36+ ASSET_NAMESPACE = __STATIC_CONTENT37+ }38+39+ const key = ASSET_MANIFEST[path]40+ if (!key) {41+ return null42+ }43+44+ // @ts-expect-error ASSET_NAMESPACE is not typed45+ const content = await ASSET_NAMESPACE.get(key, { type: 'stream' })46+ if (!content) {47+ return null48+ }49+ return content as unknown as ReadableStream50+}added:adapters/cloudflare-workers/src/websocket.test.ts+161 added
1+import { Context, Hono } from 'hono'2+import { upgradeWebSocket } from '.'3+4+describe('upgradeWebSocket middleware', () => {5+ const server = new EventTarget()6+7+ // @ts-expect-error Cloudflare API8+ globalThis.WebSocketPair = class {9+ 0: WebSocket // client10+ 1: WebSocket // server11+ constructor() {12+ this[0] = {} as WebSocket13+ this[1] = server as WebSocket14+ }15+ }16+17+ const app = new Hono()18+19+ const wsPromise = new Promise((resolve) =>20+ app.get(21+ '/ws',22+ upgradeWebSocket(() => ({23+ onMessage(evt, ws) {24+ resolve([evt.data, ws.readyState || 1])25+ },26+ }))27+ )28+ )29+ it('Should receive message and readyState is valid', async () => {30+ const sendingData = Math.random().toString()31+ await app.request('/ws', {32+ headers: {33+ Upgrade: 'websocket',34+ },35+ })36+ server.dispatchEvent(37+ new MessageEvent('message', {38+ data: sendingData,39+ })40+ )41+42+ expect([sendingData, 1]).toStrictEqual(await wsPromise)43+ })44+ it('Should call next() when header does not have upgrade', async () => {45+ const next = vi.fn()46+ await upgradeWebSocket(() => ({}))(47+ new Context(48+ new Request('http://localhost', {49+ headers: {50+ Upgrade: 'example',51+ },52+ })53+ ),54+ next55+ )56+ expect(next).toHaveBeenCalled()57+ })58+59+ const closePromise = new Promise((resolve) =>60+ app.get(61+ '/ws-close',62+ upgradeWebSocket(() => ({63+ onClose(evt, ws) {64+ resolve(true)65+ },66+ }))67+ )68+ )69+70+ it('Should call onClose when close event fires', async () => {71+ await app.request('/ws-close', {72+ headers: {73+ Upgrade: 'websocket',74+ },75+ })76+77+ server.dispatchEvent(new Event('close'))78+79+ expect(await closePromise).toBe(true)80+ })81+82+ const error = new Promise((resolve) => {83+ app.get(84+ '/ws-error',85+ upgradeWebSocket(() => ({86+ onError(evt, ws) {87+ resolve(true)88+ },89+ }))90+ )91+ })92+93+ it('Should call onError when error event fires', async () => {94+ await app.request('/ws-error', {95+ headers: {96+ Upgrade: 'websocket',97+ },98+ })99+100+ server.dispatchEvent(new Event('error'))101+ expect(await error).toBe(true)102+ })103+104+ const sendWsRef: Promise<any> = new Promise((resolve) =>105+ app.get(106+ '/ws-send',107+ upgradeWebSocket(() => ({108+ onMessage(evt, ws) {109+ resolve(ws)110+ },111+ }))112+ )113+ )114+115+ it('Should call server.send when ws.send is called', async () => {116+ // @ts-expect-error adding a mock method for the test117+ server.send = vi.fn()118+119+ await app.request('/ws-send', {120+ headers: {121+ Upgrade: 'websocket',122+ },123+ })124+ server.dispatchEvent(new MessageEvent('message', { data: 'trigger' }))125+126+ const ws = await sendWsRef127+ ws.send('hello')128+129+ // @ts-expect-error mock method130+ expect(server.send).toHaveBeenCalledWith('hello')131+ })132+133+ const closeWsRef: Promise<any> = new Promise((resolve) =>134+ app.get(135+ '/ws-close-call',136+ upgradeWebSocket(() => ({137+ onMessage(evt, ws) {138+ resolve(ws)139+ },140+ }))141+ )142+ )143+144+ it('Should call server.close when ws.close is called', async () => {145+ // @ts-expect-error adding a mock method for the test146+ server.close = vi.fn()147+148+ await app.request('/ws-close-call', {149+ headers: {150+ Upgrade: 'websocket',151+ },152+ })153+ server.dispatchEvent(new MessageEvent('message', { data: 'trigger' }))154+155+ const ws = await closeWsRef156+ ws.close(1000, 'done')157+158+ // @ts-expect-error mock method159+ expect(server.close).toHaveBeenCalledWith(1000, 'done')160+ })161+})added:adapters/cloudflare-workers/src/websocket.ts+53 added
1+import { WSContext, defineWebSocketHelper } from 'hono/ws'2+import type { UpgradeWebSocket, WSEvents, WSReadyState } from 'hono/ws'3+4+// Based on https://github.com/honojs/hono/issues/1153#issuecomment-17673213325+export const upgradeWebSocket: UpgradeWebSocket<6+ WebSocket,7+ // eslint-disable-next-line @typescript-eslint/no-explicit-any8+ any,9+ Omit<WSEvents<WebSocket>, 'onOpen'>10+> = defineWebSocketHelper(async (c, events) => {11+ const upgradeHeader = c.req.header('Upgrade')12+ if (upgradeHeader !== 'websocket') {13+ return14+ }15+16+ // @ts-expect-error WebSocketPair is not typed17+ const webSocketPair = new WebSocketPair()18+ const client: WebSocket = webSocketPair[0]19+ const server: WebSocket = webSocketPair[1]20+21+ const wsContext = new WSContext<WebSocket>({22+ close: (code, reason) => server.close(code, reason),23+ get protocol() {24+ return server.protocol25+ },26+ raw: server,27+ get readyState() {28+ return server.readyState as WSReadyState29+ },30+ url: server.url ? new URL(server.url) : null,31+ send: (source) => server.send(source),32+ })33+34+ // note: cloudflare workers doesn't support 'open' event35+36+ if (events.onClose) {37+ server.addEventListener('close', (evt: CloseEvent) => events.onClose?.(evt, wsContext))38+ }39+ if (events.onMessage) {40+ server.addEventListener('message', (evt: MessageEvent) => events.onMessage?.(evt, wsContext))41+ }42+ if (events.onError) {43+ server.addEventListener('error', (evt: Event) => events.onError?.(evt, wsContext))44+ }45+46+ // @ts-expect-error - server.accept is not typed47+ server.accept?.()48+ return new Response(null, {49+ status: 101,50+ // @ts-expect-error - webSocket is not typed51+ webSocket: client,52+ })53+})added:adapters/cloudflare-workers/package.json+37 added
1+{2+ "name": "@hono/cloudflare-workers",3+ "version": "1.0.0",4+ "description": "Cloudflare Workers adapter for Hono",5+ "type": "module",6+ "types": "./dist/index.d.ts",7+ "files": [8+ "dist"9+ ],10+ "exports": {11+ ".": {12+ "types": "./dist/index.d.ts",13+ "default": "./dist/index.js"14+ }15+ },16+ "scripts": {17+ "build": "rm -rf dist && vp pack && publint",18+ "test": "tsc -p tsconfig.json && vp test --run"19+ },20+ "license": "MIT",21+ "repository": {22+ "type": "git",23+ "url": "git+https://github.com/honojs/hono.git",24+ "directory": "adapters/cloudflare-workers"25+ },26+ "homepage": "https://hono.dev",27+ "author": "Yusuke Wada <yusuke@kamawada.com> (https://github.com/yusukebe)",28+ "peerDependencies": {29+ "hono": ">=4.13.9"30+ },31+ "engines": {32+ "node": ">=16.9.0"33+ },34+ "devDependencies": {35+ "hono": "workspace:*"36+ }37+}added:adapters/cloudflare-workers/README.md+22 added
1+# @hono/cloudflare-workers2+3+Cloudflare Workers adapter for [Hono](https://hono.dev).4+5+```sh6+npm i @hono/cloudflare-workers7+```8+9+## Migrating from `hono/cloudflare-workers`10+11+The exports are the same. Change the import path:12+13+```diff14+- import { serveStatic } from 'hono/cloudflare-workers'15++ import { serveStatic } from '@hono/cloudflare-workers'16+```17+18+`hono/cloudflare-workers` is deprecated and will be removed in Hono v5.19+20+## License21+22+MITadded:adapters/cloudflare-workers/tsconfig.json+16 added
1+{2+ "extends": "../../tsconfig.base.json",3+ "compilerOptions": {4+ "module": "ES2020",5+ "rootDir": "./src/",6+ "outDir": "./dist/",7+ "types": [8+ "node",9+ "vitest/globals"10+ ],11+ "noEmit": true12+ },13+ "include": [14+ "src/**/*.ts"15+ ]16+}added:adapters/cloudflare-workers/vite.config.ts+15 added
1+import { defineConfig } from 'vite-plus'2+3+export default defineConfig({4+ pack: {5+ entry: ['src/**/*.ts', '!src/**/*.test.ts', '!src/**/*.d.ts'],6+ tsconfig: 'tsconfig.json',7+ unbundle: true,8+ format: ['esm'],9+ dts: true,10+ outExtensions: () => ({ js: '.js', dts: '.d.ts' }),11+ },12+ test: {13+ globals: true,14+ },15+})added:adapters/deno/src/conninfo.test.ts+25 added
1+import { Context } from 'hono'2+import { getConnInfo } from './conninfo'3+4+describe('getConnInfo', () => {5+ it('Should info is valid', () => {6+ const transport = 'tcp'7+ const address = Math.random().toString()8+ const port = Math.floor(Math.random() * (65535 + 1))9+ const c = new Context(new Request('http://localhost/'), {10+ env: {11+ remoteAddr: {12+ transport,13+ hostname: address,14+ port,15+ },16+ },17+ })18+ const info = getConnInfo(c)19+20+ expect(info.remote.port).toBe(port)21+ expect(info.remote.address).toBe(address)22+ expect(info.remote.addressType).toBeUndefined()23+ expect(info.remote.transport).toBe(transport)24+ })25+})added:adapters/deno/src/conninfo.ts+17 added
1+import type { GetConnInfo } from 'hono/conninfo'2+3+/**4+ * Get conninfo with Deno5+ * @param c Context6+ * @returns ConnInfo7+ */8+export const getConnInfo: GetConnInfo = (c) => {9+ const { remoteAddr } = c.env10+ return {11+ remote: {12+ address: remoteAddr.hostname,13+ port: remoteAddr.port,14+ transport: remoteAddr.transport,15+ },16+ }17+}added:adapters/deno/src/deno.d.ts+79 added
1+declare namespace Deno {2+ interface FileHandleLike {3+ readonly readable: ReadableStream<Uint8Array>4+ }5+6+ /**7+ * Open the file using the specified path.8+ *9+ * @param path The path to open the file.10+ * @returns FileHandle object.11+ */12+ export function open(path: string): Promise<FileHandleLike>13+14+ interface StatsLike {15+ isDirectory: boolean16+ }17+18+ /**19+ * Get stats with the specified path.20+ *21+ * @param path The path to get stats.22+ * @returns Stats object.23+ */24+ export function lstatSync(path: string): StatsLike25+26+ /**27+ * Creates a new directory with the specified path.28+ *29+ * @param path The path to create a directory.30+ * @param options Options for creating a directory.31+ * @returns A promise that resolves when the directory is created.32+ */33+ export function mkdir(path: string, options?: { recursive?: boolean }): Promise<void>34+35+ /**36+ * Write a new file, with the specified path and data.37+ *38+ * @param path The path to the file to write.39+ * @param data The data to write into the file.40+ * @returns A promise that resolves when the file is written.41+ */42+ export function writeFile(path: string, data: Uint8Array): Promise<void>43+44+ /**45+ * Errors of Deno46+ */47+ export const errors: Record<string, Function>48+49+ export function upgradeWebSocket(50+ req: Request,51+ options: UpgradeWebSocketOptions52+ ): {53+ response: Response54+ socket: WebSocket55+ }56+57+ /**58+ * Options of `upgradeWebSocket`59+ */60+ export interface UpgradeWebSocketOptions {61+ /**62+ * Sets the `.protocol` property on the client-side web socket to the63+ * value provided here, which should be one of the strings specified in the64+ * `protocols` parameter when requesting the web socket. This is intended65+ * for clients and servers to specify sub-protocols to use to communicate to66+ * each other.67+ */68+ protocol?: string69+ /**70+ * If the client does not respond to this frame with a71+ * `pong` within the timeout specified, the connection is deemed72+ * unhealthy and is closed. The `close` and `error` events will be emitted.73+ *74+ * The unit is seconds, with a default of 30.75+ * Set to `0` to disable timeouts.76+ */77+ idleTimeout?: number78+ }79+}added:adapters/deno/src/index.ts+9 added
1+/**2+ * @module3+ * Deno Adapter for Hono.4+ */5+6+export { serveStatic } from './serve-static'7+export { toSSG, denoFileSystemModule } from './ssg'8+export { upgradeWebSocket } from './websocket'9+export { getConnInfo } from './conninfo'added:adapters/deno/src/serve-static.ts+42 added
1+import { join } from 'node:path'2+import type { ServeStaticOptions } from 'hono/serve-static'3+import { serveStatic as baseServeStatic } from 'hono/serve-static'4+import type { Env, MiddlewareHandler } from 'hono/types'5+6+const { open, lstatSync, errors } = Deno7+8+export const serveStatic = <E extends Env = Env>(9+ options: ServeStaticOptions<E> = {}10+): MiddlewareHandler => {11+ return async function serveStatic(c, next) {12+ const getContent = async (path: string) => {13+ try {14+ if (isDir(path)) {15+ return null16+ }17+18+ const file = await open(path)19+ return file.readable20+ } catch (e) {21+ if (!(e instanceof errors.NotFound)) {22+ console.warn(`${e}`)23+ }24+ return null25+ }26+ }27+ const isDir = (path: string) => {28+ let isDir29+ try {30+ const stat = lstatSync(path)31+ isDir = stat.isDirectory32+ } catch {}33+ return isDir34+ }35+ return baseServeStatic({36+ ...options,37+ getContent,38+ join,39+ isDir,40+ })(c, next)41+ }42+}added:adapters/deno/src/ssg.ts+27 added
1+import { toSSG as baseToSSG } from 'hono/ssg'2+import type { FileSystemModule, ToSSGAdaptorInterface } from 'hono/ssg'3+4+/**5+ * @experimental6+ * `denoFileSystemModule` is an experimental feature.7+ * The API might be changed.8+ */9+export const denoFileSystemModule: FileSystemModule = {10+ writeFile: async (path, data) => {11+ const uint8Data =12+ typeof data === 'string' ? new TextEncoder().encode(data) : new Uint8Array(data)13+ await Deno.writeFile(path, uint8Data)14+ },15+ mkdir: async (path, options) => {16+ return Deno.mkdir(path, { recursive: options?.recursive ?? false })17+ },18+}19+20+/**21+ * @experimental22+ * `toSSG` is an experimental feature.23+ * The API might be changed.24+ */25+export const toSSG: ToSSGAdaptorInterface = async (app, options) => {26+ return baseToSSG(app, denoFileSystemModule, options)27+}added:adapters/deno/src/websocket.test.ts+161 added
1+import { Context, Hono } from 'hono'2+import { upgradeWebSocket } from './websocket'3+4+globalThis.Deno = {} as typeof Deno5+6+describe('WebSockets', () => {7+ let app: Hono8+ beforeEach(() => {9+ app = new Hono()10+ })11+12+ it('Should receive data is valid', async () => {13+ const messagePromise = new Promise((resolve) =>14+ app.get(15+ '/ws',16+ upgradeWebSocket(() => ({17+ onMessage: (evt) => resolve(evt.data),18+ }))19+ )20+ )21+ const socket = new EventTarget() as WebSocket22+ Deno.upgradeWebSocket = () => {23+ return {24+ response: new Response(),25+ socket,26+ }27+ }28+ await app.request('/ws', {29+ headers: {30+ upgrade: 'websocket',31+ },32+ })33+ const data = Math.random().toString()34+ socket.onmessage &&35+ socket.onmessage(36+ new MessageEvent('message', {37+ data,38+ })39+ )40+ expect(await messagePromise).toBe(data)41+ })42+43+ 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+79+ it('Should pass the first Sec-WebSocket-Protocol value as the protocol option', async () => {80+ app.get(81+ '/ws',82+ upgradeWebSocket(() => ({}))83+ )84+ const socket = new EventTarget() as WebSocket85+ let passedOptions: Deno.UpgradeWebSocketOptions | undefined86+ Deno.upgradeWebSocket = (_req, options) => {87+ passedOptions = options88+ return {89+ response: new Response(),90+ socket,91+ }92+ }93+ await app.request('/ws', {94+ headers: {95+ upgrade: 'websocket',96+ 'sec-websocket-protocol': 'rivet, rivet_target.actor, rivet_actor.19c4f9038947cdcb',97+ },98+ })99+ expect(passedOptions?.protocol).toBe('rivet')100+ })101+102+ it('Should not set the protocol option when Sec-WebSocket-Protocol is absent', async () => {103+ app.get(104+ '/ws',105+ upgradeWebSocket(() => ({}))106+ )107+ const socket = new EventTarget() as WebSocket108+ let passedOptions: Deno.UpgradeWebSocketOptions | undefined109+ Deno.upgradeWebSocket = (_req, options) => {110+ passedOptions = options111+ return {112+ response: new Response(),113+ socket,114+ }115+ }116+ await app.request('/ws', {117+ headers: {118+ upgrade: 'websocket',119+ },120+ })121+ expect(passedOptions?.protocol).toBeUndefined()122+ })123+124+ it('Should let an explicit protocol option take precedence over the request header', async () => {125+ app.get(126+ '/ws',127+ upgradeWebSocket(() => ({}), { protocol: 'user-chosen' })128+ )129+ const socket = new EventTarget() as WebSocket130+ let passedOptions: Deno.UpgradeWebSocketOptions | undefined131+ Deno.upgradeWebSocket = (_req, options) => {132+ passedOptions = options133+ return {134+ response: new Response(),135+ socket,136+ }137+ }138+ await app.request('/ws', {139+ headers: {140+ upgrade: 'websocket',141+ 'sec-websocket-protocol': 'header-value',142+ },143+ })144+ expect(passedOptions?.protocol).toBe('user-chosen')145+ })146+147+ it('Should call next() when header does not have upgrade', async () => {148+ const next = vi.fn()149+ await upgradeWebSocket(() => ({}))(150+ new Context(151+ new Request('http://localhost', {152+ headers: {153+ Upgrade: 'example',154+ },155+ })156+ ),157+ next158+ )159+ expect(next).toBeCalled()160+ })161+})added:adapters/deno/src/websocket.ts+38 added
1+import type { UpgradeWebSocket, WSReadyState } from 'hono/ws'2+import { WSContext, defineWebSocketHelper } from 'hono/ws'3+4+export const upgradeWebSocket: UpgradeWebSocket<WebSocket, Deno.UpgradeWebSocketOptions> =5+ defineWebSocketHelper(async (c, events, options) => {6+ if (c.req.header('upgrade') !== 'websocket') {7+ return8+ }9+10+ // Echo the negotiated subprotocol back to the client. Browsers (e.g. Chrome)11+ // reject the connection when a subprotocol was requested but the response is12+ // missing the `Sec-WebSocket-Protocol` header.13+ const subprotocol = c.req.header('sec-websocket-protocol')?.split(',')[0]?.trim()14+15+ const { response, socket } = Deno.upgradeWebSocket(c.req.raw, {16+ ...(subprotocol ? { protocol: subprotocol } : {}),17+ ...options,18+ })19+20+ const wsContext: WSContext<WebSocket> = new WSContext({21+ close: (code, reason) => socket.close(code, reason),22+ get protocol() {23+ return socket.protocol24+ },25+ raw: socket,26+ get readyState() {27+ return socket.readyState as WSReadyState28+ },29+ url: socket.url ? new URL(socket.url) : null,30+ send: (source) => socket.send(source),31+ })32+ socket.onopen = (evt) => events.onOpen?.(evt, wsContext)33+ socket.onmessage = (evt) => events.onMessage?.(evt, wsContext)34+ socket.onclose = (evt) => events.onClose?.(evt, wsContext)35+ socket.onerror = (evt) => events.onError?.(evt, wsContext)36+37+ return response38+ })added:adapters/deno/package.json+37 added
1+{2+ "name": "@hono/deno",3+ "version": "1.0.0",4+ "description": "Deno adapter for Hono",5+ "type": "module",6+ "types": "./dist/index.d.ts",7+ "files": [8+ "dist"9+ ],10+ "exports": {11+ ".": {12+ "types": "./dist/index.d.ts",13+ "default": "./dist/index.js"14+ }15+ },16+ "scripts": {17+ "build": "rm -rf dist && vp pack && publint",18+ "test": "tsc -p tsconfig.json && vp test --run"19+ },20+ "license": "MIT",21+ "repository": {22+ "type": "git",23+ "url": "git+https://github.com/honojs/hono.git",24+ "directory": "adapters/deno"25+ },26+ "homepage": "https://hono.dev",27+ "author": "Yusuke Wada <yusuke@kamawada.com> (https://github.com/yusukebe)",28+ "peerDependencies": {29+ "hono": ">=4.13.9"30+ },31+ "engines": {32+ "node": ">=16.9.0"33+ },34+ "devDependencies": {35+ "hono": "workspace:*"36+ }37+}added:adapters/deno/README.md+22 added
1+# @hono/deno2+3+Deno adapter for [Hono](https://hono.dev).4+5+```sh6+deno add npm:@hono/deno7+```8+9+## Migrating from `hono/deno`10+11+The exports are the same. Change the import path:12+13+```diff14+- import { serveStatic } from 'hono/deno'15++ import { serveStatic } from '@hono/deno'16+```17+18+`hono/deno` is deprecated and will be removed in Hono v5.19+20+## License21+22+MITadded:adapters/deno/tsconfig.json+16 added
1+{2+ "extends": "../../tsconfig.base.json",3+ "compilerOptions": {4+ "module": "ES2020",5+ "rootDir": "./src/",6+ "outDir": "./dist/",7+ "types": [8+ "node",9+ "vitest/globals"10+ ],11+ "noEmit": true12+ },13+ "include": [14+ "src/**/*.ts"15+ ]16+}added:adapters/deno/vite.config.ts+15 added
1+import { defineConfig } from 'vite-plus'2+3+export default defineConfig({4+ pack: {5+ entry: ['src/**/*.ts', '!src/**/*.test.ts', '!src/**/*.d.ts'],6+ tsconfig: 'tsconfig.json',7+ unbundle: true,8+ format: ['esm'],9+ dts: true,10+ outExtensions: () => ({ js: '.js', dts: '.d.ts' }),11+ },12+ test: {13+ globals: true,14+ },15+})added:adapters/lambda-edge/src/conninfo.test.ts+27 added
1+import { Context } from 'hono'2+import { getConnInfo } from './conninfo'3+import type { CloudFrontEdgeEvent } from './handler'4+5+describe('getConnInfo', () => {6+ it('Should info is valid', () => {7+ const clientIp = Math.random().toString()8+ const env = {9+ event: {10+ Records: [11+ {12+ cf: {13+ request: {14+ clientIp,15+ },16+ },17+ },18+ ],19+ } as CloudFrontEdgeEvent,20+ }21+22+ const c = new Context(new Request('http://localhost/'), { env })23+ const info = getConnInfo(c)24+25+ expect(info.remote.address).toBe(clientIp)26+ })27+})added:adapters/lambda-edge/src/conninfo.ts+15 added
1+import type { Context } from 'hono'2+import type { GetConnInfo } from 'hono/conninfo'3+import type { CloudFrontEdgeEvent } from './handler'4+5+type Env = {6+ Bindings: {7+ event: CloudFrontEdgeEvent8+ }9+}10+11+export const getConnInfo: GetConnInfo = (c: Context<Env>) => ({12+ remote: {13+ address: c.env.event.Records[0].cf.request.clientIp,14+ },15+})added:adapters/lambda-edge/src/handler.test.ts+450 added
1+import { Hono } from 'hono'2+import { bodyLimit } from 'hono/body-limit'3+import { setCookie } from 'hono/cookie'4+import { decodeBase64, encodeBase64 } from 'hono/utils/encode'5+import { describe } from 'vitest'6+import type { Callback, CloudFrontEdgeEvent, CloudFrontRequest } from './handler'7+import { createBody, handle, isContentTypeBinary } from './handler'8+9+describe('isContentTypeBinary', () => {10+ it.each([11+ ['image/png', true],12+ ['font/woff2', true],13+ ['image/svg+xml', false],14+ ['image/svg+xml; charset=UTF-8', false],15+ ['text/plain', false],16+ ['text/plain; charset=UTF-8', false],17+ ['text/css', false],18+ ['text/javascript', false],19+ ['application/json', false],20+ ['application/ld+json', false],21+ ['application/json', false],22+ ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', true],23+ ['application/msword', true],24+ ['application/epub+zip', true],25+ ['application/ld+json', false],26+ ['application/vnd.oasis.opendocument.text', true],27+ ['application/vnd.apple.installer+xml', true],28+ ['application/vnd.apple.installer+xml; charset=UTF-8', true],29+ ['application/vnd.mozilla.xul+xml', true],30+ ['APPLICATION/VND.APPLE.INSTALLER+XML', true],31+ ['APPLICATION/JSON', false],32+ ['TEXT/PLAIN', false],33+ ])('Should determine whether %s it is binary', (mimeType: string, expected: boolean) => {34+ expect(isContentTypeBinary(mimeType)).toBe(expected)35+ })36+})37+38+describe('createBody', () => {39+ it('Should the request be a GET or HEAD, the Request must not include a Body', () => {40+ const encoder = new TextEncoder()41+ const data = encoder.encode('test')42+ const body = {43+ action: 'read-only',44+ data: encodeBase64(data.buffer),45+ encoding: 'base64',46+ inputTruncated: false,47+ }48+49+ expect(createBody('GET', body)).toEqual(undefined)50+ expect(createBody('GET', body)).not.toEqual(data)51+ expect(createBody('HEAD', body)).toEqual(undefined)52+ expect(createBody('HEAD', body)).not.toEqual(data)53+ expect(createBody('POST', body)).toEqual(data)54+ expect(createBody('POST', body)).not.toEqual(undefined)55+ })56+})57+58+describe('handle', () => {59+ const cloudFrontEdgeEvent: CloudFrontEdgeEvent = {60+ Records: [61+ {62+ cf: {63+ config: {64+ distributionDomainName: 'd111111abcdef8.cloudfront.net',65+ distributionId: 'EDFDVBD6EXAMPLE',66+ eventType: 'viewer-request',67+ requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',68+ },69+ request: {70+ clientIp: '1.2.3.4',71+ headers: {72+ host: [73+ {74+ key: 'Host',75+ value: 'hono.dev',76+ },77+ ],78+ accept: [79+ {80+ key: 'accept',81+ value: '*/*',82+ },83+ ],84+ },85+ method: 'GET',86+ querystring: '',87+ uri: '/test-path',88+ },89+ },90+ },91+ ],92+ }93+94+ it('Should support alternate domain names', async () => {95+ const app = new Hono()96+ app.get('/test-path', (c) => {97+ return c.text(c.req.url)98+ })99+ const handler = handle(app)100+101+ const res = await handler(cloudFrontEdgeEvent)102+103+ expect(res.body).toBe('https://hono.dev/test-path')104+ })105+106+ it('Should preserve all values of a multi-value request header', async () => {107+ const app = new Hono()108+ app.get('/test-path', (c) => c.text(c.req.header('x-forwarded-for') ?? ''))109+ const handler = handle(app)110+111+ const event: CloudFrontEdgeEvent = {112+ Records: [113+ {114+ cf: {115+ ...cloudFrontEdgeEvent.Records[0].cf,116+ request: {117+ ...cloudFrontEdgeEvent.Records[0].cf.request,118+ headers: {119+ host: [{ key: 'Host', value: 'hono.dev' }],120+ 'x-forwarded-for': [121+ { key: 'X-Forwarded-For', value: '10.0.0.1' },122+ { key: 'X-Forwarded-For', value: '192.168.1.1' },123+ { key: 'X-Forwarded-For', value: '203.0.113.55' },124+ ],125+ },126+ },127+ },128+ },129+ ],130+ }131+132+ const res = await handler(event)133+ expect(res.body).toBe('10.0.0.1, 192.168.1.1, 203.0.113.55')134+ })135+136+ it('Should expose async handler arity compatible with NODEJS_24_X', () => {137+ const app = new Hono()138+ const handler = handle(app)139+140+ expect(handler.length).toBeLessThanOrEqual(2)141+ })142+143+ it('Should preserve positional callback compatibility', async () => {144+ type Env = { Bindings: { callback: Callback } }145+ const app = new Hono<Env>()146+ const callback = vi.fn()147+148+ app.get('/test-path', (c) => {149+ c.env.callback?.(null, {150+ status: '200',151+ headers: {152+ 'x-test': [{ key: 'x-test', value: 'ok' }],153+ },154+ })155+ return c.text('ok')156+ })157+158+ const handler = handle(app)159+ await handler(cloudFrontEdgeEvent, undefined, callback)160+161+ expect(callback).toHaveBeenCalledWith(null, {162+ status: '200',163+ headers: {164+ 'x-test': [{ key: 'x-test', value: 'ok' }],165+ },166+ })167+ })168+169+ it('Should support multiple cookies', async () => {170+ const app = new Hono()171+ app.get('/test-path', (c) => {172+ setCookie(c, 'cookie1', 'value1')173+ setCookie(c, 'cookie2', 'value2')174+ return c.text('')175+ })176+ const handler = handle(app)177+178+ const res = await handler(cloudFrontEdgeEvent)179+180+ expect(res.headers).toEqual({181+ 'content-type': [182+ {183+ key: 'content-type',184+ value: 'text/plain; charset=UTF-8',185+ },186+ ],187+ 'set-cookie': [188+ {189+ key: 'set-cookie',190+ value: 'cookie1=value1; Path=/',191+ },192+ {193+ key: 'set-cookie',194+ value: 'cookie2=value2; Path=/',195+ },196+ ],197+ })198+ })199+200+ it('Should enforce bodyLimit when the client understates Content-Length', async () => {201+ const app = new Hono()202+ app.post(203+ '/upload',204+ bodyLimit({ maxSize: 1024, onError: (c) => c.text('too large', 413) }),205+ async (c) => c.json({ received: (await c.req.text()).length })206+ )207+ const handler = handle(app)208+209+ const event: CloudFrontEdgeEvent = {210+ Records: [211+ {212+ cf: {213+ ...cloudFrontEdgeEvent.Records[0].cf,214+ request: {215+ ...cloudFrontEdgeEvent.Records[0].cf.request,216+ method: 'POST',217+ uri: '/upload',218+ headers: {219+ host: [{ key: 'Host', value: 'hono.dev' }],220+ 'content-type': [{ key: 'Content-Type', value: 'text/plain' }],221+ 'content-length': [{ key: 'Content-Length', value: '1' }],222+ },223+ body: {224+ inputTruncated: false,225+ action: 'read-only',226+ encoding: 'text',227+ data: 'A'.repeat(10000),228+ },229+ },230+ },231+ },232+ ],233+ }234+235+ const res = await handler(event)236+ expect(res).toMatchObject({ status: '413' })237+ })238+239+ it('Should resolve with the request passed to the callback for origin forwarding', async () => {240+ type Env = { Bindings: { callback: Callback; request: CloudFrontRequest } }241+ const app = new Hono<Env>()242+ const callback = vi.fn()243+244+ app.get('*', async (c, next) => {245+ await next()246+ c.env.callback(null, c.env.request)247+ })248+249+ const handler = handle(app)250+ const result = await handler(cloudFrontEdgeEvent, undefined, callback)251+252+ expect(result).toBe(cloudFrontEdgeEvent.Records[0].cf.request)253+ expect(callback).toHaveBeenCalledWith(null, cloudFrontEdgeEvent.Records[0].cf.request)254+ })255+256+ it('Should resolve with the result passed to the callback over the app response', async () => {257+ type Env = { Bindings: { callback: Callback } }258+ const app = new Hono<Env>()259+ const customResult = {260+ status: '302',261+ headers: {262+ location: [{ key: 'location', value: 'https://example.com' }],263+ },264+ }265+266+ app.get('/test-path', (c) => {267+ c.env.callback(null, customResult)268+ return c.text('ok')269+ })270+271+ const handler = handle(app)272+ const result = await handler(cloudFrontEdgeEvent)273+274+ expect(result).toBe(customResult)275+ })276+277+ it('Should only honor the first callback invocation', async () => {278+ type Env = { Bindings: { callback: Callback; request: CloudFrontRequest } }279+ const app = new Hono<Env>()280+281+ app.get('/test-path', (c) => {282+ c.env.callback(null, c.env.request)283+ c.env.callback(null, { status: '500' })284+ return c.text('ok')285+ })286+287+ const handler = handle(app)288+ const result = await handler(cloudFrontEdgeEvent)289+290+ expect(result).toBe(cloudFrontEdgeEvent.Records[0].cf.request)291+ })292+293+ it('Should reject when the callback is called with an error', async () => {294+ type Env = { Bindings: { callback: Callback } }295+ const app = new Hono<Env>()296+ const error = new Error('edge failure')297+298+ app.get('/test-path', (c) => {299+ c.env.callback(error)300+ return c.text('ok')301+ })302+303+ const handler = handle(app)304+305+ await expect(handler(cloudFrontEdgeEvent)).rejects.toThrow('edge failure')306+ })307+308+ it('Should resolve with the app response when the callback is not used', async () => {309+ const app = new Hono()310+ app.get('/test-path', (c) => c.text('normal'))311+ const handler = handle(app)312+313+ const res = await handler(cloudFrontEdgeEvent)314+ expect(res).toMatchObject({ status: '200', body: 'normal' })315+ })316+317+ it('Should base64 encode a compressed response with a textual content-type', async () => {318+ const payload = new TextEncoder().encode('a'.repeat(100))319+ const gzipped = await new Response(320+ new Blob([payload]).stream().pipeThrough(new CompressionStream('gzip'))321+ ).arrayBuffer()322+323+ const app = new Hono()324+ app.get('/test-path', () => {325+ return new Response(gzipped, {326+ headers: {327+ 'content-type': 'text/html; charset=UTF-8',328+ 'content-encoding': 'gzip',329+ },330+ })331+ })332+ const handler = handle(app)333+334+ const body = encodeBase64(gzipped)335+ const res = await handler(cloudFrontEdgeEvent)336+337+ expect(res).toMatchObject({ bodyEncoding: 'base64', body })338+339+ const decompressed = await new Response(340+ new Blob([decodeBase64(body)]).stream().pipeThrough(new DecompressionStream('gzip'))341+ ).text()342+ expect(decompressed).toBe('a'.repeat(100))343+ })344+345+ it('Should base64 encode a response with an unknown content-encoding', async () => {346+ const app = new Hono()347+ app.get('/test-path', (c) => {348+ return c.text('zstd bytes', {349+ headers: {350+ 'content-encoding': 'zstd',351+ },352+ })353+ })354+ const handler = handle(app)355+356+ const res = await handler(cloudFrontEdgeEvent)357+358+ expect(res).toMatchObject({359+ bodyEncoding: 'base64',360+ body: encodeBase64(new TextEncoder().encode('zstd bytes').buffer),361+ })362+ })363+364+ it('Should not base64 encode a response with the identity content-encoding', async () => {365+ const app = new Hono()366+ app.get('/test-path', (c) => {367+ return c.text('plain', {368+ headers: {369+ 'content-encoding': 'identity',370+ },371+ })372+ })373+ const handler = handle(app)374+375+ const res = await handler(cloudFrontEdgeEvent)376+377+ expect(res).toMatchObject({ body: 'plain' })378+ expect(res).not.toHaveProperty('bodyEncoding')379+ })380+})381+382+describe('handle with a malformed event', () => {383+ const invalidEventMessage =384+ 'Unable to map the CloudFront event to a Request: expected `Records[0].cf.request` in the Lambda@Edge event.'385+386+ it('Should reject with a descriptive error when Records holds no CloudFront record', async () => {387+ const app = new Hono()388+ const handler = handle(app)389+390+ // The payload the AWS Lambda console prefills is an array of dummy ids.391+ const event = { Records: ['foo', 'bar'] } as unknown as CloudFrontEdgeEvent392+393+ await expect(handler(event)).rejects.toThrow(TypeError)394+ await expect(handler(event)).rejects.toThrow(invalidEventMessage)395+ })396+397+ it('Should reject with a descriptive error when Records is empty or absent', async () => {398+ const app = new Hono()399+ const handler = handle(app)400+401+ for (const event of [{ Records: [] }, {}] as unknown as CloudFrontEdgeEvent[]) {402+ await expect(handler(event)).rejects.toThrow(invalidEventMessage)403+ }404+ })405+406+ it('Should reject with a descriptive error when cf carries no request', async () => {407+ const app = new Hono()408+ const handler = handle(app)409+410+ const event = {411+ Records: [{ cf: { config: { distributionDomainName: 'd111111abcdef8.cloudfront.net' } } }],412+ } as unknown as CloudFrontEdgeEvent413+414+ await expect(handler(event)).rejects.toThrow(invalidEventMessage)415+ })416+417+ it('Should fall back to the distribution domain name when the request has no headers', async () => {418+ const app = new Hono()419+ app.get('/test-path', (c) => c.text(c.req.url))420+ const handler = handle(app)421+422+ const event = {423+ Records: [424+ {425+ cf: {426+ config: {427+ distributionDomainName: 'd111111abcdef8.cloudfront.net',428+ distributionId: 'EDFDVBD6EXAMPLE',429+ eventType: 'viewer-request',430+ requestId: '4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==',431+ },432+ request: {433+ clientIp: '1.2.3.4',434+ method: 'GET',435+ querystring: '',436+ uri: '/test-path',437+ },438+ },439+ },440+ ],441+ } as unknown as CloudFrontEdgeEvent442+443+ const res = await handler(event)444+445+ expect(res).toMatchObject({446+ status: '200',447+ body: 'https://d111111abcdef8.cloudfront.net/test-path',448+ })449+ })450+})added:adapters/lambda-edge/src/handler.ts+239 added
1+import crypto from 'node:crypto'2+import type { Hono } from 'hono'3+import { decodeBase64, encodeBase64 } from 'hono/utils/encode'4+5+// eslint-disable-next-line @typescript-eslint/ban-ts-comment6+// @ts-ignore7+globalThis.crypto ??= crypto8+9+interface CloudFrontHeader {10+ key: string11+ value: string12+}13+14+interface CloudFrontHeaders {15+ [name: string]: CloudFrontHeader[]16+}17+18+interface CloudFrontCustomOrigin {19+ customHeaders: CloudFrontHeaders20+ domainName: string21+ keepaliveTimeout: number22+ path: string23+ port: number24+ protocol: string25+ readTimeout: number26+ sslProtocols: string[]27+}28+// https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html29+interface CloudFrontS3Origin {30+ authMethod: 'origin-access-identity' | 'none'31+ customHeaders: CloudFrontHeaders32+ domainName: string33+ path: string34+ region: string35+}36+type CloudFrontOrigin =37+ | { s3: CloudFrontS3Origin; custom?: never }38+ | { custom: CloudFrontCustomOrigin; s3?: never }39+40+export interface CloudFrontRequest {41+ clientIp: string42+ headers: CloudFrontHeaders43+ method: string44+ querystring: string45+ uri: string46+ body?: {47+ inputTruncated: boolean48+ action: string49+ encoding: string50+ data: string51+ }52+ origin?: CloudFrontOrigin53+}54+55+export interface CloudFrontResponse {56+ headers: CloudFrontHeaders57+ status: string58+ statusDescription?: string59+}60+61+export interface CloudFrontConfig {62+ distributionDomainName: string63+ distributionId: string64+ eventType: string65+ requestId: string66+}67+68+interface CloudFrontEvent {69+ cf: {70+ config: CloudFrontConfig71+ request: CloudFrontRequest72+ response?: CloudFrontResponse73+ }74+}75+76+export interface CloudFrontEdgeEvent {77+ Records: CloudFrontEvent[]78+}79+80+type CloudFrontContext = {}81+82+export interface Callback {83+ (err: Error | null, result?: CloudFrontRequest | CloudFrontResult): void84+}85+86+// https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-generating-http-responses-in-requests.html#lambda-generating-http-responses-programming-model87+interface CloudFrontResult {88+ status: string89+ statusDescription?: string90+ headers?: {91+ [header: string]: {92+ key: string93+ value: string94+ }[]95+ }96+ body?: string97+ bodyEncoding?: 'text' | 'base64'98+}99+100+/**101+ * Accepts events from 'Lambda@Edge' event102+ * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html103+ */104+const convertHeaders = (headers: Headers): CloudFrontHeaders => {105+ const cfHeaders: CloudFrontHeaders = {}106+ headers.forEach((value, key) => {107+ cfHeaders[key.toLowerCase()] = [108+ ...(cfHeaders[key.toLowerCase()] || []),109+ { key: key.toLowerCase(), value },110+ ]111+ })112+ return cfHeaders113+}114+115+export const handle = (116+ // eslint-disable-next-line @typescript-eslint/no-explicit-any117+ app: Hono<any>118+): ((119+ event: CloudFrontEdgeEvent,120+ context?: CloudFrontContext,121+ callback?: Callback122+) => Promise<CloudFrontResult | CloudFrontRequest>) => {123+ return async (event, ...args: [context?: CloudFrontContext, callback?: Callback]) => {124+ const [context, callback] = args125+ let callbackError: Error | null = null126+ let callbackResult: CloudFrontResult | CloudFrontRequest | undefined127+ const cf = getCloudFrontRecord(event)128+ const res = await app.fetch(createRequest(cf), {129+ event,130+ context,131+ callback: (err: Error | null, result?: CloudFrontResult | CloudFrontRequest) => {132+ if (!callbackError && !callbackResult) {133+ callbackError = err134+ callbackResult = result135+ }136+ callback?.(err, result)137+ },138+ config: cf.config,139+ request: cf.request,140+ response: cf.response,141+ })142+ if (callbackError) {143+ throw callbackError144+ }145+ return callbackResult ?? createResult(res)146+ }147+}148+149+const createResult = async (res: Response): Promise<CloudFrontResult> => {150+ const contentEncoding = res.headers.get('content-encoding')151+ const isBase64Encoded =152+ isContentTypeBinary(res.headers.get('content-type') || '') ||153+ (!!contentEncoding && !/^identity$/i.test(contentEncoding))154+ const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()155+156+ return {157+ status: res.status.toString(),158+ headers: convertHeaders(res.headers),159+ body,160+ ...(isBase64Encoded && { bodyEncoding: 'base64' }),161+ }162+}163+164+/**165+ * Reads the CloudFront record out of a Lambda@Edge event.166+ *167+ * The event is supplied by the runtime, so a malformed one means the function168+ * was invoked with something other than a Lambda@Edge event. Fail with a169+ * message naming the adapter and the missing field, rather than letting an170+ * unattributable property access error escape.171+ */172+const getCloudFrontRecord = (event: CloudFrontEdgeEvent): CloudFrontEvent['cf'] => {173+ const cf = event?.Records?.[0]?.cf174+ if (!cf?.request) {175+ throw new TypeError(176+ 'Unable to map the CloudFront event to a Request: expected `Records[0].cf.request` in the Lambda@Edge event.'177+ )178+ }179+ return cf180+}181+182+const createRequest = (cf: CloudFrontEvent['cf']): Request => {183+ const request = cf.request184+ const queryString = request.querystring185+ const host = request.headers?.host?.[0]?.value || cf.config?.distributionDomainName186+ const urlPath = `https://${host}${request.uri}`187+ const url = queryString ? `${urlPath}?${queryString}` : urlPath188+189+ const headers = new Headers()190+ Object.entries(request.headers ?? {}).forEach(([k, v]) => {191+ v.forEach((header) => headers.append(k, header.value))192+ })193+194+ const requestBody = request.body195+ const method = request.method196+ const rawBody = createBody(method, requestBody)197+198+ let body: string | Uint8Array<ArrayBuffer> | undefined = rawBody199+ if (rawBody !== undefined) {200+ const bytes =201+ typeof rawBody === 'string'202+ ? (new TextEncoder().encode(rawBody) as Uint8Array<ArrayBuffer>)203+ : rawBody204+ body = bytes205+ headers.set('content-length', bytes.length.toString())206+ }207+208+ return new Request(url, {209+ headers,210+ method,211+ body,212+ })213+}214+215+export const createBody = (216+ method: string,217+ requestBody: CloudFrontRequest['body']218+): string | Uint8Array<ArrayBuffer> | undefined => {219+ if (!requestBody || !requestBody.data) {220+ return undefined221+ }222+ if (method === 'GET' || method === 'HEAD') {223+ return undefined224+ }225+ if (requestBody.encoding === 'base64') {226+ return decodeBase64(requestBody.data)227+ }228+ return requestBody.data229+}230+231+export const isContentTypeBinary = (contentType: string): boolean => {232+ if (/^application\/vnd\.(?:apple\.installer|mozilla\.xul)\+xml\s*(?:;|$)/i.test(contentType)) {233+ return true234+ }235+236+ return !/^text\/(?:plain|html|css|javascript|csv)|(?:\/|\+)(?:json|xml)\s*(?:;|$)/i.test(237+ contentType238+ )239+}added:adapters/lambda-edge/src/index.ts+14 added
1+/**2+ * @module3+ * Lambda@Edge Adapter for Hono.4+ */5+6+export { handle } from './handler'7+export { getConnInfo } from './conninfo'8+export type {9+ Callback,10+ CloudFrontConfig,11+ CloudFrontRequest,12+ CloudFrontResponse,13+ CloudFrontEdgeEvent,14+} from './handler'added:adapters/lambda-edge/package.json+37 added
1+{2+ "name": "@hono/lambda-edge",3+ "version": "1.0.0",4+ "description": "Lambda@Edge adapter for Hono",5+ "type": "module",6+ "types": "./dist/index.d.ts",7+ "files": [8+ "dist"9+ ],10+ "exports": {11+ ".": {12+ "types": "./dist/index.d.ts",13+ "default": "./dist/index.js"14+ }15+ },16+ "scripts": {17+ "build": "rm -rf dist && vp pack && publint",18+ "test": "tsc -p tsconfig.json && vp test --run"19+ },20+ "license": "MIT",21+ "repository": {22+ "type": "git",23+ "url": "git+https://github.com/honojs/hono.git",24+ "directory": "adapters/lambda-edge"25+ },26+ "homepage": "https://hono.dev",27+ "author": "Yusuke Wada <yusuke@kamawada.com> (https://github.com/yusukebe)",28+ "peerDependencies": {29+ "hono": ">=4.13.9"30+ },31+ "engines": {32+ "node": ">=16.9.0"33+ },34+ "devDependencies": {35+ "hono": "workspace:*"36+ }37+}added:adapters/lambda-edge/README.md+22 added
1+# @hono/lambda-edge2+3+Lambda@Edge adapter for [Hono](https://hono.dev).4+5+```sh6+npm i @hono/lambda-edge7+```8+9+## Migrating from `hono/lambda-edge`10+11+The exports are the same. Change the import path:12+13+```diff14+- import { handle } from 'hono/lambda-edge'15++ import { handle } from '@hono/lambda-edge'16+```17+18+`hono/lambda-edge` is deprecated and will be removed in Hono v5.19+20+## License21+22+MITadded:adapters/lambda-edge/tsconfig.json+16 added
1+{2+ "extends": "../../tsconfig.base.json",3+ "compilerOptions": {4+ "module": "ES2020",5+ "rootDir": "./src/",6+ "outDir": "./dist/",7+ "types": [8+ "node",9+ "vitest/globals"10+ ],11+ "noEmit": true12+ },13+ "include": [14+ "src/**/*.ts"15+ ]16+}added:adapters/lambda-edge/vite.config.ts+15 added
1+import { defineConfig } from 'vite-plus'2+3+export default defineConfig({4+ pack: {5+ entry: ['src/**/*.ts', '!src/**/*.test.ts', '!src/**/*.d.ts'],6+ tsconfig: 'tsconfig.json',7+ unbundle: true,8+ format: ['esm'],9+ dts: true,10+ outExtensions: () => ({ js: '.js', dts: '.d.ts' }),11+ },12+ test: {13+ globals: true,14+ },15+})added:adapters/netlify/src/conninfo.test.ts+41 added
1+import { Context } from 'hono'2+import { getConnInfo } from './conninfo'3+4+describe('getConnInfo', () => {5+ it('Should return the client IP from context.ip', () => {6+ const ip = '203.0.113.50'7+ const c = new Context(new Request('http://localhost/'), {8+ env: {9+ context: {10+ ip,11+ },12+ },13+ })14+15+ const info = getConnInfo(c)16+17+ expect(info.remote.address).toBe(ip)18+ })19+20+ it('Should return undefined when context.ip is not present', () => {21+ const c = new Context(new Request('http://localhost/'), {22+ env: {23+ context: {},24+ },25+ })26+27+ const info = getConnInfo(c)28+29+ expect(info.remote.address).toBeUndefined()30+ })31+32+ it('Should return undefined when context is not present', () => {33+ const c = new Context(new Request('http://localhost/'), {34+ env: {},35+ })36+37+ const info = getConnInfo(c)38+39+ expect(info.remote.address).toBeUndefined()40+ })41+})added:adapters/netlify/src/conninfo.ts+57 added
1+import type { Context } from 'hono'2+import type { GetConnInfo } from 'hono/conninfo'3+4+/**5+ * Netlify context type6+ * @see https://docs.netlify.com/functions/api/7+ */8+type NetlifyContext = {9+ ip?: string10+ geo?: {11+ city?: string12+ country?: {13+ code?: string14+ name?: string15+ }16+ subdivision?: {17+ code?: string18+ name?: string19+ }20+ latitude?: number21+ longitude?: number22+ timezone?: string23+ postalCode?: string24+ }25+ requestId?: string26+}27+28+type Env = {29+ Bindings: {30+ context: NetlifyContext31+ }32+}33+34+/**35+ * Get connection information from Netlify36+ * @param c - Context37+ * @returns Connection information including remote address38+ * @example39+ * ```ts40+ * import { Hono } from 'hono'41+ * import { handle, getConnInfo } from './index'42+ *43+ * const app = new Hono()44+ *45+ * app.get('/', (c) => {46+ * const info = getConnInfo(c)47+ * return c.text(`Your IP: ${info.remote.address}`)48+ * })49+ *50+ * export default handle(app)51+ * ```52+ */53+export const getConnInfo: GetConnInfo = (c: Context<Env>) => ({54+ remote: {55+ address: c.env.context?.ip,56+ },57+})added:adapters/netlify/src/handler.ts+10 added
1+/* eslint-disable @typescript-eslint/no-explicit-any */2+import type { Hono } from 'hono'3+4+export const handle = (5+ app: Hono<any, any>6+): ((req: Request, context: any) => Response | Promise<Response>) => {7+ return (req: Request, context: any) => {8+ return app.fetch(req, { context })9+ }10+}added:adapters/netlify/src/index.ts+6 added
1+/**2+ * @module3+ * Netlify Adapter for Hono.4+ */5+6+export * from './mod'added:adapters/netlify/src/mod.ts+2 added
1+export { handle } from './handler'2+export { getConnInfo } from './conninfo'added:adapters/netlify/package.json+37 added
1+{2+ "name": "@hono/netlify",3+ "version": "1.0.0",4+ "description": "Netlify adapter for Hono",5+ "type": "module",6+ "types": "./dist/index.d.ts",7+ "files": [8+ "dist"9+ ],10+ "exports": {11+ ".": {12+ "types": "./dist/index.d.ts",13+ "default": "./dist/index.js"14+ }15+ },16+ "scripts": {17+ "build": "rm -rf dist && vp pack && publint",18+ "test": "tsc -p tsconfig.json && vp test --run"19+ },20+ "license": "MIT",21+ "repository": {22+ "type": "git",23+ "url": "git+https://github.com/honojs/hono.git",24+ "directory": "adapters/netlify"25+ },26+ "homepage": "https://hono.dev",27+ "author": "Yusuke Wada <yusuke@kamawada.com> (https://github.com/yusukebe)",28+ "peerDependencies": {29+ "hono": ">=4.13.9"30+ },31+ "engines": {32+ "node": ">=16.9.0"33+ },34+ "devDependencies": {35+ "hono": "workspace:*"36+ }37+}added:adapters/netlify/README.md+22 added
1+# @hono/netlify2+3+Netlify adapter for [Hono](https://hono.dev).4+5+```sh6+npm i @hono/netlify7+```8+9+## Migrating from `hono/netlify`10+11+The exports are the same. Change the import path:12+13+```diff14+- import { handle } from 'hono/netlify'15++ import { handle } from '@hono/netlify'16+```17+18+`hono/netlify` is deprecated and will be removed in Hono v5.19+20+## License21+22+MITadded:adapters/netlify/tsconfig.json+16 added
1+{2+ "extends": "../../tsconfig.base.json",3+ "compilerOptions": {4+ "module": "ES2020",5+ "rootDir": "./src/",6+ "outDir": "./dist/",7+ "types": [8+ "node",9+ "vitest/globals"10+ ],11+ "noEmit": true12+ },13+ "include": [14+ "src/**/*.ts"15+ ]16+}added:adapters/netlify/vite.config.ts+15 added
1+import { defineConfig } from 'vite-plus'2+3+export default defineConfig({4+ pack: {5+ entry: ['src/**/*.ts', '!src/**/*.test.ts', '!src/**/*.d.ts'],6+ tsconfig: 'tsconfig.json',7+ unbundle: true,8+ format: ['esm'],9+ dts: true,10+ outExtensions: () => ({ js: '.js', dts: '.d.ts' }),11+ },12+ test: {13+ globals: true,14+ },15+})added:adapters/service-worker/src/handler.test.ts+121 added
1+import { Hono } from 'hono'2+import { handle } from './handler'3+import type { FetchEvent } from './types'4+5+beforeAll(() => {6+ // fetch errors when it's not bound to globalThis in service worker7+ // set a fetch stub to emulate that behavior8+ vi.stubGlobal(9+ 'fetch',10+ function fetch(this: undefined | typeof globalThis, arg0: string | Request) {11+ if (this !== globalThis) {12+ const error = new Error(13+ "Failed to execute 'fetch' on 'WorkerGlobalScope': Illegal invocation"14+ )15+ error.name = 'TypeError'16+ throw error17+ }18+ if (arg0 instanceof Request && arg0.url === 'http://localhost/fallback') {19+ return new Response('hello world')20+ }21+ return Response.error()22+ }23+ )24+})25+afterAll(() => {26+ vi.unstubAllGlobals()27+})28+29+describe('handle', () => {30+ it('Success to fetch', async () => {31+ const app = new Hono()32+ app.get('/', (c) => {33+ return c.json({ hello: 'world' })34+ })35+ const handler = handle(app)36+ const json = await new Promise<Response>((resolve) => {37+ handler({38+ request: new Request('http://localhost/'),39+ respondWith(res) {40+ resolve(res)41+ },42+ } as FetchEvent)43+ }).then((res) => res.json())44+ expect(json).toStrictEqual({ hello: 'world' })45+ })46+ it('Fallback 404', async () => {47+ const app = new Hono()48+ const handler = handle(app)49+ const text = await new Promise<Response>((resolve) => {50+ handler({51+ request: new Request('http://localhost/fallback'),52+ respondWith(res) {53+ resolve(res)54+ },55+ } as FetchEvent)56+ }).then((res) => res.text())57+ expect(text).toBe('hello world')58+ })59+ it('Fallback 404 with explicit fetch', async () => {60+ const app = new Hono()61+ const handler = handle(app, {62+ async fetch() {63+ return new Response('hello world')64+ },65+ })66+ const text = await new Promise<Response>((resolve) => {67+ handler({68+ request: new Request('http://localhost/'),69+ respondWith(res) {70+ resolve(res)71+ },72+ } as FetchEvent)73+ }).then((res) => res.text())74+ expect(text).toBe('hello world')75+ })76+ it('Do not fallback 404 when fetch is undefined', async () => {77+ const app = new Hono()78+ app.get('/', (c) => c.text('Not found', 404))79+ const handler = handle(app, {80+ fetch: undefined,81+ })82+ const result = await new Promise<Response>((resolve) =>83+ handler({84+ request: new Request('https://localhost/'),85+ respondWith(r) {86+ resolve(r)87+ },88+ } as FetchEvent)89+ )90+91+ expect(result.status).toBe(404)92+ expect(await result.text()).toBe('Not found')93+ })94+95+ it('Should pass FetchEvent as second argument to app.fetch', async () => {96+ const app = new Hono()97+98+ app.get('/', (c) => {99+ return c.json({100+ // @ts-expect-error executionCtx is FetchEvent but not typed well101+ clientId: c.executionCtx.clientId,102+ })103+ })104+105+ const handler = handle(app)106+ // @ts-expect-error Force mocking FetchEvent including custom values107+ const mockFetchEvent = {108+ clientId: 'test-client-id',109+ respondWith: vi.fn(),110+ request: new Request('http://localhost'),111+ } as FetchEvent112+113+ const response = await new Promise<Response>((resolve) => {114+ mockFetchEvent.respondWith = resolve115+ handler(mockFetchEvent)116+ })117+118+ const json = await response.json()119+ expect(json.clientId).toBe('test-client-id')120+ })121+})added:adapters/service-worker/src/handler.ts+37 added
1+/**2+ * Handler for Service Worker3+ * @module4+ */5+6+import type { Hono } from 'hono'7+import type { Env, Schema } from 'hono/types'8+import type { FetchEvent } from './types'9+10+type Handler = (evt: FetchEvent) => void11+export type HandleOptions = {12+ fetch?: typeof fetch13+}14+15+/**16+ * Adapter for Service Worker17+ */18+export const handle = <E extends Env, S extends Schema, BasePath extends string>(19+ app: Hono<E, S, BasePath>,20+ opts: HandleOptions = {21+ // To use `fetch` on a Service Worker correctly, bind it to `globalThis`.22+ fetch: globalThis.fetch.bind(globalThis),23+ }24+): Handler => {25+ return (evt) => {26+ evt.respondWith(27+ (async () => {28+ // @ts-expect-error Passing FetchEvent but app.fetch expects ExecutionContext29+ const res = await app.fetch(evt.request, {}, evt)30+ if (opts.fetch && res.status === 404) {31+ return await opts.fetch(evt.request)32+ }33+ return res34+ })()35+ )36+ }37+}added:adapters/service-worker/src/index.ts+36 added
1+/**2+ * Service Worker Adapter for Hono.3+ * @module4+ */5+import type { Hono } from 'hono'6+import type { Env, Schema } from 'hono/types'7+import { handle } from './handler'8+import type { HandleOptions } from './handler'9+10+/**11+ * Registers a Hono app to handle fetch events in a service worker.12+ * This sets up `addEventListener('fetch', handle(app, options))` for the provided app.13+ *14+ * @param app - The Hono application instance15+ * @param options - Options for handling requests (fetch defaults to undefined)16+ * @example17+ * ```ts18+ * import { Hono } from 'hono'19+ * import { fire } from './index'20+ *21+ * const app = new Hono()22+ *23+ * app.get('/', (c) => c.text('Hi'))24+ *25+ * fire(app)26+ * ```27+ */28+const fire = <E extends Env, S extends Schema, BasePath extends string>(29+ app: Hono<E, S, BasePath>,30+ options?: HandleOptions31+): void => {32+ // @ts-expect-error addEventListener is not typed well in ServiceWorker-like contexts, see: https://github.com/microsoft/TypeScript/issues/1487733+ addEventListener('fetch', handle(app, options))34+}35+36+export { handle, fire }added:adapters/service-worker/src/types.ts+14 added
1+interface ExtendableEvent extends Event {2+ // eslint-disable-next-line @typescript-eslint/no-explicit-any3+ waitUntil(f: Promise<any>): void4+}5+6+export interface FetchEvent extends ExtendableEvent {7+ readonly clientId: string8+ readonly handled: Promise<void>9+ // eslint-disable-next-line @typescript-eslint/no-explicit-any10+ readonly preloadResponse: Promise<any>11+ readonly request: Request12+ readonly resultingClientId: string13+ respondWith(r: Response | PromiseLike<Response>): void14+}added:adapters/service-worker/package.json+37 added
1+{2+ "name": "@hono/service-worker",3+ "version": "1.0.0",4+ "description": "Service Worker adapter for Hono",5+ "type": "module",6+ "types": "./dist/index.d.ts",7+ "files": [8+ "dist"9+ ],10+ "exports": {11+ ".": {12+ "types": "./dist/index.d.ts",13+ "default": "./dist/index.js"14+ }15+ },16+ "scripts": {17+ "build": "rm -rf dist && vp pack && publint",18+ "test": "tsc -p tsconfig.json && vp test --run"19+ },20+ "license": "MIT",21+ "repository": {22+ "type": "git",23+ "url": "git+https://github.com/honojs/hono.git",24+ "directory": "adapters/service-worker"25+ },26+ "homepage": "https://hono.dev",27+ "author": "Yusuke Wada <yusuke@kamawada.com> (https://github.com/yusukebe)",28+ "peerDependencies": {29+ "hono": ">=4.13.9"30+ },31+ "engines": {32+ "node": ">=16.9.0"33+ },34+ "devDependencies": {35+ "hono": "workspace:*"36+ }37+}added:adapters/service-worker/README.md+22 added
1+# @hono/service-worker2+3+Service Worker adapter for [Hono](https://hono.dev).4+5+```sh6+npm i @hono/service-worker7+```8+9+## Migrating from `hono/service-worker`10+11+The exports are the same. Change the import path:12+13+```diff14+- import { handle } from 'hono/service-worker'15++ import { handle } from '@hono/service-worker'16+```17+18+`hono/service-worker` is deprecated and will be removed in Hono v5.19+20+## License21+22+MITadded:adapters/service-worker/tsconfig.json+16 added
1+{2+ "extends": "../../tsconfig.base.json",3+ "compilerOptions": {4+ "module": "ES2020",5+ "rootDir": "./src/",6+ "outDir": "./dist/",7+ "types": [8+ "node",9+ "vitest/globals"10+ ],11+ "noEmit": true12+ },13+ "include": [14+ "src/**/*.ts"15+ ]16+}added:adapters/service-worker/vite.config.ts+15 added
1+import { defineConfig } from 'vite-plus'2+3+export default defineConfig({4+ pack: {5+ entry: ['src/**/*.ts', '!src/**/*.test.ts', '!src/**/*.d.ts'],6+ tsconfig: 'tsconfig.json',7+ unbundle: true,8+ format: ['esm'],9+ dts: true,10+ outExtensions: () => ({ js: '.js', dts: '.d.ts' }),11+ },12+ test: {13+ globals: true,14+ },15+})added:adapters/vercel/src/conninfo.test.ts+18 added
1+import { Context } from 'hono'2+import { getConnInfo } from './conninfo'3+4+describe('getConnInfo', () => {5+ it('Should getConnInfo works', () => {6+ const address = Math.random().toString()7+ const req = new Request('http://localhost/', {8+ headers: {9+ 'x-real-ip': address,10+ },11+ })12+ const c = new Context(req)13+14+ const info = getConnInfo(c)15+16+ expect(info.remote.address).toBe(address)17+ })18+})added:adapters/vercel/src/conninfo.ts+8 added
1+import type { GetConnInfo } from 'hono/conninfo'2+3+export const getConnInfo: GetConnInfo = (c) => ({4+ remote: {5+ // https://github.com/vercel/vercel/blob/b70bfb5fbf28a4650d4042ce68ca5c636d37cf44/packages/edge/src/edge-headers.ts#L10-L12C326+ address: c.req.header('x-real-ip'),7+ },8+})added:adapters/vercel/src/handler.test.ts+38 added
1+import { Hono } from 'hono'2+import { handle } from './handler'3+4+describe('Adapter for Next.js', () => {5+ it('Should return 200 response', async () => {6+ const app = new Hono()7+ app.get('/api/author/:name', async (c) => {8+ const name = c.req.param('name')9+ return c.json({10+ path: '/api/author/:name',11+ name,12+ })13+ })14+ const handler = handle(app)15+ const req = new Request('http://localhost/api/author/hono')16+ const res = await handler(req)17+ expect(res.status).toBe(200)18+ expect(await res.json()).toEqual({19+ path: '/api/author/:name',20+ name: 'hono',21+ })22+ })23+24+ it('Should not use `route()` if path argument is not passed', async () => {25+ const app = new Hono().basePath('/api')26+27+ app.onError((e) => {28+ throw e29+ })30+ app.get('/error', () => {31+ throw new Error('Custom Error')32+ })33+34+ const handler = handle(app)35+ const req = new Request('http://localhost/api/error')36+ expect(() => handler(req)).toThrowError('Custom Error')37+ })38+})added:adapters/vercel/src/handler.ts+8 added
1+/* eslint-disable @typescript-eslint/no-explicit-any */2+import type { Hono } from 'hono'3+4+export const handle =5+ (app: Hono<any, any, any>) =>6+ (req: Request): Response | Promise<Response> => {7+ return app.fetch(req)8+ }added:adapters/vercel/src/index.ts+7 added
1+/**2+ * @module3+ * Vercel Adapter for Hono.4+ */5+6+export { handle } from './handler'7+export { getConnInfo } from './conninfo'added:adapters/vercel/package.json+37 added
1+{2+ "name": "@hono/vercel",3+ "version": "1.0.0",4+ "description": "Vercel adapter for Hono",5+ "type": "module",6+ "types": "./dist/index.d.ts",7+ "files": [8+ "dist"9+ ],10+ "exports": {11+ ".": {12+ "types": "./dist/index.d.ts",13+ "default": "./dist/index.js"14+ }15+ },16+ "scripts": {17+ "build": "rm -rf dist && vp pack && publint",18+ "test": "tsc -p tsconfig.json && vp test --run"19+ },20+ "license": "MIT",21+ "repository": {22+ "type": "git",23+ "url": "git+https://github.com/honojs/hono.git",24+ "directory": "adapters/vercel"25+ },26+ "homepage": "https://hono.dev",27+ "author": "Yusuke Wada <yusuke@kamawada.com> (https://github.com/yusukebe)",28+ "peerDependencies": {29+ "hono": ">=4.13.9"30+ },31+ "engines": {32+ "node": ">=16.9.0"33+ },34+ "devDependencies": {35+ "hono": "workspace:*"36+ }37+}added:adapters/vercel/README.md+22 added
1+# @hono/vercel2+3+Vercel adapter for [Hono](https://hono.dev).4+5+```sh6+npm i @hono/vercel7+```8+9+## Migrating from `hono/vercel`10+11+The exports are the same. Change the import path:12+13+```diff14+- import { handle } from 'hono/vercel'15++ import { handle } from '@hono/vercel'16+```17+18+`hono/vercel` is deprecated and will be removed in Hono v5.19+20+## License21+22+MITadded:adapters/vercel/tsconfig.json+16 added
1+{2+ "extends": "../../tsconfig.base.json",3+ "compilerOptions": {4+ "module": "ES2020",5+ "rootDir": "./src/",6+ "outDir": "./dist/",7+ "types": [8+ "node",9+ "vitest/globals"10+ ],11+ "noEmit": true12+ },13+ "include": [14+ "src/**/*.ts"15+ ]16+}added:adapters/vercel/vite.config.ts+15 added
1+import { defineConfig } from 'vite-plus'2+3+export default defineConfig({4+ pack: {5+ entry: ['src/**/*.ts', '!src/**/*.test.ts', '!src/**/*.d.ts'],6+ tsconfig: 'tsconfig.json',7+ unbundle: true,8+ format: ['esm'],9+ dts: true,10+ outExtensions: () => ({ js: '.js', dts: '.d.ts' }),11+ },12+ test: {13+ globals: true,14+ },15+})modified:src/adapter/aws-lambda/conninfo.ts+1 added
39 unmodified lines40 * })41 *42 * export const handler = handle(app)43 * ```44+ * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.45 */46 export const getConnInfo: GetConnInfo = (c: Context<Env>) => {47 const requestContext = c.env.requestContext48 26 unmodified linesmodified:src/adapter/aws-lambda/handler.ts+44 added
19 unmodified lines20 }21 return encodeURIComponent(value)22 }23 24+/**25+ * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.26+ */27 export type LambdaEvent =28 | APIGatewayProxyEvent29 | APIGatewayProxyEventV230 | ALBProxyEvent31 | LatticeProxyEventV232 33+/**34+ * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.35+ */36 export interface LatticeProxyEventV2 {37 version: string38 path: string39 method: string4 unmodified lines44 requestContext: LatticeRequestContextV245 }46 47 // When calling HTTP API or Lambda directly through function urls48+/**49+ * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.50+ */51 export interface APIGatewayProxyEventV2 {52 version: string53 routeKey: string54 headers: Record<string, string | undefined>15 unmodified lines70 }71 }72 73 // When calling Lambda through an API Gateway74+/**75+ * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.76+ */77 export interface APIGatewayProxyEvent {78 version: string79 httpMethod: string80 headers: Record<string, string | undefined>13 unmodified lines94 stageVariables?: Record<string, string>95 }96 97 // When calling Lambda through an Application Load Balancer98+/**99+ * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.100+ */101 export interface ALBProxyEvent {102 httpMethod: string103 headers?: Record<string, string | undefined>104 multiValueHeaders?: Record<string, string[] | undefined>15 unmodified lines120 headers?: undefined121 multiValueHeaders: Record<string, string[]>122 }123 124+/**125+ * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.126+ */127 export type APIGatewayProxyResult = {128 statusCode: number129 statusDescription?: string130 body: string25 unmodified lines156 reader: ReadableStreamDefaultReader<Uint8Array>,157 writer: NodeJS.WritableStream158 ): Promise<void> => pipeline(readWebStream(reader), writer)159 160+/**161+ * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.162+ */163 export const streamHandle = <164 E extends Env = Env,165 S extends Schema = {},166 BasePath extends string = '/',92 unmodified lines259 * return contentType.startsWith('image/') || contentType === 'application/pdf'260 * }261 * })262 * ```263+ * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.264 */265 export const handle = <E extends Env = Env, S extends Schema = {}, BasePath extends string = '/'>(266 app: Hono<E, S, BasePath>,267 { isContentTypeBinary }: HandleOptions = { isContentTypeBinary: undefined }32 unmodified lines300 return processor.createResult(event, res, { isContentTypeBinary })301 }302 }303 304+/**305+ * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.306+ */307 export abstract class EventProcessor<E extends LambdaEvent> {308 protected abstract getPath(event: E): string309 310 protected abstract getMethod(event: E): string118 unmodified lines429 }430 }431 }432 433+/**434+ * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.435+ */436 export class EventV2Processor extends EventProcessor<APIGatewayProxyEventV2> {437 protected getPath(event: APIGatewayProxyEventV2): string {438 return event.rawPath439 }31 unmodified lines471 }472 473 const v2Processor: EventV2Processor = new EventV2Processor()474 475+/**476+ * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.477+ */478 export class EventV1Processor extends EventProcessor<APIGatewayProxyEvent> {479 protected getPath(event: APIGatewayProxyEvent): string {480 return event.path481 }52 unmodified lines534 }535 536 const v1Processor: EventV1Processor = new EventV1Processor()537 538+/**539+ * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.540+ */541 export class ALBProcessor extends EventProcessor<ALBProxyEvent> {542 protected getHeaders(event: ALBProxyEvent): Headers {543 const headers = new Headers()544 // if multiValueHeaders is present the ALB will use it instead of the headers field73 unmodified lines618 }619 620 const albProcessor: ALBProcessor = new ALBProcessor()621 622+/**623+ * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.624+ */625 export class LatticeV2Processor extends EventProcessor<LatticeProxyEventV2> {626 protected getPath(event: LatticeProxyEventV2): string {627 return event.path628 }33 unmodified lines662 }663 664 const latticeV2Processor: LatticeV2Processor = new LatticeV2Processor()665 666+/**667+ * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.668+ */669 export const getProcessor = (event: LambdaEvent): EventProcessor<LambdaEvent> => {670 if (isProxyEventALB(event)) {671 return albProcessor672 }32 unmodified lines705 * Check if the given content type is binary.706 * This is a default function and may be overwritten by the user via `isContentTypeBinary` option in handler().707 * @param contentType The content type to check.708 * @returns True if the content type is binary, false otherwise.709+ * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.710 */711 export const defaultIsContentTypeBinary = (contentType: string): boolean => {712 if (/^application\/vnd\.(?:apple\.installer|mozilla\.xul)\+xml\s*(?:;|$)/i.test(contentType)) {713 return true3 unmodified lines717 contentType718 )719 }720 721+/**722+ * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.723+ */724 export const isContentEncodingBinary = (contentEncoding: string | null) => {725 return !!contentEncoding && !/^identity$/i.test(contentEncoding)726 }modified:src/adapter/aws-lambda/index.ts+4 added
1 /**2 * @module3 * AWS Lambda Adapter for Hono.4+ *5+ * @deprecated6+ * This adapter will be removed from the `hono` package in v5.7+ * Install `@hono/aws-lambda` and import from there instead.8 */9 10 export { handle, streamHandle, defaultIsContentTypeBinary } from './handler'11 export { getConnInfo } from './conninfo'7 unmodified linesmodified:src/adapter/aws-lambda/types.ts+28 added
1 /* eslint-disable @typescript-eslint/no-explicit-any */2 3+/**4+ * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.5+ */6 export interface CognitoIdentity {7 cognitoIdentityId: string8 cognitoIdentityPoolId: string9 }10 11+/**12+ * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.13+ */14 export interface ClientContext {15 client: ClientContextClient16 17 Custom?: any18 env: ClientContextEnv19 }20 21+/**22+ * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.23+ */24 export interface ClientContextClient {25 installationId: string26 appTitle: string27 appVersionName: string28 appVersionCode: string29 appPackageName: string30 }31 32+/**33+ * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.34+ */35 export interface ClientContextEnv {36 platformVersion: string37 platform: string38 make: string3 unmodified lines42 43 /**44 * {@link Handler} context parameter.45 * See {@link https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html AWS documentation}.46+ * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.47 */48 export interface LambdaContext {49 callbackWaitsForEmptyEventLoop: boolean50 functionName: string10 unmodified lines61 }62 63 type Callback<TResult = any> = (error?: Error | string | null, result?: TResult) => void64 65+/**66+ * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.67+ */68 export type Handler<TEvent = any, TResult = any> = (69 event: TEvent,70 context: LambdaContext,71 callback: Callback<TResult>25 unmodified lines97 userArn?: string98 clientCert?: ClientCert99 }100 101+/**102+ * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.103+ */104 export interface ApiGatewayRequestContext {105 accountId: string106 apiId: string107 authorizer: {35 unmodified lines143 */144 lambda?: Record<string, unknown> | null145 }146 147+/**148+ * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.149+ */150 export interface ApiGatewayRequestContextV2 {151 accountId: string152 apiId: string153 authentication: null13 unmodified lines167 time: string168 timeEpoch: number169 }170 171+/**172+ * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.173+ */174 export interface ALBRequestContext {175 elb: {176 targetGroupArn: string177 }178 }179 180+/**181+ * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.182+ */183 export interface LatticeRequestContextV2 {184 serviceNetworkArn: string185 serviceArn: string186 targetGroupArn: string15 unmodified linesmodified:src/adapter/cloudflare-pages/conninfo.ts+1 added
16 unmodified lines17 * })18 *19 * export const onRequest = handle(app)20 * ```21+ * @deprecated `hono/cloudflare-pages` will be removed in v5. Cloudflare recommends Workers with static assets; use `hono` on Workers instead.22 */23 export const getConnInfo: GetConnInfo = (c) => ({24 remote: {25 address: c.req.header('cf-connecting-ip'),2 unmodified linesmodified:src/adapter/cloudflare-pages/handler.ts+10 added
7 unmodified lines8 // eslint-disable-next-line @typescript-eslint/no-explicit-any9 type Params<P extends string = any> = Record<P, string | string[]>10 11 // eslint-disable-next-line @typescript-eslint/no-explicit-any12+/**13+ * @deprecated `hono/cloudflare-pages` will be removed in v5. Cloudflare recommends Workers with static assets; use `hono` on Workers instead.14+ */15 export type EventContext<Env = {}, P extends string = any, Data = Record<string, unknown>> = {16 request: Request17 functionPath: string18 waitUntil: (promise: Promise<unknown>) => void12 unmodified lines31 Params extends string = any,32 Data extends Record<string, unknown> = Record<string, unknown>,33 > = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>34 35+/**36+ * @deprecated `hono/cloudflare-pages` will be removed in v5. Cloudflare recommends Workers with static assets; use `hono` on Workers instead.37+ */38 export const handle =39 <E extends Env = Env, S extends Schema = BlankSchema, BasePath extends string = '/'>(40 app: Hono<E, S, BasePath>41 ): PagesFunction<E['Bindings']> =>9 unmodified lines51 )52 }53 54 // eslint-disable-next-line @typescript-eslint/no-explicit-any55+/**56+ * @deprecated `hono/cloudflare-pages` will be removed in v5. Cloudflare recommends Workers with static assets; use `hono` on Workers instead.57+ */58 export function handleMiddleware<E extends Env = {}, P extends string = any, I extends Input = {}>(59 middleware: MiddlewareHandler<60 E & {61 Bindings: {56 unmodified lines118 *119 * @description `serveStatic()` is for advanced mode:120 * https://developers.cloudflare.com/pages/platform/functions/advanced-mode/#set-up-a-function121 *122+ * @deprecated `hono/cloudflare-pages` will be removed in v5. Cloudflare recommends Workers with static assets; use `hono` on Workers instead.123 */124 export const serveStatic = (): MiddlewareHandler => {125 return async (c) => {126 const env = c.env as { ASSETS: FetcherLike }7 unmodified linesmodified:src/adapter/cloudflare-pages/index.ts+4 added
1 /**2 * @module3 * Cloudflare Pages Adapter for Hono.4+ *5+ * @deprecated6+ * This adapter will be removed from the `hono` package in v5.7+ * Cloudflare recommends Workers with static assets; use `hono` on Workers instead.8 */9 10 export { handle, handleMiddleware, serveStatic } from './handler'11 export { getConnInfo } from './conninfo'1 unmodified linemodified:src/adapter/cloudflare-workers/conninfo.ts+3 added
1 import type { GetConnInfo } from '../../helper/conninfo'2 3+/**4+ * @deprecated `hono/cloudflare-workers` will be removed in v5. Install `@hono/cloudflare-workers` and import from there instead.5+ */6 export const getConnInfo: GetConnInfo = (c) => ({7 remote: {8 address: c.req.header('cf-connecting-ip'),9 },1 unmodified linemodified:src/adapter/cloudflare-workers/index.ts+4 added
1 /**2 * @module3 * Cloudflare Workers Adapter for Hono.4+ *5+ * @deprecated6+ * This adapter will be removed from the `hono` package in v5.7+ * Install `@hono/cloudflare-workers` and import from there instead.8 */9 10 export { serveStatic } from './serve-static-module'11 export { upgradeWebSocket } from './websocket'1 unmodified linemodified:src/adapter/cloudflare-workers/serve-static.ts+3 added
1 unmodified line2 import type { ServeStaticOptions as BaseServeStaticOptions } from '../../middleware/serve-static'3 import type { Env, MiddlewareHandler } from '../../types'4 import { getContentFromKVAsset } from './utils'5 6+/**7+ * @deprecated `hono/cloudflare-workers` will be removed in v5. Install `@hono/cloudflare-workers` and import from there instead.8+ */9 export type ServeStaticOptions<E extends Env = Env> = BaseServeStaticOptions<E> & {10 // namespace is KVNamespace11 namespace?: unknown12 manifest?: object | string33 unmodified linesmodified:src/adapter/cloudflare-workers/utils.ts+6 added
1 // __STATIC_CONTENT is KVNamespace2 declare const __STATIC_CONTENT: unknown3 declare const __STATIC_CONTENT_MANIFEST: string4 5+/**6+ * @deprecated `hono/cloudflare-workers` will be removed in v5. Install `@hono/cloudflare-workers` and import from there instead.7+ */8 export type KVAssetOptions = {9 manifest?: object | string10 // namespace is KVNamespace11 namespace?: unknown12 }13 14+/**15+ * @deprecated `hono/cloudflare-workers` will be removed in v5. Install `@hono/cloudflare-workers` and import from there instead.16+ */17 export const getContentFromKVAsset = async (18 path: string,19 options?: KVAssetOptions20 ): Promise<ReadableStream | null> => {36 unmodified linesmodified:src/adapter/cloudflare-workers/websocket.ts+3 added
1 import { WSContext, defineWebSocketHelper } from '../../helper/websocket'2 import type { UpgradeWebSocket, WSEvents, WSReadyState } from '../../helper/websocket'3 4 // Based on https://github.com/honojs/hono/issues/1153#issuecomment-17673213325+/**6+ * @deprecated `hono/cloudflare-workers` will be removed in v5. Install `@hono/cloudflare-workers` and import from there instead.7+ */8 export const upgradeWebSocket: UpgradeWebSocket<9 WebSocket,10 // eslint-disable-next-line @typescript-eslint/no-explicit-any11 any,45 unmodified linesmodified:src/adapter/deno/conninfo.ts+1 added
2 unmodified lines3 /**4 * Get conninfo with Deno5 * @param c Context6 * @returns ConnInfo7+ * @deprecated `hono/deno` will be removed in v5. Install `@hono/deno` and import from there instead.8 */9 export const getConnInfo: GetConnInfo = (c) => {10 const { remoteAddr } = c.env11 return {7 unmodified linesmodified:src/adapter/deno/index.ts+4 added
1 /**2 * @module3 * Deno Adapter for Hono.4+ *5+ * @deprecated6+ * This adapter will be removed from the `hono` package in v5.7+ * Install `@hono/deno` and import from there instead.8 */9 10 export { serveStatic } from './serve-static'11 export { toSSG, denoFileSystemModule } from './ssg'2 unmodified linesmodified:src/adapter/deno/serve-static.ts+3 added
3 unmodified lines4 import type { Env, MiddlewareHandler } from '../../types'5 6 const { open, lstatSync, errors } = Deno7 8+/**9+ * @deprecated `hono/deno` will be removed in v5. Install `@hono/deno` and import from there instead.10+ */11 export const serveStatic = <E extends Env = Env>(12 options: ServeStaticOptions<E> = {}13 ): MiddlewareHandler => {14 return async function serveStatic(c, next) {31 unmodified linesmodified:src/adapter/deno/ssg.ts+2 added
3 unmodified lines4 /**5 * @experimental6 * `denoFileSystemModule` is an experimental feature.7 * The API might be changed.8+ * @deprecated `hono/deno` will be removed in v5. Install `@hono/deno` and import from there instead.9 */10 export const denoFileSystemModule: FileSystemModule = {11 writeFile: async (path, data) => {12 const uint8Data =8 unmodified lines21 /**22 * @experimental23 * `toSSG` is an experimental feature.24 * The API might be changed.25+ * @deprecated `hono/deno` will be removed in v5. Install `@hono/deno` and import from there instead.26 */27 export const toSSG: ToSSGAdaptorInterface = async (app, options) => {28 return baseToSSG(app, denoFileSystemModule, options)29 }modified:src/adapter/deno/websocket.ts+3 added
1 import type { UpgradeWebSocket, WSReadyState } from '../../helper/websocket'2 import { WSContext, defineWebSocketHelper } from '../../helper/websocket'3 4+/**5+ * @deprecated `hono/deno` will be removed in v5. Install `@hono/deno` and import from there instead.6+ */7 export const upgradeWebSocket: UpgradeWebSocket<WebSocket, Deno.UpgradeWebSocketOptions> =8 defineWebSocketHelper(async (c, events, options) => {9 if (c.req.header('upgrade') !== 'websocket') {10 return31 unmodified linesmodified:src/adapter/lambda-edge/conninfo.ts+3 added
6 unmodified lines7 event: CloudFrontEdgeEvent8 }9 }10 11+/**12+ * @deprecated `hono/lambda-edge` will be removed in v5. Install `@hono/lambda-edge` and import from there instead.13+ */14 export const getConnInfo: GetConnInfo = (c: Context<Env>) => ({15 remote: {16 address: c.env.event.Records[0].cf.request.clientIp,17 },1 unmodified linemodified:src/adapter/lambda-edge/handler.ts+24 added
35 unmodified lines36 type CloudFrontOrigin =37 | { s3: CloudFrontS3Origin; custom?: never }38 | { custom: CloudFrontCustomOrigin; s3?: never }39 40+/**41+ * @deprecated `hono/lambda-edge` will be removed in v5. Install `@hono/lambda-edge` and import from there instead.42+ */43 export interface CloudFrontRequest {44 clientIp: string45 headers: CloudFrontHeaders46 method: string7 unmodified lines54 }55 origin?: CloudFrontOrigin56 }57 58+/**59+ * @deprecated `hono/lambda-edge` will be removed in v5. Install `@hono/lambda-edge` and import from there instead.60+ */61 export interface CloudFrontResponse {62 headers: CloudFrontHeaders63 status: string64 statusDescription?: string65 }66 67+/**68+ * @deprecated `hono/lambda-edge` will be removed in v5. Install `@hono/lambda-edge` and import from there instead.69+ */70 export interface CloudFrontConfig {71 distributionDomainName: string72 distributionId: string73 eventType: string7 unmodified lines81 response?: CloudFrontResponse82 }83 }84 85+/**86+ * @deprecated `hono/lambda-edge` will be removed in v5. Install `@hono/lambda-edge` and import from there instead.87+ */88 export interface CloudFrontEdgeEvent {89 Records: CloudFrontEvent[]90 }91 92 type CloudFrontContext = {}93 94+/**95+ * @deprecated `hono/lambda-edge` will be removed in v5. Install `@hono/lambda-edge` and import from there instead.96+ */97 export interface Callback {98 (err: Error | null, result?: CloudFrontRequest | CloudFrontResult): void99 }100 25 unmodified lines126 })127 return cfHeaders128 }129 130+/**131+ * @deprecated `hono/lambda-edge` will be removed in v5. Install `@hono/lambda-edge` and import from there instead.132+ */133 export const handle = (134 // eslint-disable-next-line @typescript-eslint/no-explicit-any135 app: Hono<any>136 ): ((92 unmodified lines229 body,230 })231 }232 233+/**234+ * @deprecated `hono/lambda-edge` will be removed in v5. Install `@hono/lambda-edge` and import from there instead.235+ */236 export const createBody = (237 method: string,238 requestBody: CloudFrontRequest['body']239 ): string | Uint8Array<ArrayBuffer> | undefined => {8 unmodified lines248 }249 return requestBody.data250 }251 252+/**253+ * @deprecated `hono/lambda-edge` will be removed in v5. Install `@hono/lambda-edge` and import from there instead.254+ */255 export const isContentTypeBinary = (contentType: string): boolean => {256 if (/^application\/vnd\.(?:apple\.installer|mozilla\.xul)\+xml\s*(?:;|$)/i.test(contentType)) {257 return true258 }5 unmodified linesmodified:src/adapter/lambda-edge/index.ts+4 added
1 /**2 * @module3 * Lambda@Edge Adapter for Hono.4+ *5+ * @deprecated6+ * This adapter will be removed from the `hono` package in v5.7+ * Install `@hono/lambda-edge` and import from there instead.8 */9 10 export { handle } from './handler'11 export { getConnInfo } from './conninfo'7 unmodified linesmodified:src/adapter/netlify/conninfo.ts+1 added
47 unmodified lines48 * })49 *50 * export default handle(app)51 * ```52+ * @deprecated `hono/netlify` will be removed in v5. Install `@hono/netlify` and import from there instead.53 */54 export const getConnInfo: GetConnInfo = (c: Context<Env>) => ({55 remote: {56 address: c.env.context?.ip,2 unmodified linesmodified:src/adapter/netlify/handler.ts+3 added
1 /* eslint-disable @typescript-eslint/no-explicit-any */2 import type { Hono } from '../../hono'3 4+/**5+ * @deprecated `hono/netlify` will be removed in v5. Install `@hono/netlify` and import from there instead.6+ */7 export const handle = (8 app: Hono<any, any>9 ): ((req: Request, context: any) => Response | Promise<Response>) => {10 return (req: Request, context: any) => {3 unmodified linesmodified:src/adapter/netlify/index.ts+4 added
1 /**2 * @module3 * Netlify Adapter for Hono.4+ *5+ * @deprecated6+ * This adapter will be removed from the `hono` package in v5.7+ * Install `@hono/netlify` and import from there instead.8 */9 10 export * from './mod'modified:src/adapter/service-worker/handler.ts+4 added
6 unmodified lines7 import type { Env, Schema } from '../../types'8 import type { FetchEvent } from './types'9 10 type Handler = (evt: FetchEvent) => void11+/**12+ * @deprecated `hono/service-worker` will be removed in v5. Install `@hono/service-worker` and import from there instead.13+ */14 export type HandleOptions = {15 fetch?: typeof fetch16 }17 18 /**19 * Adapter for Service Worker20+ * @deprecated `hono/service-worker` will be removed in v5. Install `@hono/service-worker` and import from there instead.21 */22 export const handle = <E extends Env, S extends Schema, BasePath extends string>(23 app: Hono<E, S, BasePath>,24 opts: HandleOptions = {17 unmodified linesmodified:src/adapter/service-worker/index.ts+4 added
1 /**2 * Service Worker Adapter for Hono.3 * @module4+ *5+ * @deprecated6+ * This adapter will be removed from the `hono` package in v5.7+ * Install `@hono/service-worker` and import from there instead.8 */9 import type { Hono } from '../../hono'10 import type { Env, Schema } from '../../types'11 import { handle } from './handler'29 unmodified linesmodified:src/adapter/service-worker/types.ts+3 added
1 unmodified line2 // eslint-disable-next-line @typescript-eslint/no-explicit-any3 waitUntil(f: Promise<any>): void4 }5 6+/**7+ * @deprecated `hono/service-worker` will be removed in v5. Install `@hono/service-worker` and import from there instead.8+ */9 export interface FetchEvent extends ExtendableEvent {10 readonly clientId: string11 readonly handled: Promise<void>12 // eslint-disable-next-line @typescript-eslint/no-explicit-any5 unmodified linesmodified:src/adapter/vercel/conninfo.ts+3 added
1 import type { GetConnInfo } from '../../helper/conninfo'2 3+/**4+ * @deprecated `hono/vercel` will be removed in v5. Install `@hono/vercel` and import from there instead.5+ */6 export const getConnInfo: GetConnInfo = (c) => ({7 remote: {8 // https://github.com/vercel/vercel/blob/b70bfb5fbf28a4650d4042ce68ca5c636d37cf44/packages/edge/src/edge-headers.ts#L10-L12C329 address: c.req.header('x-real-ip'),2 unmodified linesmodified:src/adapter/vercel/handler.ts+3 added
1 /* eslint-disable @typescript-eslint/no-explicit-any */2 import type { Hono } from '../../hono'3 4+/**5+ * @deprecated `hono/vercel` will be removed in v5. Install `@hono/vercel` and import from there instead.6+ */7 export const handle =8 (app: Hono<any, any, any>) =>9 (req: Request): Response | Promise<Response> => {10 return app.fetch(req)1 unmodified linemodified:src/adapter/vercel/index.ts+4 added
1 /**2 * @module3 * Vercel Adapter for Hono.4+ *5+ * @deprecated6+ * This adapter will be removed from the `hono` package in v5.7+ * Install `@hono/vercel` and import from there instead.8 */9 10 export { handle } from './handler'11 export { getConnInfo } from './conninfo'modified:pnpm-lock.yaml+42 added
231 unmodified lines232 zod:233 specifier: ^3.23.8234 version: 3.25.76235 236+ adapters/aws-lambda:237+ devDependencies:238+ hono:239+ specifier: workspace:*240+ version: link:../..241+242 adapters/bun:243 devDependencies:244 hono:245 specifier: workspace:*246 version: link:../..247 248+ adapters/cloudflare-workers:249+ devDependencies:250+ hono:251+ specifier: workspace:*252+ version: link:../..253+254+ adapters/deno:255+ devDependencies:256+ hono:257+ specifier: workspace:*258+ version: link:../..259+260+ adapters/lambda-edge:261+ devDependencies:262+ hono:263+ specifier: workspace:*264+ version: link:../..265+266+ adapters/netlify:267+ devDependencies:268+ hono:269+ specifier: workspace:*270+ version: link:../..271+272+ adapters/service-worker:273+ devDependencies:274+ hono:275+ specifier: workspace:*276+ version: link:../..277+278+ adapters/vercel:279+ devDependencies:280+ hono:281+ specifier: workspace:*282+ version: link:../..283+284 packages:285 286 '@andreiltd/componentize-qjs-binding-darwin-arm64@0.4.5':287 resolution: {integrity: sha512-CW+ukVP778x2NAHAC1FvXb5KVSXmUlUQxhQTFtF0mAqqOVnYrQgy4DDNUa48EGthwtLdgLT1+eE71qmQiyMEqg==}9764 unmodified lines