handler.ts
This file
Path
src/adapter/lambda-edge/handler.ts
164 lines · 4.1 KiB · TypeScript
Last changed by
fix: add missing tail to svg regex (#1788)Elias Brangebefore adoption521db64
History of this fileTake it
The walk stopped after 200 commits: lines older than 48a8729 point at it.
perf(hono-base): use `constructor.name` instead of `instanceof` (#1311)Yusuke Wadabefore adoption48a8729
lines 1–147why, one step back1// @denoify-ignore2import 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}3031export interface CloudFrontRequest {32 clientIp: string33 headers: CloudFrontHeaders34 method: string35 querystring: string36 uri: string37 body?: {38 inputTruncated: boolean39 action: string40 encoding: string41 data: string42 }43 origin?: {44 custom: CloudFrontCustomOrigin45 }46}4748export interface CloudFrontResponse {49 headers: CloudFrontHeaders50 status: string51 statusDescription?: string52}5354export interface CloudFrontConfig {55 distributionDomainName: string56 distributionId: string57 eventType: string58 requestId: string59}6061interface CloudFrontEvent {62 cf: {63 config: CloudFrontConfig64 request: CloudFrontRequest65 response?: CloudFrontResponse66 }67}6869export interface CloudFrontEdgeEvent {70 Records: CloudFrontEvent[]71}7273type CloudFrontContext = {}7475export interface Callback {76 (err: Error | null, result?: CloudFrontRequest | CloudFrontResult): void77}7879// https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-generating-http-responses-in-requests.html#lambda-generating-http-responses-programming-model80interface CloudFrontResult {81 status: string82 statusDescription?: string83 headers?: {84 [header: string]: {85 key: string86 value: string87 }[]88 }89 body?: string90 bodyEncoding?: 'text' | 'base64'91}9293/**94 * Accepts events from 'Lambda@Edge' event95 * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html96 */97const convertHeaders = (headers: Headers): CloudFrontHeaders => {98 const cfHeaders: CloudFrontHeaders = {}99 headers.forEach((value, key) => {100 cfHeaders[key.toLowerCase()] = [{ key: key.toLowerCase(), value }]101 })102 return cfHeaders103}104105// eslint-disable-next-line @typescript-eslint/no-explicit-any106export const handle = (app: Hono<any>) => {107 return async (108 event: CloudFrontEdgeEvent,109 context?: CloudFrontContext,110 callback?: Callback111 ): Promise<CloudFrontResult> => {112 const res = await app.fetch(createRequest(event), {113 event,114 context,115 callback: (err: Error | null, result?: CloudFrontResult | CloudFrontRequest) => {116 callback?.(err, result)117 },118 config: event.Records[0].cf.config,119 request: event.Records[0].cf.request,120 response: event.Records[0].cf.response,121 })122 return createResult(res)123 }124}125126const createResult = async (res: Response): Promise<CloudFrontResult> => {127 const isBase64Encoded = isContentTypeBinary(res.headers.get('content-type') || '')128 const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()129130 return {131 status: res.status.toString(),132 headers: convertHeaders(res.headers),133 body,134 }135}136137const createRequest = (event: CloudFrontEdgeEvent) => {138 const queryString = event.Records[0].cf.request.querystring139 const urlPath = `https://${event.Records[0].cf.config.distributionDomainName}${event.Records[0].cf.request.uri}`140 const url = queryString ? `${urlPath}?${queryString}` : urlPath141142 const headers = new Headers()143 Object.entries(event.Records[0].cf.request.headers).forEach(([k, v]) => {144 v.forEach((header) => headers.set(k, header.value))145 })146147 const requestBody = event.Records[0].cf.request.bodychore: add `format` script (#1334)watanybefore adoption954c06e
lines 148–149why, one step back148 const body =149 requestBody?.encoding === 'base64' && requestBody?.dataperf(hono-base): use `constructor.name` instead of `instanceof` (#1311)Yusuke Wadabefore adoption48a8729
lines 150–160why, one step back150 ? Buffer.from(requestBody.data, 'base64')151 : requestBody?.data152153 return new Request(url, {154 headers,155 method: event.Records[0].cf.request.method,156 body,157 })158}159160export const isContentTypeBinary = (contentType: string) => {fix: add missing tail to svg regex (#1788)Elias Brangebefore adoption521db64
line 161why, one step back161 return !/^(text\/(plain|html|css|javascript|csv).*|application\/(.*json|.*xml).*|image\/svg\+xml.*)$/.test(perf(hono-base): use `constructor.name` instead of `instanceof` (#1311)Yusuke Wadabefore adoption48a8729
lines 162–164why, one step back162 contentType163 )164}