-
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathhandler.js
84 lines (73 loc) · 1.96 KB
/
handler.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
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
import './shims';
import fs from 'fs';
import path from 'path';
import sirv from 'sirv';
import { fileURLToPath } from 'url';
import { getRequest, setResponse } from '@sveltejs/kit/node';
import { App } from 'APP';
import { manifest } from 'MANIFEST';
/* global BASE_ENV, PROTOCOL_HEADER, HOST_HEADER */
const app = new App(manifest);
const base = BASE_ENV && process.env[BASE_ENV];
const protocol_header = PROTOCOL_HEADER && process.env[PROTOCOL_HEADER];
const host_header = (HOST_HEADER && process.env[HOST_HEADER]) || 'host';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
/**
* @param {string} path
* @param {number} max_age
* @param {boolean} immutable
*/
function serve(path, max_age, immutable = false) {
return (
fs.existsSync(path) &&
sirv(path, {
etag: true,
maxAge: max_age,
immutable,
gzip: true,
brotli: true
})
);
}
/** @type {import('polka').Middleware} */
const ssr = async (req, res) => {
let request;
try {
request = await getRequest(base || get_base(req.headers), req);
} catch (err) {
res.statusCode = err.status || 400;
return res.end(err.reason || 'Invalid request body');
}
setResponse(res, await app.render(request));
};
/** @param {import('polka').Middleware[]} handlers */
function sequence(handlers) {
/** @type {import('polka').Middleware} */
return (req, res, next) => {
/** @param {number} i */
function handle(i) {
handlers[i](req, res, () => {
if (i < handlers.length) handle(i + 1);
else next();
});
}
handle(0);
};
}
/**
* @param {import('http').IncomingHttpHeaders} headers
* @returns
*/
function get_base(headers) {
const protocol = (protocol_header && headers[protocol_header]) || 'https';
const host = headers[host_header];
return `${protocol}://${host}`;
}
export const handler = sequence(
[
serve(path.join(__dirname, '/client'), 31536000, true),
serve(path.join(__dirname, '/static'), 0),
serve(path.join(__dirname, '/prerendered'), 0),
ssr
].filter(Boolean)
);