Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
Latest commit
executable file
·271 lines (225 loc) · 6.03 KB
/
Copy pathserver.js
File metadata and controls
executable file
·271 lines (225 loc) · 6.03 KB
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
#!/usr/bin/env node
/**
* lambda-edge-server
* AWS CloudFront Lambda@Edge handler function emulator.
*
* Copyright 2023-2025, Marc S. Brooks (https://mbrooks.info)
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*/
'use strict';
const{Command}=require('commander');
constfs=require('fs');
consthttp=require('http');
consturl=require('url');
constSERVER_PORT=3000;
// Process CLI options.
constprogram=newCommand();
program
.usage('[options]')
.option('--handler <path>','Lambda@Edge handler script.')
.option('--port <number>','HTTP server port number.',SERVER_PORT)
.option('--silent','Disable logging Router events to STDOUT',false)
.action(function(opts){
consterrors=[];
try{
constscript=process.cwd()+'/'+opts.handler;
// Validate option values.
if(opts.handler&&!fs.existsSync(script)||!opts.handler){
errors.push(" option '--handler <path>' allows path Lambda@Edge handler script");
}
if(opts.port&&!/^[0-9]{2,5}$/.test(opts.port)){
errors.push(" option '--port <number>' allows up to 5 numeric characters");
}
if(errors.length){
console.error('error: Invalid script arguments');
thrownewError(errors.join('\n'));
}
const{handler}=require(script);
if(isValidFunc(handler)){
returninitServer(handler,opts.port,!opts.silent);
}
thrownewError('error: Invalid handler method');
}catch(err){
if(errinstanceofError){
console.error(`${err.message}\n`);
}
this.outputHelp();
}
});
// Skip Commander options during testing.
if(process.env.NODE_ENV==='test'){
const{handler}=require(process.env.TEST_HANDLER);
module.exports=initServer(handler,SERVER_PORT);
}else{
program.parse();
}
/**
* Init Lambda@Edge emulator environment.
*
* @param {Function} handler
* Lambda function method.
*
* @param {Function} port
* HTTP server port number.
*
* @param {Boolean} logRouterEvents
* Log Router events to STDOUT (default: true).
*
* @return {Object}
*
* @see https://docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html
*/
functioninitServer(handler,port,logRouterEvents=true){
constserver=http.createServer(function(req,res){
letbody='';
req.on('data',function(data){
body+=data;
});
req.on('end',function(){
constpath=url.parse(req.url).pathname;
constquery=url.parse(req.url).query;
if(body){
body=encodeBody(body);
}
// Simulate AWS origin-request event.
constevent={
Records: [
{
cf: {
request: {
clientIp: res.socket?.remoteAddress,
headers: formatHeaders(req.headers).toEdge(),
method: req.method,
querystring: query,
uri: path,
body: {
data: body
}
}
}
}
]
};
// .. and callback() application handler.
constcallback=function(request,response){
let{body, bodyEncoding, headers, status}=response;
if(headers){
headers=formatHeaders(response.headers).toNode();
headers.map(header=>res.setHeader(header.key,header.value));
}
// Override Edge required media encoding.
if(bodyEncoding==='base64'){
body=Buffer.from(body,'base64');
}
if(status){
res.statusCode=status;
}
res.end(body);
};
try{
// Run lambda-lambda-lambda
if(isAsyncFunc(handler)||isPromise(handler)){
// Asynchronous handling.
handler(event)
.then(function(response){
callback(null,response);
});
}else{
// Synchronous handling.
handler(event,null,callback);
}
logRouterEvents&&console.log(Date.now(),req.method,path,JSON.stringify(event));
}catch(err){
logRouterEvents&&this.emit('error',err);
}
});
});
// Start HTTP server; increment port if used.
returnserver
.listen(port,()=>{
console.info(`HTTP server started. Listening on port ${port}`);
})
.on('error',function(err){
if(err.code==='EADDRINUSE'){
this.close();
console.error(`Port ${port} in use. Trying another port.`);
initServer(handler,port+1);
}
});
}
/**
* Return base64 encoded body as string.
*
* @param {String} str
* Body data as string.
*
* @return {String}
*/
functionencodeBody(str){
returnBuffer.from(str).toString('base64');
}
/**
* Return converted headers (lambda/node).
*
* @param {Object} obj
* Node request headers object.
*
* @return {Object}
*/
functionformatHeaders(obj){
return{
// Request format.
toEdge: function(){
Object.keys(obj).forEach(function(key){
obj[key]=[{
key,
value: obj[key]
}];
});
returnobj;
},
// Response format.
toNode: function(){
returnObject.keys(obj).map(function(key){
return{
key,
value: obj[key][0].value
};
});
}
};
}
/**
* Check if value is an async function.
*
* @param {AsyncFunction} func
* Async function.
*
* @return {Boolean}
*/
functionisAsyncFunc(value){
return(value&&(value[Symbol.toStringTag]==='AsyncFunction'));
}
/**
* Check if object is Promise.
*
* @param {Object} obj
* Promise object.
*
* @return {Boolean}
*/
functionisPromise(obj){
return(obj&&(obj[Symbol.toStringTag]==='Promise'||typeofobj.then==='function'));
}
/**
* Check if valid handler function.
*
* @param {Function} value
* Handler function.
*
* @return {Boolean}
*/
functionisValidFunc(value){
return(typeofvalue==='function'&&value.length>=1&&value.length<=3);
}