-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserverless.js
132 lines (132 loc) · 4.46 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
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
import fastifyCookie from "@fastify/cookie";
import fastifyFormbody from "@fastify/formbody";
import fastifyMultipart from "@fastify/multipart";
import fastifyStatic from "@fastify/static";
import "dotenv-flow/config";
import Fastify from "fastify";
import { jsxToString } from "jsx-async-runtime";
import { createHash } from "node:crypto";
import { readFile, stat } from "node:fs/promises";
import { join } from "node:path";
const NODE_ENV_IS_DEVELOPMENT = process.env.NODE_ENV === "development";
const serverless = Fastify({
logger: true,
disableRequestLogging: Boolean(process.env.FASTIFY_DISABLE_REQUEST_LOGGING),
bodyLimit: Number(process.env.FASTIFY_BODY_LIMIT) || void 0,
trustProxy: Boolean(process.env.FASTIFY_TRUST_PROXY)
});
serverless.register(fastifyCookie);
serverless.register(fastifyFormbody);
serverless.register(fastifyMultipart);
const FASTIFY_STATIC_HEADERS = process.env.FASTIFY_STATIC_HEADERS ? JSON.parse(String(process.env.FASTIFY_STATIC_HEADERS)) : void 0;
serverless.register(fastifyStatic, {
root: ["public", "dist/browser"].map((dir) => join(process.cwd(), dir)),
prefix: "/",
wildcard: false,
cacheControl: false,
setHeaders: FASTIFY_STATIC_HEADERS ? (reply, path) => {
for (const [suffix, headers] of Object.entries(
FASTIFY_STATIC_HEADERS
)) {
if (path.endsWith(suffix)) {
for (const [key, value] of Object.entries(headers)) {
reply.setHeader(key, value);
}
return;
}
}
} : void 0
});
serverless.decorateRequest("path", "");
serverless.addHook("onRequest", async (request, reply) => {
const index = request.url.indexOf("?");
request.path = index === -1 ? request.url : request.url.slice(0, index);
});
const modulesCache = {};
const cwd = process.cwd();
serverless.all("*", async (request, reply) => {
let response;
const context = {};
const path = request.path;
for (const route of generateRoutes(path)) {
const modulePath = join(cwd, "dist", route);
let module = modulesCache[modulePath];
if (module === null) {
continue;
}
if (module === void 0) {
try {
(await stat(modulePath)).isFile();
} catch {
if (!NODE_ENV_IS_DEVELOPMENT) {
modulesCache[modulePath] = null;
}
continue;
}
if (NODE_ENV_IS_DEVELOPMENT) {
module = await import(`file://${modulePath}?${createHash("sha1").update(await readFile(modulePath, "utf-8")).digest("hex")}`);
} else {
module = modulesCache[modulePath] = await import(`file://${modulePath}`);
}
}
response = await module.default.call(context, {
request,
reply,
...typeof response === "object" ? response : {}
});
if (reply.sent) {
return;
} else if (typeof response === "string" || Buffer.isBuffer(response)) {
break;
} else if (route.endsWith("/[...guard].js") && (response === void 0 || !isJSX(response))) {
continue;
} else if (route.endsWith("/[404].js")) {
reply.status(404);
break;
} else if (reply.statusCode === 404) {
continue;
} else {
break;
}
}
if (!reply.hasHeader("Content-Type")) {
reply.header("Content-Type", "text/html; charset=utf-8");
}
const payload = isJSX(response) ? await jsxToString.call(context, response) : response;
const responseHandler = context["response"];
return typeof responseHandler === "function" ? await responseHandler(payload) : payload;
});
function generateRoutes(path) {
const segments = generateSegments(path);
const edges = generateEdges(segments[0]);
return [
...segments.toReversed().map((segment) => `routes${segment}/[...guard].js`),
...edges.map((edge) => `routes${edge}.js`),
...segments.map((segment) => `routes${segment}/[...path].js`),
...segments.map((segment) => `routes${segment}/[404].js`)
];
}
function generateSegments(path) {
return path.split("/").filter((segment) => segment !== "").reduce((acc, segment) => {
acc.push((acc.length > 0 ? acc[acc.length - 1] : "") + "/" + segment);
return acc;
}, []).reverse().concat("");
}
function generateEdges(path) {
const edges = [];
if (path) {
const lastSegment = path.lastIndexOf("/") + 1;
edges.push(
`${path.substring(0, lastSegment)}[${path.substring(lastSegment)}]`
);
}
edges.push(`${path}/[index]`);
return edges;
}
function isJSX(obj) {
return !!obj && typeof obj === "object" && "type" in obj && "props" in obj;
}
var serverless_default = serverless;
export {
serverless_default as default
};