-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathat-edge-handler.ts
149 lines (127 loc) · 4.51 KB
/
at-edge-handler.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import { Server } from 'SERVER'
import { manifest } from 'MANIFEST'
import { prerendered, createIndex } from 'PRERENDERED'
import type {
CloudFrontHeaders,
CloudFrontRequestHandler,
CloudFrontResultResponse
} from 'aws-lambda'
import { log, toRawBody } from './util'
import { isBlaclisted } from './header-blacklist'
const server = new Server(manifest)
let envReady = false
export const handler: CloudFrontRequestHandler = async (event, context) => {
log('DEBUG', 'incoming event', event)
if (event.Records.length !== 1) {
log('ERROR', 'bad request', event)
return {
status: '400',
statusDescription: 'bad request',
}
}
const request = event.Records[0].cf.request
const config = event.Records[0].cf.config
const customHeaders = request.origin?.s3?.customHeaders
if (prerendered.includes(request.uri)) {
if (request.uri === '/' || request.uri === '') {
request.uri = '/index.html'
} else {
request.uri = `${request.uri}${createIndex ? '/index.html' : '.html'}`
}
return request
}
if (!envReady && SVELTEKIT_CDK_ENV_MAP && customHeaders) {
for (const headerName in SVELTEKIT_CDK_ENV_MAP) {
process.env[SVELTEKIT_CDK_ENV_MAP[headerName]] = customHeaders[headerName][0].value
}
log('DEBUG', 'process.env', process.env)
envReady = true
}
if (request.body && request.body.inputTruncated) {
log('ERROR', 'input trucated', request)
log('ERROR', 'ref', 'https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/edge-functions-restrictions.html#lambda-at-edge-function-restrictions')
throw new Error("input truncated");
}
const domain = request.headers.host.length > 0 ? request.headers.host[0].value : config.distributionDomainName
const querystring = request.querystring ? `?${request.querystring}` : ''
const input: Request = new Request(`https://${domain}${request.uri}${querystring}`, {
headers: transformIncomingHeaders(request.headers),
method: request.method,
body: request.body && request.body.data.length > 0 ? toRawBody(request.body) : undefined,
})
log('DEBUG', 'render input', input)
const rendered = await server.respond(input)
if (rendered) {
log('DEBUG', 'render output', rendered)
const outgoing: CloudFrontResultResponse = await transformResponse(rendered)
log('DEBUG', 'outgoing response', outgoing)
log('INFO', 'handler', {
path: request.uri,
status: rendered.status,
})
return outgoing
}
log('INFO', 'handler', {
path: request.uri,
status: 404,
})
return {
status: '404',
statusDescription: 'not found',
}
}
function transformIncomingHeaders(headers: CloudFrontHeaders): HeadersInit {
return Object.fromEntries(
Object.entries(headers).map(([k, vs]) => (
[k, vs[0].value]
))
)
}
function bodyEncondingFromMime(mime: string | null): 'base64' | 'text' | undefined {
if (!mime) return undefined
mime = mime.split(';')[0] // remove parameters
if (mime.startsWith('text/')) return 'text'
if (mime.endsWith('+xml')) return 'text'
if ([
'application/json',
'application/xml',
'application/js',
'application/javascript',
].includes(mime)) return 'text'
return 'base64'
}
async function transformResponse(rendered: Response): Promise<CloudFrontResultResponse> {
const bodyEncoding = bodyEncondingFromMime(rendered.headers.get('content-type'))
let body: string | undefined
if (bodyEncoding === 'text') {
body = await rendered.text()
} else if (bodyEncoding === 'base64') {
const aBuf = await rendered.arrayBuffer()
const buf = Buffer.from(aBuf)
body = buf.toString('base64')
}
return {
status: rendered.status.toString(),
headers: transformOutgoingHeaders(rendered.headers),
body,
bodyEncoding,
}
}
function transformOutgoingHeaders(headers: Headers): CloudFrontHeaders {
const rv: CloudFrontHeaders = {}
headers.forEach((v, k) => {
if (isBlaclisted(k.toLowerCase())) return
rv[k.toLowerCase()] = [{
key: k,
value: v,
}]
})
// default to not caching SSR content
if (!rv['cache-control']) {
rv['cache-control'] = [{
key: 'Cache-Control',
value: 'no-store',
}]
}
return rv
}