Skip to content
Myr

index.test.ts

This file

Path

runtime-tests/lambda/index.test.ts

1,089 lines 路 33.2 KiB 路 TypeScript

Last changed by

chore(builld): tsconfig project references (#4797)Jonathan Hainesbefore adoptiond69deb8

History of this file

Take it

1import { Readable } from 'stream'2import {3  ALBProcessor,4  EventV1Processor,5  EventV2Processor,6  getProcessor,7  handle,8  streamHandle,9} from '../../src/adapter/aws-lambda/handler'10import type {11  ALBProxyEvent,12  APIGatewayProxyEventV2,13  LatticeProxyEventV2,14  LambdaEvent,15} from '../../src/adapter/aws-lambda/handler'16import type {17  ApiGatewayRequestContext,18  ApiGatewayRequestContextV2,19  LatticeRequestContextV2,20  LambdaContext,21} from '../../src/adapter/aws-lambda/types'22import { getCookie, setCookie } from '../../src/helper/cookie'23import { streamSSE, streamText } from '../../src/helper/streaming'24import { Hono } from '../../src/hono'25import { basicAuth } from '../../src/middleware/basic-auth'26import './mock'2728type Bindings = {29  event: LambdaEvent30  lambdaContext: LambdaContext31  requestContext: ApiGatewayRequestContext | ApiGatewayRequestContextV232}3334const testApiGatewayRequestContextV2 = {35  accountId: '123456789012',36  apiId: 'urlid',37  authentication: null,38  authorizer: {39    iam: {40      accessKey: 'AKIA...',41      accountId: '111122223333',42      callerId: 'AIDA...',43      cognitoIdentity: null,44      principalOrgId: null,45      userArn: 'arn:aws:iam::111122223333:user/example-user',46      userId: 'AIDA...',47    },48  },49  domainName: 'example.com',50  domainPrefix: '<url-id>',51  http: {52    method: 'POST',53    path: '/my/path',54    protocol: 'HTTP/1.1',55    sourceIp: '123.123.123.123',56    userAgent: 'agent',57  },58  requestId: 'id',59  routeKey: '$default',60  stage: '$default',61  time: '12/Mar/2020:19:03:58 +0000',62  timeEpoch: 1583348638390,63  customProperty: 'customValue',64}6566const testLatticeRequestContext: LatticeRequestContextV2 = {67  serviceNetworkArn: 'arn:aws:vpc-lattice:us-east-1:111122223333:servicenetwork/sn-a1b2c3',68  serviceArn: 'arn:aws:vpc-lattice:us-east-1:111122223333:service/svc-a1b2c3',69  targetGroupArn: 'arn:aws:vpc-lattice:us-east-1:111122223333:targetgroup/tg-a1b2c3',70  region: 'us-east-1',71  timeEpoch: '1759915938150314',72  identity: {73    sourceVpcArn: 'arn:aws:ec2:us-east-1:111122223333:vpc/vpc-a1b2c3',74  },75}7677describe('AWS Lambda Adapter for Hono', () => {78  const app = new Hono<{ Bindings: Bindings }>()7980  app.get('/', (c) => {81    return c.text('Hello Lambda!')82  })8384  app.get('/binary', (c) => {85    return c.body('Fake Image', 200, {86      'Content-Type': 'image/png',87    })88  })8990  app.post('/post', async (c) => {91    const body = (await c.req.parseBody()) as { message: string }92    return c.text(body.message)93  })9495  app.post('/post/binary', async (c) => {96    const body = await c.req.blob()97    return c.text(`${body.size} bytes`)98  })99100  const username = 'hono-user-a'101  const password = 'hono-password-a'102  app.use('/auth/*', basicAuth({ username, password }))103  app.get('/auth/abc', (c) => c.text('Good Night Lambda!'))104105  app.get('/lambda-event', (c) => {106    const event = c.env.event107    return c.json(event)108  })109110  app.get('/lambda-context', (c) => {111    const fnctx = c.env.lambdaContext112    return c.json(fnctx)113  })114115  app.get('/custom-context/v1/apigw', (c) => {116    const lambdaContext = c.env.requestContext117    return c.json(lambdaContext)118  })119120  app.get('/custom-context/apigw', (c) => {121    const lambdaContext = c.env.event.requestContext122    return c.json(lambdaContext)123  })124125  app.get('/custom-context/v1/lambda', (c) => {126    const lambdaContext = c.env.requestContext127    return c.json(lambdaContext)128  })129130  app.get('/custom-context/lambda', (c) => {131    const lambdaContext = c.env.event.requestContext132    return c.json(lambdaContext)133  })134135  app.get('/query-params', (c) => {136    const queryParams = c.req.query()137    return c.json(queryParams)138  })139140  app.get('/multi-query-params', (c) => {141    const multiQueryParams = c.req.queries()142    return c.json(multiQueryParams)143  })144145  const testCookie1 = {146    key: 'id',147    value: crypto.randomUUID(),148    get serialized() {149      return `${this.key}=${this.value}; Path=/`150    },151  }152  const testCookie2 = {153    key: 'secret',154    value: crypto.randomUUID(),155    get serialized() {156      return `${this.key}=${this.value}; Path=/`157    },158  }159160  app.post('/cookie', (c) => {161    setCookie(c, testCookie1.key, testCookie1.value)162    setCookie(c, testCookie2.key, testCookie2.value)163    return c.text('Cookies Set')164  })165166  app.get('/cookie', (c) => {167    const validCookies =168      getCookie(c, testCookie1.key) === testCookie1.value &&169      getCookie(c, testCookie2.key) === testCookie2.value170    if (!validCookies) {171      return c.text('Invalid Cookies')172    }173    return c.text('Valid Cookies')174  })175176  app.post('/headers', (c) => {177    if (c.req.header('foo')?.includes('bar')) {178      return c.json({ message: 'ok' })179    }180    return c.json({ message: 'fail' }, 400)181  })182183  const handler = handle(app)184185  const testApiGatewayRequestContext = {186    accountId: '123456789012',187    apiId: 'id',188    authorizer: {189      claims: null,190      scopes: null,191    },192    domainName: 'example.com',193    domainPrefix: 'id',194    extendedRequestId: 'request-id',195    httpMethod: 'GET',196    identity: {197      sourceIp: 'IP',198      userAgent: 'user-agent',199    },200    path: '/my/path',201    protocol: 'HTTP/1.1',202    requestId: 'id=',203    requestTime: '04/Mar/2020:19:15:17 +0000',204    requestTimeEpoch: 1583349317135,205    resourcePath: '/',206    stage: '$default',207    customProperty: 'customValue',208  }209210  const testALBRequestContext = {211    elb: {212      targetGroupArn:213        'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a',214    },215  }216217  it('Should handle a GET request and return a 200 response', async () => {218    const event = {219      version: '1.0',220      resource: '/',221      httpMethod: 'GET',222      headers: { 'content-type': 'text/plain' },223      path: '/',224      body: null,225      isBase64Encoded: false,226      requestContext: testApiGatewayRequestContext,227    }228229    const response = await handler(event)230    expect(response.statusCode).toBe(200)231    expect(response.body).toBe('Hello Lambda!')232    expect(response.headers['content-type']).toMatch(/^text\/plain/)233    expect(response.multiValueHeaders).toBeUndefined()234    expect(response.isBase64Encoded).toBe(false)235  })236237  it('Should handle a GET request and return a 200 response with binary', async () => {238    const event = {239      version: '1.0',240      resource: '/binary',241      httpMethod: 'GET',242      headers: {},243      path: '/binary',244      body: null,245      isBase64Encoded: false,246      requestContext: testApiGatewayRequestContext,247    }248249    const response = await handler(event)250    expect(response.statusCode).toBe(200)251    expect(response.body).toBe('RmFrZSBJbWFnZQ==')252    expect(response.headers['content-type']).toMatch(/^image\/png/)253    expect(response.multiValueHeaders).toBeUndefined()254    expect(response.isBase64Encoded).toBe(true)255  })256257  it('Should handle a GET request and return a 200 response (LambdaFunctionUrlEvent)', async () => {258    const event = {259      version: '2.0',260      routeKey: '$default',261      headers: { 'content-type': 'text/plain' },262      rawPath: '/',263      rawQueryString: '',264      body: null,265      isBase64Encoded: false,266      requestContext: testApiGatewayRequestContextV2,267    }268269    testApiGatewayRequestContextV2.http.method = 'GET'270271    const response = await handler(event)272    expect(response.statusCode).toBe(200)273    expect(response.body).toBe('Hello Lambda!')274    expect(response.headers['content-type']).toMatch(/^text\/plain/)275    expect(response.multiValueHeaders).toBeUndefined()276    expect(response.isBase64Encoded).toBe(false)277  })278279  it('Should handle a GET request and return a 200 response (ALBEvent)', async () => {280    const event = {281      headers: { 'content-type': 'text/plain' },282      httpMethod: 'GET',283      path: '/',284      queryStringParameters: {285        query: '1234ABCD',286      },287      body: null,288      isBase64Encoded: false,289      requestContext: testALBRequestContext,290    }291292    const response = await handler(event)293    expect(response.statusCode).toBe(200)294    expect(response.body).toBe('Hello Lambda!')295    expect(response.headers['content-type']).toMatch(/^text\/plain/)296    expect(response.multiValueHeaders).toBeUndefined()297    expect(response.isBase64Encoded).toBe(false)298  })299300  it('Should handle a GET request and return a 200 response (LatticeProxyEvent)', async () => {301    const event: LatticeProxyEventV2 = {302      version: '2.0',303      path: '/?query=1234ABCD',304      method: 'GET',305      headers: { 'content-type': ['text/plain'] },306      queryStringParameters: {},307      body: null,308      isBase64Encoded: false,309      requestContext: testLatticeRequestContext,310    }311312    const response = await handler(event)313    expect(response.statusCode).toBe(200)314    expect(response.body).toBe('Hello Lambda!')315    expect(response.headers['content-type']).toMatch(/^text\/plain/)316    expect(response.multiValueHeaders).toBeUndefined()317    expect(response.isBase64Encoded).toBe(false)318  })319320  it('Should handle a GET request and return a 404 response', async () => {321    const event = {322      version: '1.0',323      resource: '/nothing',324      httpMethod: 'GET',325      headers: { 'content-type': 'text/plain' },326      path: '/nothing',327      body: null,328      isBase64Encoded: false,329      requestContext: testApiGatewayRequestContext,330    }331332    const response = await handler(event)333    expect(response.statusCode).toBe(404)334  })335336  it('Should handle a POST request and return a 200 response', async () => {337    const searchParam = new URLSearchParams()338    searchParam.append('message', 'Good Morning Lambda!')339    const event = {340      version: '1.0',341      resource: '/post',342      httpMethod: 'POST',343      headers: {344        'Content-Type': 'application/x-www-form-urlencoded',345      },346      path: '/post',347      body: Buffer.from(searchParam.toString()).toString('base64'),348      isBase64Encoded: true,349      requestContext: testApiGatewayRequestContext,350    }351352    const response = await handler(event)353    expect(response.statusCode).toBe(200)354    expect(response.body).toBe('Good Morning Lambda!')355  })356357  it('Should handle a POST request and return a 200 response (LambdaFunctionUrlEvent)', async () => {358    const searchParam = new URLSearchParams()359    searchParam.append('message', 'Good Morning Lambda!')360    const event = {361      version: '2.0',362      routeKey: '$default',363      headers: {364        'Content-Type': 'application/x-www-form-urlencoded',365      },366      rawPath: '/post',367      rawQueryString: '',368      body: Buffer.from(searchParam.toString()).toString('base64'),369      isBase64Encoded: true,370      requestContext: testApiGatewayRequestContextV2,371    }372373    testApiGatewayRequestContextV2.http.method = 'POST'374375    const response = await handler(event)376    expect(response.statusCode).toBe(200)377    expect(response.body).toBe('Good Morning Lambda!')378  })379380  it('Should handle a POST request with binary and return a 200 response', async () => {381    const array = new Uint8Array([0xc0, 0xff, 0xee])382    const buffer = Buffer.from(array)383    const event = {384      version: '1.0',385      resource: '/post/binary',386      httpMethod: 'POST',387      headers: {388        'Content-Type': 'application/x-www-form-urlencoded',389      },390      path: '/post/binary',391      body: buffer.toString('base64'),392      isBase64Encoded: true,393      requestContext: testApiGatewayRequestContext,394    }395396    const response = await handler(event)397    expect(response.statusCode).toBe(200)398    expect(response.body).toBe('3 bytes')399  })400401  it('Should handle a request and return a 401 response with Basic auth', async () => {402    const event = {403      version: '1.0',404      resource: '/auth/abc',405      httpMethod: 'GET',406      headers: {407        'Content-Type': 'plain/text',408      },409      path: '/auth/abc',410      body: null,411      isBase64Encoded: true,412      requestContext: testApiGatewayRequestContext,413    }414415    const response = await handler(event)416    expect(response.statusCode).toBe(401)417  })418419  it('Should handle a request and return a 200 response with Basic auth', async () => {420    const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'421    const event = {422      version: '1.0',423      resource: '/auth/abc',424      httpMethod: 'GET',425      headers: {426        'Content-Type': 'plain/text',427        Authorization: `Basic ${credential}`,428      },429      path: '/auth/abc',430      body: null,431      isBase64Encoded: true,432      requestContext: testApiGatewayRequestContext,433    }434435    const response = await handler(event)436    expect(response.statusCode).toBe(200)437    expect(response.body).toBe('Good Night Lambda!')438  })439440  it('Should handle a GET request and return custom context', async () => {441    const event = {442      version: '1.0',443      resource: '/custom-context/apigw',444      httpMethod: 'GET',445      headers: { 'content-type': 'application/json' },446      path: '/custom-context/apigw',447      body: null,448      isBase64Encoded: false,449      requestContext: testApiGatewayRequestContext,450    }451452    const response = await handler(event)453    expect(response.statusCode).toBe(200)454    expect(JSON.parse(response.body).customProperty).toEqual('customValue')455  })456457  it('Should handle a GET request and context', async () => {458    const event = {459      version: '1.0',460      resource: '/lambda-context',461      httpMethod: 'GET',462      headers: { 'content-type': 'application/json' },463      path: '/lambda-context',464      body: null,465      isBase64Encoded: false,466      requestContext: testApiGatewayRequestContext,467    }468    const context: LambdaContext = {469      callbackWaitsForEmptyEventLoop: false,470      functionName: 'myLambdaFunction',471      functionVersion: '1.0.0',472      invokedFunctionArn: 'arn:aws:lambda:us-west-2:123456789012:function:myLambdaFunction',473      memoryLimitInMB: '128',474      awsRequestId: 'c6af9ac6-a7b0-11e6-80f5-76304dec7eb7',475      logGroupName: '/aws/lambda/myLambdaFunction',476      logStreamName: '2016/11/14/[$LATEST]f2d4b21cfb33490da2e8f8ef79a483s4',477      getRemainingTimeInMillis: () => {478        return 60000 // 60 seconds479      },480    }481    const response = await handler(event, context)482    expect(response.statusCode).toBe(200)483    expect(JSON.parse(response.body).callbackWaitsForEmptyEventLoop).toEqual(false)484  })485486  it('Should handle a POST request and return a 200 response with cookies set (APIGatewayProxyEvent V1 and V2)', async () => {487    const apiGatewayEvent = {488      version: '1.0',489      resource: '/cookie',490      httpMethod: 'POST',491      headers: { 'content-type': 'text/plain' },492      path: '/cookie',493      body: null,494      isBase64Encoded: false,495      requestContext: testApiGatewayRequestContext,496    }497498    const apiGatewayResponse = await handler(apiGatewayEvent)499500    expect(apiGatewayResponse.statusCode).toBe(200)501    expect(apiGatewayResponse.multiValueHeaders).toHaveProperty('set-cookie', [502      testCookie1.serialized,503      testCookie2.serialized,504    ])505506    const apiGatewayEventV2 = {507      version: '2.0',508      routeKey: '$default',509      httpMethod: 'POST',510      headers: { 'content-type': 'text/plain' },511      rawPath: '/cookie',512      rawQueryString: '',513      body: null,514      isBase64Encoded: false,515      requestContext: testApiGatewayRequestContextV2,516    }517518    const apiGatewayResponseV2 = await handler(apiGatewayEventV2)519520    expect(apiGatewayResponseV2.statusCode).toBe(200)521    expect(apiGatewayResponseV2).toHaveProperty('cookies', [522      testCookie1.serialized,523      testCookie2.serialized,524    ])525  })526527  it('Should handle a POST request and return a 200 response with cookies set (LatticeProxyEvent V2)', async () => {528    const latticeProxyEvent: LatticeProxyEventV2 = {529      version: '2.0',530      path: '/cookie',531      method: 'POST',532      headers: { 'content-type': ['text/plain'] },533      queryStringParameters: {},534      body: null,535      isBase64Encoded: false,536      requestContext: testLatticeRequestContext,537    }538539    const latticeResponse = await handler(latticeProxyEvent)540541    expect(latticeResponse.statusCode).toBe(200)542    expect(latticeResponse.headers).toHaveProperty(543      'set-cookie',544      [testCookie1.serialized, testCookie2.serialized].join(', ')545    )546  })547548  describe('headers', () => {549    describe('single-value headers', () => {550      it('Should extract single-value headers and return 200 (ALBProxyEvent)', async () => {551        const event = {552          body: '{}',553          httpMethod: 'POST',554          isBase64Encoded: false,555          path: '/headers',556          headers: {557            host: 'localhost',558            foo: 'bar',559          },560          requestContext: testALBRequestContext,561        }562        const albResponse = await handler(event)563        expect(albResponse.statusCode).toBe(200)564        expect(albResponse.headers).toEqual(565          expect.objectContaining({566            'content-type': 'application/json',567          })568        )569        expect(albResponse.multiValueHeaders).toBeUndefined()570      })571572      it('Should extract single-value headers and return 200 (APIGatewayProxyEvent)', async () => {573        const apigatewayProxyEvent = {574          version: '1.0',575          resource: '/headers',576          httpMethod: 'POST',577          headers: {578            host: 'localhost',579            foo: 'bar',580          },581          path: '/headers',582          body: null,583          isBase64Encoded: false,584          requestContext: testApiGatewayRequestContext,585        }586        const apiGatewayResponseV2 = await handler(apigatewayProxyEvent)587        expect(apiGatewayResponseV2.statusCode).toBe(200)588      })589590      it('Should extract single-value headers and return 200 (APIGatewayProxyEventV2)', async () => {591        const apigatewayProxyV2Event = {592          version: '2.0',593          routeKey: '$default',594          headers: {595            host: 'localhost',596            foo: 'bar',597          },598          rawPath: '/headers',599          rawQueryString: '',600          requestContext: testApiGatewayRequestContextV2,601          resource: '/headers',602          body: null,603          isBase64Encoded: false,604        }605        const apiGatewayResponseV2 = await handler(apigatewayProxyV2Event)606        expect(apiGatewayResponseV2.statusCode).toBe(200)607      })608    })609610    describe('multi-value headers', () => {611      it('Should extract multi-value headers and return 200 (ALBProxyEvent)', async () => {612        const event = {613          body: '{}',614          httpMethod: 'POST',615          isBase64Encoded: false,616          path: '/headers',617          multiValueHeaders: {618            host: ['localhost'],619            foo: ['bar'],620          },621          requestContext: testALBRequestContext,622        }623        const albResponse = await handler(event)624        expect(albResponse.statusCode).toBe(200)625        expect(albResponse.multiValueHeaders).toBeDefined()626        expect(albResponse.multiValueHeaders).toEqual(627          expect.objectContaining({628            'content-type': ['application/json'],629          })630        )631      })632633      it('Should extract multi-value headers and return 200 (APIGatewayProxyEvent)', async () => {634        const apigatewayProxyEvent = {635          version: '1.0',636          resource: '/headers',637          httpMethod: 'POST',638          headers: {},639          multiValueHeaders: {640            host: ['localhost'],641            foo: ['bar'],642          },643          path: '/headers',644          body: null,645          isBase64Encoded: false,646          requestContext: testApiGatewayRequestContext,647        }648        const apiGatewayResponseV2 = await handler(apigatewayProxyEvent)649        expect(apiGatewayResponseV2.statusCode).toBe(200)650      })651652      it('Should extract multi-value headers and return 200 (LatticeProxyEvent)', async () => {653        const event: LatticeProxyEventV2 = {654          version: '2.0',655          path: '/headers',656          method: 'POST',657          headers: {658            host: ['localhost'],659            foo: ['bar'],660          },661          queryStringParameters: {},662          body: null,663          isBase64Encoded: false,664          requestContext: testLatticeRequestContext,665        }666667        const response = await handler(event)668669        expect(response.statusCode).toBe(200)670      })671    })672  })673674  it('Should handle a POST request and return a 200 response if cookies match (APIGatewayProxyEvent V1 and V2)', async () => {675    const apiGatewayEvent = {676      version: '1.0',677      resource: '/cookie',678      httpMethod: 'GET',679      headers: {680        'content-type': 'text/plain',681        cookie: [testCookie1.serialized, testCookie2.serialized].join('; '),682      },683      path: '/cookie',684      body: null,685      isBase64Encoded: false,686      requestContext: testApiGatewayRequestContext,687    }688689    const apiGatewayResponse = await handler(apiGatewayEvent)690691    expect(apiGatewayResponse.statusCode).toBe(200)692    expect(apiGatewayResponse.body).toBe('Valid Cookies')693    expect(apiGatewayResponse.headers['content-type']).toMatch(/^text\/plain/)694    expect(apiGatewayResponse.isBase64Encoded).toBe(false)695696    const apiGatewayEventV2 = {697      version: '2.0',698      routeKey: '$default',699      headers: { 'content-type': 'text/plain' },700      rawPath: '/cookie',701      cookies: [testCookie1.serialized, testCookie2.serialized],702      rawQueryString: '',703      body: null,704      isBase64Encoded: false,705      requestContext: testApiGatewayRequestContextV2,706    }707    testApiGatewayRequestContextV2.http.method = 'GET'708709    const apiGatewayResponseV2 = await handler(apiGatewayEventV2)710711    expect(apiGatewayResponseV2.statusCode).toBe(200)712    expect(apiGatewayResponseV2.body).toBe('Valid Cookies')713    expect(apiGatewayResponseV2.headers['content-type']).toMatch(/^text\/plain/)714    expect(apiGatewayResponseV2.isBase64Encoded).toBe(false)715  })716717  it('Should handle a GET request and return a 200 response if cookies match (ALBProxyEvent) with default headers', async () => {718    const albEventDefaultHeaders = {719      version: '1.0',720      resource: '/cookie',721      httpMethod: 'GET',722      headers: {723        'content-type': 'text/plain',724        cookie: [testCookie1.serialized, testCookie2.serialized].join('; '),725      },726      path: '/cookie',727      body: null,728      isBase64Encoded: false,729      requestContext: testALBRequestContext,730    }731732    const albResponse = await handler(albEventDefaultHeaders)733734    expect(albResponse.statusCode).toBe(200)735    expect(albResponse.body).toBe('Valid Cookies')736    expect(albResponse.headers['content-type']).toMatch(/^text\/plain/)737    expect(albResponse.multiValueHeaders).toBeUndefined()738    expect(albResponse.isBase64Encoded).toBe(false)739  })740741  it('Should handle a GET request and return a 200 response if cookies match (ALBProxyEvent) with multi value headers', async () => {742    const albEventMultiValueHeaders = {743      version: '1.0',744      resource: '/cookie',745      httpMethod: 'GET',746      multiValueHeaders: {747        'content-type': ['text/plain'],748        cookie: [testCookie1.serialized, testCookie2.serialized],749      },750      path: '/cookie',751      body: null,752      isBase64Encoded: false,753      requestContext: testALBRequestContext,754    }755756    const albResponse = await handler(albEventMultiValueHeaders)757758    expect(albResponse.statusCode).toBe(200)759    expect(albResponse.body).toBe('Valid Cookies')760    expect(albResponse.headers).toBeUndefined()761    expect(albResponse.multiValueHeaders['content-type']).toEqual([762      expect.stringMatching(/^text\/plain/),763    ])764    expect(albResponse.isBase64Encoded).toBe(false)765  })766767  it('Should handle a POST request and return a 200 response with cookies (ALBProxyEvent) with default headers', async () => {768    const albEventDefaultHeaders = {769      version: '1.0',770      resource: '/cookie',771      httpMethod: 'POST',772      headers: {773        'content-type': 'text/plain',774        cookie: [testCookie1.serialized, testCookie2.serialized].join(', '),775      },776      path: '/cookie',777      body: null,778      isBase64Encoded: false,779      requestContext: testALBRequestContext,780    }781782    const albResponse = await handler(albEventDefaultHeaders)783784    expect(albResponse.statusCode).toBe(200)785    expect(albResponse.body).toBe('Cookies Set')786    expect(albResponse.headers['content-type']).toMatch(/^text\/plain/)787    expect(albResponse.multiValueHeaders).toBeUndefined()788    expect(albResponse.headers['set-cookie']).toEqual(789      [testCookie1.serialized, testCookie2.serialized].join(', ')790    )791    expect(albResponse.isBase64Encoded).toBe(false)792  })793794  it('Should handle a POST request and return a 200 response with cookies (ALBProxyEvent) with multi value headers', async () => {795    const albEventDefaultHeaders = {796      version: '1.0',797      resource: '/cookie',798      httpMethod: 'POST',799      multiValueHeaders: {800        'content-type': ['text/plain'],801        cookie: [testCookie1.serialized, testCookie2.serialized],802      },803      path: '/cookie',804      body: null,805      isBase64Encoded: false,806      requestContext: testALBRequestContext,807    }808809    const albResponse = await handler(albEventDefaultHeaders)810811    expect(albResponse.statusCode).toBe(200)812    expect(albResponse.body).toBe('Cookies Set')813    expect(albResponse.headers).toBeUndefined()814    expect(albResponse.multiValueHeaders['set-cookie']).toEqual(815      expect.arrayContaining([testCookie1.serialized, testCookie2.serialized])816    )817    expect(albResponse.isBase64Encoded).toBe(false)818  })819820  it('Should handle a GET request and return a 200 response with queryStringParameters (ALBProxyEvent)', async () => {821    const albEventDefaultHeaders = {822      resource: '/query-params',823      httpMethod: 'GET',824      headers: {825        'content-type': 'application/json',826      },827      queryStringParameters: {828        key1: 'value1',829        key2: 'value2',830      },831      path: '/query-params',832      body: null,833      isBase64Encoded: false,834      requestContext: testALBRequestContext,835    }836837    const albResponse = await handler(albEventDefaultHeaders)838839    expect(albResponse.statusCode).toBe(200)840    expect(albResponse.body).toContain(841      JSON.stringify({842        key1: 'value1',843        key2: 'value2',844      })845    )846    expect(albResponse.headers['content-type']).toMatch(/^application\/json/)847    expect(albResponse.multiValueHeaders).toBeUndefined()848    expect(albResponse.isBase64Encoded).toBe(false)849  })850851  it('Should handle a GET request and return a 200 response with single value multiQueryStringParameters (ALBProxyEvent)', async () => {852    const albEventDefaultHeaders = {853      resource: '/query-params',854      httpMethod: 'GET',855      multiValueHeaders: {856        'content-type': ['application/json'],857      },858      multiValueQueryStringParameters: {859        key1: ['value1'],860        key2: ['value2'],861      },862      path: '/query-params',863      body: null,864      isBase64Encoded: false,865      requestContext: testALBRequestContext,866    }867868    const albResponse = await handler(albEventDefaultHeaders)869870    expect(albResponse.statusCode).toBe(200)871    expect(albResponse.body).toContain(872      JSON.stringify({873        key1: 'value1',874        key2: 'value2',875      })876    )877    expect(albResponse.headers).toBeUndefined()878    expect(albResponse.multiValueHeaders['content-type']).toEqual([879      expect.stringMatching(/^application\/json/),880    ])881    expect(albResponse.isBase64Encoded).toBe(false)882  })883884  it('Should handle a GET request and return a 200 response with multi value multiQueryStringParameters (ALBProxyEvent)', async () => {885    const albEventDefaultHeaders = {886      resource: '/query-params',887      httpMethod: 'GET',888      multiValueHeaders: {889        'content-type': ['application/json'],890      },891      multiValueQueryStringParameters: {892        key1: ['value1'],893        key2: ['value2', 'otherValue2'],894      },895      path: '/multi-query-params',896      body: null,897      isBase64Encoded: false,898      requestContext: testALBRequestContext,899    }900901    const albResponse = await handler(albEventDefaultHeaders)902903    expect(albResponse.statusCode).toBe(200)904    expect(albResponse.body).toContain(905      JSON.stringify({906        key1: ['value1'],907        key2: ['value2', 'otherValue2'],908      })909    )910    expect(albResponse.headers).toBeUndefined()911    expect(albResponse.multiValueHeaders['content-type']).toEqual([912      expect.stringMatching(/^application\/json/),913    ])914    expect(albResponse.isBase64Encoded).toBe(false)915  })916})917918describe('streamHandle function', () => {919  const app = new Hono<{ Bindings: Bindings }>()920921  app.get('/', (c) => {922    return c.text('Hello Lambda!')923  })924925  app.get('/stream/text', async (c) => {926    return streamText(c, async (stream) => {927      for (let i = 0; i < 3; i++) {928        await stream.writeln(`${i}`)929        await stream.sleep(1)930      }931    })932  })933934  app.get('/sse', async (c) => {935    return streamSSE(c, async (stream) => {936      let id = 0937      const maxIterations = 2938939      while (id < maxIterations) {940        const message = `Message\nIt is ${id}`941        await stream.writeSSE({ data: message, event: 'time-update', id: String(id++) })942        await stream.sleep(10)943      }944    })945  })946947  const handler = streamHandle(app)948949  it('Should streamHandle a GET request and return a 200 response (LambdaFunctionUrlEvent)', async () => {950    const event = {951      headers: { 'content-type': ' binary/octet-stream' },952      rawPath: '/stream/text',953      rawQueryString: '',954      body: null,955      isBase64Encoded: false,956      requestContext: testApiGatewayRequestContextV2,957    }958959    testApiGatewayRequestContextV2.http.method = 'GET'960961    const mockReadableStream = new Readable({962      // eslint-disable-next-line @typescript-eslint/no-empty-function963      read() {},964    })965966    mockReadableStream.push('0\n')967    mockReadableStream.push('1\n')968    mockReadableStream.push('2\n')969    mockReadableStream.push('3\n')970    mockReadableStream.push(null) // EOF971972    // @ts-expect-error should this be a ReadbleStream?973    await handler(event, mockReadableStream, vi.fn())974975    const chunks = []976    for await (const chunk of mockReadableStream) {977      chunks.push(chunk)978    }979    expect(chunks.join('')).toContain('0\n1\n2\n3\n')980  })981982  it('Should handle a GET request for an SSE stream and return the correct chunks', async () => {983    const event = {984      headers: { 'content-type': 'text/event-stream' },985      rawPath: '/sse',986      rawQueryString: '',987      body: null,988      isBase64Encoded: false,989      requestContext: testApiGatewayRequestContextV2,990    }991992    testApiGatewayRequestContextV2.http.method = 'GET'993994    const mockReadableStream = new Readable({995      // eslint-disable-next-line @typescript-eslint/no-empty-function996      read() {},997    })998999    const initContentType = {1000      'Content-Type': 'application/vnd.awslambda.http-integration-response',1001    }1002    mockReadableStream.push(JSON.stringify(initContentType))10031004    // Send JSON formatted response headers, followed by 8 NULL characters as a separator1005    const httpResponseMetadata = {1006      statusCode: 200,1007      headers: { 'Custom-Header': 'value' },1008      cookies: ['session=abcd1234'],1009    }1010    const jsonResponsePrelude = JSON.stringify(httpResponseMetadata) + Buffer.alloc(8, 0).toString()1011    mockReadableStream.push(jsonResponsePrelude)10121013    mockReadableStream.push('data: Message\ndata: It is 0\n\n')1014    mockReadableStream.push('data: Message\ndata: It is 1\n\n')1015    mockReadableStream.push(null) // EOF10161017    // @ts-expect-error should this be a ReadbleStream?1018    await handler(event, mockReadableStream, vi.fn())10191020    const chunks = []1021    for await (const chunk of mockReadableStream) {1022      chunks.push(chunk)1023    }10241025    // If you have chunks, you might want to convert them to strings before checking1026    const output = Buffer.concat(chunks).toString()1027    expect(output).toContain('data: Message\ndata: It is 0\n\n')1028    expect(output).toContain('data: Message\ndata: It is 1\n\n')10291030    // Assertions for the newly added header and prelude1031    expect(output).toContain('application/vnd.awslambda.http-integration-response')1032    expect(output).toContain('Custom-Header')1033    expect(output).toContain('session=abcd1234')10341035    // Check for JSON prelude and NULL sequence1036    const nullSequence = '\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000'1037    expect(output).toContain(jsonResponsePrelude.replace(nullSequence, ''))1038  })1039})10401041describe('getProcessor function', () => {1042  it('Should return ALBProcessor for an ALBProxyEvent event', () => {1043    const event: ALBProxyEvent = {1044      httpMethod: 'GET',1045      path: '/',1046      body: null,1047      isBase64Encoded: false,1048      requestContext: {1049        elb: {1050          targetGroupArn:1051            'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a',1052        },1053      },1054    }10551056    const processor = getProcessor(event)1057    expect(processor).toBeInstanceOf(ALBProcessor)1058  })10591060  it('Should return EventV1Processor for an event without requestContext', () => {1061    const event = {1062      httpMethod: 'GET',1063      path: '/',1064      body: null,1065      isBase64Encoded: false,1066    }10671068    // while LambdaEvent RequestContext property is mandatory, it can be absent when testing through invoke-api or AWS Console1069    // in such cases, a V1 processor should be returned1070    const processor = getProcessor(event as unknown as LambdaEvent)1071    expect(processor).toBeInstanceOf(EventV1Processor)1072  })10731074  it('Should return EventV2Processor for an APIGatewayProxyEventV2 event', () => {1075    const event: APIGatewayProxyEventV2 = {1076      version: '2.0',1077      routeKey: '$default',1078      headers: { 'content-type': 'text/plain' },1079      rawPath: '/',1080      rawQueryString: '',1081      body: null,1082      isBase64Encoded: false,1083      requestContext: testApiGatewayRequestContextV2,1084    }10851086    const processor = getProcessor(event)1087    expect(processor).toBeInstanceOf(EventV2Processor)1088  })1089})