Skip to content
Myr

handler.ts

This file

Path

src/adapter/lambda-edge/handler.ts

174 lines · 4.5 KiB · TypeScript

Last changed by

feat(lambda-edge): Add Type to request for Lambda@Edge adapter to support S3 origin (#1991)moslebefore adoptiona00fc56

History of this file

Take it

The walk stopped after 200 commits: lines older than 2f9a07d point at it.

perf(hono-base): use `instanceOf` (#1565)Yusuke Wadabefore adoption2f9a07d

lines 1–29why, one step back
1// @denoify-ignore
2import crypto from 'crypto'3import type { Hono } from '../../hono'45import { encodeBase64 } from '../../utils/encode'67// eslint-disable-next-line @typescript-eslint/ban-ts-comment8// @ts-ignore9globalThis.crypto ??= crypto1011interface CloudFrontHeader {12 key: string13 value: string14}1516interface CloudFrontHeaders {17 [name: string]: CloudFrontHeader[]18}1920interface CloudFrontCustomOrigin {21 customHeaders: CloudFrontHeaders22 domainName: string23 keepaliveTimeout: number24 path: string25 port: number26 protocol: string27 readTimeout: number28 sslProtocols: string[]29}

feat(lambda-edge): Add Type to request for Lambda@Edge adapter to support S3 origin (#1991)moslebefore adoptiona00fc56

lines 30–40why, one step back
30// https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html
31interface CloudFrontS3Origin {32 authMethod: 'origin-access-identity' | 'none'33 customHeaders: CloudFrontHeaders34 domainName: string35 path: string36 region: string37}38type CloudFrontOrigin =39 | { s3: CloudFrontS3Origin; custom?: never }40 | { custom: CloudFrontCustomOrigin; s3?: never }

perf(hono-base): use `instanceOf` (#1565)Yusuke Wadabefore adoption2f9a07d

lines 41–53why, one step back
41
42export interface CloudFrontRequest {43 clientIp: string44 headers: CloudFrontHeaders45 method: string46 querystring: string47 uri: string48 body?: {49 inputTruncated: boolean50 action: string51 encoding: string52 data: string53 }

feat(lambda-edge): Add Type to request for Lambda@Edge adapter to support S3 origin (#1991)moslebefore adoptiona00fc56

line 54why, one step back
54 origin?: CloudFrontOrigin

perf(hono-base): use `instanceOf` (#1565)Yusuke Wadabefore adoption2f9a07d

lines 55–142why, one step back
55}
5657export interface CloudFrontResponse {58 headers: CloudFrontHeaders59 status: string60 statusDescription?: string61}6263export interface CloudFrontConfig {64 distributionDomainName: string65 distributionId: string66 eventType: string67 requestId: string68}6970interface CloudFrontEvent {71 cf: {72 config: CloudFrontConfig73 request: CloudFrontRequest74 response?: CloudFrontResponse75 }76}7778export interface CloudFrontEdgeEvent {79 Records: CloudFrontEvent[]80}8182type CloudFrontContext = {}8384export interface Callback {85 (err: Error | null, result?: CloudFrontRequest | CloudFrontResult): void86}8788// https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-generating-http-responses-in-requests.html#lambda-generating-http-responses-programming-model89interface CloudFrontResult {90 status: string91 statusDescription?: string92 headers?: {93 [header: string]: {94 key: string95 value: string96 }[]97 }98 body?: string99 bodyEncoding?: 'text' | 'base64'100}101102/**103 * Accepts events from 'Lambda@Edge' event104 * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html105 */106const convertHeaders = (headers: Headers): CloudFrontHeaders => {107 const cfHeaders: CloudFrontHeaders = {}108 headers.forEach((value, key) => {109 cfHeaders[key.toLowerCase()] = [{ key: key.toLowerCase(), value }]110 })111 return cfHeaders112}113114// eslint-disable-next-line @typescript-eslint/no-explicit-any115export const handle = (app: Hono<any>) => {116 return async (117 event: CloudFrontEdgeEvent,118 context?: CloudFrontContext,119 callback?: Callback120 ): Promise<CloudFrontResult> => {121 const res = await app.fetch(createRequest(event), {122 event,123 context,124 callback: (err: Error | null, result?: CloudFrontResult | CloudFrontRequest) => {125 callback?.(err, result)126 },127 config: event.Records[0].cf.config,128 request: event.Records[0].cf.request,129 response: event.Records[0].cf.response,130 })131 return createResult(res)132 }133}134135const createResult = async (res: Response): Promise<CloudFrontResult> => {136 const isBase64Encoded = isContentTypeBinary(res.headers.get('content-type') || '')137 const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()138139 return {140 status: res.status.toString(),141 headers: convertHeaders(res.headers),142 body,

fix(lambda@edge): add bodyEncoding property for base64 response (#1949)moslebefore adoption92e3556

line 143why, one step back
143 ...(isBase64Encoded ? { bodyEncoding: 'base64' } : {}),

perf(hono-base): use `instanceOf` (#1565)Yusuke Wadabefore adoption2f9a07d

lines 144–170why, one step back
144 }
145}146147const createRequest = (event: CloudFrontEdgeEvent) => {148 const queryString = event.Records[0].cf.request.querystring149 const urlPath = `https://${event.Records[0].cf.config.distributionDomainName}${event.Records[0].cf.request.uri}`150 const url = queryString ? `${urlPath}?${queryString}` : urlPath151152 const headers = new Headers()153 Object.entries(event.Records[0].cf.request.headers).forEach(([k, v]) => {154 v.forEach((header) => headers.set(k, header.value))155 })156157 const requestBody = event.Records[0].cf.request.body158 const body =159 requestBody?.encoding === 'base64' && requestBody?.data160 ? Buffer.from(requestBody.data, 'base64')161 : requestBody?.data162163 return new Request(url, {164 headers,165 method: event.Records[0].cf.request.method,166 body,167 })168}169170export const isContentTypeBinary = (contentType: string) => {

fix: add missing tail to svg regex (#1788)Elias Brangebefore adoption521db64

line 171why, one step back
171 return !/^(text\/(plain|html|css|javascript|csv).*|application\/(.*json|.*xml).*|image\/svg\+xml.*)$/.test(

perf(hono-base): use `instanceOf` (#1565)Yusuke Wadabefore adoption2f9a07d

lines 172–174why, one step back
172 contentType
173 )174}