@thexjs/core 1.2.3 → 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 +151 -152
- package/dist/data.d.ts +7 -7
- package/dist/data.js +78 -78
- package/dist/index.d.ts +114 -114
- package/dist/index.js +1420 -1422
- package/package.json +6 -2
package/dist/index.js
CHANGED
|
@@ -14,418 +14,79 @@ import {
|
|
|
14
14
|
writeManifest
|
|
15
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,212 +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/avif",
|
|
614
|
-
"image/x-icon"
|
|
615
|
-
]);
|
|
616
|
-
function createImageProxyHandler(options = {}) {
|
|
617
|
-
const allowedHosts = new Set(options.remoteHosts ?? []);
|
|
618
|
-
return async (req) => {
|
|
619
|
-
const reqUrl = new URL(req.url);
|
|
620
|
-
if (reqUrl.pathname !== "/_x/image") return null;
|
|
621
|
-
if (req.method !== "GET" && req.method !== "HEAD") return null;
|
|
622
|
-
const target = reqUrl.searchParams.get("url");
|
|
623
|
-
if (!target) return new Response("missing url param", { status: 400 });
|
|
624
|
-
let parsed;
|
|
625
|
-
try {
|
|
626
|
-
parsed = new URL(target);
|
|
627
|
-
} catch {
|
|
628
|
-
return new Response("invalid url param", { status: 400 });
|
|
629
|
-
}
|
|
630
|
-
const allowedUrl = (u) => (u.protocol === "http:" || u.protocol === "https:") && allowedHosts.has(u.hostname);
|
|
631
|
-
if (!allowedUrl(parsed)) {
|
|
632
|
-
return new Response("host not allow-listed for image proxy", { status: 403 });
|
|
633
|
-
}
|
|
634
|
-
const isRedirect = (status) => status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
|
|
635
|
-
let upstream;
|
|
636
|
-
try {
|
|
637
|
-
upstream = await fetch(parsed, { redirect: "manual" });
|
|
638
|
-
for (let hop = 0; hop < 5; hop++) {
|
|
639
|
-
if (!isRedirect(upstream.status)) break;
|
|
640
|
-
const location = upstream.headers.get("location");
|
|
641
|
-
let next;
|
|
642
|
-
try {
|
|
643
|
-
next = new URL(location ?? "", parsed);
|
|
644
|
-
} catch {
|
|
645
|
-
return new Response("upstream redirect was not a valid URL", { status: 502 });
|
|
646
|
-
}
|
|
647
|
-
if (!allowedUrl(next)) {
|
|
648
|
-
return new Response("upstream redirected off the allow-list", { status: 403 });
|
|
649
|
-
}
|
|
650
|
-
upstream = await fetch(next, { redirect: "manual" });
|
|
651
|
-
}
|
|
652
|
-
} catch (err) {
|
|
653
|
-
return new Response(`upstream fetch failed: ${String(err)}`, { status: 502 });
|
|
654
|
-
}
|
|
655
|
-
if (isRedirect(upstream.status)) {
|
|
656
|
-
return new Response("too many upstream redirects", { status: 502 });
|
|
657
|
-
}
|
|
658
|
-
if (!upstream.ok) {
|
|
659
|
-
return new Response("upstream error", { status: 502 });
|
|
660
|
-
}
|
|
661
|
-
const contentType = upstream.headers.get("content-type") ?? "";
|
|
662
|
-
const baseContentType = (contentType.split(";")[0] ?? "").trim();
|
|
663
|
-
if (!ALLOWED_CONTENT_TYPES.has(baseContentType)) {
|
|
664
|
-
return new Response("upstream did not return an image", { status: 502 });
|
|
665
|
-
}
|
|
666
|
-
return new Response(upstream.body, {
|
|
667
|
-
status: 200,
|
|
668
|
-
headers: {
|
|
669
|
-
"Content-Type": contentType,
|
|
670
|
-
// Cache aggressively client + edge side — the proxied URL is the
|
|
671
|
-
// cache key, and remote asset URLs like this one are typically
|
|
672
|
-
// content-hashed by the origin already.
|
|
673
|
-
"Cache-Control": "public, max-age=86400, immutable"
|
|
674
|
-
}
|
|
675
|
-
});
|
|
676
|
-
};
|
|
677
|
-
}
|
|
678
|
-
|
|
679
|
-
// src/island.tsx
|
|
680
|
-
import { createContext, useContext } from "react";
|
|
681
|
-
import { jsx as jsx2 } from "react/jsx-runtime";
|
|
682
|
-
function createIslandRegistry() {
|
|
683
|
-
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: [] };
|
|
684
151
|
}
|
|
685
152
|
var IslandContext = createContext(null);
|
|
686
153
|
function IslandProvider({
|
|
687
154
|
registry,
|
|
688
155
|
children
|
|
689
156
|
}) {
|
|
690
|
-
return /* @__PURE__ */
|
|
157
|
+
return /* @__PURE__ */ jsx(IslandContext.Provider, { value: registry, children });
|
|
691
158
|
}
|
|
692
159
|
var islandCounter = 0;
|
|
693
160
|
function Island({
|
|
@@ -700,7 +167,7 @@ function Island({
|
|
|
700
167
|
if (registry) {
|
|
701
168
|
registry.entries.push({ name, id });
|
|
702
169
|
}
|
|
703
|
-
return /* @__PURE__ */
|
|
170
|
+
return /* @__PURE__ */ jsx("div", { "data-island": name, "data-island-id": id, "data-island-client": client, children });
|
|
704
171
|
}
|
|
705
172
|
|
|
706
173
|
// src/island-bundle.ts
|
|
@@ -1113,485 +580,1319 @@ async function buildIslandBundleInMemory(routeFilePath, layoutFilePaths, islandN
|
|
|
1113
580
|
}
|
|
1114
581
|
}
|
|
1115
582
|
|
|
1116
|
-
// src/
|
|
1117
|
-
|
|
1118
|
-
return async (ctx, _next) => {
|
|
1119
|
-
let index = -1;
|
|
1120
|
-
const dispatch = async (i) => {
|
|
1121
|
-
if (i <= index) throw new Error("next() called multiple times");
|
|
1122
|
-
index = i;
|
|
1123
|
-
const fn = fns[i];
|
|
1124
|
-
if (fn) {
|
|
1125
|
-
return fn(ctx, () => dispatch(i + 1));
|
|
1126
|
-
}
|
|
1127
|
-
return handler(ctx);
|
|
1128
|
-
};
|
|
1129
|
-
return dispatch(0);
|
|
1130
|
-
};
|
|
1131
|
-
}
|
|
583
|
+
// src/render.ts
|
|
584
|
+
import { renderToReadableStream, renderToStaticMarkup, renderToString } from "react-dom/server";
|
|
1132
585
|
|
|
1133
|
-
// src/
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
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 },
|
|
1148
611
|
);
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
}
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
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;
|
|
1161
649
|
}
|
|
1162
|
-
return null;
|
|
1163
|
-
|
|
1164
|
-
|
|
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
|
+
}
|
|
1165
655
|
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
const entry = {
|
|
1169
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1170
|
-
level,
|
|
1171
|
-
message,
|
|
1172
|
-
...fields
|
|
1173
|
-
};
|
|
1174
|
-
const line = JSON.stringify(entry);
|
|
1175
|
-
if (level === "error") {
|
|
1176
|
-
console.error(line);
|
|
1177
|
-
} else if (level === "warn") {
|
|
1178
|
-
console.warn(line);
|
|
1179
|
-
} else {
|
|
1180
|
-
console.log(line);
|
|
656
|
+
function setLoading(on) {
|
|
657
|
+
document.documentElement.classList.toggle("x-nav-loading", on);
|
|
1181
658
|
}
|
|
1182
|
-
}
|
|
1183
|
-
var logger = {
|
|
1184
|
-
info: (message, fields) => write("info", message, fields),
|
|
1185
|
-
warn: (message, fields) => write("warn", message, fields),
|
|
1186
|
-
error: (message, fields) => write("error", message, fields)
|
|
1187
|
-
};
|
|
1188
|
-
function withRequestLogging(handler) {
|
|
1189
|
-
return async (req, server) => {
|
|
1190
|
-
const start = performance.now();
|
|
1191
|
-
const requestId = req.headers.get("x-request-id") ?? crypto.randomUUID();
|
|
1192
|
-
const route = new URL(req.url).pathname;
|
|
1193
|
-
try {
|
|
1194
|
-
const res = await handler(req, server);
|
|
1195
|
-
const isStream = res.headers.get("content-type")?.includes("text/event-stream");
|
|
1196
|
-
console.log(
|
|
1197
|
-
`[x][request] ${req.method} ${route} -> ${res.status}${isStream ? " (stream opened, not closed)" : ""}`
|
|
1198
|
-
);
|
|
1199
|
-
write("info", isStream ? "stream opened" : "request completed", {
|
|
1200
|
-
requestId,
|
|
1201
|
-
route,
|
|
1202
|
-
method: req.method,
|
|
1203
|
-
status: res.status,
|
|
1204
|
-
durationMs: Math.round(performance.now() - start)
|
|
1205
|
-
});
|
|
1206
|
-
if (!res.headers.has("x-request-id")) {
|
|
1207
|
-
res.headers.set("x-request-id", requestId);
|
|
1208
|
-
}
|
|
1209
|
-
return res;
|
|
1210
|
-
} catch (err) {
|
|
1211
|
-
write("error", "request failed", {
|
|
1212
|
-
requestId,
|
|
1213
|
-
route,
|
|
1214
|
-
method: req.method,
|
|
1215
|
-
status: 500,
|
|
1216
|
-
durationMs: Math.round(performance.now() - start),
|
|
1217
|
-
error: err instanceof Error ? err.message : String(err)
|
|
1218
|
-
});
|
|
1219
|
-
throw err;
|
|
1220
|
-
}
|
|
1221
|
-
};
|
|
1222
|
-
}
|
|
1223
659
|
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
};
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
}
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
const histograms = /* @__PURE__ */ new Map();
|
|
1241
|
-
function incr(name, delta = 1, labels) {
|
|
1242
|
-
const key = seriesKey(name, labels);
|
|
1243
|
-
let series = counters.get(key);
|
|
1244
|
-
if (!series) {
|
|
1245
|
-
series = { name, labels: labels ?? {}, value: 0 };
|
|
1246
|
-
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);
|
|
1247
676
|
}
|
|
1248
|
-
|
|
677
|
+
cache.set(url.href, promise);
|
|
678
|
+
return promise;
|
|
1249
679
|
}
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
acc.count += 1;
|
|
1259
|
-
for (let i = 0; i < buckets.length; i += 1) {
|
|
1260
|
-
const bound = buckets[i];
|
|
1261
|
-
if (bound === void 0) break;
|
|
1262
|
-
if (value <= bound) {
|
|
1263
|
-
for (let j = i; j < buckets.length; j += 1) {
|
|
1264
|
-
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;
|
|
1265
688
|
}
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
if (
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
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
|
+
});
|
|
1292
715
|
}
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
for (
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
const labels = { ...h.labels, le };
|
|
1303
|
-
return formatLabels(labels);
|
|
1304
|
-
};
|
|
1305
|
-
lines.push(`# TYPE ${h.name} histogram`);
|
|
1306
|
-
for (let i = 0; i < buckets.length; i += 1) {
|
|
1307
|
-
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);
|
|
1308
725
|
}
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
lines.push(`${h.name}_count${formatLabels(h.labels)} ${h.count}`);
|
|
726
|
+
el.textContent = old.textContent;
|
|
727
|
+
old.replaceWith(el);
|
|
1312
728
|
}
|
|
1313
|
-
return `${lines.join("\n")}
|
|
1314
|
-
`;
|
|
1315
|
-
}
|
|
1316
|
-
function handleMetrics(req) {
|
|
1317
|
-
if (new URL(req.url).pathname !== "/metrics") return null;
|
|
1318
|
-
return new Response(renderMetrics(), {
|
|
1319
|
-
headers: { "Content-Type": "text/plain; version=0.0.4; charset=utf-8" }
|
|
1320
|
-
});
|
|
1321
729
|
}
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
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);
|
|
734
|
+
};
|
|
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();
|
|
1329
748
|
}
|
|
749
|
+
});
|
|
750
|
+
es.addEventListener("hb", function () {});
|
|
751
|
+
es.onerror = function () {
|
|
752
|
+
es.close();
|
|
1330
753
|
};
|
|
754
|
+
})();
|
|
755
|
+
`.trim();
|
|
756
|
+
|
|
757
|
+
// src/render.ts
|
|
758
|
+
function escapeHtml2(s) {
|
|
759
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
1331
760
|
}
|
|
1332
|
-
function
|
|
1333
|
-
|
|
1334
|
-
const histograms = /* @__PURE__ */ new Map();
|
|
1335
|
-
return {
|
|
1336
|
-
incr(name, delta, labels) {
|
|
1337
|
-
let counter = counters.get(name);
|
|
1338
|
-
if (!counter) {
|
|
1339
|
-
counter = meter.createCounter(name, { description: `Counter ${name}` });
|
|
1340
|
-
counters.set(name, counter);
|
|
1341
|
-
}
|
|
1342
|
-
counter.add(delta ?? 1, labels);
|
|
1343
|
-
},
|
|
1344
|
-
observe(name, value, labels) {
|
|
1345
|
-
let histogram = histograms.get(name);
|
|
1346
|
-
if (!histogram) {
|
|
1347
|
-
histogram = meter.createHistogram(name, { description: `Histogram ${name}` });
|
|
1348
|
-
histograms.set(name, histogram);
|
|
1349
|
-
}
|
|
1350
|
-
histogram.record(value, labels);
|
|
1351
|
-
}
|
|
1352
|
-
};
|
|
761
|
+
function escapeJsonForScript(s) {
|
|
762
|
+
return s.replace(/<\//g, "<\\/");
|
|
1353
763
|
}
|
|
1354
|
-
function
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
const escaped = entries.map(([k, v]) => `${k}="${escapeLabelValue(v)}"`).join(",");
|
|
1358
|
-
return `{${escaped}}`;
|
|
764
|
+
function buildHeadExtras(stylesheet) {
|
|
765
|
+
return stylesheet ? `
|
|
766
|
+
<link rel="stylesheet" href="${escapeHtml2(stylesheet)}" />` : "";
|
|
1359
767
|
}
|
|
1360
|
-
function
|
|
1361
|
-
return
|
|
768
|
+
function buildNavScriptTag(clientNav) {
|
|
769
|
+
return clientNav === false ? "" : `
|
|
770
|
+
<script>${CLIENT_NAV_SCRIPT}</script>`;
|
|
1362
771
|
}
|
|
1363
|
-
function
|
|
1364
|
-
return
|
|
1365
|
-
|
|
1366
|
-
const method = req.method;
|
|
1367
|
-
try {
|
|
1368
|
-
const res = await handler(req, server);
|
|
1369
|
-
reporter.incr("x_http_requests_total", 1, { method, status: String(res.status) });
|
|
1370
|
-
reporter.observe("x_http_request_duration_ms", performance.now() - start, { method });
|
|
1371
|
-
return res;
|
|
1372
|
-
} catch (err) {
|
|
1373
|
-
reporter.incr("x_http_requests_total", 1, { method, status: "500" });
|
|
1374
|
-
reporter.incr("x_http_errors_total", 1, { method });
|
|
1375
|
-
reporter.observe("x_http_request_duration_ms", performance.now() - start, { method });
|
|
1376
|
-
throw err;
|
|
1377
|
-
}
|
|
1378
|
-
};
|
|
772
|
+
function buildLiveReloadTag(liveReload) {
|
|
773
|
+
return liveReload ? `
|
|
774
|
+
<script>${LIVE_RELOAD_SCRIPT}</script>` : "";
|
|
1379
775
|
}
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
const contentTypeOptions = options.contentTypeOptions ?? "nosniff";
|
|
1398
|
-
if (contentTypeOptions !== false) headers.set("X-Content-Type-Options", contentTypeOptions);
|
|
1399
|
-
const referrerPolicy = options.referrerPolicy ?? "strict-origin-when-cross-origin";
|
|
1400
|
-
if (referrerPolicy !== false) headers.set("Referrer-Policy", referrerPolicy);
|
|
1401
|
-
return headers;
|
|
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>`;
|
|
1402
793
|
}
|
|
1403
|
-
function
|
|
1404
|
-
const
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
}
|
|
1410
|
-
return
|
|
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
|
+
);
|
|
1411
810
|
}
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
}
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
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
|
+
);
|
|
1422
827
|
}
|
|
1423
|
-
function
|
|
1424
|
-
const
|
|
1425
|
-
const
|
|
1426
|
-
const
|
|
1427
|
-
const
|
|
1428
|
-
const
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
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);
|
|
1434
846
|
}
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
847
|
+
});
|
|
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();
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
await pump();
|
|
1440
885
|
}
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
886
|
+
});
|
|
887
|
+
}
|
|
888
|
+
|
|
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)}`);
|
|
1444
909
|
}
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
910
|
+
let routeEntries = [];
|
|
911
|
+
if (pagesDir && existsSync(pagesDir)) {
|
|
912
|
+
routeEntries = scanPages(pagesDir);
|
|
913
|
+
}
|
|
914
|
+
if (apiDir && existsSync(apiDir)) {
|
|
915
|
+
routeEntries.push(...scanApiDir(apiDir));
|
|
916
|
+
}
|
|
917
|
+
const legacyApiDir = pagesDir ? join4(pagesDir, "api") : "";
|
|
918
|
+
if (legacyApiDir && existsSync(legacyApiDir) && legacyApiDir !== apiDir) {
|
|
919
|
+
routeEntries.push(...scanApiDir(legacyApiDir));
|
|
920
|
+
}
|
|
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));
|
|
932
|
+
}
|
|
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
|
|
937
|
+
});
|
|
938
|
+
fnNames.push(key);
|
|
939
|
+
}
|
|
940
|
+
if (fnNames.length > 0) {
|
|
941
|
+
actionModules.set(actionFile.filePath, { parentPath, fnNames });
|
|
942
|
+
}
|
|
1449
943
|
}
|
|
1450
944
|
}
|
|
1451
|
-
const
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
const
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
headers: {
|
|
1462
|
-
"Content-Type": "text/plain; charset=utf-8",
|
|
1463
|
-
"Retry-After": String(retryAfterSeconds),
|
|
1464
|
-
"X-RateLimit-Limit": String(result.limit),
|
|
1465
|
-
"X-RateLimit-Remaining": String(result.remaining)
|
|
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;
|
|
1466
955
|
}
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
const
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
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,
|
|
977
|
+
mode,
|
|
978
|
+
Component,
|
|
979
|
+
layoutModules,
|
|
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(", ")}`
|
|
1496
1021
|
);
|
|
1497
1022
|
}
|
|
1498
|
-
|
|
1023
|
+
const finalHtml = renderStaticPage(content, { islandScripts, stylesheet: stylesheetHref });
|
|
1024
|
+
writeFileSync3(fullPath, finalHtml, "utf-8");
|
|
1025
|
+
console.log(` [static] ${page.entry.routePath} -> ${outPath}`);
|
|
1499
1026
|
}
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
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`);
|
|
1510
1044
|
}
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
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}`);
|
|
1529
1070
|
}
|
|
1530
|
-
function
|
|
1531
|
-
|
|
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");
|
|
1532
1079
|
try {
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
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);
|
|
1536
1100
|
}
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
if (target !== root && !target.startsWith(root + sep2)) return null;
|
|
1540
|
-
return target;
|
|
1541
|
-
}
|
|
1542
|
-
async function serveStaticAsset(publicDir, req) {
|
|
1543
|
-
if (!publicDir) return null;
|
|
1544
|
-
if (req.method !== "GET" && req.method !== "HEAD") return null;
|
|
1545
|
-
const pathname = new URL(req.url).pathname;
|
|
1546
|
-
if (pathname === "/" || pathname.endsWith("/")) return null;
|
|
1547
|
-
const filePath = resolvePublicAsset(publicDir, pathname);
|
|
1548
|
-
if (!filePath) return null;
|
|
1549
|
-
const bun = globalThis.Bun;
|
|
1550
|
-
if (!bun) return null;
|
|
1551
|
-
const file = bun.file(filePath);
|
|
1552
|
-
if (!await file.exists()) return null;
|
|
1553
|
-
return new Response(file);
|
|
1101
|
+
writeFileSync3(bundlePath, wrapIslandBundle(generateFallbackHydration(islandNames)), "utf-8");
|
|
1102
|
+
return [`/_islands/${entryId}/${entryId}.js`];
|
|
1554
1103
|
}
|
|
1555
|
-
function
|
|
1556
|
-
let content = createElement(Component, { params
|
|
1104
|
+
function renderPageWithLayout(Component, params, layoutModules) {
|
|
1105
|
+
let content = createElement(Component, { params });
|
|
1557
1106
|
for (const Layout of [...layoutModules].reverse()) {
|
|
1558
1107
|
content = createElement(Layout, null, content);
|
|
1559
1108
|
}
|
|
1560
1109
|
return content;
|
|
1561
1110
|
}
|
|
1562
|
-
function
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
createElement(
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
// biome-ignore lint/security/noDangerouslySetInnerHtml: body is markdown rendered to HTML
|
|
1572
|
-
dangerouslySetInnerHTML: { __html: bodyHtml }
|
|
1573
|
-
})
|
|
1574
|
-
),
|
|
1575
|
-
{ title, stylesheet, liveReload: dev }
|
|
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
|
+
})
|
|
1576
1120
|
);
|
|
1577
|
-
return body;
|
|
1578
|
-
}
|
|
1579
|
-
function defineConfig(config) {
|
|
1580
|
-
return config;
|
|
1581
1121
|
}
|
|
1582
|
-
function
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
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;
|
|
1595
1896
|
let notFoundLayout;
|
|
1596
1897
|
const serverFnHandler = getServerFunctionHandler(options.security?.csrf);
|
|
1597
1898
|
const staticCache = /* @__PURE__ */ new Map();
|
|
@@ -1640,8 +1941,8 @@ async function createApp(options) {
|
|
|
1640
1941
|
function withResponseHardening(res) {
|
|
1641
1942
|
return securityHeadersOptions === false ? res : applySecurityHeaders(res, securityHeadersOptions);
|
|
1642
1943
|
}
|
|
1643
|
-
async function renderNotFound(
|
|
1644
|
-
const content = notFoundLayout ?
|
|
1944
|
+
async function renderNotFound(_req) {
|
|
1945
|
+
const content = notFoundLayout ? createElement2(notFoundLayout, null, createElement2(notFoundComponent, { params: {} })) : createElement2(notFoundComponent, { params: {} });
|
|
1645
1946
|
const html = renderPage(content, {
|
|
1646
1947
|
title: "404 \u2014 Not Found",
|
|
1647
1948
|
stylesheet: stylesheetHref,
|
|
@@ -1703,7 +2004,7 @@ async function createApp(options) {
|
|
|
1703
2004
|
loaderData2 = result;
|
|
1704
2005
|
}
|
|
1705
2006
|
const registry2 = createIslandRegistry();
|
|
1706
|
-
const content2 =
|
|
2007
|
+
const content2 = createElement2(
|
|
1707
2008
|
IslandProvider,
|
|
1708
2009
|
{ registry: registry2 },
|
|
1709
2010
|
wrapWithLayouts(Component, ctx.params, loaderData2, layoutModules)
|
|
@@ -1745,7 +2046,7 @@ async function createApp(options) {
|
|
|
1745
2046
|
loaderData = result;
|
|
1746
2047
|
}
|
|
1747
2048
|
const registry = createIslandRegistry();
|
|
1748
|
-
const content =
|
|
2049
|
+
const content = createElement2(
|
|
1749
2050
|
IslandProvider,
|
|
1750
2051
|
{ registry },
|
|
1751
2052
|
wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
|
|
@@ -1795,9 +2096,9 @@ async function createApp(options) {
|
|
|
1795
2096
|
async function buildHandlers() {
|
|
1796
2097
|
if (options.preloaded) {
|
|
1797
2098
|
const preloaded = options.preloaded;
|
|
1798
|
-
const candidatePublicDir2 =
|
|
1799
|
-
publicDir =
|
|
1800
|
-
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);
|
|
1801
2102
|
if (preloaded.notFoundComponent) notFoundComponent = preloaded.notFoundComponent;
|
|
1802
2103
|
if (preloaded.notFoundLayout) notFoundLayout = preloaded.notFoundLayout;
|
|
1803
2104
|
const loaded2 = [];
|
|
@@ -1845,14 +2146,13 @@ async function createApp(options) {
|
|
|
1845
2146
|
islandFileCache.clear();
|
|
1846
2147
|
const pagesDir = primaryDir;
|
|
1847
2148
|
const apiDir = options.apiDir;
|
|
1848
|
-
const layoutsDir = options.layoutsDir || pagesDir;
|
|
1849
2149
|
let found = scanPages(pagesDir);
|
|
1850
2150
|
const apiFound = [];
|
|
1851
|
-
if (apiDir &&
|
|
2151
|
+
if (apiDir && existsSync2(apiDir)) {
|
|
1852
2152
|
apiFound.push(...scanApiDir(apiDir));
|
|
1853
2153
|
}
|
|
1854
|
-
const legacyApiDir =
|
|
1855
|
-
if (
|
|
2154
|
+
const legacyApiDir = join5(pagesDir, "api");
|
|
2155
|
+
if (existsSync2(legacyApiDir) && legacyApiDir !== apiDir) {
|
|
1856
2156
|
apiFound.push(...scanApiDir(legacyApiDir));
|
|
1857
2157
|
}
|
|
1858
2158
|
found = found.filter((r) => !r.isApi);
|
|
@@ -1886,9 +2186,9 @@ async function createApp(options) {
|
|
|
1886
2186
|
}
|
|
1887
2187
|
}
|
|
1888
2188
|
}
|
|
1889
|
-
const candidatePublicDir =
|
|
1890
|
-
publicDir =
|
|
1891
|
-
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);
|
|
1892
2192
|
const notFoundEntry = scanNotFound(pagesDir);
|
|
1893
2193
|
if (notFoundEntry) {
|
|
1894
2194
|
const mod = await importDev(notFoundEntry.filePath, dev);
|
|
@@ -2048,7 +2348,7 @@ async function createApp(options) {
|
|
|
2048
2348
|
let rebuildTimeout = null;
|
|
2049
2349
|
const sseClients = /* @__PURE__ */ new Set();
|
|
2050
2350
|
try {
|
|
2051
|
-
const srcDir =
|
|
2351
|
+
const srcDir = join5(primaryDir, "..", "..", "src");
|
|
2052
2352
|
const watchDirs = [
|
|
2053
2353
|
...new Set(
|
|
2054
2354
|
[primaryDir, options.apiDir, options.layoutsDir, resolvedActionsDir, srcDir].filter(
|
|
@@ -2129,378 +2429,76 @@ data: ${data}
|
|
|
2129
2429
|
if (islandBundle !== null) return islandBundle;
|
|
2130
2430
|
const proxiedImage = await imageProxyHandler(req);
|
|
2131
2431
|
if (proxiedImage !== null) return proxiedImage;
|
|
2132
|
-
for (const h of handlers) {
|
|
2133
|
-
const params = extractParams(h.entry.routePath, h.entry.paramNames, url);
|
|
2134
|
-
if (params !== null) {
|
|
2135
|
-
return h.handler(req);
|
|
2136
|
-
}
|
|
2137
|
-
}
|
|
2138
|
-
for (const h of contentHandlers) {
|
|
2139
|
-
if (h.entry.routePath === url) {
|
|
2140
|
-
return h.handler(req);
|
|
2141
|
-
}
|
|
2142
|
-
}
|
|
2143
|
-
return renderNotFound(req);
|
|
2144
|
-
};
|
|
2145
|
-
const devFetchHardened = async (req, server) => withResponseHardening(await devFetchInner(req, server));
|
|
2146
|
-
const devFetchBase = loggingEnabled ? withRequestLogging(devFetchHardened) : devFetchHardened;
|
|
2147
|
-
const devFetch = metricsReporter ? withRequestMetrics(metricsReporter, devFetchBase) : devFetchBase;
|
|
2148
|
-
return {
|
|
2149
|
-
routes: {},
|
|
2150
|
-
development: true,
|
|
2151
|
-
port: options.port ?? 3e3,
|
|
2152
|
-
fetch: devFetch
|
|
2153
|
-
};
|
|
2154
|
-
}
|
|
2155
|
-
const prodFetchInner = async (req, server) => {
|
|
2156
|
-
const url = new URL(req.url).pathname;
|
|
2157
|
-
const healthResult = await healthHandler(req);
|
|
2158
|
-
if (healthResult !== null) return healthResult;
|
|
2159
|
-
if (metricsReporter?.handleMetrics) {
|
|
2160
|
-
const metricsResult = await metricsReporter.handleMetrics(req);
|
|
2161
|
-
if (metricsResult !== null) return metricsResult;
|
|
2162
|
-
}
|
|
2163
|
-
if (rateLimiter) {
|
|
2164
|
-
const limited = await rateLimitMiddleware(rateLimiter, req, server);
|
|
2165
|
-
if (limited !== null) {
|
|
2166
|
-
metricsReporter?.incr("x_rate_limit_rejections_total", 1, { method: req.method });
|
|
2167
|
-
return limited;
|
|
2168
|
-
}
|
|
2169
|
-
}
|
|
2170
|
-
const revalidationResult = await handleRevalidation(req);
|
|
2171
|
-
if (revalidationResult !== null) return revalidationResult;
|
|
2172
|
-
const serverFnResult = await serverFnHandler(req);
|
|
2173
|
-
if (serverFnResult !== null) return serverFnResult;
|
|
2174
|
-
const staticAsset = await serveStaticAsset(publicDir, req);
|
|
2175
|
-
if (staticAsset !== null) return staticAsset;
|
|
2176
|
-
const islandBundle = serveIslandBundle(req);
|
|
2177
|
-
if (islandBundle !== null) return islandBundle;
|
|
2178
|
-
const proxiedImage = await imageProxyHandler(req);
|
|
2179
|
-
if (proxiedImage !== null) return proxiedImage;
|
|
2180
|
-
for (const h of handlers) {
|
|
2181
|
-
const params = extractParams(h.entry.routePath, h.entry.paramNames, url);
|
|
2182
|
-
if (params !== null) {
|
|
2183
|
-
return h.handler(req);
|
|
2184
|
-
}
|
|
2185
|
-
}
|
|
2186
|
-
for (const h of contentHandlers) {
|
|
2187
|
-
if (h.entry.routePath === url) {
|
|
2188
|
-
return h.handler(req);
|
|
2189
|
-
}
|
|
2190
|
-
}
|
|
2191
|
-
return renderNotFound(req);
|
|
2192
|
-
};
|
|
2193
|
-
const prodFetchHardened = async (req, server) => withResponseHardening(await prodFetchInner(req, server));
|
|
2194
|
-
const prodFetchBase = loggingEnabled ? withRequestLogging(prodFetchHardened) : prodFetchHardened;
|
|
2195
|
-
const prodFetch = metricsReporter ? withRequestMetrics(metricsReporter, prodFetchBase) : prodFetchBase;
|
|
2196
|
-
return {
|
|
2197
|
-
routes: {},
|
|
2198
|
-
development: false,
|
|
2199
|
-
port: options.port ?? 3e3,
|
|
2200
|
-
fetch: prodFetch
|
|
2201
|
-
};
|
|
2202
|
-
}
|
|
2203
|
-
|
|
2204
|
-
// src/build.ts
|
|
2205
|
-
import { cpSync, existsSync as existsSync2, mkdirSync as mkdirSync2, writeFileSync as writeFileSync3 } from "fs";
|
|
2206
|
-
import { join as join5, relative as relative2 } from "path";
|
|
2207
|
-
import { createElement as createElement2 } from "react";
|
|
2208
|
-
async function build(options) {
|
|
2209
|
-
const outDir = options.outDir ?? join5(process.cwd(), ".x");
|
|
2210
|
-
const clientDir = join5(outDir, "client");
|
|
2211
|
-
const serverDir = join5(outDir, "server");
|
|
2212
|
-
const islandsDir = join5(clientDir, "_islands");
|
|
2213
|
-
mkdirSync2(clientDir, { recursive: true });
|
|
2214
|
-
mkdirSync2(serverDir, { recursive: true });
|
|
2215
|
-
mkdirSync2(islandsDir, { recursive: true });
|
|
2216
|
-
const pagesDir = options.pagesDir ?? options.routesDir ?? "";
|
|
2217
|
-
const apiDir = options.apiDir;
|
|
2218
|
-
const actionsDir = options.actionsDir;
|
|
2219
|
-
const layoutsDir = options.layoutsDir ?? pagesDir;
|
|
2220
|
-
const projectRoot = pagesDir ? join5(pagesDir, "..", "..") : process.cwd();
|
|
2221
|
-
const publicDir = join5(projectRoot, "public");
|
|
2222
|
-
const hasPublicDir = existsSync2(publicDir);
|
|
2223
|
-
const stylesheetHref = hasPublicDir && existsSync2(join5(publicDir, "styles.css")) ? "/styles.css" : void 0;
|
|
2224
|
-
if (hasPublicDir) {
|
|
2225
|
-
cpSync(publicDir, clientDir, { recursive: true });
|
|
2226
|
-
console.log(`[x] build: copied public/ -> ${relative2(process.cwd(), clientDir)}`);
|
|
2227
|
-
}
|
|
2228
|
-
let routeEntries = [];
|
|
2229
|
-
if (pagesDir && existsSync2(pagesDir)) {
|
|
2230
|
-
routeEntries = scanPages(pagesDir);
|
|
2231
|
-
}
|
|
2232
|
-
if (apiDir && existsSync2(apiDir)) {
|
|
2233
|
-
routeEntries.push(...scanApiDir(apiDir));
|
|
2234
|
-
}
|
|
2235
|
-
const legacyApiDir = pagesDir ? join5(pagesDir, "api") : "";
|
|
2236
|
-
if (legacyApiDir && existsSync2(legacyApiDir) && legacyApiDir !== apiDir) {
|
|
2237
|
-
routeEntries.push(...scanApiDir(legacyApiDir));
|
|
2238
|
-
}
|
|
2239
|
-
const actionModules = /* @__PURE__ */ new Map();
|
|
2240
|
-
if (actionsDir && existsSync2(actionsDir)) {
|
|
2241
|
-
for (const actionFile of scanRoutes(actionsDir)) {
|
|
2242
|
-
const mod = await import(actionFile.filePath);
|
|
2243
|
-
const segments = actionFile.routePath.split("/").filter(Boolean);
|
|
2244
|
-
const parentPath = `/${segments.slice(0, -1).join("/")}`;
|
|
2245
|
-
const fnNames = [];
|
|
2246
|
-
const actions = mod.actions;
|
|
2247
|
-
if (actions) {
|
|
2248
|
-
registerServerFunctions(parentPath, actionFile.paramNames, actions);
|
|
2249
|
-
fnNames.push(...Object.keys(actions));
|
|
2250
|
-
}
|
|
2251
|
-
for (const [key, value] of Object.entries(mod)) {
|
|
2252
|
-
if (key === "default" || key === "actions" || typeof value !== "function") continue;
|
|
2253
|
-
registerServerFunctions(parentPath, actionFile.paramNames, {
|
|
2254
|
-
[key]: value
|
|
2255
|
-
});
|
|
2256
|
-
fnNames.push(key);
|
|
2257
|
-
}
|
|
2258
|
-
if (fnNames.length > 0) {
|
|
2259
|
-
actionModules.set(actionFile.filePath, { parentPath, fnNames });
|
|
2260
|
-
}
|
|
2261
|
-
}
|
|
2262
|
-
}
|
|
2263
|
-
const dedicatedLayouts = layoutsDir && layoutsDir !== pagesDir && existsSync2(layoutsDir) ? scanLayoutsDir(layoutsDir) : [];
|
|
2264
|
-
const nestedLayouts = pagesDir && existsSync2(pagesDir) ? scanLayouts(pagesDir) : [];
|
|
2265
|
-
const layouts = [...dedicatedLayouts, ...nestedLayouts];
|
|
2266
|
-
const staticPages = [];
|
|
2267
|
-
const serverPages = [];
|
|
2268
|
-
const apiRoutes = [];
|
|
2269
|
-
for (const entry of routeEntries) {
|
|
2270
|
-
if (entry.isApi) {
|
|
2271
|
-
apiRoutes.push(entry);
|
|
2272
|
-
continue;
|
|
2273
|
-
}
|
|
2274
|
-
const mod = await import(entry.filePath);
|
|
2275
|
-
const Component = mod.default;
|
|
2276
|
-
if (!Component) {
|
|
2277
|
-
console.warn(`[x] ${entry.filePath} has no default export -- skipping`);
|
|
2278
|
-
continue;
|
|
2279
|
-
}
|
|
2280
|
-
const mode = mod.mode ?? "server";
|
|
2281
|
-
const layoutChain = findLayoutChain(entry.filePath, layouts, pagesDir);
|
|
2282
|
-
for (const rootLayout of dedicatedLayouts) {
|
|
2283
|
-
if (!layoutChain.some((l) => l.filePath === rootLayout.filePath)) {
|
|
2284
|
-
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
|
+
}
|
|
2285
2437
|
}
|
|
2286
|
-
|
|
2287
|
-
|
|
2288
|
-
|
|
2289
|
-
|
|
2290
|
-
|
|
2291
|
-
|
|
2292
|
-
|
|
2293
|
-
|
|
2294
|
-
|
|
2295
|
-
|
|
2296
|
-
|
|
2297
|
-
|
|
2298
|
-
|
|
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
|
|
2299
2453
|
};
|
|
2300
|
-
if (mode === "static") {
|
|
2301
|
-
staticPages.push(page);
|
|
2302
|
-
} else {
|
|
2303
|
-
serverPages.push(page);
|
|
2304
|
-
}
|
|
2305
|
-
}
|
|
2306
|
-
let contentEntries = [];
|
|
2307
|
-
if (options.contentDir) {
|
|
2308
|
-
contentEntries = scanContent(options.contentDir);
|
|
2309
2454
|
}
|
|
2310
|
-
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
const pageContent = renderPageWithLayout(page.Component, params, page.layoutModules);
|
|
2318
|
-
const content = createElement2(IslandProvider, { registry }, pageContent);
|
|
2319
|
-
const html = renderStaticPage(content, { stylesheet: stylesheetHref });
|
|
2320
|
-
const outPath = page.entry.routePath === "/" ? "/index.html" : `${page.entry.routePath}/index.html`;
|
|
2321
|
-
const fullPath = join5(clientDir, outPath);
|
|
2322
|
-
mkdirSync2(join5(fullPath, ".."), { recursive: true });
|
|
2323
|
-
if (writtenPaths.has(outPath)) {
|
|
2324
|
-
console.warn(` [warn] collision: ${page.entry.routePath} overwrites existing output`);
|
|
2325
|
-
}
|
|
2326
|
-
writtenPaths.add(outPath);
|
|
2327
|
-
let islandScripts = [];
|
|
2328
|
-
if (registry.entries.length > 0) {
|
|
2329
|
-
const uniqueNames = [...new Set(registry.entries.map((e) => e.name))];
|
|
2330
|
-
islandScripts = await bundleRouteIslands(
|
|
2331
|
-
page.filePath,
|
|
2332
|
-
page.layoutFilePaths,
|
|
2333
|
-
uniqueNames,
|
|
2334
|
-
islandsDir,
|
|
2335
|
-
actionModules
|
|
2336
|
-
);
|
|
2337
|
-
console.log(
|
|
2338
|
-
` [islands] ${uniqueNames.length} island(s) on ${page.entry.routePath} -> ${islandScripts.join(", ")}`
|
|
2339
|
-
);
|
|
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;
|
|
2340
2462
|
}
|
|
2341
|
-
|
|
2342
|
-
|
|
2343
|
-
|
|
2344
|
-
|
|
2345
|
-
|
|
2346
|
-
|
|
2347
|
-
const bodyHtml = renderMarkdown(content.body);
|
|
2348
|
-
const pageContent = createElement2(StaticContentPage, {
|
|
2349
|
-
content,
|
|
2350
|
-
bodyHtml
|
|
2351
|
-
});
|
|
2352
|
-
const rendered = createElement2(IslandProvider, { registry }, pageContent);
|
|
2353
|
-
const html = renderStaticPage(rendered, {
|
|
2354
|
-
title: content.frontmatter.title ?? content.slug,
|
|
2355
|
-
stylesheet: stylesheetHref
|
|
2356
|
-
});
|
|
2357
|
-
const outPath = content.routePath === "/" ? "/index.html" : `${content.routePath}/index.html`;
|
|
2358
|
-
const fullPath = join5(clientDir, outPath);
|
|
2359
|
-
mkdirSync2(join5(fullPath, ".."), { recursive: true });
|
|
2360
|
-
if (writtenPaths.has(outPath)) {
|
|
2361
|
-
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
|
+
}
|
|
2362
2469
|
}
|
|
2363
|
-
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2367
|
-
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
|
|
2371
|
-
|
|
2372
|
-
if (
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
configImportPath,
|
|
2379
|
-
stylesheetHref
|
|
2380
|
-
);
|
|
2381
|
-
const serverEntryPath = join5(serverDir, "index.ts");
|
|
2382
|
-
writeFileSync3(serverEntryPath, serverEntry, "utf-8");
|
|
2383
|
-
console.log(
|
|
2384
|
-
` [server] ${serverPages.length} page routes, ${apiRoutes.length} api routes -> server/index.ts`
|
|
2385
|
-
);
|
|
2386
|
-
}
|
|
2387
|
-
console.log(`[x] build complete -> ${outDir}`);
|
|
2388
|
-
}
|
|
2389
|
-
async function bundleRouteIslands(routeFilePath, layoutFilePaths, islandNames, islandsDir, actionModules) {
|
|
2390
|
-
const entryId = islandEntryId(routeFilePath);
|
|
2391
|
-
const outdir = join5(islandsDir, entryId);
|
|
2392
|
-
mkdirSync2(outdir, { recursive: true });
|
|
2393
|
-
const bundlePath = join5(outdir, `${entryId}.js`);
|
|
2394
|
-
const hydrateEntry = generateHydrateEntry(routeFilePath, layoutFilePaths);
|
|
2395
|
-
const entryPath = join5(outdir, `${entryId}.tsx`);
|
|
2396
|
-
writeFileSync3(entryPath, hydrateEntry, "utf-8");
|
|
2397
|
-
try {
|
|
2398
|
-
const result = await Bun.build({
|
|
2399
|
-
entrypoints: [entryPath],
|
|
2400
|
-
target: "browser",
|
|
2401
|
-
plugins: [actionsRewritePlugin(actionModules)]
|
|
2402
|
-
});
|
|
2403
|
-
if (result.success) {
|
|
2404
|
-
const outputs = result.outputs.filter((o) => o.kind === "entry-point");
|
|
2405
|
-
const built = outputs[0] ?? result.outputs[0];
|
|
2406
|
-
if (!built) throw new Error("bun build produced no output");
|
|
2407
|
-
const code = await built.text();
|
|
2408
|
-
assertNoEnvLeakage(code, bundlePath);
|
|
2409
|
-
writeFileSync3(bundlePath, wrapIslandBundle(code), "utf-8");
|
|
2410
|
-
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
|
+
}
|
|
2411
2485
|
}
|
|
2412
|
-
for (const
|
|
2413
|
-
|
|
2486
|
+
for (const h of contentHandlers) {
|
|
2487
|
+
if (h.entry.routePath === url) {
|
|
2488
|
+
return h.handler(req);
|
|
2489
|
+
}
|
|
2414
2490
|
}
|
|
2415
|
-
|
|
2416
|
-
|
|
2417
|
-
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
return
|
|
2421
|
-
}
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
}
|
|
2427
|
-
return content;
|
|
2428
|
-
}
|
|
2429
|
-
function StaticContentPage({
|
|
2430
|
-
content,
|
|
2431
|
-
bodyHtml
|
|
2432
|
-
}) {
|
|
2433
|
-
return createElement2(
|
|
2434
|
-
"article",
|
|
2435
|
-
null,
|
|
2436
|
-
content.frontmatter.title ? createElement2("h1", null, content.frontmatter.title) : null,
|
|
2437
|
-
createElement2("div", {
|
|
2438
|
-
// biome-ignore lint/security/noDangerouslySetInnerHtml: body is markdown rendered to HTML
|
|
2439
|
-
dangerouslySetInnerHTML: { __html: bodyHtml }
|
|
2440
|
-
})
|
|
2441
|
-
);
|
|
2442
|
-
}
|
|
2443
|
-
function buildServerEntry(opts, configImportPath, stylesheetHref) {
|
|
2444
|
-
const dirKeys = ["pagesDir", "apiDir", "layoutsDir", "actionsDir", "contentDir"];
|
|
2445
|
-
const lines = [
|
|
2446
|
-
"// Auto-generated by @thexjs/core build",
|
|
2447
|
-
'import { createApp } from "@thexjs/core";'
|
|
2448
|
-
];
|
|
2449
|
-
if (configImportPath) {
|
|
2450
|
-
lines.push("", "let userConfig = {};", "try {");
|
|
2451
|
-
lines.push(` const mod = await import(${JSON.stringify(configImportPath)});`);
|
|
2452
|
-
lines.push(" userConfig = mod.default ?? {};");
|
|
2453
|
-
lines.push("} catch (err) {");
|
|
2454
|
-
lines.push(
|
|
2455
|
-
' console.warn("[x] failed to load x.config for security/observability options:", err);'
|
|
2456
|
-
);
|
|
2457
|
-
lines.push("}");
|
|
2458
|
-
}
|
|
2459
|
-
lines.push("", "const app = await createApp({");
|
|
2460
|
-
for (const key of dirKeys) {
|
|
2461
|
-
const val = opts[key];
|
|
2462
|
-
if (val) lines.push(` ${key}: ${JSON.stringify(val)},`);
|
|
2463
|
-
}
|
|
2464
|
-
if (stylesheetHref) lines.push(` stylesheetHref: ${JSON.stringify(stylesheetHref)},`);
|
|
2465
|
-
lines.push(' port: parseInt(process.env.PORT || "3000", 10),', " development: false,");
|
|
2466
|
-
if (configImportPath) {
|
|
2467
|
-
lines.push(" ...(userConfig.security ? { security: userConfig.security } : {}),");
|
|
2468
|
-
lines.push(
|
|
2469
|
-
" ...(userConfig.observability ? { observability: userConfig.observability } : {}),"
|
|
2470
|
-
);
|
|
2471
|
-
lines.push(" ...(userConfig.images ? { images: userConfig.images } : {}),");
|
|
2472
|
-
}
|
|
2473
|
-
lines.push(
|
|
2474
|
-
"});",
|
|
2475
|
-
"",
|
|
2476
|
-
"const server = Bun.serve(app);",
|
|
2477
|
-
"",
|
|
2478
|
-
"console.log(`[x] production server running at ${server.url}`);",
|
|
2479
|
-
"",
|
|
2480
|
-
"// Graceful shutdown: stop accepting new connections, flush the error",
|
|
2481
|
-
"// reporter, then exit after in-flight requests have a moment to drain.",
|
|
2482
|
-
"let shuttingDown = false;",
|
|
2483
|
-
"async function shutdown(signal: string): Promise<void> {",
|
|
2484
|
-
" if (shuttingDown) return;",
|
|
2485
|
-
" shuttingDown = true;",
|
|
2486
|
-
" console.log(`[x] received ${signal} - shutting down`);",
|
|
2487
|
-
" try {",
|
|
2488
|
-
' const { getErrorReporter } = await import("@thexjs/core");',
|
|
2489
|
-
" await getErrorReporter().flush?.();",
|
|
2490
|
-
" } catch {}",
|
|
2491
|
-
" server.stop(true);",
|
|
2492
|
-
" const exit = () => process.exit(0);",
|
|
2493
|
-
" const drainTimer = setTimeout(exit, 3000);",
|
|
2494
|
-
" drainTimer.unref?.();",
|
|
2495
|
-
"}",
|
|
2496
|
-
'process.on("SIGTERM", () => shutdown("SIGTERM"));',
|
|
2497
|
-
'process.on("SIGINT", () => shutdown("SIGINT"));'
|
|
2498
|
-
);
|
|
2499
|
-
return lines.join("\n");
|
|
2500
|
-
}
|
|
2501
|
-
function relativeImportPath(fromDir, toFile) {
|
|
2502
|
-
const rel = relative2(fromDir, toFile).replace(/\\/g, "/").replace(/\.(ts|js|mjs)$/, "");
|
|
2503
|
-
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
|
+
};
|
|
2504
2502
|
}
|
|
2505
2503
|
|
|
2506
2504
|
// src/link.tsx
|
|
@@ -2543,7 +2541,7 @@ export {
|
|
|
2543
2541
|
createRedisRateLimitStore,
|
|
2544
2542
|
createSentryReporter,
|
|
2545
2543
|
defineConfig,
|
|
2546
|
-
|
|
2544
|
+
escapeHtml,
|
|
2547
2545
|
findLayoutChain,
|
|
2548
2546
|
findLeakedEnvKeys,
|
|
2549
2547
|
findMiddlewareChain,
|