@thexjs/core 1.2.2 → 1.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter.d.ts +52 -52
- package/dist/adapter.js +152 -153
- package/dist/{chunk-Y3MLOFAG.js → chunk-O6SIM7EF.js} +8 -1
- package/dist/data.d.ts +7 -7
- package/dist/data.js +84 -70
- package/dist/index.d.ts +114 -114
- package/dist/index.js +1605 -1554
- package/package.json +6 -2
package/dist/index.js
CHANGED
|
@@ -12,420 +12,81 @@ import {
|
|
|
12
12
|
scanPages,
|
|
13
13
|
scanRoutes,
|
|
14
14
|
writeManifest
|
|
15
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-O6SIM7EF.js";
|
|
16
16
|
|
|
17
|
-
// src/
|
|
18
|
-
import {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
"main",
|
|
22
|
-
{
|
|
23
|
-
style: {
|
|
24
|
-
maxWidth: 640,
|
|
25
|
-
margin: "4rem auto",
|
|
26
|
-
padding: "0 1rem",
|
|
27
|
-
fontFamily: "system-ui, -apple-system, sans-serif",
|
|
28
|
-
textAlign: "center"
|
|
29
|
-
},
|
|
30
|
-
children: [
|
|
31
|
-
/* @__PURE__ */ jsx("h1", { style: { fontSize: "4rem", fontWeight: 700, margin: "0 0 0.5rem", color: "#e74c3c" }, children: "404" }),
|
|
32
|
-
/* @__PURE__ */ jsx("p", { style: { fontSize: "1.125rem", color: "#666", margin: "0 0 2rem" }, children: "This page could not be found." }),
|
|
33
|
-
/* @__PURE__ */ jsx(
|
|
34
|
-
"a",
|
|
35
|
-
{
|
|
36
|
-
href: "/",
|
|
37
|
-
style: {
|
|
38
|
-
color: "#6ab0ff",
|
|
39
|
-
textDecoration: "underline",
|
|
40
|
-
fontSize: "0.875rem"
|
|
41
|
-
},
|
|
42
|
-
children: "Back to home"
|
|
43
|
-
}
|
|
44
|
-
)
|
|
45
|
-
]
|
|
46
|
-
}
|
|
47
|
-
);
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
// src/render.ts
|
|
51
|
-
import { renderToReadableStream, renderToStaticMarkup, renderToString } from "react-dom/server";
|
|
52
|
-
|
|
53
|
-
// src/client-nav.ts
|
|
54
|
-
var CLIENT_NAV_SCRIPT = `
|
|
55
|
-
(function () {
|
|
56
|
-
if (window.__xNav) return;
|
|
57
|
-
window.__xNav = true;
|
|
58
|
-
|
|
59
|
-
var cache = new Map();
|
|
60
|
-
|
|
61
|
-
document.addEventListener("click", function (ev) {
|
|
62
|
-
if (ev.defaultPrevented || ev.button !== 0) return;
|
|
63
|
-
if (ev.metaKey || ev.ctrlKey || ev.shiftKey || ev.altKey) return;
|
|
64
|
-
var anchor = resolveLink(ev.target && ev.target.closest ? ev.target.closest("a[href]") : null);
|
|
65
|
-
if (!anchor) return;
|
|
66
|
-
ev.preventDefault();
|
|
67
|
-
if (anchor.href !== location.href) navigate(anchor, true);
|
|
68
|
-
});
|
|
69
|
-
|
|
70
|
-
document.addEventListener(
|
|
71
|
-
"mouseover",
|
|
72
|
-
function (ev) {
|
|
73
|
-
var anchor = resolveLink(ev.target && ev.target.closest ? ev.target.closest("a[href]") : null);
|
|
74
|
-
if (!anchor || anchor.hasAttribute("data-no-prefetch")) return;
|
|
75
|
-
prefetch(anchor);
|
|
76
|
-
},
|
|
77
|
-
{ passive: true },
|
|
78
|
-
);
|
|
79
|
-
|
|
80
|
-
document.addEventListener(
|
|
81
|
-
"focusin",
|
|
82
|
-
function (ev) {
|
|
83
|
-
var anchor = resolveLink(ev.target && ev.target.closest ? ev.target.closest("a[href]") : null);
|
|
84
|
-
if (!anchor || anchor.hasAttribute("data-no-prefetch")) return;
|
|
85
|
-
prefetch(anchor);
|
|
86
|
-
},
|
|
87
|
-
{ passive: true },
|
|
88
|
-
);
|
|
89
|
-
|
|
90
|
-
window.addEventListener("popstate", function () {
|
|
91
|
-
navigate(new URL(location.href), false);
|
|
92
|
-
});
|
|
93
|
-
|
|
94
|
-
var style = document.createElement("style");
|
|
95
|
-
style.textContent = [
|
|
96
|
-
".x-nav-loading{cursor:progress}",
|
|
97
|
-
".x-nav-loading::after{content:'';position:fixed;top:0;left:0;height:2px;width:100%;",
|
|
98
|
-
"background:var(--x-accent,#6ab0ff);z-index:9999;animation:x-nav-progress .8s ease-in-out infinite}",
|
|
99
|
-
"@keyframes x-nav-progress{0%{transform:translateX(-100%)}50%{transform:translateX(0)}100%{transform:translateX(100%)}}",
|
|
100
|
-
].join("");
|
|
101
|
-
document.head.appendChild(style);
|
|
17
|
+
// src/build.ts
|
|
18
|
+
import { cpSync, existsSync, mkdirSync as mkdirSync2, writeFileSync as writeFileSync3 } from "fs";
|
|
19
|
+
import { join as join4, relative as relative2 } from "path";
|
|
20
|
+
import { createElement } from "react";
|
|
102
21
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
22
|
+
// src/content.ts
|
|
23
|
+
import { readdirSync, readFileSync, statSync } from "fs";
|
|
24
|
+
import { join, relative, sep } from "path";
|
|
25
|
+
var CONTENT_FILE = /\.(md|mdx)$/;
|
|
26
|
+
function scanContent(rootDir) {
|
|
27
|
+
const entries = [];
|
|
28
|
+
function walk(dir) {
|
|
29
|
+
for (const name of readdirSync(dir)) {
|
|
30
|
+
if (name.startsWith(".")) continue;
|
|
31
|
+
const full = join(dir, name);
|
|
32
|
+
const stat = statSync(full);
|
|
33
|
+
if (stat.isDirectory()) {
|
|
34
|
+
walk(full);
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
if (!CONTENT_FILE.test(name)) continue;
|
|
38
|
+
const raw = readFileSync(full, "utf-8");
|
|
39
|
+
const { frontmatter, body } = parseFrontmatter(raw);
|
|
40
|
+
const rel = relative(rootDir, full).replace(CONTENT_FILE, "");
|
|
41
|
+
const slug = name.replace(CONTENT_FILE, "");
|
|
42
|
+
const routePath = toContentRoutePath(rel);
|
|
43
|
+
entries.push({ filePath: full, routePath, slug, frontmatter, body });
|
|
116
44
|
}
|
|
117
|
-
if (url.origin !== location.origin) return null;
|
|
118
|
-
var here = new URL(location.href);
|
|
119
|
-
if (url.pathname === here.pathname && url.search === here.search && url.hash) return null;
|
|
120
|
-
return anchor;
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
function setLoading(on) {
|
|
124
|
-
document.documentElement.classList.toggle("x-nav-loading", on);
|
|
125
45
|
}
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
throw err;
|
|
139
|
-
});
|
|
140
|
-
if (cache.size >= 30) {
|
|
141
|
-
var first = cache.keys().next().value;
|
|
142
|
-
if (first !== undefined) cache.delete(first);
|
|
143
|
-
}
|
|
144
|
-
cache.set(url.href, promise);
|
|
145
|
-
return promise;
|
|
46
|
+
walk(rootDir);
|
|
47
|
+
return entries;
|
|
48
|
+
}
|
|
49
|
+
function toContentRoutePath(relPath) {
|
|
50
|
+
const segments = relPath.split(sep).filter((s) => s !== "index");
|
|
51
|
+
const joined = segments.join("/");
|
|
52
|
+
return joined.length === 0 ? "/" : `/${joined}`;
|
|
53
|
+
}
|
|
54
|
+
function parseFrontmatter(raw) {
|
|
55
|
+
const trimmed = raw.trimStart();
|
|
56
|
+
if (!trimmed.startsWith("---")) {
|
|
57
|
+
return { frontmatter: {}, body: trimmed };
|
|
146
58
|
}
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
prefetch(url)
|
|
151
|
-
.then(function (payload) {
|
|
152
|
-
if (!payload.isHtml) {
|
|
153
|
-
location.href = url.href;
|
|
154
|
-
return;
|
|
155
|
-
}
|
|
156
|
-
var doc = new DOMParser().parseFromString(payload.html, "text/html");
|
|
157
|
-
var next = doc.getElementById("root");
|
|
158
|
-
var root = document.getElementById("root");
|
|
159
|
-
if (!next || !root) {
|
|
160
|
-
location.href = url.href;
|
|
161
|
-
return;
|
|
162
|
-
}
|
|
163
|
-
if (push) history.pushState({ xNav: true }, "", payload.finalUrl);
|
|
164
|
-
if (doc.title) document.title = doc.title;
|
|
165
|
-
root.innerHTML = next.innerHTML;
|
|
166
|
-
reexecuteScripts(root);
|
|
167
|
-
if (url.hash) {
|
|
168
|
-
var target = document.getElementById(url.hash.slice(1));
|
|
169
|
-
if (target) {
|
|
170
|
-
target.scrollIntoView();
|
|
171
|
-
return;
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
window.scrollTo(0, 0);
|
|
175
|
-
})
|
|
176
|
-
.catch(function () {
|
|
177
|
-
location.href = url.href;
|
|
178
|
-
})
|
|
179
|
-
.finally(function () {
|
|
180
|
-
setLoading(false);
|
|
181
|
-
});
|
|
59
|
+
const endIndex = trimmed.indexOf("---", 3);
|
|
60
|
+
if (endIndex === -1) {
|
|
61
|
+
return { frontmatter: {}, body: trimmed };
|
|
182
62
|
}
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
63
|
+
const fmRaw = trimmed.slice(3, endIndex).trim();
|
|
64
|
+
const body = trimmed.slice(endIndex + 3).trimStart();
|
|
65
|
+
const frontmatter = parseYamlLines(fmRaw);
|
|
66
|
+
return { frontmatter, body };
|
|
67
|
+
}
|
|
68
|
+
function parseYamlLines(raw) {
|
|
69
|
+
const result = {};
|
|
70
|
+
for (const line of raw.split("\n")) {
|
|
71
|
+
const colon = line.indexOf(":");
|
|
72
|
+
if (colon === -1) continue;
|
|
73
|
+
const key = line.slice(0, colon).trim();
|
|
74
|
+
let value = line.slice(colon + 1).trim();
|
|
75
|
+
if (typeof value === "string" && value.startsWith('"') && value.endsWith('"')) {
|
|
76
|
+
value = value.slice(1, -1);
|
|
77
|
+
}
|
|
78
|
+
if (typeof value === "string" && value.startsWith("[")) {
|
|
79
|
+
try {
|
|
80
|
+
value = JSON.parse(value);
|
|
81
|
+
} catch {
|
|
82
|
+
value = value.slice(1, -1).split(",").map((s) => s.trim()).filter(Boolean);
|
|
192
83
|
}
|
|
193
|
-
el.textContent = old.textContent;
|
|
194
|
-
old.replaceWith(el);
|
|
195
84
|
}
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
/** Soft reload current page without a full document reload (used by dev live-reload). */
|
|
199
|
-
window.__xSoftReload = function () {
|
|
200
|
-
navigate(new URL(location.href), false);
|
|
201
|
-
};
|
|
202
|
-
})();
|
|
203
|
-
`.trim();
|
|
204
|
-
|
|
205
|
-
// src/live-reload.ts
|
|
206
|
-
var LIVE_RELOAD_SCRIPT = `
|
|
207
|
-
(function () {
|
|
208
|
-
var es = new EventSource("/__x/reload");
|
|
209
|
-
es.addEventListener("reload", function () {
|
|
210
|
-
es.close();
|
|
211
|
-
if (typeof window.__xSoftReload === "function") {
|
|
212
|
-
window.__xSoftReload();
|
|
213
|
-
} else {
|
|
214
|
-
window.location.reload();
|
|
215
|
-
}
|
|
216
|
-
});
|
|
217
|
-
es.addEventListener("hb", function () {});
|
|
218
|
-
es.onerror = function () {
|
|
219
|
-
es.close();
|
|
220
|
-
};
|
|
221
|
-
})();
|
|
222
|
-
`.trim();
|
|
223
|
-
|
|
224
|
-
// src/render.ts
|
|
225
|
-
function escapeHtml(s) {
|
|
226
|
-
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
227
|
-
}
|
|
228
|
-
function escapeJsonForScript(s) {
|
|
229
|
-
return s.replace(/<\//g, "<\\/");
|
|
230
|
-
}
|
|
231
|
-
function buildHeadExtras(stylesheet) {
|
|
232
|
-
return stylesheet ? `
|
|
233
|
-
<link rel="stylesheet" href="${escapeHtml(stylesheet)}" />` : "";
|
|
234
|
-
}
|
|
235
|
-
function buildNavScriptTag(clientNav) {
|
|
236
|
-
return clientNav === false ? "" : `
|
|
237
|
-
<script>${CLIENT_NAV_SCRIPT}</script>`;
|
|
238
|
-
}
|
|
239
|
-
function buildLiveReloadTag(liveReload) {
|
|
240
|
-
return liveReload ? `
|
|
241
|
-
<script>${LIVE_RELOAD_SCRIPT}</script>` : "";
|
|
242
|
-
}
|
|
243
|
-
function htmlShell(title, headExtras, propsScript, scripts, bodySlot, navScriptTag, liveReloadTag) {
|
|
244
|
-
const finalScripts = scripts ?? "";
|
|
245
|
-
const inside = `${bodySlot}${propsScript ? `
|
|
246
|
-
${propsScript}` : ""}${finalScripts ? `
|
|
247
|
-
${finalScripts}` : ""}`;
|
|
248
|
-
return `<!DOCTYPE html>
|
|
249
|
-
<html lang="en">
|
|
250
|
-
<head>
|
|
251
|
-
<meta charset="UTF-8" />
|
|
252
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
253
|
-
<title>${escapeHtml(title)}</title>${headExtras}
|
|
254
|
-
</head>
|
|
255
|
-
<body>
|
|
256
|
-
<div id="root">${inside}</div>
|
|
257
|
-
${navScriptTag ? ` ${navScriptTag}
|
|
258
|
-
` : ""}${liveReloadTag} </body>
|
|
259
|
-
</html>`;
|
|
260
|
-
}
|
|
261
|
-
function renderPage(node, options = {}) {
|
|
262
|
-
const { islandScripts, islandProps } = options;
|
|
263
|
-
const title = options.title ?? "x app";
|
|
264
|
-
const body = renderToString(node);
|
|
265
|
-
const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
|
|
266
|
-
const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json">${propsJson}</script>` : "";
|
|
267
|
-
const islandScriptsHtml = islandScripts?.map((src) => `<script data-island-script src="${escapeHtml(src)}"></script>`).join("\n ");
|
|
268
|
-
return htmlShell(
|
|
269
|
-
title,
|
|
270
|
-
buildHeadExtras(options.stylesheet),
|
|
271
|
-
propsScript,
|
|
272
|
-
islandScriptsHtml,
|
|
273
|
-
body,
|
|
274
|
-
buildNavScriptTag(options.clientNav),
|
|
275
|
-
buildLiveReloadTag(options.liveReload)
|
|
276
|
-
);
|
|
277
|
-
}
|
|
278
|
-
function renderStaticPage(node, options = {}) {
|
|
279
|
-
const { islandScripts, islandProps } = options;
|
|
280
|
-
const title = options.title ?? "x app";
|
|
281
|
-
const body = renderToStaticMarkup(node);
|
|
282
|
-
const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
|
|
283
|
-
const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json">${propsJson}</script>` : "";
|
|
284
|
-
const islandScriptsHtml = islandScripts?.map((src) => `<script data-island-script src="${escapeHtml(src)}"></script>`).join("\n ");
|
|
285
|
-
return htmlShell(
|
|
286
|
-
title,
|
|
287
|
-
buildHeadExtras(options.stylesheet),
|
|
288
|
-
propsScript,
|
|
289
|
-
islandScriptsHtml,
|
|
290
|
-
body,
|
|
291
|
-
buildNavScriptTag(options.clientNav),
|
|
292
|
-
buildLiveReloadTag(options.liveReload)
|
|
293
|
-
);
|
|
294
|
-
}
|
|
295
|
-
async function renderStreamingPage(node, options = {}) {
|
|
296
|
-
const { islandScripts, islandProps } = options;
|
|
297
|
-
const title = escapeHtml(options.title ?? "x app");
|
|
298
|
-
const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
|
|
299
|
-
const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json">${propsJson}</script>` : "";
|
|
300
|
-
const islandScriptsHtml = islandScripts?.map((src) => `<script data-island-script src="${escapeHtml(src)}"></script>`).join("\n ");
|
|
301
|
-
const navScriptTag = buildNavScriptTag(options.clientNav);
|
|
302
|
-
const liveReloadTag = buildLiveReloadTag(options.liveReload);
|
|
303
|
-
const headExtras = buildHeadExtras(options.stylesheet);
|
|
304
|
-
const rootFooter = `${propsScript ? ` ${propsScript}
|
|
305
|
-
` : ""}${islandScriptsHtml ? ` ${islandScriptsHtml}
|
|
306
|
-
` : ""}`;
|
|
307
|
-
const footer = `</div>${navScriptTag}
|
|
308
|
-
${liveReloadTag} </body>
|
|
309
|
-
</html>`;
|
|
310
|
-
const reactStream = await renderToReadableStream(node, {
|
|
311
|
-
onError(err) {
|
|
312
|
-
console.error("[x] render error:", err);
|
|
313
|
-
}
|
|
314
|
-
});
|
|
315
|
-
const encoder = new TextEncoder();
|
|
316
|
-
const header = `<!DOCTYPE html>
|
|
317
|
-
<html lang="en">
|
|
318
|
-
<head>
|
|
319
|
-
<meta charset="UTF-8" />
|
|
320
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
321
|
-
<title>${title}</title>${headExtras}
|
|
322
|
-
</head>
|
|
323
|
-
<body>
|
|
324
|
-
<div id="root">`;
|
|
325
|
-
return new ReadableStream({
|
|
326
|
-
async start(controller) {
|
|
327
|
-
controller.enqueue(encoder.encode(header));
|
|
328
|
-
const reader = reactStream.getReader();
|
|
329
|
-
async function pump() {
|
|
330
|
-
try {
|
|
331
|
-
const { done, value } = await reader.read();
|
|
332
|
-
if (done) {
|
|
333
|
-
controller.enqueue(encoder.encode(`${rootFooter}
|
|
334
|
-
${footer}`));
|
|
335
|
-
controller.close();
|
|
336
|
-
return;
|
|
337
|
-
}
|
|
338
|
-
controller.enqueue(value);
|
|
339
|
-
await pump();
|
|
340
|
-
} catch (err) {
|
|
341
|
-
console.error("[x] stream read error:", err);
|
|
342
|
-
controller.enqueue(
|
|
343
|
-
encoder.encode(
|
|
344
|
-
`${rootFooter}<div style="color:red;padding:1em;margin:1rem">Render error: ${err instanceof Error ? err.message : "Unknown"}</div>
|
|
345
|
-
${footer}`
|
|
346
|
-
)
|
|
347
|
-
);
|
|
348
|
-
controller.close();
|
|
349
|
-
}
|
|
350
|
-
}
|
|
351
|
-
await pump();
|
|
352
|
-
}
|
|
353
|
-
});
|
|
354
|
-
}
|
|
355
|
-
|
|
356
|
-
// src/createApp.ts
|
|
357
|
-
import { existsSync, watch } from "fs";
|
|
358
|
-
import { join as join4, resolve, sep as sep2 } from "path";
|
|
359
|
-
import { createElement } from "react";
|
|
360
|
-
|
|
361
|
-
// src/content.ts
|
|
362
|
-
import { readFileSync, readdirSync, statSync } from "fs";
|
|
363
|
-
import { join, relative, sep } from "path";
|
|
364
|
-
var CONTENT_FILE = /\.(md|mdx)$/;
|
|
365
|
-
function scanContent(rootDir) {
|
|
366
|
-
const entries = [];
|
|
367
|
-
function walk(dir) {
|
|
368
|
-
for (const name of readdirSync(dir)) {
|
|
369
|
-
if (name.startsWith(".")) continue;
|
|
370
|
-
const full = join(dir, name);
|
|
371
|
-
const stat = statSync(full);
|
|
372
|
-
if (stat.isDirectory()) {
|
|
373
|
-
walk(full);
|
|
374
|
-
continue;
|
|
375
|
-
}
|
|
376
|
-
if (!CONTENT_FILE.test(name)) continue;
|
|
377
|
-
const raw = readFileSync(full, "utf-8");
|
|
378
|
-
const { frontmatter, body } = parseFrontmatter(raw);
|
|
379
|
-
const rel = relative(rootDir, full).replace(CONTENT_FILE, "");
|
|
380
|
-
const slug = name.replace(CONTENT_FILE, "");
|
|
381
|
-
const routePath = toContentRoutePath(rel);
|
|
382
|
-
entries.push({ filePath: full, routePath, slug, frontmatter, body });
|
|
383
|
-
}
|
|
384
|
-
}
|
|
385
|
-
walk(rootDir);
|
|
386
|
-
return entries;
|
|
387
|
-
}
|
|
388
|
-
function toContentRoutePath(relPath) {
|
|
389
|
-
const segments = relPath.split(sep).filter((s) => s !== "index");
|
|
390
|
-
const joined = segments.join("/");
|
|
391
|
-
return joined.length === 0 ? "/" : `/${joined}`;
|
|
392
|
-
}
|
|
393
|
-
function parseFrontmatter(raw) {
|
|
394
|
-
const trimmed = raw.trimStart();
|
|
395
|
-
if (!trimmed.startsWith("---")) {
|
|
396
|
-
return { frontmatter: {}, body: trimmed };
|
|
397
|
-
}
|
|
398
|
-
const endIndex = trimmed.indexOf("---", 3);
|
|
399
|
-
if (endIndex === -1) {
|
|
400
|
-
return { frontmatter: {}, body: trimmed };
|
|
401
|
-
}
|
|
402
|
-
const fmRaw = trimmed.slice(3, endIndex).trim();
|
|
403
|
-
const body = trimmed.slice(endIndex + 3).trimStart();
|
|
404
|
-
const frontmatter = parseYamlLines(fmRaw);
|
|
405
|
-
return { frontmatter, body };
|
|
406
|
-
}
|
|
407
|
-
function parseYamlLines(raw) {
|
|
408
|
-
const result = {};
|
|
409
|
-
for (const line of raw.split("\n")) {
|
|
410
|
-
const colon = line.indexOf(":");
|
|
411
|
-
if (colon === -1) continue;
|
|
412
|
-
const key = line.slice(0, colon).trim();
|
|
413
|
-
let value = line.slice(colon + 1).trim();
|
|
414
|
-
if (typeof value === "string" && value.startsWith('"') && value.endsWith('"')) {
|
|
415
|
-
value = value.slice(1, -1);
|
|
416
|
-
}
|
|
417
|
-
if (typeof value === "string" && value.startsWith("[")) {
|
|
418
|
-
try {
|
|
419
|
-
value = JSON.parse(value);
|
|
420
|
-
} catch {
|
|
421
|
-
value = value.slice(1, -1).split(",").map((s) => s.trim()).filter(Boolean);
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
result[key] = value;
|
|
85
|
+
result[key] = value;
|
|
425
86
|
}
|
|
426
87
|
return result;
|
|
427
88
|
}
|
|
428
|
-
function
|
|
89
|
+
function escapeHtml(s) {
|
|
429
90
|
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
430
91
|
}
|
|
431
92
|
function renderListBlock(block) {
|
|
@@ -457,7 +118,7 @@ function isSafeLinkUrl(url) {
|
|
|
457
118
|
function renderMarkdown(md) {
|
|
458
119
|
const inlineCodes = [];
|
|
459
120
|
const fences = [];
|
|
460
|
-
let html =
|
|
121
|
+
let html = escapeHtml(md).replace(/`{3}(\w*)\n([\s\S]*?)`{3}/gm, (_m, _lang, code) => {
|
|
461
122
|
fences.push(`<pre><code>${code.trim()}</code></pre>`);
|
|
462
123
|
return `__X_FENCE_${fences.length - 1}__`;
|
|
463
124
|
});
|
|
@@ -467,8 +128,8 @@ function renderMarkdown(md) {
|
|
|
467
128
|
}).replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>").replace(/\*([^*]+)\*/g, "<em>$1</em>").replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m, text, href) => {
|
|
468
129
|
const clean = stripUrlControlChars(href);
|
|
469
130
|
return isSafeLinkUrl(clean) ? `<a href="${clean}">${text}</a>` : text;
|
|
470
|
-
}).replace(/__X_CODE_(\d+)__/g, (_m, i) => `<code>${inlineCodes[Number.parseInt(i)]}</code>`);
|
|
471
|
-
html = html.replace(/__X_FENCE_(\d+)__/g, (_m, i) => fences[Number.parseInt(i)] ?? "");
|
|
131
|
+
}).replace(/__X_CODE_(\d+)__/g, (_m, i) => `<code>${inlineCodes[Number.parseInt(i, 10)]}</code>`);
|
|
132
|
+
html = html.replace(/__X_FENCE_(\d+)__/g, (_m, i) => fences[Number.parseInt(i, 10)] ?? "");
|
|
472
133
|
const blocks = html.split(/\n\n+/);
|
|
473
134
|
html = blocks.map((b) => {
|
|
474
135
|
const t = b.trim();
|
|
@@ -482,194 +143,18 @@ function renderMarkdown(md) {
|
|
|
482
143
|
return html;
|
|
483
144
|
}
|
|
484
145
|
|
|
485
|
-
// src/
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
const message = error instanceof Error ? error.message : "Unknown error";
|
|
491
|
-
const stack = error instanceof Error ? error.stack ?? "" : "";
|
|
492
|
-
const frames = stack.split("\n").slice(1).map((line) => `<span class="frame">${escapeHtml3(line.trim())}</span>`).join("\n");
|
|
493
|
-
return `<!DOCTYPE html>
|
|
494
|
-
<html lang="en">
|
|
495
|
-
<head>
|
|
496
|
-
<meta charset="UTF-8" />
|
|
497
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
498
|
-
<title>Server Error</title>
|
|
499
|
-
<style>
|
|
500
|
-
* { margin: 0; padding: 0; box-sizing: border-box; }
|
|
501
|
-
body {
|
|
502
|
-
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
|
503
|
-
background: #1a1a2e;
|
|
504
|
-
color: #e0e0e0;
|
|
505
|
-
min-height: 100vh;
|
|
506
|
-
display: flex;
|
|
507
|
-
flex-direction: column;
|
|
508
|
-
}
|
|
509
|
-
.overlay {
|
|
510
|
-
flex: 1;
|
|
511
|
-
padding: 40px 24px;
|
|
512
|
-
max-width: 900px;
|
|
513
|
-
margin: 0 auto;
|
|
514
|
-
width: 100%;
|
|
515
|
-
}
|
|
516
|
-
.header { margin-bottom: 32px; }
|
|
517
|
-
.badge {
|
|
518
|
-
display: inline-block;
|
|
519
|
-
background: #e74c3c;
|
|
520
|
-
color: #fff;
|
|
521
|
-
font-size: 11px;
|
|
522
|
-
font-weight: 700;
|
|
523
|
-
letter-spacing: 0.05em;
|
|
524
|
-
text-transform: uppercase;
|
|
525
|
-
padding: 3px 10px;
|
|
526
|
-
border-radius: 4px;
|
|
527
|
-
margin-bottom: 12px;
|
|
528
|
-
}
|
|
529
|
-
h1 {
|
|
530
|
-
font-size: 22px;
|
|
531
|
-
font-weight: 600;
|
|
532
|
-
color: #f0f0f0;
|
|
533
|
-
line-height: 1.3;
|
|
534
|
-
}
|
|
535
|
-
.message-box {
|
|
536
|
-
background: #2a2a4a;
|
|
537
|
-
border: 1px solid #3a3a5a;
|
|
538
|
-
border-radius: 8px;
|
|
539
|
-
padding: 20px;
|
|
540
|
-
margin-bottom: 24px;
|
|
541
|
-
font-size: 15px;
|
|
542
|
-
word-break: break-word;
|
|
543
|
-
}
|
|
544
|
-
.message-box .label {
|
|
545
|
-
font-size: 11px;
|
|
546
|
-
font-weight: 600;
|
|
547
|
-
text-transform: uppercase;
|
|
548
|
-
letter-spacing: 0.05em;
|
|
549
|
-
color: #888;
|
|
550
|
-
margin-bottom: 8px;
|
|
551
|
-
}
|
|
552
|
-
.message-box .message {
|
|
553
|
-
color: #ff6b6b;
|
|
554
|
-
font-family: "SF Mono", "Fira Code", "Fira Mono", monospace;
|
|
555
|
-
font-size: 14px;
|
|
556
|
-
white-space: pre-wrap;
|
|
557
|
-
}
|
|
558
|
-
.stack-section { margin-bottom: 24px; }
|
|
559
|
-
.stack-section .label {
|
|
560
|
-
font-size: 11px;
|
|
561
|
-
font-weight: 600;
|
|
562
|
-
text-transform: uppercase;
|
|
563
|
-
letter-spacing: 0.05em;
|
|
564
|
-
color: #888;
|
|
565
|
-
margin-bottom: 12px;
|
|
566
|
-
}
|
|
567
|
-
.frame {
|
|
568
|
-
display: block;
|
|
569
|
-
padding: 6px 12px;
|
|
570
|
-
font-family: "SF Mono", "Fira Code", "Fira Mono", monospace;
|
|
571
|
-
font-size: 12px;
|
|
572
|
-
color: #b0b0d0;
|
|
573
|
-
line-height: 1.6;
|
|
574
|
-
border-left: 2px solid #3a3a5a;
|
|
575
|
-
margin-bottom: 2px;
|
|
576
|
-
}
|
|
577
|
-
.frame:first-child { border-left-color: #e74c3c; }
|
|
578
|
-
.hint {
|
|
579
|
-
font-size: 13px;
|
|
580
|
-
color: #888;
|
|
581
|
-
border-top: 1px solid #3a3a5a;
|
|
582
|
-
padding-top: 20px;
|
|
583
|
-
margin-top: 8px;
|
|
584
|
-
}
|
|
585
|
-
.hint a { color: #6ab0ff; }
|
|
586
|
-
</style>
|
|
587
|
-
</head>
|
|
588
|
-
<body>
|
|
589
|
-
<div class="overlay">
|
|
590
|
-
<div class="header">
|
|
591
|
-
<div class="badge">Server Error</div>
|
|
592
|
-
<h1>Unhandled Error During Render</h1>
|
|
593
|
-
</div>
|
|
594
|
-
<div class="message-box">
|
|
595
|
-
<div class="label">Error</div>
|
|
596
|
-
<div class="message">${escapeHtml3(message)}</div>
|
|
597
|
-
</div>
|
|
598
|
-
${stack ? `<div class="stack-section"><div class="label">Stack Trace</div>${frames}</div>` : ""}
|
|
599
|
-
<div class="hint">
|
|
600
|
-
Fix the error and save the file. In development mode, the server will reload automatically.
|
|
601
|
-
</div>
|
|
602
|
-
</div>
|
|
603
|
-
</body>
|
|
604
|
-
</html>`;
|
|
605
|
-
}
|
|
606
|
-
|
|
607
|
-
// src/images/proxy.ts
|
|
608
|
-
var ALLOWED_CONTENT_TYPES = /* @__PURE__ */ new Set([
|
|
609
|
-
"image/png",
|
|
610
|
-
"image/jpeg",
|
|
611
|
-
"image/gif",
|
|
612
|
-
"image/webp",
|
|
613
|
-
"image/svg+xml",
|
|
614
|
-
"image/avif",
|
|
615
|
-
"image/x-icon"
|
|
616
|
-
]);
|
|
617
|
-
function createImageProxyHandler(options = {}) {
|
|
618
|
-
const allowedHosts = new Set(options.remoteHosts ?? []);
|
|
619
|
-
return async (req) => {
|
|
620
|
-
const reqUrl = new URL(req.url);
|
|
621
|
-
if (reqUrl.pathname !== "/_x/image") return null;
|
|
622
|
-
if (req.method !== "GET" && req.method !== "HEAD") return null;
|
|
623
|
-
const target = reqUrl.searchParams.get("url");
|
|
624
|
-
if (!target) return new Response("missing url param", { status: 400 });
|
|
625
|
-
let parsed;
|
|
626
|
-
try {
|
|
627
|
-
parsed = new URL(target);
|
|
628
|
-
} catch {
|
|
629
|
-
return new Response("invalid url param", { status: 400 });
|
|
630
|
-
}
|
|
631
|
-
if (parsed.protocol !== "http:" && parsed.protocol !== "https:" || !allowedHosts.has(parsed.hostname)) {
|
|
632
|
-
return new Response("host not allow-listed for image proxy", { status: 403 });
|
|
633
|
-
}
|
|
634
|
-
let upstream;
|
|
635
|
-
try {
|
|
636
|
-
upstream = await fetch(parsed);
|
|
637
|
-
} catch (err) {
|
|
638
|
-
return new Response(`upstream fetch failed: ${String(err)}`, { status: 502 });
|
|
639
|
-
}
|
|
640
|
-
if (!upstream.ok) {
|
|
641
|
-
return new Response("upstream error", { status: 502 });
|
|
642
|
-
}
|
|
643
|
-
const contentType = upstream.headers.get("content-type") ?? "";
|
|
644
|
-
const baseContentType = (contentType.split(";")[0] ?? "").trim();
|
|
645
|
-
if (!ALLOWED_CONTENT_TYPES.has(baseContentType)) {
|
|
646
|
-
return new Response("upstream did not return an image", { status: 502 });
|
|
647
|
-
}
|
|
648
|
-
return new Response(upstream.body, {
|
|
649
|
-
status: 200,
|
|
650
|
-
headers: {
|
|
651
|
-
"Content-Type": contentType,
|
|
652
|
-
// Cache aggressively client + edge side — the proxied URL is the
|
|
653
|
-
// cache key, and remote asset URLs like this one are typically
|
|
654
|
-
// content-hashed by the origin already.
|
|
655
|
-
"Cache-Control": "public, max-age=86400, immutable"
|
|
656
|
-
}
|
|
657
|
-
});
|
|
658
|
-
};
|
|
659
|
-
}
|
|
660
|
-
|
|
661
|
-
// src/island.tsx
|
|
662
|
-
import { createContext, useContext } from "react";
|
|
663
|
-
import { jsx as jsx2 } from "react/jsx-runtime";
|
|
664
|
-
function createIslandRegistry() {
|
|
665
|
-
return { entries: [] };
|
|
146
|
+
// src/island.tsx
|
|
147
|
+
import { createContext, useContext } from "react";
|
|
148
|
+
import { jsx } from "react/jsx-runtime";
|
|
149
|
+
function createIslandRegistry() {
|
|
150
|
+
return { entries: [] };
|
|
666
151
|
}
|
|
667
152
|
var IslandContext = createContext(null);
|
|
668
153
|
function IslandProvider({
|
|
669
154
|
registry,
|
|
670
155
|
children
|
|
671
156
|
}) {
|
|
672
|
-
return /* @__PURE__ */
|
|
157
|
+
return /* @__PURE__ */ jsx(IslandContext.Provider, { value: registry, children });
|
|
673
158
|
}
|
|
674
159
|
var islandCounter = 0;
|
|
675
160
|
function Island({
|
|
@@ -682,7 +167,7 @@ function Island({
|
|
|
682
167
|
if (registry) {
|
|
683
168
|
registry.entries.push({ name, id });
|
|
684
169
|
}
|
|
685
|
-
return /* @__PURE__ */
|
|
170
|
+
return /* @__PURE__ */ jsx("div", { "data-island": name, "data-island-id": id, "data-island-client": client, children });
|
|
686
171
|
}
|
|
687
172
|
|
|
688
173
|
// src/island-bundle.ts
|
|
@@ -970,12 +455,19 @@ function extractActionParams(routePath, paramNames, url) {
|
|
|
970
455
|
for (const name of paramNames) {
|
|
971
456
|
const value = match[idx];
|
|
972
457
|
if (value !== void 0) {
|
|
973
|
-
params[name] = value;
|
|
458
|
+
params[name] = safeDecodeURIComponent(value);
|
|
974
459
|
}
|
|
975
460
|
idx++;
|
|
976
461
|
}
|
|
977
462
|
return params;
|
|
978
463
|
}
|
|
464
|
+
function safeDecodeURIComponent(value) {
|
|
465
|
+
try {
|
|
466
|
+
return decodeURIComponent(value);
|
|
467
|
+
} catch {
|
|
468
|
+
return value;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
979
471
|
|
|
980
472
|
// src/island-bundle.ts
|
|
981
473
|
function actionsRewritePlugin(actionModules) {
|
|
@@ -1088,633 +580,1491 @@ async function buildIslandBundleInMemory(routeFilePath, layoutFilePaths, islandN
|
|
|
1088
580
|
}
|
|
1089
581
|
}
|
|
1090
582
|
|
|
1091
|
-
// src/
|
|
1092
|
-
|
|
1093
|
-
return async (ctx, _next) => {
|
|
1094
|
-
let index = -1;
|
|
1095
|
-
const dispatch = async (i) => {
|
|
1096
|
-
if (i <= index) throw new Error("next() called multiple times");
|
|
1097
|
-
index = i;
|
|
1098
|
-
const fn = fns[i];
|
|
1099
|
-
if (fn) {
|
|
1100
|
-
return fn(ctx, () => dispatch(i + 1));
|
|
1101
|
-
}
|
|
1102
|
-
return handler(ctx);
|
|
1103
|
-
};
|
|
1104
|
-
return dispatch(0);
|
|
1105
|
-
};
|
|
1106
|
-
}
|
|
583
|
+
// src/render.ts
|
|
584
|
+
import { renderToReadableStream, renderToStaticMarkup, renderToString } from "react-dom/server";
|
|
1107
585
|
|
|
1108
|
-
// src/
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
586
|
+
// src/client-nav.ts
|
|
587
|
+
var CLIENT_NAV_SCRIPT = `
|
|
588
|
+
(function () {
|
|
589
|
+
if (window.__xNav) return;
|
|
590
|
+
window.__xNav = true;
|
|
591
|
+
|
|
592
|
+
var cache = new Map();
|
|
593
|
+
|
|
594
|
+
document.addEventListener("click", function (ev) {
|
|
595
|
+
if (ev.defaultPrevented || ev.button !== 0) return;
|
|
596
|
+
if (ev.metaKey || ev.ctrlKey || ev.shiftKey || ev.altKey) return;
|
|
597
|
+
var anchor = resolveLink(ev.target && ev.target.closest ? ev.target.closest("a[href]") : null);
|
|
598
|
+
if (!anchor) return;
|
|
599
|
+
ev.preventDefault();
|
|
600
|
+
if (anchor.href !== location.href) navigate(anchor, true);
|
|
601
|
+
});
|
|
602
|
+
|
|
603
|
+
document.addEventListener(
|
|
604
|
+
"mouseover",
|
|
605
|
+
function (ev) {
|
|
606
|
+
var anchor = resolveLink(ev.target && ev.target.closest ? ev.target.closest("a[href]") : null);
|
|
607
|
+
if (!anchor || anchor.hasAttribute("data-no-prefetch")) return;
|
|
608
|
+
prefetch(anchor);
|
|
609
|
+
},
|
|
610
|
+
{ passive: true },
|
|
1123
611
|
);
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
}
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
612
|
+
|
|
613
|
+
document.addEventListener(
|
|
614
|
+
"focusin",
|
|
615
|
+
function (ev) {
|
|
616
|
+
var anchor = resolveLink(ev.target && ev.target.closest ? ev.target.closest("a[href]") : null);
|
|
617
|
+
if (!anchor || anchor.hasAttribute("data-no-prefetch")) return;
|
|
618
|
+
prefetch(anchor);
|
|
619
|
+
},
|
|
620
|
+
{ passive: true },
|
|
621
|
+
);
|
|
622
|
+
|
|
623
|
+
window.addEventListener("popstate", function () {
|
|
624
|
+
navigate(new URL(location.href), false);
|
|
625
|
+
});
|
|
626
|
+
|
|
627
|
+
var style = document.createElement("style");
|
|
628
|
+
style.textContent = [
|
|
629
|
+
".x-nav-loading{cursor:progress}",
|
|
630
|
+
".x-nav-loading::after{content:'';position:fixed;top:0;left:0;height:2px;width:100%;",
|
|
631
|
+
"background:var(--x-accent,#6ab0ff);z-index:9999;animation:x-nav-progress .8s ease-in-out infinite}",
|
|
632
|
+
"@keyframes x-nav-progress{0%{transform:translateX(-100%)}50%{transform:translateX(0)}100%{transform:translateX(100%)}}",
|
|
633
|
+
].join("");
|
|
634
|
+
document.head.appendChild(style);
|
|
635
|
+
|
|
636
|
+
function resolveLink(anchor) {
|
|
637
|
+
if (!anchor) return null;
|
|
638
|
+
if (anchor.hasAttribute("data-no-nav")) return null;
|
|
639
|
+
if (anchor.target && anchor.target !== "_self") return null;
|
|
640
|
+
if (anchor.hasAttribute("download")) return null;
|
|
641
|
+
var href = anchor.getAttribute("href");
|
|
642
|
+
if (!href) return null;
|
|
643
|
+
if (/^(#|mailto:|tel:|javascript:)/i.test(href)) return null;
|
|
644
|
+
var url;
|
|
645
|
+
try {
|
|
646
|
+
url = new URL(href, location.href);
|
|
647
|
+
} catch (_) {
|
|
648
|
+
return null;
|
|
1136
649
|
}
|
|
1137
|
-
return null;
|
|
1138
|
-
|
|
1139
|
-
|
|
650
|
+
if (url.origin !== location.origin) return null;
|
|
651
|
+
var here = new URL(location.href);
|
|
652
|
+
if (url.pathname === here.pathname && url.search === here.search && url.hash) return null;
|
|
653
|
+
return anchor;
|
|
654
|
+
}
|
|
1140
655
|
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
const entry = {
|
|
1144
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1145
|
-
level,
|
|
1146
|
-
message,
|
|
1147
|
-
...fields
|
|
1148
|
-
};
|
|
1149
|
-
const line = JSON.stringify(entry);
|
|
1150
|
-
if (level === "error") {
|
|
1151
|
-
console.error(line);
|
|
1152
|
-
} else if (level === "warn") {
|
|
1153
|
-
console.warn(line);
|
|
1154
|
-
} else {
|
|
1155
|
-
console.log(line);
|
|
656
|
+
function setLoading(on) {
|
|
657
|
+
document.documentElement.classList.toggle("x-nav-loading", on);
|
|
1156
658
|
}
|
|
1157
|
-
}
|
|
1158
|
-
var logger = {
|
|
1159
|
-
info: (message, fields) => write("info", message, fields),
|
|
1160
|
-
warn: (message, fields) => write("warn", message, fields),
|
|
1161
|
-
error: (message, fields) => write("error", message, fields)
|
|
1162
|
-
};
|
|
1163
|
-
function withRequestLogging(handler) {
|
|
1164
|
-
return async (req, server) => {
|
|
1165
|
-
const start = performance.now();
|
|
1166
|
-
const requestId = req.headers.get("x-request-id") ?? crypto.randomUUID();
|
|
1167
|
-
const route = new URL(req.url).pathname;
|
|
1168
|
-
try {
|
|
1169
|
-
const res = await handler(req, server);
|
|
1170
|
-
const isStream = res.headers.get("content-type")?.includes("text/event-stream");
|
|
1171
|
-
console.log(
|
|
1172
|
-
`[x][request] ${req.method} ${route} -> ${res.status}${isStream ? " (stream opened, not closed)" : ""}`
|
|
1173
|
-
);
|
|
1174
|
-
write("info", isStream ? "stream opened" : "request completed", {
|
|
1175
|
-
requestId,
|
|
1176
|
-
route,
|
|
1177
|
-
method: req.method,
|
|
1178
|
-
status: res.status,
|
|
1179
|
-
durationMs: Math.round(performance.now() - start)
|
|
1180
|
-
});
|
|
1181
|
-
if (!res.headers.has("x-request-id")) {
|
|
1182
|
-
res.headers.set("x-request-id", requestId);
|
|
1183
|
-
}
|
|
1184
|
-
return res;
|
|
1185
|
-
} catch (err) {
|
|
1186
|
-
write("error", "request failed", {
|
|
1187
|
-
requestId,
|
|
1188
|
-
route,
|
|
1189
|
-
method: req.method,
|
|
1190
|
-
status: 500,
|
|
1191
|
-
durationMs: Math.round(performance.now() - start),
|
|
1192
|
-
error: err instanceof Error ? err.message : String(err)
|
|
1193
|
-
});
|
|
1194
|
-
throw err;
|
|
1195
|
-
}
|
|
1196
|
-
};
|
|
1197
|
-
}
|
|
1198
659
|
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
};
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
}
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
const histograms = /* @__PURE__ */ new Map();
|
|
1216
|
-
function incr(name, delta = 1, labels) {
|
|
1217
|
-
const key = seriesKey(name, labels);
|
|
1218
|
-
let series = counters.get(key);
|
|
1219
|
-
if (!series) {
|
|
1220
|
-
series = { name, labels: labels ?? {}, value: 0 };
|
|
1221
|
-
counters.set(key, series);
|
|
660
|
+
function prefetch(url) {
|
|
661
|
+
if (cache.has(url.href)) return cache.get(url.href);
|
|
662
|
+
var promise = fetch(url.href, { headers: { "X-X-Nav": "1" } })
|
|
663
|
+
.then(function (res) {
|
|
664
|
+
return res.text().then(function (html) {
|
|
665
|
+
var ct = res.headers.get("content-type") || "";
|
|
666
|
+
return { html: html, ok: res.ok, finalUrl: res.url || url.href, isHtml: ct.indexOf("text/html") !== -1 };
|
|
667
|
+
});
|
|
668
|
+
})
|
|
669
|
+
.catch(function (err) {
|
|
670
|
+
cache.delete(url.href);
|
|
671
|
+
throw err;
|
|
672
|
+
});
|
|
673
|
+
if (cache.size >= 30) {
|
|
674
|
+
var first = cache.keys().next().value;
|
|
675
|
+
if (first !== undefined) cache.delete(first);
|
|
1222
676
|
}
|
|
1223
|
-
|
|
677
|
+
cache.set(url.href, promise);
|
|
678
|
+
return promise;
|
|
1224
679
|
}
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
acc.count += 1;
|
|
1234
|
-
for (let i = 0; i < buckets.length; i += 1) {
|
|
1235
|
-
const bound = buckets[i];
|
|
1236
|
-
if (bound === void 0) break;
|
|
1237
|
-
if (value <= bound) {
|
|
1238
|
-
for (let j = i; j < buckets.length; j += 1) {
|
|
1239
|
-
acc.bucketCounts[j] = (acc.bucketCounts[j] ?? 0) + 1;
|
|
680
|
+
|
|
681
|
+
function navigate(url, push) {
|
|
682
|
+
setLoading(true);
|
|
683
|
+
prefetch(url)
|
|
684
|
+
.then(function (payload) {
|
|
685
|
+
if (!payload.isHtml) {
|
|
686
|
+
location.href = url.href;
|
|
687
|
+
return;
|
|
1240
688
|
}
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
if (
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
689
|
+
var doc = new DOMParser().parseFromString(payload.html, "text/html");
|
|
690
|
+
var next = doc.getElementById("root");
|
|
691
|
+
var root = document.getElementById("root");
|
|
692
|
+
if (!next || !root) {
|
|
693
|
+
location.href = url.href;
|
|
694
|
+
return;
|
|
695
|
+
}
|
|
696
|
+
if (push) history.pushState({ xNav: true }, "", payload.finalUrl);
|
|
697
|
+
if (doc.title) document.title = doc.title;
|
|
698
|
+
root.innerHTML = next.innerHTML;
|
|
699
|
+
reexecuteScripts(root);
|
|
700
|
+
if (url.hash) {
|
|
701
|
+
var target = document.getElementById(url.hash.slice(1));
|
|
702
|
+
if (target) {
|
|
703
|
+
target.scrollIntoView();
|
|
704
|
+
return;
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
window.scrollTo(0, 0);
|
|
708
|
+
})
|
|
709
|
+
.catch(function () {
|
|
710
|
+
location.href = url.href;
|
|
711
|
+
})
|
|
712
|
+
.finally(function () {
|
|
713
|
+
setLoading(false);
|
|
714
|
+
});
|
|
1267
715
|
}
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
for (
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
const labels = { ...h.labels, le };
|
|
1278
|
-
return formatLabels(labels);
|
|
1279
|
-
};
|
|
1280
|
-
lines.push(`# TYPE ${h.name} histogram`);
|
|
1281
|
-
for (let i = 0; i < buckets.length; i += 1) {
|
|
1282
|
-
lines.push(`${h.name}_bucket${labelWithLe(String(buckets[i]))} ${h.bucketCounts[i]}`);
|
|
716
|
+
|
|
717
|
+
function reexecuteScripts(root) {
|
|
718
|
+
var scripts = root.querySelectorAll("script");
|
|
719
|
+
for (var i = 0; i < scripts.length; i++) {
|
|
720
|
+
var old = scripts[i];
|
|
721
|
+
var el = document.createElement("script");
|
|
722
|
+
for (var j = 0; j < old.attributes.length; j++) {
|
|
723
|
+
var attr = old.attributes[j];
|
|
724
|
+
el.setAttribute(attr.name, attr.value);
|
|
1283
725
|
}
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
lines.push(`${h.name}_count${formatLabels(h.labels)} ${h.count}`);
|
|
726
|
+
el.textContent = old.textContent;
|
|
727
|
+
old.replaceWith(el);
|
|
1287
728
|
}
|
|
1288
|
-
return `${lines.join("\n")}
|
|
1289
|
-
`;
|
|
1290
|
-
}
|
|
1291
|
-
function handleMetrics(req) {
|
|
1292
|
-
if (new URL(req.url).pathname !== "/metrics") return null;
|
|
1293
|
-
return new Response(renderMetrics(), {
|
|
1294
|
-
headers: { "Content-Type": "text/plain; version=0.0.4; charset=utf-8" }
|
|
1295
|
-
});
|
|
1296
729
|
}
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
renderMetrics,
|
|
1302
|
-
handleMetrics,
|
|
1303
|
-
async flush() {
|
|
1304
|
-
}
|
|
730
|
+
|
|
731
|
+
/** Soft reload current page without a full document reload (used by dev live-reload). */
|
|
732
|
+
window.__xSoftReload = function () {
|
|
733
|
+
navigate(new URL(location.href), false);
|
|
1305
734
|
};
|
|
1306
|
-
}
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
observe(name, value, labels) {
|
|
1320
|
-
let histogram = histograms.get(name);
|
|
1321
|
-
if (!histogram) {
|
|
1322
|
-
histogram = meter.createHistogram(name, { description: `Histogram ${name}` });
|
|
1323
|
-
histograms.set(name, histogram);
|
|
1324
|
-
}
|
|
1325
|
-
histogram.record(value, labels);
|
|
735
|
+
})();
|
|
736
|
+
`.trim();
|
|
737
|
+
|
|
738
|
+
// src/live-reload.ts
|
|
739
|
+
var LIVE_RELOAD_SCRIPT = `
|
|
740
|
+
(function () {
|
|
741
|
+
var es = new EventSource("/__x/reload");
|
|
742
|
+
es.addEventListener("reload", function () {
|
|
743
|
+
es.close();
|
|
744
|
+
if (typeof window.__xSoftReload === "function") {
|
|
745
|
+
window.__xSoftReload();
|
|
746
|
+
} else {
|
|
747
|
+
window.location.reload();
|
|
1326
748
|
}
|
|
749
|
+
});
|
|
750
|
+
es.addEventListener("hb", function () {});
|
|
751
|
+
es.onerror = function () {
|
|
752
|
+
es.close();
|
|
1327
753
|
};
|
|
754
|
+
})();
|
|
755
|
+
`.trim();
|
|
756
|
+
|
|
757
|
+
// src/render.ts
|
|
758
|
+
function escapeHtml2(s) {
|
|
759
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
1328
760
|
}
|
|
1329
|
-
function
|
|
1330
|
-
|
|
1331
|
-
if (entries.length === 0) return "";
|
|
1332
|
-
const escaped = entries.map(([k, v]) => `${k}="${escapeLabelValue(v)}"`).join(",");
|
|
1333
|
-
return `{${escaped}}`;
|
|
761
|
+
function escapeJsonForScript(s) {
|
|
762
|
+
return s.replace(/<\//g, "<\\/");
|
|
1334
763
|
}
|
|
1335
|
-
function
|
|
1336
|
-
return
|
|
764
|
+
function buildHeadExtras(stylesheet) {
|
|
765
|
+
return stylesheet ? `
|
|
766
|
+
<link rel="stylesheet" href="${escapeHtml2(stylesheet)}" />` : "";
|
|
1337
767
|
}
|
|
1338
|
-
function
|
|
1339
|
-
return
|
|
1340
|
-
|
|
1341
|
-
const method = req.method;
|
|
1342
|
-
try {
|
|
1343
|
-
const res = await handler(req, server);
|
|
1344
|
-
reporter.incr("x_http_requests_total", 1, { method, status: String(res.status) });
|
|
1345
|
-
reporter.observe("x_http_request_duration_ms", performance.now() - start, { method });
|
|
1346
|
-
return res;
|
|
1347
|
-
} catch (err) {
|
|
1348
|
-
reporter.incr("x_http_requests_total", 1, { method, status: "500" });
|
|
1349
|
-
reporter.incr("x_http_errors_total", 1, { method });
|
|
1350
|
-
reporter.observe("x_http_request_duration_ms", performance.now() - start, { method });
|
|
1351
|
-
throw err;
|
|
1352
|
-
}
|
|
1353
|
-
};
|
|
768
|
+
function buildNavScriptTag(clientNav) {
|
|
769
|
+
return clientNav === false ? "" : `
|
|
770
|
+
<script>${CLIENT_NAV_SCRIPT}</script>`;
|
|
1354
771
|
}
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
function buildSecurityHeaders(options = {}) {
|
|
1359
|
-
const headers = new Headers();
|
|
1360
|
-
const csp = options.contentSecurityPolicy ?? DEFAULT_CSP;
|
|
1361
|
-
if (csp !== false) headers.set("Content-Security-Policy", csp);
|
|
1362
|
-
const hstsMaxAge = options.hstsMaxAge ?? 15552e3;
|
|
1363
|
-
if (hstsMaxAge !== false) {
|
|
1364
|
-
const includeSub = options.hstsIncludeSubDomains ?? true;
|
|
1365
|
-
headers.set(
|
|
1366
|
-
"Strict-Transport-Security",
|
|
1367
|
-
`max-age=${hstsMaxAge}${includeSub ? "; includeSubDomains" : ""}`
|
|
1368
|
-
);
|
|
1369
|
-
}
|
|
1370
|
-
const frameOptions = options.frameOptions ?? "DENY";
|
|
1371
|
-
if (frameOptions !== false) headers.set("X-Frame-Options", frameOptions);
|
|
1372
|
-
const contentTypeOptions = options.contentTypeOptions ?? "nosniff";
|
|
1373
|
-
if (contentTypeOptions !== false) headers.set("X-Content-Type-Options", contentTypeOptions);
|
|
1374
|
-
const referrerPolicy = options.referrerPolicy ?? "strict-origin-when-cross-origin";
|
|
1375
|
-
if (referrerPolicy !== false) headers.set("Referrer-Policy", referrerPolicy);
|
|
1376
|
-
return headers;
|
|
772
|
+
function buildLiveReloadTag(liveReload) {
|
|
773
|
+
return liveReload ? `
|
|
774
|
+
<script>${LIVE_RELOAD_SCRIPT}</script>` : "";
|
|
1377
775
|
}
|
|
1378
|
-
function
|
|
1379
|
-
const
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
776
|
+
function htmlShell(title, headExtras, propsScript, scripts, bodySlot, navScriptTag, liveReloadTag) {
|
|
777
|
+
const finalScripts = scripts ?? "";
|
|
778
|
+
const inside = `${bodySlot}${propsScript ? `
|
|
779
|
+
${propsScript}` : ""}${finalScripts ? `
|
|
780
|
+
${finalScripts}` : ""}`;
|
|
781
|
+
return `<!DOCTYPE html>
|
|
782
|
+
<html lang="en">
|
|
783
|
+
<head>
|
|
784
|
+
<meta charset="UTF-8" />
|
|
785
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
786
|
+
<title>${escapeHtml2(title)}</title>${headExtras}
|
|
787
|
+
</head>
|
|
788
|
+
<body>
|
|
789
|
+
<div id="root">${inside}</div>
|
|
790
|
+
${navScriptTag ? ` ${navScriptTag}
|
|
791
|
+
` : ""}${liveReloadTag} </body>
|
|
792
|
+
</html>`;
|
|
1386
793
|
}
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
}
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
794
|
+
function renderPage(node, options = {}) {
|
|
795
|
+
const { islandScripts, islandProps } = options;
|
|
796
|
+
const title = options.title ?? "x app";
|
|
797
|
+
const body = renderToString(node);
|
|
798
|
+
const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
|
|
799
|
+
const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json">${propsJson}</script>` : "";
|
|
800
|
+
const islandScriptsHtml = islandScripts?.map((src) => `<script data-island-script src="${escapeHtml2(src)}"></script>`).join("\n ");
|
|
801
|
+
return htmlShell(
|
|
802
|
+
title,
|
|
803
|
+
buildHeadExtras(options.stylesheet),
|
|
804
|
+
propsScript,
|
|
805
|
+
islandScriptsHtml,
|
|
806
|
+
body,
|
|
807
|
+
buildNavScriptTag(options.clientNav),
|
|
808
|
+
buildLiveReloadTag(options.liveReload)
|
|
809
|
+
);
|
|
1397
810
|
}
|
|
1398
|
-
function
|
|
1399
|
-
const
|
|
1400
|
-
const
|
|
1401
|
-
const
|
|
1402
|
-
const
|
|
1403
|
-
const
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
buckets.set(key, bucket);
|
|
1415
|
-
}
|
|
1416
|
-
bucket.count += 1;
|
|
1417
|
-
const ok = bucket.count <= limit;
|
|
1418
|
-
return { ok, limit, remaining: Math.max(0, limit - bucket.count), resetAt: bucket.resetAt };
|
|
1419
|
-
}
|
|
1420
|
-
function sweep() {
|
|
1421
|
-
const now = Date.now();
|
|
1422
|
-
for (const [key, bucket] of buckets) {
|
|
1423
|
-
if (bucket.resetAt <= now) buckets.delete(key);
|
|
1424
|
-
}
|
|
1425
|
-
}
|
|
1426
|
-
const timer = setInterval(sweep, Math.max(windowMs, 1e3));
|
|
1427
|
-
timer.unref?.();
|
|
1428
|
-
return { check, sweep, buckets, dispose: () => clearInterval(timer) };
|
|
811
|
+
function renderStaticPage(node, options = {}) {
|
|
812
|
+
const { islandScripts, islandProps } = options;
|
|
813
|
+
const title = options.title ?? "x app";
|
|
814
|
+
const body = renderToStaticMarkup(node);
|
|
815
|
+
const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
|
|
816
|
+
const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json">${propsJson}</script>` : "";
|
|
817
|
+
const islandScriptsHtml = islandScripts?.map((src) => `<script data-island-script src="${escapeHtml2(src)}"></script>`).join("\n ");
|
|
818
|
+
return htmlShell(
|
|
819
|
+
title,
|
|
820
|
+
buildHeadExtras(options.stylesheet),
|
|
821
|
+
propsScript,
|
|
822
|
+
islandScriptsHtml,
|
|
823
|
+
body,
|
|
824
|
+
buildNavScriptTag(options.clientNav),
|
|
825
|
+
buildLiveReloadTag(options.liveReload)
|
|
826
|
+
);
|
|
1429
827
|
}
|
|
1430
|
-
async function
|
|
1431
|
-
const
|
|
1432
|
-
|
|
1433
|
-
const
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
828
|
+
async function renderStreamingPage(node, options = {}) {
|
|
829
|
+
const { islandScripts, islandProps } = options;
|
|
830
|
+
const title = escapeHtml2(options.title ?? "x app");
|
|
831
|
+
const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
|
|
832
|
+
const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json">${propsJson}</script>` : "";
|
|
833
|
+
const islandScriptsHtml = islandScripts?.map((src) => `<script data-island-script src="${escapeHtml2(src)}"></script>`).join("\n ");
|
|
834
|
+
const navScriptTag = buildNavScriptTag(options.clientNav);
|
|
835
|
+
const liveReloadTag = buildLiveReloadTag(options.liveReload);
|
|
836
|
+
const headExtras = buildHeadExtras(options.stylesheet);
|
|
837
|
+
const rootFooter = `${propsScript ? ` ${propsScript}
|
|
838
|
+
` : ""}${islandScriptsHtml ? ` ${islandScriptsHtml}
|
|
839
|
+
` : ""}`;
|
|
840
|
+
const footer = `</div>${navScriptTag}
|
|
841
|
+
${liveReloadTag} </body>
|
|
842
|
+
</html>`;
|
|
843
|
+
const reactStream = await renderToReadableStream(node, {
|
|
844
|
+
onError(err) {
|
|
845
|
+
console.error("[x] render error:", err);
|
|
1441
846
|
}
|
|
1442
847
|
});
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
848
|
+
const encoder = new TextEncoder();
|
|
849
|
+
const header = `<!DOCTYPE html>
|
|
850
|
+
<html lang="en">
|
|
851
|
+
<head>
|
|
852
|
+
<meta charset="UTF-8" />
|
|
853
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
854
|
+
<title>${title}</title>${headExtras}
|
|
855
|
+
</head>
|
|
856
|
+
<body>
|
|
857
|
+
<div id="root">`;
|
|
858
|
+
return new ReadableStream({
|
|
859
|
+
async start(controller) {
|
|
860
|
+
controller.enqueue(encoder.encode(header));
|
|
861
|
+
const reader = reactStream.getReader();
|
|
862
|
+
async function pump() {
|
|
863
|
+
try {
|
|
864
|
+
const { done, value } = await reader.read();
|
|
865
|
+
if (done) {
|
|
866
|
+
controller.enqueue(encoder.encode(`${rootFooter}
|
|
867
|
+
${footer}`));
|
|
868
|
+
controller.close();
|
|
869
|
+
return;
|
|
870
|
+
}
|
|
871
|
+
controller.enqueue(value);
|
|
872
|
+
await pump();
|
|
873
|
+
} catch (err) {
|
|
874
|
+
console.error("[x] stream read error:", err);
|
|
875
|
+
controller.enqueue(
|
|
876
|
+
encoder.encode(
|
|
877
|
+
`${rootFooter}<div style="color:red;padding:1em;margin:1rem">Render error: ${err instanceof Error ? err.message : "Unknown"}</div>
|
|
878
|
+
${footer}`
|
|
879
|
+
)
|
|
880
|
+
);
|
|
881
|
+
controller.close();
|
|
1470
882
|
}
|
|
1471
|
-
);
|
|
1472
|
-
}
|
|
1473
|
-
return connecting;
|
|
1474
|
-
}
|
|
1475
|
-
return {
|
|
1476
|
-
async incr(key, windowMs) {
|
|
1477
|
-
const c = await getClient();
|
|
1478
|
-
const redisKey = `x:ratelimit:${key}`;
|
|
1479
|
-
const ttlSeconds = Math.max(1, Math.ceil(windowMs / 1e3));
|
|
1480
|
-
const count = Number(await c.sendCommand("INCR", redisKey));
|
|
1481
|
-
if (count === 1) {
|
|
1482
|
-
await c.sendCommand("EXPIRE", redisKey, String(ttlSeconds));
|
|
1483
883
|
}
|
|
1484
|
-
|
|
884
|
+
await pump();
|
|
1485
885
|
}
|
|
1486
|
-
};
|
|
886
|
+
});
|
|
1487
887
|
}
|
|
1488
888
|
|
|
1489
|
-
// src/
|
|
1490
|
-
function
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
const
|
|
1501
|
-
const
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
if (
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
if (pathname === "/" || pathname.endsWith("/")) return null;
|
|
1510
|
-
const filePath = resolvePublicAsset(publicDir, pathname);
|
|
1511
|
-
if (!filePath) return null;
|
|
1512
|
-
const bun = globalThis.Bun;
|
|
1513
|
-
if (!bun) return null;
|
|
1514
|
-
const file = bun.file(filePath);
|
|
1515
|
-
if (!await file.exists()) return null;
|
|
1516
|
-
return new Response(file);
|
|
1517
|
-
}
|
|
1518
|
-
function wrapWithLayouts(Component, params, loaderData, layoutModules) {
|
|
1519
|
-
let content = createElement(Component, { params, loaderData });
|
|
1520
|
-
for (const Layout of [...layoutModules].reverse()) {
|
|
1521
|
-
content = createElement(Layout, null, content);
|
|
1522
|
-
}
|
|
1523
|
-
return content;
|
|
1524
|
-
}
|
|
1525
|
-
function renderContentPage(content, stylesheet, dev = false) {
|
|
1526
|
-
const title = content.frontmatter.title ?? content.slug;
|
|
1527
|
-
const bodyHtml = renderMarkdown(content.body);
|
|
1528
|
-
const body = renderPage(
|
|
1529
|
-
createElement(
|
|
1530
|
-
"article",
|
|
1531
|
-
null,
|
|
1532
|
-
content.frontmatter.title ? createElement("h1", null, content.frontmatter.title) : null,
|
|
1533
|
-
createElement("div", {
|
|
1534
|
-
// biome-ignore lint/security/noDangerouslySetInnerHtml: body is markdown rendered to HTML
|
|
1535
|
-
dangerouslySetInnerHTML: { __html: bodyHtml }
|
|
1536
|
-
})
|
|
1537
|
-
),
|
|
1538
|
-
{ title, stylesheet, liveReload: dev }
|
|
1539
|
-
);
|
|
1540
|
-
return body;
|
|
1541
|
-
}
|
|
1542
|
-
function defineConfig(config) {
|
|
1543
|
-
return config;
|
|
1544
|
-
}
|
|
1545
|
-
function importDev(path, dev) {
|
|
1546
|
-
return dev ? import(`${path}?t=${Date.now()}`) : import(path);
|
|
1547
|
-
}
|
|
1548
|
-
async function createApp(options) {
|
|
1549
|
-
const dev = options.development ?? false;
|
|
1550
|
-
const primaryDir = options.pagesDir || options.routesDir || "src/pages";
|
|
1551
|
-
const projectRoot = projectRootFromRoutesDir(primaryDir);
|
|
1552
|
-
const resolvedActionsDir = options.actionsDir ?? (existsSync(join4(projectRoot, "src", "actions")) ? join4(projectRoot, "src", "actions") : void 0);
|
|
1553
|
-
let handlers = [];
|
|
1554
|
-
let contentHandlers = [];
|
|
1555
|
-
let publicDir = null;
|
|
1556
|
-
let stylesheetHref;
|
|
1557
|
-
let notFoundComponent = DefaultNotFound;
|
|
1558
|
-
let notFoundLayout;
|
|
1559
|
-
const serverFnHandler = getServerFunctionHandler(options.security?.csrf);
|
|
1560
|
-
const staticCache = /* @__PURE__ */ new Map();
|
|
1561
|
-
let actionModules = /* @__PURE__ */ new Map();
|
|
1562
|
-
const islandBundleCache = /* @__PURE__ */ new Map();
|
|
1563
|
-
const islandFileCache = /* @__PURE__ */ new Map();
|
|
1564
|
-
async function resolveIslandScripts(routeFilePath, layoutFilePaths, entries) {
|
|
1565
|
-
if (entries.length === 0) return [];
|
|
1566
|
-
const uniqueNames = [...new Set(entries.map((e) => e.name))].sort();
|
|
1567
|
-
const cacheKey = `${routeFilePath}::${layoutFilePaths.join("|")}::${uniqueNames.join(",")}`;
|
|
1568
|
-
const cached = islandBundleCache.get(cacheKey);
|
|
1569
|
-
if (cached) return cached;
|
|
1570
|
-
const code = await buildIslandBundleInMemory(
|
|
1571
|
-
routeFilePath,
|
|
1572
|
-
layoutFilePaths,
|
|
1573
|
-
uniqueNames,
|
|
1574
|
-
actionModules,
|
|
1575
|
-
projectRoot
|
|
1576
|
-
);
|
|
1577
|
-
const entryId = islandEntryId(routeFilePath);
|
|
1578
|
-
const url = `/_islands/${entryId}/${entryId}.js`;
|
|
1579
|
-
islandFileCache.set(url, code);
|
|
1580
|
-
const scripts = [url];
|
|
1581
|
-
islandBundleCache.set(cacheKey, scripts);
|
|
1582
|
-
return scripts;
|
|
1583
|
-
}
|
|
1584
|
-
function serveIslandBundle(req) {
|
|
1585
|
-
if (req.method !== "GET" && req.method !== "HEAD") return null;
|
|
1586
|
-
const pathname = new URL(req.url).pathname;
|
|
1587
|
-
if (!pathname.startsWith("/_islands/")) return null;
|
|
1588
|
-
const code = islandFileCache.get(pathname);
|
|
1589
|
-
if (code === void 0) return null;
|
|
1590
|
-
return new Response(code, {
|
|
1591
|
-
headers: { "Content-Type": "application/javascript; charset=utf-8" }
|
|
1592
|
-
});
|
|
889
|
+
// src/build.ts
|
|
890
|
+
async function build(options) {
|
|
891
|
+
const outDir = options.outDir ?? join4(process.cwd(), ".x");
|
|
892
|
+
const clientDir = join4(outDir, "client");
|
|
893
|
+
const serverDir = join4(outDir, "server");
|
|
894
|
+
const islandsDir = join4(clientDir, "_islands");
|
|
895
|
+
mkdirSync2(clientDir, { recursive: true });
|
|
896
|
+
mkdirSync2(serverDir, { recursive: true });
|
|
897
|
+
mkdirSync2(islandsDir, { recursive: true });
|
|
898
|
+
const pagesDir = options.pagesDir ?? options.routesDir ?? "";
|
|
899
|
+
const apiDir = options.apiDir;
|
|
900
|
+
const actionsDir = options.actionsDir;
|
|
901
|
+
const layoutsDir = options.layoutsDir ?? pagesDir;
|
|
902
|
+
const projectRoot = pagesDir ? join4(pagesDir, "..", "..") : process.cwd();
|
|
903
|
+
const publicDir = join4(projectRoot, "public");
|
|
904
|
+
const hasPublicDir = existsSync(publicDir);
|
|
905
|
+
const stylesheetHref = hasPublicDir && existsSync(join4(publicDir, "styles.css")) ? "/styles.css" : void 0;
|
|
906
|
+
if (hasPublicDir) {
|
|
907
|
+
cpSync(publicDir, clientDir, { recursive: true });
|
|
908
|
+
console.log(`[x] build: copied public/ -> ${relative2(process.cwd(), clientDir)}`);
|
|
1593
909
|
}
|
|
1594
|
-
|
|
1595
|
-
|
|
910
|
+
let routeEntries = [];
|
|
911
|
+
if (pagesDir && existsSync(pagesDir)) {
|
|
912
|
+
routeEntries = scanPages(pagesDir);
|
|
1596
913
|
}
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
const rateLimiter = options.security?.rateLimit === false ? null : createRateLimiter(options.security?.rateLimit ?? {});
|
|
1600
|
-
const securityHeadersOptions = options.security?.headers;
|
|
1601
|
-
const loggingEnabled = options.observability?.logging ?? true;
|
|
1602
|
-
const imageProxyHandler = createImageProxyHandler(options.images);
|
|
1603
|
-
function withResponseHardening(res) {
|
|
1604
|
-
return securityHeadersOptions === false ? res : applySecurityHeaders(res, securityHeadersOptions);
|
|
914
|
+
if (apiDir && existsSync(apiDir)) {
|
|
915
|
+
routeEntries.push(...scanApiDir(apiDir));
|
|
1605
916
|
}
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
title: "404 \u2014 Not Found",
|
|
1610
|
-
stylesheet: stylesheetHref,
|
|
1611
|
-
liveReload: dev
|
|
1612
|
-
});
|
|
1613
|
-
return new Response(html, {
|
|
1614
|
-
status: 404,
|
|
1615
|
-
headers: { "Content-Type": "text/html; charset=utf-8" }
|
|
1616
|
-
});
|
|
917
|
+
const legacyApiDir = pagesDir ? join4(pagesDir, "api") : "";
|
|
918
|
+
if (legacyApiDir && existsSync(legacyApiDir) && legacyApiDir !== apiDir) {
|
|
919
|
+
routeEntries.push(...scanApiDir(legacyApiDir));
|
|
1617
920
|
}
|
|
1618
|
-
const
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
const
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
921
|
+
const actionModules = /* @__PURE__ */ new Map();
|
|
922
|
+
if (actionsDir && existsSync(actionsDir)) {
|
|
923
|
+
for (const actionFile of scanRoutes(actionsDir)) {
|
|
924
|
+
const mod = await import(actionFile.filePath);
|
|
925
|
+
const segments = actionFile.routePath.split("/").filter(Boolean);
|
|
926
|
+
const parentPath = `/${segments.slice(0, -1).join("/")}`;
|
|
927
|
+
const fnNames = [];
|
|
928
|
+
const actions = mod.actions;
|
|
929
|
+
if (actions) {
|
|
930
|
+
registerServerFunctions(parentPath, actionFile.paramNames, actions);
|
|
931
|
+
fnNames.push(...Object.keys(actions));
|
|
1629
932
|
}
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
console.error("[x] API handler error:", err);
|
|
1635
|
-
if (dev) {
|
|
1636
|
-
return new Response(renderErrorOverlay(err), {
|
|
1637
|
-
status: 500,
|
|
1638
|
-
headers: { "Content-Type": "text/html; charset=utf-8" }
|
|
933
|
+
for (const [key, value] of Object.entries(mod)) {
|
|
934
|
+
if (key === "default" || key === "actions" || typeof value !== "function") continue;
|
|
935
|
+
registerServerFunctions(parentPath, actionFile.paramNames, {
|
|
936
|
+
[key]: value
|
|
1639
937
|
});
|
|
938
|
+
fnNames.push(key);
|
|
939
|
+
}
|
|
940
|
+
if (fnNames.length > 0) {
|
|
941
|
+
actionModules.set(actionFile.filePath, { parentPath, fnNames });
|
|
1640
942
|
}
|
|
1641
|
-
return new Response("Internal server error", { status: 500 });
|
|
1642
943
|
}
|
|
1643
|
-
}
|
|
1644
|
-
const
|
|
1645
|
-
|
|
1646
|
-
|
|
944
|
+
}
|
|
945
|
+
const dedicatedLayouts = layoutsDir && layoutsDir !== pagesDir && existsSync(layoutsDir) ? scanLayoutsDir(layoutsDir) : [];
|
|
946
|
+
const nestedLayouts = pagesDir && existsSync(pagesDir) ? scanLayouts(pagesDir) : [];
|
|
947
|
+
const layouts = [...dedicatedLayouts, ...nestedLayouts];
|
|
948
|
+
const staticPages = [];
|
|
949
|
+
const serverPages = [];
|
|
950
|
+
const apiRoutes = [];
|
|
951
|
+
for (const entry of routeEntries) {
|
|
952
|
+
if (entry.isApi) {
|
|
953
|
+
apiRoutes.push(entry);
|
|
954
|
+
continue;
|
|
955
|
+
}
|
|
956
|
+
const mod = await import(entry.filePath);
|
|
957
|
+
const Component = mod.default;
|
|
958
|
+
if (!Component) {
|
|
959
|
+
console.warn(`[x] ${entry.filePath} has no default export -- skipping`);
|
|
960
|
+
continue;
|
|
961
|
+
}
|
|
962
|
+
const mode = mod.mode ?? "server";
|
|
963
|
+
const layoutChain = findLayoutChain(entry.filePath, layouts, pagesDir);
|
|
964
|
+
for (const rootLayout of dedicatedLayouts) {
|
|
965
|
+
if (!layoutChain.some((l) => l.filePath === rootLayout.filePath)) {
|
|
966
|
+
layoutChain.unshift(rootLayout);
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
const layoutModules = [];
|
|
970
|
+
for (const l of layoutChain) {
|
|
971
|
+
const layoutMod = await import(l.filePath);
|
|
972
|
+
if (layoutMod.default) layoutModules.push(layoutMod.default);
|
|
973
|
+
}
|
|
974
|
+
const page = {
|
|
975
|
+
entry,
|
|
976
|
+
filePath: entry.filePath,
|
|
1647
977
|
mode,
|
|
1648
|
-
revalidate,
|
|
1649
|
-
loader,
|
|
1650
978
|
Component,
|
|
1651
979
|
layoutModules,
|
|
1652
|
-
layoutFilePaths
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
980
|
+
layoutFilePaths: layoutChain.map((l) => l.filePath)
|
|
981
|
+
};
|
|
982
|
+
if (mode === "static") {
|
|
983
|
+
staticPages.push(page);
|
|
984
|
+
} else {
|
|
985
|
+
serverPages.push(page);
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
let contentEntries = [];
|
|
989
|
+
if (options.contentDir) {
|
|
990
|
+
contentEntries = scanContent(options.contentDir);
|
|
991
|
+
}
|
|
992
|
+
console.log(
|
|
993
|
+
`[x] build: ${staticPages.length} static, ${serverPages.length} server, ${contentEntries.length} content pages`
|
|
994
|
+
);
|
|
995
|
+
const writtenPaths = /* @__PURE__ */ new Set();
|
|
996
|
+
for (const page of staticPages) {
|
|
997
|
+
const params = {};
|
|
998
|
+
const registry = createIslandRegistry();
|
|
999
|
+
const pageContent = renderPageWithLayout(page.Component, params, page.layoutModules);
|
|
1000
|
+
const content = createElement(IslandProvider, { registry }, pageContent);
|
|
1001
|
+
const _html = renderStaticPage(content, { stylesheet: stylesheetHref });
|
|
1002
|
+
const outPath = page.entry.routePath === "/" ? "/index.html" : `${page.entry.routePath}/index.html`;
|
|
1003
|
+
const fullPath = join4(clientDir, outPath);
|
|
1004
|
+
mkdirSync2(join4(fullPath, ".."), { recursive: true });
|
|
1005
|
+
if (writtenPaths.has(outPath)) {
|
|
1006
|
+
console.warn(` [warn] collision: ${page.entry.routePath} overwrites existing output`);
|
|
1007
|
+
}
|
|
1008
|
+
writtenPaths.add(outPath);
|
|
1009
|
+
let islandScripts = [];
|
|
1010
|
+
if (registry.entries.length > 0) {
|
|
1011
|
+
const uniqueNames = [...new Set(registry.entries.map((e) => e.name))];
|
|
1012
|
+
islandScripts = await bundleRouteIslands(
|
|
1013
|
+
page.filePath,
|
|
1014
|
+
page.layoutFilePaths,
|
|
1015
|
+
uniqueNames,
|
|
1016
|
+
islandsDir,
|
|
1017
|
+
actionModules
|
|
1018
|
+
);
|
|
1019
|
+
console.log(
|
|
1020
|
+
` [islands] ${uniqueNames.length} island(s) on ${page.entry.routePath} -> ${islandScripts.join(", ")}`
|
|
1021
|
+
);
|
|
1022
|
+
}
|
|
1023
|
+
const finalHtml = renderStaticPage(content, { islandScripts, stylesheet: stylesheetHref });
|
|
1024
|
+
writeFileSync3(fullPath, finalHtml, "utf-8");
|
|
1025
|
+
console.log(` [static] ${page.entry.routePath} -> ${outPath}`);
|
|
1026
|
+
}
|
|
1027
|
+
for (const content of contentEntries) {
|
|
1028
|
+
const registry = createIslandRegistry();
|
|
1029
|
+
const bodyHtml = renderMarkdown(content.body);
|
|
1030
|
+
const pageContent = createElement(StaticContentPage, {
|
|
1031
|
+
content,
|
|
1032
|
+
bodyHtml
|
|
1033
|
+
});
|
|
1034
|
+
const rendered = createElement(IslandProvider, { registry }, pageContent);
|
|
1035
|
+
const html = renderStaticPage(rendered, {
|
|
1036
|
+
title: content.frontmatter.title ?? content.slug,
|
|
1037
|
+
stylesheet: stylesheetHref
|
|
1038
|
+
});
|
|
1039
|
+
const outPath = content.routePath === "/" ? "/index.html" : `${content.routePath}/index.html`;
|
|
1040
|
+
const fullPath = join4(clientDir, outPath);
|
|
1041
|
+
mkdirSync2(join4(fullPath, ".."), { recursive: true });
|
|
1042
|
+
if (writtenPaths.has(outPath)) {
|
|
1043
|
+
console.warn(` [warn] collision: content ${content.routePath} overwrites existing output`);
|
|
1044
|
+
}
|
|
1045
|
+
writtenPaths.add(outPath);
|
|
1046
|
+
writeFileSync3(fullPath, html, "utf-8");
|
|
1047
|
+
console.log(` [content] ${content.routePath} -> ${outPath}`);
|
|
1048
|
+
}
|
|
1049
|
+
if (pagesDir || options.routesDir || options.contentDir) {
|
|
1050
|
+
const srvOpts = {
|
|
1051
|
+
pagesDir: pagesDir || options.routesDir || ""
|
|
1052
|
+
};
|
|
1053
|
+
if (options.apiDir) srvOpts.apiDir = options.apiDir;
|
|
1054
|
+
if (options.layoutsDir) srvOpts.layoutsDir = options.layoutsDir;
|
|
1055
|
+
if (options.actionsDir) srvOpts.actionsDir = options.actionsDir;
|
|
1056
|
+
if (options.contentDir) srvOpts.contentDir = options.contentDir;
|
|
1057
|
+
const configImportPath = options.configPath ? relativeImportPath(serverDir, options.configPath) : void 0;
|
|
1058
|
+
const serverEntry = buildServerEntry(
|
|
1059
|
+
srvOpts,
|
|
1060
|
+
configImportPath,
|
|
1061
|
+
stylesheetHref
|
|
1062
|
+
);
|
|
1063
|
+
const serverEntryPath = join4(serverDir, "index.ts");
|
|
1064
|
+
writeFileSync3(serverEntryPath, serverEntry, "utf-8");
|
|
1065
|
+
console.log(
|
|
1066
|
+
` [server] ${serverPages.length} page routes, ${apiRoutes.length} api routes -> server/index.ts`
|
|
1067
|
+
);
|
|
1068
|
+
}
|
|
1069
|
+
console.log(`[x] build complete -> ${outDir}`);
|
|
1070
|
+
}
|
|
1071
|
+
async function bundleRouteIslands(routeFilePath, layoutFilePaths, islandNames, islandsDir, actionModules) {
|
|
1072
|
+
const entryId = islandEntryId(routeFilePath);
|
|
1073
|
+
const outdir = join4(islandsDir, entryId);
|
|
1074
|
+
mkdirSync2(outdir, { recursive: true });
|
|
1075
|
+
const bundlePath = join4(outdir, `${entryId}.js`);
|
|
1076
|
+
const hydrateEntry = generateHydrateEntry(routeFilePath, layoutFilePaths);
|
|
1077
|
+
const entryPath = join4(outdir, `${entryId}.tsx`);
|
|
1078
|
+
writeFileSync3(entryPath, hydrateEntry, "utf-8");
|
|
1079
|
+
try {
|
|
1080
|
+
const result = await Bun.build({
|
|
1081
|
+
entrypoints: [entryPath],
|
|
1082
|
+
target: "browser",
|
|
1083
|
+
plugins: [actionsRewritePlugin(actionModules)]
|
|
1084
|
+
});
|
|
1085
|
+
if (result.success) {
|
|
1086
|
+
const outputs = result.outputs.filter((o) => o.kind === "entry-point");
|
|
1087
|
+
const built = outputs[0] ?? result.outputs[0];
|
|
1088
|
+
if (!built) throw new Error("bun build produced no output");
|
|
1089
|
+
const code = await built.text();
|
|
1090
|
+
assertNoEnvLeakage(code, bundlePath);
|
|
1091
|
+
writeFileSync3(bundlePath, wrapIslandBundle(code), "utf-8");
|
|
1092
|
+
return [`/_islands/${entryId}/${entryId}.js`];
|
|
1093
|
+
}
|
|
1094
|
+
for (const log of result.logs) {
|
|
1095
|
+
console.warn(` [islands] build error: ${log.message}`);
|
|
1096
|
+
}
|
|
1097
|
+
} catch (err) {
|
|
1098
|
+
if (err instanceof EnvLeakageError) throw err;
|
|
1099
|
+
console.warn(` [islands] build failed for ${routeFilePath}:`, err);
|
|
1100
|
+
}
|
|
1101
|
+
writeFileSync3(bundlePath, wrapIslandBundle(generateFallbackHydration(islandNames)), "utf-8");
|
|
1102
|
+
return [`/_islands/${entryId}/${entryId}.js`];
|
|
1103
|
+
}
|
|
1104
|
+
function renderPageWithLayout(Component, params, layoutModules) {
|
|
1105
|
+
let content = createElement(Component, { params });
|
|
1106
|
+
for (const Layout of [...layoutModules].reverse()) {
|
|
1107
|
+
content = createElement(Layout, null, content);
|
|
1108
|
+
}
|
|
1109
|
+
return content;
|
|
1110
|
+
}
|
|
1111
|
+
function StaticContentPage({ content, bodyHtml }) {
|
|
1112
|
+
return createElement(
|
|
1113
|
+
"article",
|
|
1114
|
+
null,
|
|
1115
|
+
content.frontmatter.title ? createElement("h1", null, content.frontmatter.title) : null,
|
|
1116
|
+
createElement("div", {
|
|
1117
|
+
// biome-ignore lint/security/noDangerouslySetInnerHtml: body is markdown rendered to HTML
|
|
1118
|
+
dangerouslySetInnerHTML: { __html: bodyHtml }
|
|
1119
|
+
})
|
|
1120
|
+
);
|
|
1121
|
+
}
|
|
1122
|
+
function buildServerEntry(opts, configImportPath, stylesheetHref) {
|
|
1123
|
+
const dirKeys = ["pagesDir", "apiDir", "layoutsDir", "actionsDir", "contentDir"];
|
|
1124
|
+
const lines = [
|
|
1125
|
+
"// Auto-generated by @thexjs/core build",
|
|
1126
|
+
'import { createApp } from "@thexjs/core";'
|
|
1127
|
+
];
|
|
1128
|
+
if (configImportPath) {
|
|
1129
|
+
lines.push("", "let userConfig = {};", "try {");
|
|
1130
|
+
lines.push(` const mod = await import(${JSON.stringify(configImportPath)});`);
|
|
1131
|
+
lines.push(" userConfig = mod.default ?? {};");
|
|
1132
|
+
lines.push("} catch (err) {");
|
|
1133
|
+
lines.push(
|
|
1134
|
+
' console.warn("[x] failed to load x.config for security/observability options:", err);'
|
|
1135
|
+
);
|
|
1136
|
+
lines.push("}");
|
|
1137
|
+
}
|
|
1138
|
+
lines.push("", "const app = await createApp({");
|
|
1139
|
+
for (const key of dirKeys) {
|
|
1140
|
+
const val = opts[key];
|
|
1141
|
+
if (val) lines.push(` ${key}: ${JSON.stringify(val)},`);
|
|
1142
|
+
}
|
|
1143
|
+
if (stylesheetHref) lines.push(` stylesheetHref: ${JSON.stringify(stylesheetHref)},`);
|
|
1144
|
+
lines.push(' port: parseInt(process.env.PORT || "3000", 10),', " development: false,");
|
|
1145
|
+
if (configImportPath) {
|
|
1146
|
+
lines.push(" ...(userConfig.security ? { security: userConfig.security } : {}),");
|
|
1147
|
+
lines.push(
|
|
1148
|
+
" ...(userConfig.observability ? { observability: userConfig.observability } : {}),"
|
|
1149
|
+
);
|
|
1150
|
+
lines.push(" ...(userConfig.images ? { images: userConfig.images } : {}),");
|
|
1151
|
+
}
|
|
1152
|
+
lines.push(
|
|
1153
|
+
"});",
|
|
1154
|
+
"",
|
|
1155
|
+
"const server = Bun.serve(app);",
|
|
1156
|
+
"",
|
|
1157
|
+
"console.log(`[x] production server running at ${server.url}`);",
|
|
1158
|
+
"",
|
|
1159
|
+
"// Graceful shutdown: stop accepting new connections, flush the error",
|
|
1160
|
+
"// reporter, then exit after in-flight requests have a moment to drain.",
|
|
1161
|
+
"let shuttingDown = false;",
|
|
1162
|
+
"async function shutdown(signal: string): Promise<void> {",
|
|
1163
|
+
" if (shuttingDown) return;",
|
|
1164
|
+
" shuttingDown = true;",
|
|
1165
|
+
" console.log(`[x] received ${signal} - shutting down`);",
|
|
1166
|
+
" try {",
|
|
1167
|
+
' const { getErrorReporter } = await import("@thexjs/core");',
|
|
1168
|
+
" await getErrorReporter().flush?.();",
|
|
1169
|
+
" } catch {}",
|
|
1170
|
+
" server.stop(true);",
|
|
1171
|
+
" const exit = () => process.exit(0);",
|
|
1172
|
+
" const drainTimer = setTimeout(exit, 3000);",
|
|
1173
|
+
" drainTimer.unref?.();",
|
|
1174
|
+
"}",
|
|
1175
|
+
'process.on("SIGTERM", () => shutdown("SIGTERM"));',
|
|
1176
|
+
'process.on("SIGINT", () => shutdown("SIGINT"));'
|
|
1177
|
+
);
|
|
1178
|
+
return lines.join("\n");
|
|
1179
|
+
}
|
|
1180
|
+
function relativeImportPath(fromDir, toFile) {
|
|
1181
|
+
const rel = relative2(fromDir, toFile).replace(/\\/g, "/").replace(/\.(ts|js|mjs)$/, "");
|
|
1182
|
+
return rel.startsWith(".") ? rel : `./${rel}`;
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
// src/createApp.ts
|
|
1186
|
+
import { existsSync as existsSync2, watch } from "fs";
|
|
1187
|
+
import { join as join5, resolve, sep as sep2 } from "path";
|
|
1188
|
+
import { createElement as createElement2 } from "react";
|
|
1189
|
+
|
|
1190
|
+
// src/error-overlay.ts
|
|
1191
|
+
function escapeHtml3(s) {
|
|
1192
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
1193
|
+
}
|
|
1194
|
+
function renderErrorOverlay(error) {
|
|
1195
|
+
const message = error instanceof Error ? error.message : "Unknown error";
|
|
1196
|
+
const stack = error instanceof Error ? error.stack ?? "" : "";
|
|
1197
|
+
const frames = stack.split("\n").slice(1).map((line) => `<span class="frame">${escapeHtml3(line.trim())}</span>`).join("\n");
|
|
1198
|
+
return `<!DOCTYPE html>
|
|
1199
|
+
<html lang="en">
|
|
1200
|
+
<head>
|
|
1201
|
+
<meta charset="UTF-8" />
|
|
1202
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
1203
|
+
<title>Server Error</title>
|
|
1204
|
+
<style>
|
|
1205
|
+
* { margin: 0; padding: 0; box-sizing: border-box; }
|
|
1206
|
+
body {
|
|
1207
|
+
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
|
1208
|
+
background: #1a1a2e;
|
|
1209
|
+
color: #e0e0e0;
|
|
1210
|
+
min-height: 100vh;
|
|
1211
|
+
display: flex;
|
|
1212
|
+
flex-direction: column;
|
|
1213
|
+
}
|
|
1214
|
+
.overlay {
|
|
1215
|
+
flex: 1;
|
|
1216
|
+
padding: 40px 24px;
|
|
1217
|
+
max-width: 900px;
|
|
1218
|
+
margin: 0 auto;
|
|
1219
|
+
width: 100%;
|
|
1220
|
+
}
|
|
1221
|
+
.header { margin-bottom: 32px; }
|
|
1222
|
+
.badge {
|
|
1223
|
+
display: inline-block;
|
|
1224
|
+
background: #e74c3c;
|
|
1225
|
+
color: #fff;
|
|
1226
|
+
font-size: 11px;
|
|
1227
|
+
font-weight: 700;
|
|
1228
|
+
letter-spacing: 0.05em;
|
|
1229
|
+
text-transform: uppercase;
|
|
1230
|
+
padding: 3px 10px;
|
|
1231
|
+
border-radius: 4px;
|
|
1232
|
+
margin-bottom: 12px;
|
|
1233
|
+
}
|
|
1234
|
+
h1 {
|
|
1235
|
+
font-size: 22px;
|
|
1236
|
+
font-weight: 600;
|
|
1237
|
+
color: #f0f0f0;
|
|
1238
|
+
line-height: 1.3;
|
|
1239
|
+
}
|
|
1240
|
+
.message-box {
|
|
1241
|
+
background: #2a2a4a;
|
|
1242
|
+
border: 1px solid #3a3a5a;
|
|
1243
|
+
border-radius: 8px;
|
|
1244
|
+
padding: 20px;
|
|
1245
|
+
margin-bottom: 24px;
|
|
1246
|
+
font-size: 15px;
|
|
1247
|
+
word-break: break-word;
|
|
1248
|
+
}
|
|
1249
|
+
.message-box .label {
|
|
1250
|
+
font-size: 11px;
|
|
1251
|
+
font-weight: 600;
|
|
1252
|
+
text-transform: uppercase;
|
|
1253
|
+
letter-spacing: 0.05em;
|
|
1254
|
+
color: #888;
|
|
1255
|
+
margin-bottom: 8px;
|
|
1256
|
+
}
|
|
1257
|
+
.message-box .message {
|
|
1258
|
+
color: #ff6b6b;
|
|
1259
|
+
font-family: "SF Mono", "Fira Code", "Fira Mono", monospace;
|
|
1260
|
+
font-size: 14px;
|
|
1261
|
+
white-space: pre-wrap;
|
|
1262
|
+
}
|
|
1263
|
+
.stack-section { margin-bottom: 24px; }
|
|
1264
|
+
.stack-section .label {
|
|
1265
|
+
font-size: 11px;
|
|
1266
|
+
font-weight: 600;
|
|
1267
|
+
text-transform: uppercase;
|
|
1268
|
+
letter-spacing: 0.05em;
|
|
1269
|
+
color: #888;
|
|
1270
|
+
margin-bottom: 12px;
|
|
1271
|
+
}
|
|
1272
|
+
.frame {
|
|
1273
|
+
display: block;
|
|
1274
|
+
padding: 6px 12px;
|
|
1275
|
+
font-family: "SF Mono", "Fira Code", "Fira Mono", monospace;
|
|
1276
|
+
font-size: 12px;
|
|
1277
|
+
color: #b0b0d0;
|
|
1278
|
+
line-height: 1.6;
|
|
1279
|
+
border-left: 2px solid #3a3a5a;
|
|
1280
|
+
margin-bottom: 2px;
|
|
1281
|
+
}
|
|
1282
|
+
.frame:first-child { border-left-color: #e74c3c; }
|
|
1283
|
+
.hint {
|
|
1284
|
+
font-size: 13px;
|
|
1285
|
+
color: #888;
|
|
1286
|
+
border-top: 1px solid #3a3a5a;
|
|
1287
|
+
padding-top: 20px;
|
|
1288
|
+
margin-top: 8px;
|
|
1289
|
+
}
|
|
1290
|
+
.hint a { color: #6ab0ff; }
|
|
1291
|
+
</style>
|
|
1292
|
+
</head>
|
|
1293
|
+
<body>
|
|
1294
|
+
<div class="overlay">
|
|
1295
|
+
<div class="header">
|
|
1296
|
+
<div class="badge">Server Error</div>
|
|
1297
|
+
<h1>Unhandled Error During Render</h1>
|
|
1298
|
+
</div>
|
|
1299
|
+
<div class="message-box">
|
|
1300
|
+
<div class="label">Error</div>
|
|
1301
|
+
<div class="message">${escapeHtml3(message)}</div>
|
|
1302
|
+
</div>
|
|
1303
|
+
${stack ? `<div class="stack-section"><div class="label">Stack Trace</div>${frames}</div>` : ""}
|
|
1304
|
+
<div class="hint">
|
|
1305
|
+
Fix the error and save the file. In development mode, the server will reload automatically.
|
|
1306
|
+
</div>
|
|
1307
|
+
</div>
|
|
1308
|
+
</body>
|
|
1309
|
+
</html>`;
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
// src/images/proxy.ts
|
|
1313
|
+
var ALLOWED_CONTENT_TYPES = /* @__PURE__ */ new Set([
|
|
1314
|
+
"image/png",
|
|
1315
|
+
"image/jpeg",
|
|
1316
|
+
"image/gif",
|
|
1317
|
+
"image/webp",
|
|
1318
|
+
"image/avif",
|
|
1319
|
+
"image/x-icon"
|
|
1320
|
+
]);
|
|
1321
|
+
function createImageProxyHandler(options = {}) {
|
|
1322
|
+
const allowedHosts = new Set(options.remoteHosts ?? []);
|
|
1323
|
+
return async (req) => {
|
|
1324
|
+
const reqUrl = new URL(req.url);
|
|
1325
|
+
if (reqUrl.pathname !== "/_x/image") return null;
|
|
1326
|
+
if (req.method !== "GET" && req.method !== "HEAD") return null;
|
|
1327
|
+
const target = reqUrl.searchParams.get("url");
|
|
1328
|
+
if (!target) return new Response("missing url param", { status: 400 });
|
|
1329
|
+
let parsed;
|
|
1330
|
+
try {
|
|
1331
|
+
parsed = new URL(target);
|
|
1332
|
+
} catch {
|
|
1333
|
+
return new Response("invalid url param", { status: 400 });
|
|
1334
|
+
}
|
|
1335
|
+
const allowedUrl = (u) => (u.protocol === "http:" || u.protocol === "https:") && allowedHosts.has(u.hostname);
|
|
1336
|
+
if (!allowedUrl(parsed)) {
|
|
1337
|
+
return new Response("host not allow-listed for image proxy", { status: 403 });
|
|
1338
|
+
}
|
|
1339
|
+
const isRedirect = (status) => status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
|
|
1340
|
+
let upstream;
|
|
1341
|
+
try {
|
|
1342
|
+
upstream = await fetch(parsed, { redirect: "manual" });
|
|
1343
|
+
for (let hop = 0; hop < 5; hop++) {
|
|
1344
|
+
if (!isRedirect(upstream.status)) break;
|
|
1345
|
+
const location = upstream.headers.get("location");
|
|
1346
|
+
let next;
|
|
1347
|
+
try {
|
|
1348
|
+
next = new URL(location ?? "", parsed);
|
|
1349
|
+
} catch {
|
|
1350
|
+
return new Response("upstream redirect was not a valid URL", { status: 502 });
|
|
1351
|
+
}
|
|
1352
|
+
if (!allowedUrl(next)) {
|
|
1353
|
+
return new Response("upstream redirected off the allow-list", { status: 403 });
|
|
1354
|
+
}
|
|
1355
|
+
upstream = await fetch(next, { redirect: "manual" });
|
|
1356
|
+
}
|
|
1357
|
+
} catch (err) {
|
|
1358
|
+
return new Response(`upstream fetch failed: ${String(err)}`, { status: 502 });
|
|
1359
|
+
}
|
|
1360
|
+
if (isRedirect(upstream.status)) {
|
|
1361
|
+
return new Response("too many upstream redirects", { status: 502 });
|
|
1362
|
+
}
|
|
1363
|
+
if (!upstream.ok) {
|
|
1364
|
+
return new Response("upstream error", { status: 502 });
|
|
1365
|
+
}
|
|
1366
|
+
const contentType = upstream.headers.get("content-type") ?? "";
|
|
1367
|
+
const baseContentType = (contentType.split(";")[0] ?? "").trim();
|
|
1368
|
+
if (!ALLOWED_CONTENT_TYPES.has(baseContentType)) {
|
|
1369
|
+
return new Response("upstream did not return an image", { status: 502 });
|
|
1370
|
+
}
|
|
1371
|
+
return new Response(upstream.body, {
|
|
1372
|
+
status: 200,
|
|
1373
|
+
headers: {
|
|
1374
|
+
"Content-Type": contentType,
|
|
1375
|
+
// Cache aggressively client + edge side — the proxied URL is the
|
|
1376
|
+
// cache key, and remote asset URLs like this one are typically
|
|
1377
|
+
// content-hashed by the origin already.
|
|
1378
|
+
"Cache-Control": "public, max-age=86400, immutable"
|
|
1379
|
+
}
|
|
1380
|
+
});
|
|
1381
|
+
};
|
|
1382
|
+
}
|
|
1383
|
+
|
|
1384
|
+
// src/middleware.ts
|
|
1385
|
+
function composeMiddleware(fns, handler) {
|
|
1386
|
+
return async (ctx, _next) => {
|
|
1387
|
+
let index = -1;
|
|
1388
|
+
const dispatch = async (i) => {
|
|
1389
|
+
if (i <= index) throw new Error("next() called multiple times");
|
|
1390
|
+
index = i;
|
|
1391
|
+
const fn = fns[i];
|
|
1392
|
+
if (fn) {
|
|
1393
|
+
return fn(ctx, () => dispatch(i + 1));
|
|
1394
|
+
}
|
|
1395
|
+
return handler(ctx);
|
|
1396
|
+
};
|
|
1397
|
+
return dispatch(0);
|
|
1398
|
+
};
|
|
1399
|
+
}
|
|
1400
|
+
|
|
1401
|
+
// src/not-found.tsx
|
|
1402
|
+
import { jsx as jsx2, jsxs } from "react/jsx-runtime";
|
|
1403
|
+
function DefaultNotFound(_props) {
|
|
1404
|
+
return /* @__PURE__ */ jsxs(
|
|
1405
|
+
"main",
|
|
1406
|
+
{
|
|
1407
|
+
style: {
|
|
1408
|
+
maxWidth: 640,
|
|
1409
|
+
margin: "4rem auto",
|
|
1410
|
+
padding: "0 1rem",
|
|
1411
|
+
fontFamily: "system-ui, -apple-system, sans-serif",
|
|
1412
|
+
textAlign: "center"
|
|
1413
|
+
},
|
|
1414
|
+
children: [
|
|
1415
|
+
/* @__PURE__ */ jsx2("h1", { style: { fontSize: "4rem", fontWeight: 700, margin: "0 0 0.5rem", color: "#e74c3c" }, children: "404" }),
|
|
1416
|
+
/* @__PURE__ */ jsx2("p", { style: { fontSize: "1.125rem", color: "#666", margin: "0 0 2rem" }, children: "This page could not be found." }),
|
|
1417
|
+
/* @__PURE__ */ jsx2(
|
|
1418
|
+
"a",
|
|
1419
|
+
{
|
|
1420
|
+
href: "/",
|
|
1421
|
+
style: {
|
|
1422
|
+
color: "#6ab0ff",
|
|
1423
|
+
textDecoration: "underline",
|
|
1424
|
+
fontSize: "0.875rem"
|
|
1425
|
+
},
|
|
1426
|
+
children: "Back to home"
|
|
1427
|
+
}
|
|
1428
|
+
)
|
|
1429
|
+
]
|
|
1430
|
+
}
|
|
1431
|
+
);
|
|
1432
|
+
}
|
|
1433
|
+
|
|
1434
|
+
// src/observability/health.ts
|
|
1435
|
+
async function runChecks(checks) {
|
|
1436
|
+
const results = {};
|
|
1437
|
+
let allOk = true;
|
|
1438
|
+
await Promise.all(
|
|
1439
|
+
Object.entries(checks).map(async ([name, check]) => {
|
|
1440
|
+
try {
|
|
1441
|
+
const ok = await check();
|
|
1442
|
+
results[name] = ok ? "ok" : "error";
|
|
1443
|
+
if (!ok) allOk = false;
|
|
1444
|
+
} catch {
|
|
1445
|
+
results[name] = "error";
|
|
1446
|
+
allOk = false;
|
|
1447
|
+
}
|
|
1448
|
+
})
|
|
1449
|
+
);
|
|
1450
|
+
return { status: allOk ? "ok" : "error", checks: results };
|
|
1451
|
+
}
|
|
1452
|
+
function createHealthCheckHandler(options = {}) {
|
|
1453
|
+
const checks = options.checks ?? {};
|
|
1454
|
+
return async (req) => {
|
|
1455
|
+
const pathname = new URL(req.url).pathname;
|
|
1456
|
+
if (pathname === "/healthz") {
|
|
1457
|
+
return Response.json({ status: "ok" }, { status: 200 });
|
|
1458
|
+
}
|
|
1459
|
+
if (pathname === "/readyz") {
|
|
1460
|
+
const result = await runChecks(checks);
|
|
1461
|
+
return Response.json(result, { status: result.status === "ok" ? 200 : 503 });
|
|
1462
|
+
}
|
|
1463
|
+
return null;
|
|
1464
|
+
};
|
|
1465
|
+
}
|
|
1466
|
+
|
|
1467
|
+
// src/observability/logger.ts
|
|
1468
|
+
function write(level, message, fields) {
|
|
1469
|
+
const entry = {
|
|
1470
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1471
|
+
level,
|
|
1472
|
+
message,
|
|
1473
|
+
...fields
|
|
1474
|
+
};
|
|
1475
|
+
const line = JSON.stringify(entry);
|
|
1476
|
+
if (level === "error") {
|
|
1477
|
+
console.error(line);
|
|
1478
|
+
} else if (level === "warn") {
|
|
1479
|
+
console.warn(line);
|
|
1480
|
+
} else {
|
|
1481
|
+
console.log(line);
|
|
1482
|
+
}
|
|
1483
|
+
}
|
|
1484
|
+
var logger = {
|
|
1485
|
+
info: (message, fields) => write("info", message, fields),
|
|
1486
|
+
warn: (message, fields) => write("warn", message, fields),
|
|
1487
|
+
error: (message, fields) => write("error", message, fields)
|
|
1488
|
+
};
|
|
1489
|
+
function withRequestLogging(handler) {
|
|
1490
|
+
return async (req, server) => {
|
|
1491
|
+
const start = performance.now();
|
|
1492
|
+
const requestId = req.headers.get("x-request-id") ?? crypto.randomUUID();
|
|
1493
|
+
const route = new URL(req.url).pathname;
|
|
1494
|
+
try {
|
|
1495
|
+
const res = await handler(req, server);
|
|
1496
|
+
const isStream = res.headers.get("content-type")?.includes("text/event-stream");
|
|
1497
|
+
console.log(
|
|
1498
|
+
`[x][request] ${req.method} ${route} -> ${res.status}${isStream ? " (stream opened, not closed)" : ""}`
|
|
1499
|
+
);
|
|
1500
|
+
write("info", isStream ? "stream opened" : "request completed", {
|
|
1501
|
+
requestId,
|
|
1502
|
+
route,
|
|
1503
|
+
method: req.method,
|
|
1504
|
+
status: res.status,
|
|
1505
|
+
durationMs: Math.round(performance.now() - start)
|
|
1506
|
+
});
|
|
1507
|
+
if (!res.headers.has("x-request-id")) {
|
|
1508
|
+
res.headers.set("x-request-id", requestId);
|
|
1509
|
+
}
|
|
1510
|
+
return res;
|
|
1511
|
+
} catch (err) {
|
|
1512
|
+
write("error", "request failed", {
|
|
1513
|
+
requestId,
|
|
1514
|
+
route,
|
|
1515
|
+
method: req.method,
|
|
1516
|
+
status: 500,
|
|
1517
|
+
durationMs: Math.round(performance.now() - start),
|
|
1518
|
+
error: err instanceof Error ? err.message : String(err)
|
|
1519
|
+
});
|
|
1520
|
+
throw err;
|
|
1521
|
+
}
|
|
1522
|
+
};
|
|
1523
|
+
}
|
|
1524
|
+
|
|
1525
|
+
// src/observability/metrics.ts
|
|
1526
|
+
var noopMetrics = {
|
|
1527
|
+
incr: () => {
|
|
1528
|
+
},
|
|
1529
|
+
observe: () => {
|
|
1530
|
+
}
|
|
1531
|
+
};
|
|
1532
|
+
var DEFAULT_HISTOGRAM_BUCKETS_MS = [5, 10, 25, 50, 100, 250, 500, 1e3, 2500, 5e3, 1e4];
|
|
1533
|
+
function seriesKey(name, labels) {
|
|
1534
|
+
if (!labels) return name;
|
|
1535
|
+
const sorted = Object.entries(labels).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${k}=${v}`);
|
|
1536
|
+
return `${name}\0${sorted.join("\0")}`;
|
|
1537
|
+
}
|
|
1538
|
+
function createInMemoryMetrics(options = {}) {
|
|
1539
|
+
const buckets = options.histogramBuckets ?? DEFAULT_HISTOGRAM_BUCKETS_MS;
|
|
1540
|
+
const counters = /* @__PURE__ */ new Map();
|
|
1541
|
+
const histograms = /* @__PURE__ */ new Map();
|
|
1542
|
+
function incr(name, delta = 1, labels) {
|
|
1543
|
+
const key = seriesKey(name, labels);
|
|
1544
|
+
let series = counters.get(key);
|
|
1545
|
+
if (!series) {
|
|
1546
|
+
series = { name, labels: labels ?? {}, value: 0 };
|
|
1547
|
+
counters.set(key, series);
|
|
1548
|
+
}
|
|
1549
|
+
series.value += delta;
|
|
1550
|
+
}
|
|
1551
|
+
function observe(name, value, labels) {
|
|
1552
|
+
const key = seriesKey(name, labels);
|
|
1553
|
+
let acc = histograms.get(key);
|
|
1554
|
+
if (!acc) {
|
|
1555
|
+
acc = { bucketCounts: new Array(buckets.length).fill(0), sum: 0, count: 0 };
|
|
1556
|
+
histograms.set(key, acc);
|
|
1557
|
+
}
|
|
1558
|
+
acc.sum += value;
|
|
1559
|
+
acc.count += 1;
|
|
1560
|
+
for (let i = 0; i < buckets.length; i += 1) {
|
|
1561
|
+
const bound = buckets[i];
|
|
1562
|
+
if (bound === void 0) break;
|
|
1563
|
+
if (value <= bound) {
|
|
1564
|
+
for (let j = i; j < buckets.length; j += 1) {
|
|
1565
|
+
acc.bucketCounts[j] = (acc.bucketCounts[j] ?? 0) + 1;
|
|
1566
|
+
}
|
|
1567
|
+
break;
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
function labelsFromKey(key) {
|
|
1572
|
+
const [name] = key.split("\0");
|
|
1573
|
+
const labelPart = name !== void 0 ? key.slice(name.length + 1) : "";
|
|
1574
|
+
const labels = {};
|
|
1575
|
+
if (labelPart) {
|
|
1576
|
+
for (const pair of labelPart.split("\0")) {
|
|
1577
|
+
const eq = pair.indexOf("=");
|
|
1578
|
+
if (eq > 0) labels[pair.slice(0, eq)] = pair.slice(eq + 1);
|
|
1579
|
+
}
|
|
1580
|
+
}
|
|
1581
|
+
return { name: name ?? key, labels };
|
|
1582
|
+
}
|
|
1583
|
+
function snapshot() {
|
|
1584
|
+
const sortedCounters = [...counters.entries()].sort(([a], [b]) => a < b ? -1 : 1).map(([key, series]) => {
|
|
1585
|
+
const { name, labels } = labelsFromKey(key);
|
|
1586
|
+
return { name, labels, value: series.value };
|
|
1587
|
+
});
|
|
1588
|
+
const sortedHistograms = [...histograms.entries()].sort(([a], [b]) => a < b ? -1 : 1).map(([key, acc]) => {
|
|
1589
|
+
const { name, labels } = labelsFromKey(key);
|
|
1590
|
+
return { name, labels, bucketCounts: acc.bucketCounts, sum: acc.sum, count: acc.count };
|
|
1591
|
+
});
|
|
1592
|
+
return { counters: sortedCounters, histograms: sortedHistograms };
|
|
1593
|
+
}
|
|
1594
|
+
function renderMetrics() {
|
|
1595
|
+
const snap = snapshot();
|
|
1596
|
+
const lines = [];
|
|
1597
|
+
for (const counter of snap.counters) {
|
|
1598
|
+
lines.push(`# TYPE ${counter.name} counter`);
|
|
1599
|
+
lines.push(`${counter.name}${formatLabels(counter.labels)} ${counter.value}`);
|
|
1600
|
+
}
|
|
1601
|
+
for (const h of snap.histograms) {
|
|
1602
|
+
const labelWithLe = (le) => {
|
|
1603
|
+
const labels = { ...h.labels, le };
|
|
1604
|
+
return formatLabels(labels);
|
|
1605
|
+
};
|
|
1606
|
+
lines.push(`# TYPE ${h.name} histogram`);
|
|
1607
|
+
for (let i = 0; i < buckets.length; i += 1) {
|
|
1608
|
+
lines.push(`${h.name}_bucket${labelWithLe(String(buckets[i]))} ${h.bucketCounts[i]}`);
|
|
1609
|
+
}
|
|
1610
|
+
lines.push(`${h.name}_bucket${labelWithLe("+Inf")} ${h.count}`);
|
|
1611
|
+
lines.push(`${h.name}_sum${formatLabels(h.labels)} ${h.sum}`);
|
|
1612
|
+
lines.push(`${h.name}_count${formatLabels(h.labels)} ${h.count}`);
|
|
1613
|
+
}
|
|
1614
|
+
return `${lines.join("\n")}
|
|
1615
|
+
`;
|
|
1616
|
+
}
|
|
1617
|
+
function handleMetrics(req) {
|
|
1618
|
+
if (new URL(req.url).pathname !== "/metrics") return null;
|
|
1619
|
+
return new Response(renderMetrics(), {
|
|
1620
|
+
headers: { "Content-Type": "text/plain; version=0.0.4; charset=utf-8" }
|
|
1621
|
+
});
|
|
1622
|
+
}
|
|
1623
|
+
return {
|
|
1624
|
+
incr,
|
|
1625
|
+
observe,
|
|
1626
|
+
snapshot,
|
|
1627
|
+
renderMetrics,
|
|
1628
|
+
handleMetrics,
|
|
1629
|
+
async flush() {
|
|
1630
|
+
}
|
|
1631
|
+
};
|
|
1632
|
+
}
|
|
1633
|
+
function createOtlpMetricsReporter(meter) {
|
|
1634
|
+
const counters = /* @__PURE__ */ new Map();
|
|
1635
|
+
const histograms = /* @__PURE__ */ new Map();
|
|
1636
|
+
return {
|
|
1637
|
+
incr(name, delta, labels) {
|
|
1638
|
+
let counter = counters.get(name);
|
|
1639
|
+
if (!counter) {
|
|
1640
|
+
counter = meter.createCounter(name, { description: `Counter ${name}` });
|
|
1641
|
+
counters.set(name, counter);
|
|
1642
|
+
}
|
|
1643
|
+
counter.add(delta ?? 1, labels);
|
|
1644
|
+
},
|
|
1645
|
+
observe(name, value, labels) {
|
|
1646
|
+
let histogram = histograms.get(name);
|
|
1647
|
+
if (!histogram) {
|
|
1648
|
+
histogram = meter.createHistogram(name, { description: `Histogram ${name}` });
|
|
1649
|
+
histograms.set(name, histogram);
|
|
1650
|
+
}
|
|
1651
|
+
histogram.record(value, labels);
|
|
1652
|
+
}
|
|
1653
|
+
};
|
|
1654
|
+
}
|
|
1655
|
+
function formatLabels(labels) {
|
|
1656
|
+
const entries = Object.entries(labels);
|
|
1657
|
+
if (entries.length === 0) return "";
|
|
1658
|
+
const escaped = entries.map(([k, v]) => `${k}="${escapeLabelValue(v)}"`).join(",");
|
|
1659
|
+
return `{${escaped}}`;
|
|
1660
|
+
}
|
|
1661
|
+
function escapeLabelValue(value) {
|
|
1662
|
+
return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n");
|
|
1663
|
+
}
|
|
1664
|
+
function withRequestMetrics(reporter, handler) {
|
|
1665
|
+
return async (req, server) => {
|
|
1666
|
+
const start = performance.now();
|
|
1667
|
+
const method = req.method;
|
|
1668
|
+
try {
|
|
1669
|
+
const res = await handler(req, server);
|
|
1670
|
+
reporter.incr("x_http_requests_total", 1, { method, status: String(res.status) });
|
|
1671
|
+
reporter.observe("x_http_request_duration_ms", performance.now() - start, { method });
|
|
1672
|
+
return res;
|
|
1673
|
+
} catch (err) {
|
|
1674
|
+
reporter.incr("x_http_requests_total", 1, { method, status: "500" });
|
|
1675
|
+
reporter.incr("x_http_errors_total", 1, { method });
|
|
1676
|
+
reporter.observe("x_http_request_duration_ms", performance.now() - start, { method });
|
|
1677
|
+
throw err;
|
|
1678
|
+
}
|
|
1679
|
+
};
|
|
1680
|
+
}
|
|
1681
|
+
|
|
1682
|
+
// src/security/headers.ts
|
|
1683
|
+
var DEFAULT_CSP = "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'";
|
|
1684
|
+
function buildSecurityHeaders(options = {}) {
|
|
1685
|
+
const headers = new Headers();
|
|
1686
|
+
const csp = options.contentSecurityPolicy ?? DEFAULT_CSP;
|
|
1687
|
+
if (csp !== false) headers.set("Content-Security-Policy", csp);
|
|
1688
|
+
const hstsMaxAge = options.hstsMaxAge ?? 15552e3;
|
|
1689
|
+
if (hstsMaxAge !== false) {
|
|
1690
|
+
const includeSub = options.hstsIncludeSubDomains ?? true;
|
|
1691
|
+
headers.set(
|
|
1692
|
+
"Strict-Transport-Security",
|
|
1693
|
+
`max-age=${hstsMaxAge}${includeSub ? "; includeSubDomains" : ""}`
|
|
1694
|
+
);
|
|
1695
|
+
}
|
|
1696
|
+
const frameOptions = options.frameOptions ?? "DENY";
|
|
1697
|
+
if (frameOptions !== false) headers.set("X-Frame-Options", frameOptions);
|
|
1698
|
+
const contentTypeOptions = options.contentTypeOptions ?? "nosniff";
|
|
1699
|
+
if (contentTypeOptions !== false) headers.set("X-Content-Type-Options", contentTypeOptions);
|
|
1700
|
+
const referrerPolicy = options.referrerPolicy ?? "strict-origin-when-cross-origin";
|
|
1701
|
+
if (referrerPolicy !== false) headers.set("Referrer-Policy", referrerPolicy);
|
|
1702
|
+
return headers;
|
|
1703
|
+
}
|
|
1704
|
+
function applySecurityHeaders(res, options = {}) {
|
|
1705
|
+
const extra = buildSecurityHeaders(options);
|
|
1706
|
+
for (const [key, value] of extra.entries()) {
|
|
1707
|
+
if (!res.headers.has(key)) {
|
|
1708
|
+
res.headers.set(key, value);
|
|
1709
|
+
}
|
|
1710
|
+
}
|
|
1711
|
+
return res;
|
|
1712
|
+
}
|
|
1713
|
+
|
|
1714
|
+
// src/security/rate-limit.ts
|
|
1715
|
+
function defaultKeyFn(req, server) {
|
|
1716
|
+
if (server?.requestIP) {
|
|
1717
|
+
const ip = server.requestIP(req);
|
|
1718
|
+
if (ip) return ip.address;
|
|
1719
|
+
}
|
|
1720
|
+
const forwarded = req.headers.get("x-forwarded-for");
|
|
1721
|
+
if (forwarded) return forwarded.split(",")[0]?.trim() ?? "unknown";
|
|
1722
|
+
return req.headers.get("x-real-ip") ?? "unknown";
|
|
1723
|
+
}
|
|
1724
|
+
function createRateLimiter(options = {}) {
|
|
1725
|
+
const limit = options.limit ?? 60;
|
|
1726
|
+
const windowMs = options.windowMs ?? 6e4;
|
|
1727
|
+
const keyFn = options.keyFn ?? defaultKeyFn;
|
|
1728
|
+
const store = options.store;
|
|
1729
|
+
const buckets = /* @__PURE__ */ new Map();
|
|
1730
|
+
async function check(req, server) {
|
|
1731
|
+
const key = keyFn(req, server);
|
|
1732
|
+
if (store) {
|
|
1733
|
+
const { count, resetAt } = await store.incr(key, windowMs);
|
|
1734
|
+
return { ok: count <= limit, limit, remaining: Math.max(0, limit - count), resetAt };
|
|
1735
|
+
}
|
|
1736
|
+
const now = Date.now();
|
|
1737
|
+
let bucket = buckets.get(key);
|
|
1738
|
+
if (!bucket || bucket.resetAt <= now) {
|
|
1739
|
+
bucket = { count: 0, resetAt: now + windowMs };
|
|
1740
|
+
buckets.set(key, bucket);
|
|
1741
|
+
}
|
|
1742
|
+
bucket.count += 1;
|
|
1743
|
+
const ok = bucket.count <= limit;
|
|
1744
|
+
return { ok, limit, remaining: Math.max(0, limit - bucket.count), resetAt: bucket.resetAt };
|
|
1745
|
+
}
|
|
1746
|
+
function sweep() {
|
|
1747
|
+
const now = Date.now();
|
|
1748
|
+
for (const [key, bucket] of buckets) {
|
|
1749
|
+
if (bucket.resetAt <= now) buckets.delete(key);
|
|
1750
|
+
}
|
|
1751
|
+
}
|
|
1752
|
+
const timer = setInterval(sweep, Math.max(windowMs, 1e3));
|
|
1753
|
+
timer.unref?.();
|
|
1754
|
+
return { check, sweep, buckets, dispose: () => clearInterval(timer) };
|
|
1755
|
+
}
|
|
1756
|
+
async function rateLimitMiddleware(limiter, req, server) {
|
|
1757
|
+
const result = await limiter.check(req, server);
|
|
1758
|
+
if (result.ok) return null;
|
|
1759
|
+
const retryAfterSeconds = Math.max(1, Math.ceil((result.resetAt - Date.now()) / 1e3));
|
|
1760
|
+
return new Response("Too Many Requests", {
|
|
1761
|
+
status: 429,
|
|
1762
|
+
headers: {
|
|
1763
|
+
"Content-Type": "text/plain; charset=utf-8",
|
|
1764
|
+
"Retry-After": String(retryAfterSeconds),
|
|
1765
|
+
"X-RateLimit-Limit": String(result.limit),
|
|
1766
|
+
"X-RateLimit-Remaining": String(result.remaining)
|
|
1767
|
+
}
|
|
1768
|
+
});
|
|
1769
|
+
}
|
|
1770
|
+
function createBunRedisClient(options) {
|
|
1771
|
+
return async () => {
|
|
1772
|
+
const require2 = import.meta.require;
|
|
1773
|
+
const mod = require2("bun:redis");
|
|
1774
|
+
const instance = options.url ? new mod.RedisClient({ url: options.url }) : new mod.RedisClient();
|
|
1775
|
+
await instance.connect();
|
|
1776
|
+
return instance;
|
|
1777
|
+
};
|
|
1778
|
+
}
|
|
1779
|
+
function createRedisRateLimitStore(options = {}) {
|
|
1780
|
+
return createRedisRateLimitStoreFromClient(createBunRedisClient(options));
|
|
1781
|
+
}
|
|
1782
|
+
function createRedisRateLimitStoreFromClient(clientFactory) {
|
|
1783
|
+
let client = null;
|
|
1784
|
+
let connecting = null;
|
|
1785
|
+
function getClient() {
|
|
1786
|
+
if (client) return Promise.resolve(client);
|
|
1787
|
+
if (!connecting) {
|
|
1788
|
+
connecting = clientFactory().then(
|
|
1789
|
+
(c) => {
|
|
1790
|
+
client = c;
|
|
1791
|
+
return c;
|
|
1792
|
+
},
|
|
1793
|
+
(err) => {
|
|
1794
|
+
connecting = null;
|
|
1795
|
+
throw err;
|
|
1796
|
+
}
|
|
1797
|
+
);
|
|
1798
|
+
}
|
|
1799
|
+
return connecting;
|
|
1800
|
+
}
|
|
1801
|
+
return {
|
|
1802
|
+
async incr(key, windowMs) {
|
|
1803
|
+
const c = await getClient();
|
|
1804
|
+
const redisKey = `x:ratelimit:${key}`;
|
|
1805
|
+
const ttlSeconds = Math.max(1, Math.ceil(windowMs / 1e3));
|
|
1806
|
+
const count = Number(await c.sendCommand("INCR", redisKey));
|
|
1807
|
+
if (count === 1) {
|
|
1808
|
+
await c.sendCommand("EXPIRE", redisKey, String(ttlSeconds));
|
|
1809
|
+
}
|
|
1810
|
+
return { count, resetAt: Date.now() + windowMs };
|
|
1811
|
+
}
|
|
1812
|
+
};
|
|
1813
|
+
}
|
|
1814
|
+
|
|
1815
|
+
// src/createApp.ts
|
|
1816
|
+
function sortRoutes(handlers) {
|
|
1817
|
+
return handlers.sort((a, b) => {
|
|
1818
|
+
const bp = routeMatchesForSort(b.entry);
|
|
1819
|
+
const ap = routeMatchesForSort(a.entry);
|
|
1820
|
+
return ap - bp;
|
|
1821
|
+
});
|
|
1822
|
+
}
|
|
1823
|
+
function routeMatchesForSort(entry) {
|
|
1824
|
+
const isStatic = entry.paramNames.length === 0;
|
|
1825
|
+
const isCatchAll = entry.routePath.includes("*");
|
|
1826
|
+
return isStatic ? 0 : isCatchAll ? 2 : 1;
|
|
1827
|
+
}
|
|
1828
|
+
function projectRootFromRoutesDir(routesDir) {
|
|
1829
|
+
return join5(routesDir, "..", "..");
|
|
1830
|
+
}
|
|
1831
|
+
function resolvePublicAsset(publicDir, pathname) {
|
|
1832
|
+
let decoded;
|
|
1833
|
+
try {
|
|
1834
|
+
decoded = decodeURIComponent(pathname);
|
|
1835
|
+
} catch {
|
|
1836
|
+
return null;
|
|
1837
|
+
}
|
|
1838
|
+
const target = resolve(join5(publicDir, decoded));
|
|
1839
|
+
const root = resolve(publicDir);
|
|
1840
|
+
if (target !== root && !target.startsWith(root + sep2)) return null;
|
|
1841
|
+
return target;
|
|
1842
|
+
}
|
|
1843
|
+
async function serveStaticAsset(publicDir, req) {
|
|
1844
|
+
if (!publicDir) return null;
|
|
1845
|
+
if (req.method !== "GET" && req.method !== "HEAD") return null;
|
|
1846
|
+
const pathname = new URL(req.url).pathname;
|
|
1847
|
+
if (pathname === "/" || pathname.endsWith("/")) return null;
|
|
1848
|
+
const filePath = resolvePublicAsset(publicDir, pathname);
|
|
1849
|
+
if (!filePath) return null;
|
|
1850
|
+
const bun = globalThis.Bun;
|
|
1851
|
+
if (!bun) return null;
|
|
1852
|
+
const file = bun.file(filePath);
|
|
1853
|
+
if (!await file.exists()) return null;
|
|
1854
|
+
return new Response(file);
|
|
1855
|
+
}
|
|
1856
|
+
function wrapWithLayouts(Component, params, loaderData, layoutModules) {
|
|
1857
|
+
let content = createElement2(Component, { params, loaderData });
|
|
1858
|
+
for (const Layout of [...layoutModules].reverse()) {
|
|
1859
|
+
content = createElement2(Layout, null, content);
|
|
1860
|
+
}
|
|
1861
|
+
return content;
|
|
1862
|
+
}
|
|
1863
|
+
function renderContentPage(content, stylesheet, dev = false) {
|
|
1864
|
+
const title = content.frontmatter.title ?? content.slug;
|
|
1865
|
+
const bodyHtml = renderMarkdown(content.body);
|
|
1866
|
+
const body = renderPage(
|
|
1867
|
+
createElement2(
|
|
1868
|
+
"article",
|
|
1869
|
+
null,
|
|
1870
|
+
content.frontmatter.title ? createElement2("h1", null, content.frontmatter.title) : null,
|
|
1871
|
+
createElement2("div", {
|
|
1872
|
+
// biome-ignore lint/security/noDangerouslySetInnerHtml: body is markdown rendered to HTML
|
|
1873
|
+
dangerouslySetInnerHTML: { __html: bodyHtml }
|
|
1874
|
+
})
|
|
1875
|
+
),
|
|
1876
|
+
{ title, stylesheet, liveReload: dev }
|
|
1877
|
+
);
|
|
1878
|
+
return body;
|
|
1879
|
+
}
|
|
1880
|
+
function defineConfig(config) {
|
|
1881
|
+
return config;
|
|
1882
|
+
}
|
|
1883
|
+
function importDev(path, dev) {
|
|
1884
|
+
return dev ? import(`${path}?t=${Date.now()}`) : import(path);
|
|
1885
|
+
}
|
|
1886
|
+
async function createApp(options) {
|
|
1887
|
+
const dev = options.development ?? false;
|
|
1888
|
+
const primaryDir = options.pagesDir || options.routesDir || "src/pages";
|
|
1889
|
+
const projectRoot = projectRootFromRoutesDir(primaryDir);
|
|
1890
|
+
const resolvedActionsDir = options.actionsDir ?? (existsSync2(join5(projectRoot, "src", "actions")) ? join5(projectRoot, "src", "actions") : void 0);
|
|
1891
|
+
let handlers = [];
|
|
1892
|
+
let contentHandlers = [];
|
|
1893
|
+
let publicDir = null;
|
|
1894
|
+
let stylesheetHref;
|
|
1895
|
+
let notFoundComponent = DefaultNotFound;
|
|
1896
|
+
let notFoundLayout;
|
|
1897
|
+
const serverFnHandler = getServerFunctionHandler(options.security?.csrf);
|
|
1898
|
+
const staticCache = /* @__PURE__ */ new Map();
|
|
1899
|
+
let actionModules = /* @__PURE__ */ new Map();
|
|
1900
|
+
const islandBundleCache = /* @__PURE__ */ new Map();
|
|
1901
|
+
const islandFileCache = /* @__PURE__ */ new Map();
|
|
1902
|
+
async function resolveIslandScripts(routeFilePath, layoutFilePaths, entries) {
|
|
1903
|
+
if (entries.length === 0) return [];
|
|
1904
|
+
const uniqueNames = [...new Set(entries.map((e) => e.name))].sort();
|
|
1905
|
+
const cacheKey = `${routeFilePath}::${layoutFilePaths.join("|")}::${uniqueNames.join(",")}`;
|
|
1906
|
+
const cached = islandBundleCache.get(cacheKey);
|
|
1907
|
+
if (cached) return cached;
|
|
1908
|
+
const code = await buildIslandBundleInMemory(
|
|
1909
|
+
routeFilePath,
|
|
1910
|
+
layoutFilePaths,
|
|
1911
|
+
uniqueNames,
|
|
1912
|
+
actionModules,
|
|
1913
|
+
projectRoot
|
|
1914
|
+
);
|
|
1915
|
+
const entryId = islandEntryId(routeFilePath);
|
|
1916
|
+
const url = `/_islands/${entryId}/${entryId}.js`;
|
|
1917
|
+
islandFileCache.set(url, code);
|
|
1918
|
+
const scripts = [url];
|
|
1919
|
+
islandBundleCache.set(cacheKey, scripts);
|
|
1920
|
+
return scripts;
|
|
1921
|
+
}
|
|
1922
|
+
function serveIslandBundle(req) {
|
|
1923
|
+
if (req.method !== "GET" && req.method !== "HEAD") return null;
|
|
1924
|
+
const pathname = new URL(req.url).pathname;
|
|
1925
|
+
if (!pathname.startsWith("/_islands/")) return null;
|
|
1926
|
+
const code = islandFileCache.get(pathname);
|
|
1927
|
+
if (code === void 0) return null;
|
|
1928
|
+
return new Response(code, {
|
|
1929
|
+
headers: { "Content-Type": "application/javascript; charset=utf-8" }
|
|
1930
|
+
});
|
|
1931
|
+
}
|
|
1932
|
+
if (options.observability?.errorReporter) {
|
|
1933
|
+
setErrorReporter(options.observability.errorReporter);
|
|
1934
|
+
}
|
|
1935
|
+
const healthHandler = createHealthCheckHandler(options.observability?.health ?? {});
|
|
1936
|
+
const metricsReporter = options.observability?.metrics;
|
|
1937
|
+
const rateLimiter = options.security?.rateLimit === false ? null : createRateLimiter(options.security?.rateLimit ?? {});
|
|
1938
|
+
const securityHeadersOptions = options.security?.headers;
|
|
1939
|
+
const loggingEnabled = options.observability?.logging ?? true;
|
|
1940
|
+
const imageProxyHandler = createImageProxyHandler(options.images);
|
|
1941
|
+
function withResponseHardening(res) {
|
|
1942
|
+
return securityHeadersOptions === false ? res : applySecurityHeaders(res, securityHeadersOptions);
|
|
1943
|
+
}
|
|
1944
|
+
async function renderNotFound(_req) {
|
|
1945
|
+
const content = notFoundLayout ? createElement2(notFoundLayout, null, createElement2(notFoundComponent, { params: {} })) : createElement2(notFoundComponent, { params: {} });
|
|
1946
|
+
const html = renderPage(content, {
|
|
1947
|
+
title: "404 \u2014 Not Found",
|
|
1948
|
+
stylesheet: stylesheetHref,
|
|
1949
|
+
liveReload: dev
|
|
1950
|
+
});
|
|
1951
|
+
return new Response(html, {
|
|
1952
|
+
status: 404,
|
|
1953
|
+
headers: { "Content-Type": "text/html; charset=utf-8" }
|
|
1954
|
+
});
|
|
1955
|
+
}
|
|
1956
|
+
const makeApiHandler = (route, module) => async (req) => {
|
|
1957
|
+
try {
|
|
1958
|
+
const method = req.method;
|
|
1959
|
+
const handlerFn = module[method];
|
|
1960
|
+
if (typeof handlerFn === "function") {
|
|
1961
|
+
const result = await handlerFn(req);
|
|
1962
|
+
if (result instanceof Response) return result;
|
|
1963
|
+
if (result === void 0 || result === null) {
|
|
1964
|
+
return new Response("OK", { status: 200 });
|
|
1965
|
+
}
|
|
1966
|
+
return Response.json(result);
|
|
1967
|
+
}
|
|
1968
|
+
return new Response(`Method ${method} not allowed`, { status: 405 });
|
|
1969
|
+
} catch (err) {
|
|
1970
|
+
reportException(err, { route: route.routePath, phase: "api" });
|
|
1971
|
+
metricsReporter?.incr("x_http_errors_total", 1, { phase: "api" });
|
|
1972
|
+
console.error("[x] API handler error:", err);
|
|
1973
|
+
if (dev) {
|
|
1974
|
+
return new Response(renderErrorOverlay(err), {
|
|
1975
|
+
status: 500,
|
|
1976
|
+
headers: { "Content-Type": "text/html; charset=utf-8" }
|
|
1977
|
+
});
|
|
1978
|
+
}
|
|
1979
|
+
return new Response("Internal server error", { status: 500 });
|
|
1980
|
+
}
|
|
1981
|
+
};
|
|
1982
|
+
const makePageHandler = (opts) => {
|
|
1983
|
+
const {
|
|
1984
|
+
route,
|
|
1985
|
+
mode,
|
|
1986
|
+
revalidate,
|
|
1987
|
+
loader,
|
|
1988
|
+
Component,
|
|
1989
|
+
layoutModules,
|
|
1990
|
+
layoutFilePaths,
|
|
1991
|
+
middlewareModules,
|
|
1992
|
+
islandScripts
|
|
1993
|
+
} = opts;
|
|
1994
|
+
return async (req) => {
|
|
1995
|
+
try {
|
|
1996
|
+
const params = extractParams(route.routePath, route.paramNames, new URL(req.url).pathname) ?? {};
|
|
1997
|
+
const baseHandler = async (ctx) => {
|
|
1998
|
+
const cacheKey = new URL(ctx.request.url).pathname;
|
|
1999
|
+
if (mode === "server") {
|
|
2000
|
+
let loaderData2 = {};
|
|
2001
|
+
if (loader) {
|
|
2002
|
+
const result = await loader(ctx);
|
|
2003
|
+
if (result instanceof Response) return result;
|
|
2004
|
+
loaderData2 = result;
|
|
2005
|
+
}
|
|
2006
|
+
const registry2 = createIslandRegistry();
|
|
2007
|
+
const content2 = createElement2(
|
|
2008
|
+
IslandProvider,
|
|
2009
|
+
{ registry: registry2 },
|
|
2010
|
+
wrapWithLayouts(Component, ctx.params, loaderData2, layoutModules)
|
|
2011
|
+
);
|
|
2012
|
+
let scripts2 = islandScripts;
|
|
2013
|
+
if (scripts2 === void 0) {
|
|
2014
|
+
renderPage(content2, { stylesheet: stylesheetHref, liveReload: dev });
|
|
2015
|
+
scripts2 = await resolveIslandScripts(
|
|
2016
|
+
route.filePath,
|
|
2017
|
+
layoutFilePaths,
|
|
2018
|
+
registry2.entries
|
|
2019
|
+
);
|
|
2020
|
+
}
|
|
2021
|
+
const stream = await renderStreamingPage(content2, {
|
|
2022
|
+
stylesheet: stylesheetHref,
|
|
2023
|
+
liveReload: dev,
|
|
2024
|
+
islandScripts: scripts2
|
|
2025
|
+
});
|
|
2026
|
+
return new Response(stream, {
|
|
2027
|
+
headers: { "Content-Type": "text/html; charset=utf-8" }
|
|
2028
|
+
});
|
|
2029
|
+
}
|
|
2030
|
+
const revalidateSeconds = revalidate ?? 0;
|
|
2031
|
+
if (revalidateSeconds > 0) {
|
|
2032
|
+
const cached = staticCache.get(cacheKey);
|
|
2033
|
+
if (cached && Date.now() - cached.timestamp < revalidateSeconds * 1e3) {
|
|
2034
|
+
return new Response(cached.html, {
|
|
2035
|
+
headers: {
|
|
2036
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
2037
|
+
"X-Revalidated": "hit"
|
|
2038
|
+
}
|
|
2039
|
+
});
|
|
2040
|
+
}
|
|
2041
|
+
}
|
|
2042
|
+
let loaderData = {};
|
|
2043
|
+
if (loader) {
|
|
2044
|
+
const result = await loader(ctx);
|
|
2045
|
+
if (result instanceof Response) return result;
|
|
2046
|
+
loaderData = result;
|
|
2047
|
+
}
|
|
2048
|
+
const registry = createIslandRegistry();
|
|
2049
|
+
const content = createElement2(
|
|
2050
|
+
IslandProvider,
|
|
2051
|
+
{ registry },
|
|
2052
|
+
wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
|
|
2053
|
+
);
|
|
2054
|
+
let scripts = islandScripts;
|
|
2055
|
+
if (scripts === void 0) {
|
|
2056
|
+
renderPage(content, { stylesheet: stylesheetHref, liveReload: dev });
|
|
2057
|
+
scripts = await resolveIslandScripts(route.filePath, layoutFilePaths, registry.entries);
|
|
2058
|
+
}
|
|
2059
|
+
const html = renderPage(content, {
|
|
2060
|
+
stylesheet: stylesheetHref,
|
|
2061
|
+
liveReload: dev,
|
|
2062
|
+
islandScripts: scripts
|
|
2063
|
+
});
|
|
2064
|
+
if (revalidateSeconds > 0) {
|
|
2065
|
+
staticCache.set(cacheKey, { html, timestamp: Date.now() });
|
|
2066
|
+
}
|
|
2067
|
+
return new Response(html, {
|
|
1718
2068
|
headers: {
|
|
1719
2069
|
"Content-Type": "text/html; charset=utf-8",
|
|
1720
2070
|
"X-Revalidated": revalidateSeconds > 0 ? "miss" : "none"
|
|
@@ -1746,9 +2096,9 @@ async function createApp(options) {
|
|
|
1746
2096
|
async function buildHandlers() {
|
|
1747
2097
|
if (options.preloaded) {
|
|
1748
2098
|
const preloaded = options.preloaded;
|
|
1749
|
-
const candidatePublicDir2 =
|
|
1750
|
-
publicDir =
|
|
1751
|
-
stylesheetHref = options.stylesheetHref ?? (publicDir &&
|
|
2099
|
+
const candidatePublicDir2 = join5(projectRoot, "public");
|
|
2100
|
+
publicDir = existsSync2(candidatePublicDir2) ? candidatePublicDir2 : null;
|
|
2101
|
+
stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync2(join5(publicDir, "styles.css")) ? "/styles.css" : void 0);
|
|
1752
2102
|
if (preloaded.notFoundComponent) notFoundComponent = preloaded.notFoundComponent;
|
|
1753
2103
|
if (preloaded.notFoundLayout) notFoundLayout = preloaded.notFoundLayout;
|
|
1754
2104
|
const loaded2 = [];
|
|
@@ -1787,7 +2137,7 @@ async function createApp(options) {
|
|
|
1787
2137
|
})
|
|
1788
2138
|
});
|
|
1789
2139
|
}
|
|
1790
|
-
handlers = loaded2;
|
|
2140
|
+
handlers = sortRoutes(loaded2);
|
|
1791
2141
|
return;
|
|
1792
2142
|
}
|
|
1793
2143
|
resetServerFunctions();
|
|
@@ -1796,14 +2146,13 @@ async function createApp(options) {
|
|
|
1796
2146
|
islandFileCache.clear();
|
|
1797
2147
|
const pagesDir = primaryDir;
|
|
1798
2148
|
const apiDir = options.apiDir;
|
|
1799
|
-
const layoutsDir = options.layoutsDir || pagesDir;
|
|
1800
2149
|
let found = scanPages(pagesDir);
|
|
1801
2150
|
const apiFound = [];
|
|
1802
|
-
if (apiDir &&
|
|
2151
|
+
if (apiDir && existsSync2(apiDir)) {
|
|
1803
2152
|
apiFound.push(...scanApiDir(apiDir));
|
|
1804
2153
|
}
|
|
1805
|
-
const legacyApiDir =
|
|
1806
|
-
if (
|
|
2154
|
+
const legacyApiDir = join5(pagesDir, "api");
|
|
2155
|
+
if (existsSync2(legacyApiDir) && legacyApiDir !== apiDir) {
|
|
1807
2156
|
apiFound.push(...scanApiDir(legacyApiDir));
|
|
1808
2157
|
}
|
|
1809
2158
|
found = found.filter((r) => !r.isApi);
|
|
@@ -1837,9 +2186,9 @@ async function createApp(options) {
|
|
|
1837
2186
|
}
|
|
1838
2187
|
}
|
|
1839
2188
|
}
|
|
1840
|
-
const candidatePublicDir =
|
|
1841
|
-
publicDir =
|
|
1842
|
-
stylesheetHref = options.stylesheetHref ?? (publicDir &&
|
|
2189
|
+
const candidatePublicDir = join5(projectRoot, "public");
|
|
2190
|
+
publicDir = existsSync2(candidatePublicDir) ? candidatePublicDir : null;
|
|
2191
|
+
stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync2(join5(publicDir, "styles.css")) ? "/styles.css" : void 0);
|
|
1843
2192
|
const notFoundEntry = scanNotFound(pagesDir);
|
|
1844
2193
|
if (notFoundEntry) {
|
|
1845
2194
|
const mod = await importDev(notFoundEntry.filePath, dev);
|
|
@@ -1927,7 +2276,7 @@ async function createApp(options) {
|
|
|
1927
2276
|
})
|
|
1928
2277
|
});
|
|
1929
2278
|
}
|
|
1930
|
-
handlers = loaded;
|
|
2279
|
+
handlers = sortRoutes(loaded);
|
|
1931
2280
|
if (options.contentDir) {
|
|
1932
2281
|
const content = scanContent(options.contentDir);
|
|
1933
2282
|
const loadedContent = content.map((entry) => ({
|
|
@@ -1946,6 +2295,10 @@ async function createApp(options) {
|
|
|
1946
2295
|
async function handleRevalidation(req) {
|
|
1947
2296
|
if (new URL(req.url).pathname !== "/__x/revalidate") return null;
|
|
1948
2297
|
if (req.method !== "POST") return new Response("Method not allowed", { status: 405 });
|
|
2298
|
+
const csrfResult = checkCsrf(req, options.security?.csrf);
|
|
2299
|
+
if (!csrfResult.ok) {
|
|
2300
|
+
return new Response(`Forbidden: ${csrfResult.reason}`, { status: 403 });
|
|
2301
|
+
}
|
|
1949
2302
|
const body = await req.json();
|
|
1950
2303
|
if (body.path) {
|
|
1951
2304
|
staticCache.delete(body.path);
|
|
@@ -1995,7 +2348,7 @@ async function createApp(options) {
|
|
|
1995
2348
|
let rebuildTimeout = null;
|
|
1996
2349
|
const sseClients = /* @__PURE__ */ new Set();
|
|
1997
2350
|
try {
|
|
1998
|
-
const srcDir =
|
|
2351
|
+
const srcDir = join5(primaryDir, "..", "..", "src");
|
|
1999
2352
|
const watchDirs = [
|
|
2000
2353
|
...new Set(
|
|
2001
2354
|
[primaryDir, options.apiDir, options.layoutsDir, resolvedActionsDir, srcDir].filter(
|
|
@@ -2076,378 +2429,76 @@ data: ${data}
|
|
|
2076
2429
|
if (islandBundle !== null) return islandBundle;
|
|
2077
2430
|
const proxiedImage = await imageProxyHandler(req);
|
|
2078
2431
|
if (proxiedImage !== null) return proxiedImage;
|
|
2079
|
-
for (const h of handlers) {
|
|
2080
|
-
const params = extractParams(h.entry.routePath, h.entry.paramNames, url);
|
|
2081
|
-
if (params !== null) {
|
|
2082
|
-
return h.handler(req);
|
|
2083
|
-
}
|
|
2084
|
-
}
|
|
2085
|
-
for (const h of contentHandlers) {
|
|
2086
|
-
if (h.entry.routePath === url) {
|
|
2087
|
-
return h.handler(req);
|
|
2088
|
-
}
|
|
2089
|
-
}
|
|
2090
|
-
return renderNotFound(req);
|
|
2091
|
-
};
|
|
2092
|
-
const devFetchHardened = async (req, server) => withResponseHardening(await devFetchInner(req, server));
|
|
2093
|
-
const devFetchBase = loggingEnabled ? withRequestLogging(devFetchHardened) : devFetchHardened;
|
|
2094
|
-
const devFetch = metricsReporter ? withRequestMetrics(metricsReporter, devFetchBase) : devFetchBase;
|
|
2095
|
-
return {
|
|
2096
|
-
routes: {},
|
|
2097
|
-
development: true,
|
|
2098
|
-
port: options.port ?? 3e3,
|
|
2099
|
-
fetch: devFetch
|
|
2100
|
-
};
|
|
2101
|
-
}
|
|
2102
|
-
const prodFetchInner = async (req, server) => {
|
|
2103
|
-
const url = new URL(req.url).pathname;
|
|
2104
|
-
const healthResult = await healthHandler(req);
|
|
2105
|
-
if (healthResult !== null) return healthResult;
|
|
2106
|
-
if (metricsReporter?.handleMetrics) {
|
|
2107
|
-
const metricsResult = await metricsReporter.handleMetrics(req);
|
|
2108
|
-
if (metricsResult !== null) return metricsResult;
|
|
2109
|
-
}
|
|
2110
|
-
if (rateLimiter) {
|
|
2111
|
-
const limited = await rateLimitMiddleware(rateLimiter, req, server);
|
|
2112
|
-
if (limited !== null) {
|
|
2113
|
-
metricsReporter?.incr("x_rate_limit_rejections_total", 1, { method: req.method });
|
|
2114
|
-
return limited;
|
|
2115
|
-
}
|
|
2116
|
-
}
|
|
2117
|
-
const revalidationResult = await handleRevalidation(req);
|
|
2118
|
-
if (revalidationResult !== null) return revalidationResult;
|
|
2119
|
-
const serverFnResult = await serverFnHandler(req);
|
|
2120
|
-
if (serverFnResult !== null) return serverFnResult;
|
|
2121
|
-
const staticAsset = await serveStaticAsset(publicDir, req);
|
|
2122
|
-
if (staticAsset !== null) return staticAsset;
|
|
2123
|
-
const islandBundle = serveIslandBundle(req);
|
|
2124
|
-
if (islandBundle !== null) return islandBundle;
|
|
2125
|
-
const proxiedImage = await imageProxyHandler(req);
|
|
2126
|
-
if (proxiedImage !== null) return proxiedImage;
|
|
2127
|
-
for (const h of handlers) {
|
|
2128
|
-
const params = extractParams(h.entry.routePath, h.entry.paramNames, url);
|
|
2129
|
-
if (params !== null) {
|
|
2130
|
-
return h.handler(req);
|
|
2131
|
-
}
|
|
2132
|
-
}
|
|
2133
|
-
for (const h of contentHandlers) {
|
|
2134
|
-
if (h.entry.routePath === url) {
|
|
2135
|
-
return h.handler(req);
|
|
2136
|
-
}
|
|
2137
|
-
}
|
|
2138
|
-
return renderNotFound(req);
|
|
2139
|
-
};
|
|
2140
|
-
const prodFetchHardened = async (req, server) => withResponseHardening(await prodFetchInner(req, server));
|
|
2141
|
-
const prodFetchBase = loggingEnabled ? withRequestLogging(prodFetchHardened) : prodFetchHardened;
|
|
2142
|
-
const prodFetch = metricsReporter ? withRequestMetrics(metricsReporter, prodFetchBase) : prodFetchBase;
|
|
2143
|
-
return {
|
|
2144
|
-
routes: {},
|
|
2145
|
-
development: false,
|
|
2146
|
-
port: options.port ?? 3e3,
|
|
2147
|
-
fetch: prodFetch
|
|
2148
|
-
};
|
|
2149
|
-
}
|
|
2150
|
-
|
|
2151
|
-
// src/build.ts
|
|
2152
|
-
import { cpSync, existsSync as existsSync2, mkdirSync as mkdirSync2, writeFileSync as writeFileSync3 } from "fs";
|
|
2153
|
-
import { join as join5, relative as relative2 } from "path";
|
|
2154
|
-
import { createElement as createElement2 } from "react";
|
|
2155
|
-
async function build(options) {
|
|
2156
|
-
const outDir = options.outDir ?? join5(process.cwd(), ".x");
|
|
2157
|
-
const clientDir = join5(outDir, "client");
|
|
2158
|
-
const serverDir = join5(outDir, "server");
|
|
2159
|
-
const islandsDir = join5(clientDir, "_islands");
|
|
2160
|
-
mkdirSync2(clientDir, { recursive: true });
|
|
2161
|
-
mkdirSync2(serverDir, { recursive: true });
|
|
2162
|
-
mkdirSync2(islandsDir, { recursive: true });
|
|
2163
|
-
const pagesDir = options.pagesDir ?? options.routesDir ?? "";
|
|
2164
|
-
const apiDir = options.apiDir;
|
|
2165
|
-
const actionsDir = options.actionsDir;
|
|
2166
|
-
const layoutsDir = options.layoutsDir ?? pagesDir;
|
|
2167
|
-
const projectRoot = pagesDir ? join5(pagesDir, "..", "..") : process.cwd();
|
|
2168
|
-
const publicDir = join5(projectRoot, "public");
|
|
2169
|
-
const hasPublicDir = existsSync2(publicDir);
|
|
2170
|
-
const stylesheetHref = hasPublicDir && existsSync2(join5(publicDir, "styles.css")) ? "/styles.css" : void 0;
|
|
2171
|
-
if (hasPublicDir) {
|
|
2172
|
-
cpSync(publicDir, clientDir, { recursive: true });
|
|
2173
|
-
console.log(`[x] build: copied public/ -> ${relative2(process.cwd(), clientDir)}`);
|
|
2174
|
-
}
|
|
2175
|
-
let routeEntries = [];
|
|
2176
|
-
if (pagesDir && existsSync2(pagesDir)) {
|
|
2177
|
-
routeEntries = scanPages(pagesDir);
|
|
2178
|
-
}
|
|
2179
|
-
if (apiDir && existsSync2(apiDir)) {
|
|
2180
|
-
routeEntries.push(...scanApiDir(apiDir));
|
|
2181
|
-
}
|
|
2182
|
-
const legacyApiDir = pagesDir ? join5(pagesDir, "api") : "";
|
|
2183
|
-
if (legacyApiDir && existsSync2(legacyApiDir) && legacyApiDir !== apiDir) {
|
|
2184
|
-
routeEntries.push(...scanApiDir(legacyApiDir));
|
|
2185
|
-
}
|
|
2186
|
-
const actionModules = /* @__PURE__ */ new Map();
|
|
2187
|
-
if (actionsDir && existsSync2(actionsDir)) {
|
|
2188
|
-
for (const actionFile of scanRoutes(actionsDir)) {
|
|
2189
|
-
const mod = await import(actionFile.filePath);
|
|
2190
|
-
const segments = actionFile.routePath.split("/").filter(Boolean);
|
|
2191
|
-
const parentPath = `/${segments.slice(0, -1).join("/")}`;
|
|
2192
|
-
const fnNames = [];
|
|
2193
|
-
const actions = mod.actions;
|
|
2194
|
-
if (actions) {
|
|
2195
|
-
registerServerFunctions(parentPath, actionFile.paramNames, actions);
|
|
2196
|
-
fnNames.push(...Object.keys(actions));
|
|
2197
|
-
}
|
|
2198
|
-
for (const [key, value] of Object.entries(mod)) {
|
|
2199
|
-
if (key === "default" || key === "actions" || typeof value !== "function") continue;
|
|
2200
|
-
registerServerFunctions(parentPath, actionFile.paramNames, {
|
|
2201
|
-
[key]: value
|
|
2202
|
-
});
|
|
2203
|
-
fnNames.push(key);
|
|
2204
|
-
}
|
|
2205
|
-
if (fnNames.length > 0) {
|
|
2206
|
-
actionModules.set(actionFile.filePath, { parentPath, fnNames });
|
|
2207
|
-
}
|
|
2208
|
-
}
|
|
2209
|
-
}
|
|
2210
|
-
const dedicatedLayouts = layoutsDir && layoutsDir !== pagesDir && existsSync2(layoutsDir) ? scanLayoutsDir(layoutsDir) : [];
|
|
2211
|
-
const nestedLayouts = pagesDir && existsSync2(pagesDir) ? scanLayouts(pagesDir) : [];
|
|
2212
|
-
const layouts = [...dedicatedLayouts, ...nestedLayouts];
|
|
2213
|
-
const staticPages = [];
|
|
2214
|
-
const serverPages = [];
|
|
2215
|
-
const apiRoutes = [];
|
|
2216
|
-
for (const entry of routeEntries) {
|
|
2217
|
-
if (entry.isApi) {
|
|
2218
|
-
apiRoutes.push(entry);
|
|
2219
|
-
continue;
|
|
2220
|
-
}
|
|
2221
|
-
const mod = await import(entry.filePath);
|
|
2222
|
-
const Component = mod.default;
|
|
2223
|
-
if (!Component) {
|
|
2224
|
-
console.warn(`[x] ${entry.filePath} has no default export -- skipping`);
|
|
2225
|
-
continue;
|
|
2226
|
-
}
|
|
2227
|
-
const mode = mod.mode ?? "server";
|
|
2228
|
-
const layoutChain = findLayoutChain(entry.filePath, layouts, pagesDir);
|
|
2229
|
-
for (const rootLayout of dedicatedLayouts) {
|
|
2230
|
-
if (!layoutChain.some((l) => l.filePath === rootLayout.filePath)) {
|
|
2231
|
-
layoutChain.unshift(rootLayout);
|
|
2432
|
+
for (const h of handlers) {
|
|
2433
|
+
const params = extractParams(h.entry.routePath, h.entry.paramNames, url);
|
|
2434
|
+
if (params !== null) {
|
|
2435
|
+
return h.handler(req);
|
|
2436
|
+
}
|
|
2232
2437
|
}
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
2237
|
-
|
|
2238
|
-
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
|
|
2245
|
-
|
|
2438
|
+
for (const h of contentHandlers) {
|
|
2439
|
+
if (h.entry.routePath === url) {
|
|
2440
|
+
return h.handler(req);
|
|
2441
|
+
}
|
|
2442
|
+
}
|
|
2443
|
+
return renderNotFound(req);
|
|
2444
|
+
};
|
|
2445
|
+
const devFetchHardened = async (req, server) => withResponseHardening(await devFetchInner(req, server));
|
|
2446
|
+
const devFetchBase = loggingEnabled ? withRequestLogging(devFetchHardened) : devFetchHardened;
|
|
2447
|
+
const devFetch = metricsReporter ? withRequestMetrics(metricsReporter, devFetchBase) : devFetchBase;
|
|
2448
|
+
return {
|
|
2449
|
+
routes: {},
|
|
2450
|
+
development: true,
|
|
2451
|
+
port: options.port ?? 3e3,
|
|
2452
|
+
fetch: devFetch
|
|
2246
2453
|
};
|
|
2247
|
-
if (mode === "static") {
|
|
2248
|
-
staticPages.push(page);
|
|
2249
|
-
} else {
|
|
2250
|
-
serverPages.push(page);
|
|
2251
|
-
}
|
|
2252
|
-
}
|
|
2253
|
-
let contentEntries = [];
|
|
2254
|
-
if (options.contentDir) {
|
|
2255
|
-
contentEntries = scanContent(options.contentDir);
|
|
2256
2454
|
}
|
|
2257
|
-
|
|
2258
|
-
|
|
2259
|
-
|
|
2260
|
-
|
|
2261
|
-
|
|
2262
|
-
|
|
2263
|
-
|
|
2264
|
-
const pageContent = renderPageWithLayout(page.Component, params, page.layoutModules);
|
|
2265
|
-
const content = createElement2(IslandProvider, { registry }, pageContent);
|
|
2266
|
-
const html = renderStaticPage(content, { stylesheet: stylesheetHref });
|
|
2267
|
-
const outPath = page.entry.routePath === "/" ? "/index.html" : `${page.entry.routePath}/index.html`;
|
|
2268
|
-
const fullPath = join5(clientDir, outPath);
|
|
2269
|
-
mkdirSync2(join5(fullPath, ".."), { recursive: true });
|
|
2270
|
-
if (writtenPaths.has(outPath)) {
|
|
2271
|
-
console.warn(` [warn] collision: ${page.entry.routePath} overwrites existing output`);
|
|
2272
|
-
}
|
|
2273
|
-
writtenPaths.add(outPath);
|
|
2274
|
-
let islandScripts = [];
|
|
2275
|
-
if (registry.entries.length > 0) {
|
|
2276
|
-
const uniqueNames = [...new Set(registry.entries.map((e) => e.name))];
|
|
2277
|
-
islandScripts = await bundleRouteIslands(
|
|
2278
|
-
page.filePath,
|
|
2279
|
-
page.layoutFilePaths,
|
|
2280
|
-
uniqueNames,
|
|
2281
|
-
islandsDir,
|
|
2282
|
-
actionModules
|
|
2283
|
-
);
|
|
2284
|
-
console.log(
|
|
2285
|
-
` [islands] ${uniqueNames.length} island(s) on ${page.entry.routePath} -> ${islandScripts.join(", ")}`
|
|
2286
|
-
);
|
|
2455
|
+
const prodFetchInner = async (req, server) => {
|
|
2456
|
+
const url = new URL(req.url).pathname;
|
|
2457
|
+
const healthResult = await healthHandler(req);
|
|
2458
|
+
if (healthResult !== null) return healthResult;
|
|
2459
|
+
if (metricsReporter?.handleMetrics) {
|
|
2460
|
+
const metricsResult = await metricsReporter.handleMetrics(req);
|
|
2461
|
+
if (metricsResult !== null) return metricsResult;
|
|
2287
2462
|
}
|
|
2288
|
-
|
|
2289
|
-
|
|
2290
|
-
|
|
2291
|
-
|
|
2292
|
-
|
|
2293
|
-
|
|
2294
|
-
const bodyHtml = renderMarkdown(content.body);
|
|
2295
|
-
const pageContent = createElement2(StaticContentPage, {
|
|
2296
|
-
content,
|
|
2297
|
-
bodyHtml
|
|
2298
|
-
});
|
|
2299
|
-
const rendered = createElement2(IslandProvider, { registry }, pageContent);
|
|
2300
|
-
const html = renderStaticPage(rendered, {
|
|
2301
|
-
title: content.frontmatter.title ?? content.slug,
|
|
2302
|
-
stylesheet: stylesheetHref
|
|
2303
|
-
});
|
|
2304
|
-
const outPath = content.routePath === "/" ? "/index.html" : `${content.routePath}/index.html`;
|
|
2305
|
-
const fullPath = join5(clientDir, outPath);
|
|
2306
|
-
mkdirSync2(join5(fullPath, ".."), { recursive: true });
|
|
2307
|
-
if (writtenPaths.has(outPath)) {
|
|
2308
|
-
console.warn(` [warn] collision: content ${content.routePath} overwrites existing output`);
|
|
2463
|
+
if (rateLimiter) {
|
|
2464
|
+
const limited = await rateLimitMiddleware(rateLimiter, req, server);
|
|
2465
|
+
if (limited !== null) {
|
|
2466
|
+
metricsReporter?.incr("x_rate_limit_rejections_total", 1, { method: req.method });
|
|
2467
|
+
return limited;
|
|
2468
|
+
}
|
|
2309
2469
|
}
|
|
2310
|
-
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
if (
|
|
2320
|
-
|
|
2321
|
-
|
|
2322
|
-
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
configImportPath,
|
|
2326
|
-
stylesheetHref
|
|
2327
|
-
);
|
|
2328
|
-
const serverEntryPath = join5(serverDir, "index.ts");
|
|
2329
|
-
writeFileSync3(serverEntryPath, serverEntry, "utf-8");
|
|
2330
|
-
console.log(
|
|
2331
|
-
` [server] ${serverPages.length} page routes, ${apiRoutes.length} api routes -> server/index.ts`
|
|
2332
|
-
);
|
|
2333
|
-
}
|
|
2334
|
-
console.log(`[x] build complete -> ${outDir}`);
|
|
2335
|
-
}
|
|
2336
|
-
async function bundleRouteIslands(routeFilePath, layoutFilePaths, islandNames, islandsDir, actionModules) {
|
|
2337
|
-
const entryId = islandEntryId(routeFilePath);
|
|
2338
|
-
const outdir = join5(islandsDir, entryId);
|
|
2339
|
-
mkdirSync2(outdir, { recursive: true });
|
|
2340
|
-
const bundlePath = join5(outdir, `${entryId}.js`);
|
|
2341
|
-
const hydrateEntry = generateHydrateEntry(routeFilePath, layoutFilePaths);
|
|
2342
|
-
const entryPath = join5(outdir, `${entryId}.tsx`);
|
|
2343
|
-
writeFileSync3(entryPath, hydrateEntry, "utf-8");
|
|
2344
|
-
try {
|
|
2345
|
-
const result = await Bun.build({
|
|
2346
|
-
entrypoints: [entryPath],
|
|
2347
|
-
target: "browser",
|
|
2348
|
-
plugins: [actionsRewritePlugin(actionModules)]
|
|
2349
|
-
});
|
|
2350
|
-
if (result.success) {
|
|
2351
|
-
const outputs = result.outputs.filter((o) => o.kind === "entry-point");
|
|
2352
|
-
const built = outputs[0] ?? result.outputs[0];
|
|
2353
|
-
if (!built) throw new Error("bun build produced no output");
|
|
2354
|
-
const code = await built.text();
|
|
2355
|
-
assertNoEnvLeakage(code, bundlePath);
|
|
2356
|
-
writeFileSync3(bundlePath, wrapIslandBundle(code), "utf-8");
|
|
2357
|
-
return [`/_islands/${entryId}/${entryId}.js`];
|
|
2470
|
+
const revalidationResult = await handleRevalidation(req);
|
|
2471
|
+
if (revalidationResult !== null) return revalidationResult;
|
|
2472
|
+
const serverFnResult = await serverFnHandler(req);
|
|
2473
|
+
if (serverFnResult !== null) return serverFnResult;
|
|
2474
|
+
const staticAsset = await serveStaticAsset(publicDir, req);
|
|
2475
|
+
if (staticAsset !== null) return staticAsset;
|
|
2476
|
+
const islandBundle = serveIslandBundle(req);
|
|
2477
|
+
if (islandBundle !== null) return islandBundle;
|
|
2478
|
+
const proxiedImage = await imageProxyHandler(req);
|
|
2479
|
+
if (proxiedImage !== null) return proxiedImage;
|
|
2480
|
+
for (const h of handlers) {
|
|
2481
|
+
const params = extractParams(h.entry.routePath, h.entry.paramNames, url);
|
|
2482
|
+
if (params !== null) {
|
|
2483
|
+
return h.handler(req);
|
|
2484
|
+
}
|
|
2358
2485
|
}
|
|
2359
|
-
for (const
|
|
2360
|
-
|
|
2486
|
+
for (const h of contentHandlers) {
|
|
2487
|
+
if (h.entry.routePath === url) {
|
|
2488
|
+
return h.handler(req);
|
|
2489
|
+
}
|
|
2361
2490
|
}
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2367
|
-
return
|
|
2368
|
-
}
|
|
2369
|
-
|
|
2370
|
-
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
}
|
|
2374
|
-
return content;
|
|
2375
|
-
}
|
|
2376
|
-
function StaticContentPage({
|
|
2377
|
-
content,
|
|
2378
|
-
bodyHtml
|
|
2379
|
-
}) {
|
|
2380
|
-
return createElement2(
|
|
2381
|
-
"article",
|
|
2382
|
-
null,
|
|
2383
|
-
content.frontmatter.title ? createElement2("h1", null, content.frontmatter.title) : null,
|
|
2384
|
-
createElement2("div", {
|
|
2385
|
-
// biome-ignore lint/security/noDangerouslySetInnerHtml: body is markdown rendered to HTML
|
|
2386
|
-
dangerouslySetInnerHTML: { __html: bodyHtml }
|
|
2387
|
-
})
|
|
2388
|
-
);
|
|
2389
|
-
}
|
|
2390
|
-
function buildServerEntry(opts, configImportPath, stylesheetHref) {
|
|
2391
|
-
const dirKeys = ["pagesDir", "apiDir", "layoutsDir", "actionsDir", "contentDir"];
|
|
2392
|
-
const lines = [
|
|
2393
|
-
"// Auto-generated by @thexjs/core build",
|
|
2394
|
-
'import { createApp } from "@thexjs/core";'
|
|
2395
|
-
];
|
|
2396
|
-
if (configImportPath) {
|
|
2397
|
-
lines.push("", "let userConfig = {};", "try {");
|
|
2398
|
-
lines.push(` const mod = await import(${JSON.stringify(configImportPath)});`);
|
|
2399
|
-
lines.push(" userConfig = mod.default ?? {};");
|
|
2400
|
-
lines.push("} catch (err) {");
|
|
2401
|
-
lines.push(
|
|
2402
|
-
' console.warn("[x] failed to load x.config for security/observability options:", err);'
|
|
2403
|
-
);
|
|
2404
|
-
lines.push("}");
|
|
2405
|
-
}
|
|
2406
|
-
lines.push("", "const app = await createApp({");
|
|
2407
|
-
for (const key of dirKeys) {
|
|
2408
|
-
const val = opts[key];
|
|
2409
|
-
if (val) lines.push(` ${key}: ${JSON.stringify(val)},`);
|
|
2410
|
-
}
|
|
2411
|
-
if (stylesheetHref) lines.push(` stylesheetHref: ${JSON.stringify(stylesheetHref)},`);
|
|
2412
|
-
lines.push(' port: parseInt(process.env.PORT || "3000", 10),', " development: false,");
|
|
2413
|
-
if (configImportPath) {
|
|
2414
|
-
lines.push(" ...(userConfig.security ? { security: userConfig.security } : {}),");
|
|
2415
|
-
lines.push(
|
|
2416
|
-
" ...(userConfig.observability ? { observability: userConfig.observability } : {}),"
|
|
2417
|
-
);
|
|
2418
|
-
lines.push(" ...(userConfig.images ? { images: userConfig.images } : {}),");
|
|
2419
|
-
}
|
|
2420
|
-
lines.push(
|
|
2421
|
-
"});",
|
|
2422
|
-
"",
|
|
2423
|
-
"const server = Bun.serve(app);",
|
|
2424
|
-
"",
|
|
2425
|
-
"console.log(`[x] production server running at ${server.url}`);",
|
|
2426
|
-
"",
|
|
2427
|
-
"// Graceful shutdown: stop accepting new connections, flush the error",
|
|
2428
|
-
"// reporter, then exit after in-flight requests have a moment to drain.",
|
|
2429
|
-
"let shuttingDown = false;",
|
|
2430
|
-
"async function shutdown(signal: string): Promise<void> {",
|
|
2431
|
-
" if (shuttingDown) return;",
|
|
2432
|
-
" shuttingDown = true;",
|
|
2433
|
-
" console.log(`[x] received ${signal} - shutting down`);",
|
|
2434
|
-
" try {",
|
|
2435
|
-
' const { getErrorReporter } = await import("@thexjs/core");',
|
|
2436
|
-
" await getErrorReporter().flush?.();",
|
|
2437
|
-
" } catch {}",
|
|
2438
|
-
" server.stop(true);",
|
|
2439
|
-
" const exit = () => process.exit(0);",
|
|
2440
|
-
" const drainTimer = setTimeout(exit, 3000);",
|
|
2441
|
-
" drainTimer.unref?.();",
|
|
2442
|
-
"}",
|
|
2443
|
-
'process.on("SIGTERM", () => shutdown("SIGTERM"));',
|
|
2444
|
-
'process.on("SIGINT", () => shutdown("SIGINT"));'
|
|
2445
|
-
);
|
|
2446
|
-
return lines.join("\n");
|
|
2447
|
-
}
|
|
2448
|
-
function relativeImportPath(fromDir, toFile) {
|
|
2449
|
-
const rel = relative2(fromDir, toFile).replace(/\\/g, "/").replace(/\.(ts|js|mjs)$/, "");
|
|
2450
|
-
return rel.startsWith(".") ? rel : `./${rel}`;
|
|
2491
|
+
return renderNotFound(req);
|
|
2492
|
+
};
|
|
2493
|
+
const prodFetchHardened = async (req, server) => withResponseHardening(await prodFetchInner(req, server));
|
|
2494
|
+
const prodFetchBase = loggingEnabled ? withRequestLogging(prodFetchHardened) : prodFetchHardened;
|
|
2495
|
+
const prodFetch = metricsReporter ? withRequestMetrics(metricsReporter, prodFetchBase) : prodFetchBase;
|
|
2496
|
+
return {
|
|
2497
|
+
routes: {},
|
|
2498
|
+
development: false,
|
|
2499
|
+
port: options.port ?? 3e3,
|
|
2500
|
+
fetch: prodFetch
|
|
2501
|
+
};
|
|
2451
2502
|
}
|
|
2452
2503
|
|
|
2453
2504
|
// src/link.tsx
|
|
@@ -2490,7 +2541,7 @@ export {
|
|
|
2490
2541
|
createRedisRateLimitStore,
|
|
2491
2542
|
createSentryReporter,
|
|
2492
2543
|
defineConfig,
|
|
2493
|
-
|
|
2544
|
+
escapeHtml,
|
|
2494
2545
|
findLayoutChain,
|
|
2495
2546
|
findLeakedEnvKeys,
|
|
2496
2547
|
findMiddlewareChain,
|