handler.ts
This file
Path
src/adapter/aws-lambda/handler.ts
726 lines 路 22.2 KiB 路 TypeScript
Last changed by
feat(adapters): add the seven adapters as workspace packages (#5463)Yusuke Wadabefore adoptionb877827
History of this fileTake it
1import { pipeline } from 'node:stream/promises'2import type { Hono } from '../../hono'3import type { Env, Schema } from '../../types'4import { decodeBase64, encodeBase64 } from '../../utils/encode'5import type {6 ALBRequestContext,7 ApiGatewayRequestContext,8 ApiGatewayRequestContextV2,9 Handler,10 LambdaContext,11 LatticeRequestContextV2,12} from './types'1314function 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}2324/**25 * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.26 */27export type LambdaEvent =28 | APIGatewayProxyEvent29 | APIGatewayProxyEventV230 | ALBProxyEvent31 | LatticeProxyEventV23233/**34 * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.35 */36export interface LatticeProxyEventV2 {37 version: string38 path: string39 method: string40 headers: Record<string, string[] | undefined>41 queryStringParameters: Record<string, string[] | undefined>42 body: string | null43 isBase64Encoded: boolean44 requestContext: LatticeRequestContextV245}4647// 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 */51export interface APIGatewayProxyEventV2 {52 version: string53 routeKey: string54 headers: Record<string, string | undefined>55 multiValueHeaders?: undefined56 cookies?: string[]57 rawPath: string58 rawQueryString: string59 body: string | null60 isBase64Encoded: boolean61 requestContext: ApiGatewayRequestContextV262 queryStringParameters?: {63 [name: string]: string | undefined64 }65 pathParameters?: {66 [name: string]: string | undefined67 }68 stageVariables?: {69 [name: string]: string | undefined70 }71}7273// 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 */77export interface APIGatewayProxyEvent {78 version: string79 httpMethod: string80 headers: Record<string, string | undefined>81 multiValueHeaders?: {82 [headerKey: string]: string[]83 }84 path: string85 body: string | null86 isBase64Encoded: boolean87 queryStringParameters?: Record<string, string | undefined>88 requestContext: ApiGatewayRequestContext89 resource: string90 multiValueQueryStringParameters?: {91 [parameterKey: string]: string[]92 }93 pathParameters?: Record<string, string>94 stageVariables?: Record<string, string>95}9697// 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 */101export interface ALBProxyEvent {102 httpMethod: string103 headers?: Record<string, string | undefined>104 multiValueHeaders?: Record<string, string[] | undefined>105 path: string106 body: string | null107 isBase64Encoded: boolean108 queryStringParameters?: Record<string, string | undefined>109 multiValueQueryStringParameters?: {110 [parameterKey: string]: string[]111 }112 requestContext: ALBRequestContext113}114115type WithHeaders = {116 headers: Record<string, string | string[]>117 multiValueHeaders?: undefined118}119type WithMultiValueHeaders = {120 headers?: undefined121 multiValueHeaders: Record<string, string[]>122}123124/**125 * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.126 */127export type APIGatewayProxyResult = {128 statusCode: number129 statusDescription?: string130 body: string131 cookies?: string[]132 isBase64Encoded: boolean133} & (WithHeaders | WithMultiValueHeaders)134135const getRequestContext = (136 event: LambdaEvent137):138 | ApiGatewayRequestContext139 | ApiGatewayRequestContextV2140 | ALBRequestContext141 | LatticeRequestContextV2 => {142 return event.requestContext143}144145async function* readWebStream(146 reader: ReadableStreamDefaultReader<Uint8Array>147): AsyncGenerator<Uint8Array> {148 let readResult = await reader.read()149 while (!readResult.done) {150 yield readResult.value151 readResult = await reader.read()152 }153}154155const streamToNodeStream = (156 reader: ReadableStreamDefaultReader<Uint8Array>,157 writer: NodeJS.WritableStream158): Promise<void> => pipeline(readWebStream(reader), writer)159160/**161 * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.162 */163export const streamHandle = <164 E extends Env = Env,165 S extends Schema = {},166 BasePath extends string = '/',167>(168 app: Hono<E, S, BasePath>169): Handler => {170 // @ts-expect-error awslambda is not a standard API171 return awslambda.streamifyResponse(172 async (event: LambdaEvent, responseStream: NodeJS.WritableStream, context: LambdaContext) => {173 const processor = getProcessor(event)174 try {175 const req = processor.createRequest(event)176 const requestContext = getRequestContext(event)177178 const res = await app.fetch(req, {179 event,180 requestContext,181 context,182 })183184 const headers: Record<string, string> = {}185 const cookies: string[] = []186 res.headers.forEach((value, name) => {187 if (name === 'set-cookie') {188 cookies.push(value)189 } else {190 headers[name] = value191 }192 })193194 // Check content type195 const httpResponseMetadata = {196 statusCode: res.status,197 headers,198 cookies,199 }200201 // Update response stream202 // @ts-expect-error awslambda is not a standard API203 responseStream = awslambda.HttpResponseStream.from(responseStream, httpResponseMetadata)204205 if (res.body) {206 await streamToNodeStream(res.body.getReader(), responseStream)207 } else {208 responseStream.write('')209 }210 } catch (error) {211 console.error('Error processing request:', error)212 responseStream.write('Internal Server Error')213 } finally {214 responseStream.end()215 }216 }217 )218}219220type HandleOptions = {221 isContentTypeBinary: ((contentType: string) => boolean) | undefined222}223224/**225 * Converts a Hono application to an AWS Lambda handler.226 *227 * Accepts events from API Gateway (v1 and v2), Application Load Balancer (ALB),228 * and Lambda Function URLs.229 *230 * @param app - The Hono application instance231 * @param options - Optional configuration232 * @param options.isContentTypeBinary - A function to determine if the content type is binary.233 * If not provided, the default function will be used.234 * @returns Lambda handler function235 *236 * @example237 * ```js238 * import { Hono } from 'hono'239 * import { handle } from 'hono/aws-lambda'240 *241 * const app = new Hono()242 *243 * app.get('/', (c) => c.text('Hello from Lambda'))244 * app.get('/json', (c) => c.json({ message: 'Hello JSON' }))245 *246 * export const handler = handle(app)247 * ```248 *249 * @example250 * ```js251 * // With custom binary content type detection252 * import { handle, defaultIsContentTypeBinary } from 'hono/aws-lambda'253 * export const handler = handle(app, {254 * isContentTypeBinary: (contentType) => {255 * if (defaultIsContentTypeBinary(contentType)) {256 * // default logic same as prior to v4.8.4257 * return true258 * }259 * 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 */265export const handle = <E extends Env = Env, S extends Schema = {}, BasePath extends string = '/'>(266 app: Hono<E, S, BasePath>,267 { isContentTypeBinary }: HandleOptions = { isContentTypeBinary: undefined }268): (<L extends LambdaEvent>(269 event: L,270 lambdaContext?: LambdaContext271) => Promise<272 APIGatewayProxyResult &273 (L extends { multiValueHeaders: Record<string, string[]> }274 ? WithMultiValueHeaders275 : WithHeaders)276>) => {277 // @ts-expect-error conditional return type is not inferable278 return async (event, lambdaContext?) => {279 const processor = getProcessor(event)280281 let req, requestContext282 try {283 req = processor.createRequest(event)284 requestContext = getRequestContext(event)285 } catch (error) {286 console.error('Error processing request:', error)287 const errorResponse =288 error instanceof TypeError289 ? new Response('Invalid request', { status: 400 })290 : new Response('Internal Server Error', { status: 500 })291 return processor.createResult(event, errorResponse, { isContentTypeBinary })292 }293294 const res = await app.fetch(req, {295 event,296 requestContext,297 lambdaContext,298 })299300 return processor.createResult(event, res, { isContentTypeBinary })301 }302}303304/**305 * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.306 */307export abstract class EventProcessor<E extends LambdaEvent> {308 protected abstract getPath(event: E): string309310 protected abstract getMethod(event: E): string311312 protected abstract getQueryString(event: E): string313314 protected abstract getHeaders(event: E): Headers315316 protected abstract getCookies(event: E, headers: Headers): void317318 protected abstract setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void319320 protected getHeaderValue(headers: E['headers'], key: string): string | undefined {321 const value = headers322 ? Array.isArray(headers[key])323 ? headers[key][0]324 : headers[key]325 : undefined326327 return value328 }329330 protected getDomainName(event: E): string | undefined {331 if (event.requestContext && 'domainName' in event.requestContext) {332 return event.requestContext.domainName333 }334335 const hostFromHeaders = this.getHeaderValue(event.headers, 'host')336337 if (hostFromHeaders) {338 return hostFromHeaders339 }340341 const multiValueHeaders = 'multiValueHeaders' in event ? event.multiValueHeaders : {}342 const hostFromMultiValueHeaders = this.getHeaderValue(multiValueHeaders, 'host')343344 return hostFromMultiValueHeaders345 }346347 createRequest(event: E): Request {348 const queryString = this.getQueryString(event)349 const domainName = this.getDomainName(event)350 const path = this.getPath(event)351 const urlPath = `https://${domainName}${path}`352 const url = queryString ? `${urlPath}?${queryString}` : urlPath353354 const headers = this.getHeaders(event)355356 const method = this.getMethod(event)357 const requestInit: RequestInit = {358 headers,359 method,360 }361362 if (event.body) {363 const body = event.isBase64Encoded364 ? decodeBase64(event.body)365 : new TextEncoder().encode(event.body)366 requestInit.body = body367 headers.set('content-length', body.length.toString())368 }369370 return new Request(url, requestInit)371 }372373 async createResult(374 event: E,375 res: Response,376 options: Pick<HandleOptions, 'isContentTypeBinary'>377 ): Promise<APIGatewayProxyResult> {378 // determine whether the response body should be base64 encoded379 const contentType = res.headers.get('content-type')380 const isContentTypeBinary = options.isContentTypeBinary ?? defaultIsContentTypeBinary // overwrite default function if provided381 let isBase64Encoded = contentType && isContentTypeBinary(contentType) ? true : false382383 if (!isBase64Encoded) {384 const contentEncoding = res.headers.get('content-encoding')385 isBase64Encoded = isContentEncodingBinary(contentEncoding)386 }387388 const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()389390 const result: APIGatewayProxyResult = {391 body: body,392 statusCode: res.status,393 isBase64Encoded,394 ...('multiValueHeaders' in event && event.multiValueHeaders395 ? {396 multiValueHeaders: {},397 }398 : {399 headers: {},400 }),401 }402403 this.setCookies(event, res, result)404 if (result.multiValueHeaders) {405 res.headers.forEach((value, key) => {406 result.multiValueHeaders[key] = [value]407 })408 } else {409 res.headers.forEach((value, key) => {410 result.headers[key] = value411 })412 }413414 return result415 }416417 setCookies(_event: E, res: Response, result: APIGatewayProxyResult) {418 if (res.headers.has('set-cookie')) {419 const cookies = res.headers.getSetCookie420 ? res.headers.getSetCookie()421 : Array.from(res.headers.entries())422 .filter(([k]) => k === 'set-cookie')423 .map(([, v]) => v)424425 if (Array.isArray(cookies)) {426 this.setCookiesToResult(result, cookies)427 res.headers.delete('set-cookie')428 }429 }430 }431}432433/**434 * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.435 */436export class EventV2Processor extends EventProcessor<APIGatewayProxyEventV2> {437 protected getPath(event: APIGatewayProxyEventV2): string {438 return event.rawPath439 }440441 protected getMethod(event: APIGatewayProxyEventV2): string {442 return event.requestContext.http.method443 }444445 protected getQueryString(event: APIGatewayProxyEventV2): string {446 return event.rawQueryString447 }448449 protected getCookies(event: APIGatewayProxyEventV2, headers: Headers): void {450 if (Array.isArray(event.cookies)) {451 headers.set('Cookie', event.cookies.join('; '))452 }453 }454455 protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {456 result.cookies = cookies457 }458459 protected getHeaders(event: APIGatewayProxyEventV2): Headers {460 const headers = new Headers()461 this.getCookies(event, headers)462 if (event.headers) {463 for (const [k, v] of Object.entries(event.headers)) {464 if (v) {465 headers.set(k, v)466 }467 }468 }469 return headers470 }471}472473const v2Processor: EventV2Processor = new EventV2Processor()474475/**476 * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.477 */478export class EventV1Processor extends EventProcessor<APIGatewayProxyEvent> {479 protected getPath(event: APIGatewayProxyEvent): string {480 return event.path481 }482483 protected getMethod(event: APIGatewayProxyEvent): string {484 return event.httpMethod485 }486487 protected getQueryString(event: APIGatewayProxyEvent): string {488 // In the case of gateway Integration either queryStringParameters or multiValueQueryStringParameters can be present not both489 // API Gateway passes decoded values, so we need to re-encode them to preserve the original URL490 if (event.multiValueQueryStringParameters) {491 return Object.entries(event.multiValueQueryStringParameters || {})492 .filter(([, value]) => value)493 .map(([key, values]) =>494 values.map((value) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join('&')495 )496 .join('&')497 } else {498 return Object.entries(event.queryStringParameters || {})499 .filter(([, value]) => value !== undefined)500 .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value || '')}`)501 .join('&')502 }503 }504505 protected getCookies(_event: APIGatewayProxyEvent, _headers: Headers): void {506 // nop507 }508509 protected getHeaders(event: APIGatewayProxyEvent): Headers {510 const headers = new Headers()511 this.getCookies(event, headers)512 if (event.multiValueHeaders) {513 for (const [k, values] of Object.entries(event.multiValueHeaders)) {514 if (values) {515 values.forEach((v) => headers.append(k, sanitizeHeaderValue(v)))516 }517 }518 }519 if (event.headers) {520 for (const [k, v] of Object.entries(event.headers)) {521 if (v && !headers.has(k)) {522 headers.set(k, sanitizeHeaderValue(v))523 }524 }525 }526 return headers527 }528529 protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {530 result.multiValueHeaders = {531 'set-cookie': cookies,532 }533 }534}535536const v1Processor: EventV1Processor = new EventV1Processor()537538/**539 * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.540 */541export 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 field545 // https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html#multi-value-headers546 if (event.multiValueHeaders) {547 for (const [key, values] of Object.entries(event.multiValueHeaders)) {548 if (values && Array.isArray(values)) {549 // https://www.rfc-editor.org/rfc/rfc9110.html#name-common-rules-for-defining-f550 const sanitizedValue = sanitizeHeaderValue(values.join('; '))551 headers.set(key, sanitizedValue)552 }553 }554 } else {555 for (const [key, value] of Object.entries(event.headers ?? {})) {556 if (value) {557 headers.set(key, sanitizeHeaderValue(value))558 }559 }560 }561 return headers562 }563564 protected getPath(event: ALBProxyEvent): string {565 return event.path566 }567568 protected getMethod(event: ALBProxyEvent): string {569 return event.httpMethod570 }571572 protected getQueryString(event: ALBProxyEvent): string {573 // In the case of ALB Integration either queryStringParameters or multiValueQueryStringParameters can be present not both574 /*575 In other cases like when using the serverless framework, the event object does contain both queryStringParameters and multiValueQueryStringParameters:576 Below is an example event object for this URL: /payment/b8c55e69?select=amount&select=currency577 {578 ...579 queryStringParameters: { select: 'currency' },580 multiValueQueryStringParameters: { select: [ 'amount', 'currency' ] },581 }582 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.583 A simple fix would be to invert the if statement and check the multiValueQueryStringParameters first.584 */585 if (event.multiValueQueryStringParameters) {586 return Object.entries(event.multiValueQueryStringParameters || {})587 .filter(([, value]) => value)588 .map(([key, value]) => `${key}=${value.join(`&${key}=`)}`)589 .join('&')590 } else {591 return Object.entries(event.queryStringParameters || {})592 .filter(([, value]) => value !== undefined)593 .map(([key, value]) => `${key}=${value}`)594 .join('&')595 }596 }597598 protected getCookies(event: ALBProxyEvent, headers: Headers): void {599 let cookie600 if (event.multiValueHeaders) {601 cookie = event.multiValueHeaders['cookie']?.join('; ')602 } else {603 cookie = event.headers ? event.headers['cookie'] : undefined604 }605 if (cookie) {606 headers.append('Cookie', cookie)607 }608 }609610 protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {611 // when multi value headers is enabled612 if (result.multiValueHeaders) {613 result.multiValueHeaders['set-cookie'] = cookies614 } else {615 result.headers['set-cookie'] = cookies[0]616 }617 }618}619620const albProcessor: ALBProcessor = new ALBProcessor()621622/**623 * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.624 */625export class LatticeV2Processor extends EventProcessor<LatticeProxyEventV2> {626 protected getPath(event: LatticeProxyEventV2): string {627 return event.path628 }629630 protected getMethod(event: LatticeProxyEventV2): string {631 return event.method632 }633634 protected getQueryString(): string {635 return ''636 }637638 protected getHeaders(event: LatticeProxyEventV2): Headers {639 const headers = new Headers()640641 if (event.headers) {642 for (const [k, values] of Object.entries(event.headers)) {643 if (values) {644 values.forEach((v) => headers.append(k, sanitizeHeaderValue(v)))645 }646 }647 }648649 return headers650 }651652 protected getCookies(): void {653 // nop654 }655656 protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {657 result.headers = {658 ...result.headers,659 'set-cookie': cookies,660 }661 }662}663664const latticeV2Processor: LatticeV2Processor = new LatticeV2Processor()665666/**667 * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.668 */669export const getProcessor = (event: LambdaEvent): EventProcessor<LambdaEvent> => {670 if (isProxyEventALB(event)) {671 return albProcessor672 }673 if (isProxyEventV2(event)) {674 return v2Processor675 }676 if (isLatticeEventV2(event)) {677 return latticeV2Processor678 }679680 return v1Processor681}682683const isProxyEventALB = (event: LambdaEvent): event is ALBProxyEvent => {684 if (event.requestContext) {685 return Object.hasOwn(event.requestContext, 'elb')686 }687 return false688}689690const isProxyEventV2 = (event: LambdaEvent): event is APIGatewayProxyEventV2 => {691 // A V1 (REST API) event behind a custom domain base path mapping also carries a692 // `rawPath`, so `rawPath` alone is not enough to identify a V2 event. Every V2693 // (HTTP API / function URL) event has an `http` object on its request context.694 return Object.hasOwn(event, 'rawPath') && Object.hasOwn(event.requestContext ?? {}, 'http')695}696697const isLatticeEventV2 = (event: LambdaEvent): event is LatticeProxyEventV2 => {698 if (event.requestContext) {699 return Object.hasOwn(event.requestContext, 'serviceArn')700 }701 return false702}703704/**705 * 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 */711export const defaultIsContentTypeBinary = (contentType: string): boolean => {712 if (/^application\/vnd\.(?:apple\.installer|mozilla\.xul)\+xml\s*(?:;|$)/i.test(contentType)) {713 return true714 }715716 return !/^text\/(?:plain|html|css|javascript|csv)|(?:\/|\+)(?:json|xml)\s*(?:;|$)/i.test(717 contentType718 )719}720721/**722 * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.723 */724export const isContentEncodingBinary = (contentEncoding: string | null) => {725 return !!contentEncoding && !/^identity$/i.test(contentEncoding)726}