-
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathserverless.js
47 lines (38 loc) · 1.3 KB
/
serverless.js
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
import { installPolyfills } from '@sveltejs/kit/node/polyfills';
import { getRequest, setResponse, createReadableStream } from '@sveltejs/kit/node';
import { Server } from 'SERVER';
import { manifest } from 'MANIFEST';
import process from 'node:process';
installPolyfills();
const server = new Server(manifest);
await server.init({
env: /** @type {Record<string, string>} */ (process.env),
read: createReadableStream
});
const DATA_SUFFIX = '/__data.json';
/**
* @param {import('http').IncomingMessage} req
* @param {import('http').ServerResponse} res
*/
export default async (req, res) => {
if (req.url) {
const [path, search] = req.url.split('?');
const params = new URLSearchParams(search);
let pathname = params.get('__pathname');
if (pathname) {
params.delete('__pathname');
// Optional routes' pathname replacements look like `/foo/$1/bar` which means we could end up with an url like /foo//bar
pathname = pathname.replace(/\/+/g, '/');
req.url = `${pathname}${path.endsWith(DATA_SUFFIX) ? DATA_SUFFIX : ''}?${params}`;
}
}
const request = await getRequest({ base: `https://${req.headers.host}`, request: req });
setResponse(
res,
await server.respond(request, {
getClientAddress() {
return /** @type {string} */ (request.headers.get('x-forwarded-for'));
}
})
);
};