-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
serverless-handler.mts
109 lines (96 loc) · 3.18 KB
/
serverless-handler.mts
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
import { addHelpers } from './helpers.js';
import { createServer } from 'http';
import { serializeBody } from '../utils.js';
import { streamToBuffer } from '@vercel/build-utils';
import exitHook from 'exit-hook';
import fetch from 'node-fetch';
import { listen } from 'async-listen';
import { isAbsolute } from 'path';
import { pathToFileURL } from 'url';
import type { ServerResponse, IncomingMessage } from 'http';
import type { VercelProxyResponse } from '../types.js';
import type { VercelRequest, VercelResponse } from './helpers.js';
type ServerlessServerOptions = {
shouldAddHelpers: boolean;
mode: 'streaming' | 'buffer';
};
type ServerlessFunctionSignature = (
req: IncomingMessage | VercelRequest,
res: ServerResponse | VercelResponse
) => void;
const [NODE_MAJOR] = process.versions.node.split('.').map(v => Number(v));
/* https://nextjs.org/docs/app/building-your-application/routing/router-handlers#supported-http-methods */
const HTTP_METHODS = [
'GET',
'HEAD',
'OPTIONS',
'POST',
'PUT',
'DELETE',
'PATCH',
];
async function createServerlessServer(userCode: ServerlessFunctionSignature) {
const server = createServer(userCode);
exitHook(() => server.close());
return { url: await listen(server) };
}
async function compileUserCode(
entrypointPath: string,
options: ServerlessServerOptions
) {
const id = isAbsolute(entrypointPath)
? pathToFileURL(entrypointPath).href
: entrypointPath;
let listener = await import(id);
/**
* In some cases we might have nested default props due to TS => JS
*/
for (let i = 0; i < 5; i++) {
if (listener.default) listener = listener.default;
}
if (HTTP_METHODS.some(method => typeof listener[method] === 'function')) {
if (NODE_MAJOR < 18) {
throw new Error('Node.js v18 or above is required to use HTTP method exports in your functions.');
}
const { getWebExportsHandler } = await import('./helpers-web.js');
return getWebExportsHandler(listener, HTTP_METHODS);
}
return async (req: IncomingMessage, res: ServerResponse) => {
if (options.shouldAddHelpers) await addHelpers(req, res);
return listener(req, res);
};
}
export async function createServerlessEventHandler(
entrypointPath: string,
options: ServerlessServerOptions
): Promise<(request: IncomingMessage) => Promise<VercelProxyResponse>> {
const userCode = await compileUserCode(entrypointPath, options);
const server = await createServerlessServer(userCode);
return async function (request: IncomingMessage) {
const url = new URL(request.url ?? '/', server.url);
// @ts-expect-error
const response = await fetch(url, {
body: await serializeBody(request),
headers: {
...request.headers,
host: request.headers['x-forwarded-host'],
},
method: request.method,
redirect: 'manual',
});
let body;
if (options.mode === 'streaming') {
body = response.body;
} else {
body = await streamToBuffer(response.body);
response.headers.delete('transfer-encoding');
response.headers.set('content-length', body.length);
}
return {
status: response.status,
headers: response.headers,
body,
encoding: 'utf8',
};
};
}