@thexjs/core 1.2.3 → 1.3.0
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 +154 -112
- package/dist/index.js +1360 -1234
- package/package.json +6 -2
package/dist/index.js
CHANGED
|
@@ -14,352 +14,13 @@ import {
|
|
|
14
14
|
writeManifest
|
|
15
15
|
} from "./chunk-O6SIM7EF.js";
|
|
16
16
|
|
|
17
|
-
// src/
|
|
18
|
-
import {
|
|
19
|
-
|
|
20
|
-
return /* @__PURE__ */ jsxs(
|
|
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);
|
|
102
|
-
|
|
103
|
-
function resolveLink(anchor) {
|
|
104
|
-
if (!anchor) return null;
|
|
105
|
-
if (anchor.hasAttribute("data-no-nav")) return null;
|
|
106
|
-
if (anchor.target && anchor.target !== "_self") return null;
|
|
107
|
-
if (anchor.hasAttribute("download")) return null;
|
|
108
|
-
var href = anchor.getAttribute("href");
|
|
109
|
-
if (!href) return null;
|
|
110
|
-
if (/^(#|mailto:|tel:|javascript:)/i.test(href)) return null;
|
|
111
|
-
var url;
|
|
112
|
-
try {
|
|
113
|
-
url = new URL(href, location.href);
|
|
114
|
-
} catch (_) {
|
|
115
|
-
return null;
|
|
116
|
-
}
|
|
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
|
-
}
|
|
126
|
-
|
|
127
|
-
function prefetch(url) {
|
|
128
|
-
if (cache.has(url.href)) return cache.get(url.href);
|
|
129
|
-
var promise = fetch(url.href, { headers: { "X-X-Nav": "1" } })
|
|
130
|
-
.then(function (res) {
|
|
131
|
-
return res.text().then(function (html) {
|
|
132
|
-
var ct = res.headers.get("content-type") || "";
|
|
133
|
-
return { html: html, ok: res.ok, finalUrl: res.url || url.href, isHtml: ct.indexOf("text/html") !== -1 };
|
|
134
|
-
});
|
|
135
|
-
})
|
|
136
|
-
.catch(function (err) {
|
|
137
|
-
cache.delete(url.href);
|
|
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;
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
function navigate(url, push) {
|
|
149
|
-
setLoading(true);
|
|
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
|
-
});
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
function reexecuteScripts(root) {
|
|
185
|
-
var scripts = root.querySelectorAll("script");
|
|
186
|
-
for (var i = 0; i < scripts.length; i++) {
|
|
187
|
-
var old = scripts[i];
|
|
188
|
-
var el = document.createElement("script");
|
|
189
|
-
for (var j = 0; j < old.attributes.length; j++) {
|
|
190
|
-
var attr = old.attributes[j];
|
|
191
|
-
el.setAttribute(attr.name, attr.value);
|
|
192
|
-
}
|
|
193
|
-
el.textContent = old.textContent;
|
|
194
|
-
old.replaceWith(el);
|
|
195
|
-
}
|
|
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";
|
|
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";
|
|
359
20
|
import { createElement } from "react";
|
|
360
21
|
|
|
361
22
|
// src/content.ts
|
|
362
|
-
import {
|
|
23
|
+
import { readdirSync, readFileSync, statSync } from "fs";
|
|
363
24
|
import { join, relative, sep } from "path";
|
|
364
25
|
var CONTENT_FILE = /\.(md|mdx)$/;
|
|
365
26
|
function scanContent(rootDir) {
|
|
@@ -425,7 +86,7 @@ function parseYamlLines(raw) {
|
|
|
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,218 +128,24 @@ 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
|
-
html = blocks.map((b) => {
|
|
474
|
-
const t = b.trim();
|
|
475
|
-
if (!t) return "";
|
|
476
|
-
const listBlock = renderListBlock(t);
|
|
477
|
-
if (listBlock !== t) return listBlock;
|
|
478
|
-
if (t.startsWith("<h") || t.startsWith("<pre") || t.startsWith("<ul") || t.startsWith("<ol"))
|
|
479
|
-
return t;
|
|
480
|
-
return `<p>${t}</p>`;
|
|
481
|
-
}).join("\n");
|
|
482
|
-
return html;
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
// src/error-overlay.ts
|
|
486
|
-
function escapeHtml3(s) {
|
|
487
|
-
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
488
|
-
}
|
|
489
|
-
function renderErrorOverlay(error) {
|
|
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
|
-
};
|
|
134
|
+
html = blocks.map((b) => {
|
|
135
|
+
const t = b.trim();
|
|
136
|
+
if (!t) return "";
|
|
137
|
+
const listBlock = renderListBlock(t);
|
|
138
|
+
if (listBlock !== t) return listBlock;
|
|
139
|
+
if (t.startsWith("<h") || t.startsWith("<pre") || t.startsWith("<ul") || t.startsWith("<ol"))
|
|
140
|
+
return t;
|
|
141
|
+
return `<p>${t}</p>`;
|
|
142
|
+
}).join("\n");
|
|
143
|
+
return html;
|
|
677
144
|
}
|
|
678
145
|
|
|
679
146
|
// src/island.tsx
|
|
680
147
|
import { createContext, useContext } from "react";
|
|
681
|
-
import { jsx
|
|
148
|
+
import { jsx } from "react/jsx-runtime";
|
|
682
149
|
function createIslandRegistry() {
|
|
683
150
|
return { entries: [] };
|
|
684
151
|
}
|
|
@@ -687,7 +154,7 @@ 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
|
|
@@ -766,351 +233,1166 @@ function assertNoEnvLeakage(code, file) {
|
|
|
766
233
|
}
|
|
767
234
|
}
|
|
768
235
|
|
|
769
|
-
// src/server-functions.ts
|
|
770
|
-
import { writeFileSync } from "fs";
|
|
771
|
-
import { join as join2 } from "path";
|
|
236
|
+
// src/server-functions.ts
|
|
237
|
+
import { writeFileSync } from "fs";
|
|
238
|
+
import { join as join2 } from "path";
|
|
239
|
+
|
|
240
|
+
// src/observability/monitoring.ts
|
|
241
|
+
var noopReporter = {
|
|
242
|
+
captureException: () => {
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
var activeReporter = noopReporter;
|
|
246
|
+
function setErrorReporter(reporter) {
|
|
247
|
+
activeReporter = reporter;
|
|
248
|
+
}
|
|
249
|
+
function getErrorReporter() {
|
|
250
|
+
return activeReporter;
|
|
251
|
+
}
|
|
252
|
+
function reportException(error, context) {
|
|
253
|
+
try {
|
|
254
|
+
activeReporter.captureException(error, context);
|
|
255
|
+
} catch (reportingError) {
|
|
256
|
+
console.error("[x] error reporter threw while handling an exception:", reportingError);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
function createSentryReporter(sentry) {
|
|
260
|
+
return {
|
|
261
|
+
captureException(error, context) {
|
|
262
|
+
sentry.captureException(error, { extra: { ...context } });
|
|
263
|
+
},
|
|
264
|
+
async flush() {
|
|
265
|
+
await sentry.flush?.(2e3);
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
var OTEL_ERROR_STATUS_CODE = 2;
|
|
270
|
+
function createOtelReporter(tracer) {
|
|
271
|
+
return {
|
|
272
|
+
captureException(error, context) {
|
|
273
|
+
const span = tracer.startSpan(`x.${context.phase}.error`);
|
|
274
|
+
span.recordException(error);
|
|
275
|
+
span.setStatus({
|
|
276
|
+
code: OTEL_ERROR_STATUS_CODE,
|
|
277
|
+
message: error instanceof Error ? error.message : String(error)
|
|
278
|
+
});
|
|
279
|
+
span.end();
|
|
280
|
+
}
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
function combineReporters(...reporters) {
|
|
284
|
+
return {
|
|
285
|
+
captureException(error, context) {
|
|
286
|
+
for (const reporter of reporters) {
|
|
287
|
+
try {
|
|
288
|
+
reporter.captureException(error, context);
|
|
289
|
+
} catch (err) {
|
|
290
|
+
console.error("[x] error reporter threw while handling an exception:", err);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
},
|
|
294
|
+
async flush() {
|
|
295
|
+
await Promise.all(reporters.map((r) => r.flush?.()));
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// src/security/csrf.ts
|
|
301
|
+
var CSRF_COOKIE_NAME = "x_csrf_token";
|
|
302
|
+
var CSRF_HEADER_NAME = "x-csrf-token";
|
|
303
|
+
var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
|
|
304
|
+
var SECURE_COOKIE_FLAG = process.env.NODE_ENV === "production" ? "; Secure" : "";
|
|
305
|
+
function originFromHeader(value) {
|
|
306
|
+
if (!value) return null;
|
|
307
|
+
try {
|
|
308
|
+
return new URL(value).origin;
|
|
309
|
+
} catch {
|
|
310
|
+
return null;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
function requestOrigin(req) {
|
|
314
|
+
const url = new URL(req.url);
|
|
315
|
+
return `${url.protocol}//${url.host}`;
|
|
316
|
+
}
|
|
317
|
+
function verifyOrigin(req, allowedOrigins = []) {
|
|
318
|
+
if (SAFE_METHODS.has(req.method)) return { ok: true };
|
|
319
|
+
const selfOrigin = requestOrigin(req);
|
|
320
|
+
const allowed = new Set([selfOrigin, ...allowedOrigins].filter(Boolean));
|
|
321
|
+
const origin = originFromHeader(req.headers.get("origin"));
|
|
322
|
+
if (origin) {
|
|
323
|
+
return allowed.has(origin) ? { ok: true } : { ok: false, reason: `origin "${origin}" is not an allowed origin` };
|
|
324
|
+
}
|
|
325
|
+
const referer = originFromHeader(req.headers.get("referer"));
|
|
326
|
+
if (referer) {
|
|
327
|
+
return allowed.has(referer) ? { ok: true } : { ok: false, reason: `referer origin "${referer}" is not an allowed origin` };
|
|
328
|
+
}
|
|
329
|
+
return { ok: false, reason: "missing Origin and Referer headers on a mutating request" };
|
|
330
|
+
}
|
|
331
|
+
function generateCsrfToken() {
|
|
332
|
+
return crypto.randomUUID().replace(/-/g, "") + crypto.randomUUID().replace(/-/g, "");
|
|
333
|
+
}
|
|
334
|
+
function readCookie(req, name) {
|
|
335
|
+
const header = req.headers.get("cookie");
|
|
336
|
+
if (!header) return null;
|
|
337
|
+
for (const part of header.split(";")) {
|
|
338
|
+
const [key, ...rest] = part.trim().split("=");
|
|
339
|
+
if (key === name) return rest.join("=");
|
|
340
|
+
}
|
|
341
|
+
return null;
|
|
342
|
+
}
|
|
343
|
+
function verifyCsrfToken(req) {
|
|
344
|
+
if (SAFE_METHODS.has(req.method)) return { ok: true };
|
|
345
|
+
const cookieToken = readCookie(req, CSRF_COOKIE_NAME);
|
|
346
|
+
const headerToken = req.headers.get(CSRF_HEADER_NAME);
|
|
347
|
+
if (!cookieToken || !headerToken) {
|
|
348
|
+
return { ok: false, reason: `missing CSRF cookie or "${CSRF_HEADER_NAME}" header` };
|
|
349
|
+
}
|
|
350
|
+
if (cookieToken !== headerToken) {
|
|
351
|
+
return { ok: false, reason: "CSRF token mismatch" };
|
|
352
|
+
}
|
|
353
|
+
return { ok: true };
|
|
354
|
+
}
|
|
355
|
+
function withCsrfCookie(req, res) {
|
|
356
|
+
if (readCookie(req, CSRF_COOKIE_NAME)) return res;
|
|
357
|
+
const token = generateCsrfToken();
|
|
358
|
+
const headers = new Headers(res.headers);
|
|
359
|
+
headers.append(
|
|
360
|
+
"Set-Cookie",
|
|
361
|
+
`${CSRF_COOKIE_NAME}=${token}; Path=/; SameSite=Lax${SECURE_COOKIE_FLAG}`
|
|
362
|
+
);
|
|
363
|
+
return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
|
|
364
|
+
}
|
|
365
|
+
function checkCsrf(req, options = {}) {
|
|
366
|
+
if (options.disabled) return { ok: true };
|
|
367
|
+
const originResult = verifyOrigin(req, options.allowedOrigins ?? []);
|
|
368
|
+
if (!originResult.ok) return originResult;
|
|
369
|
+
if (options.requireToken) {
|
|
370
|
+
const tokenResult = verifyCsrfToken(req);
|
|
371
|
+
if (!tokenResult.ok) return tokenResult;
|
|
372
|
+
}
|
|
373
|
+
return { ok: true };
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// src/server-functions.ts
|
|
377
|
+
function generateServerFunctionClient(routeFilePath, fnNames, endpointBase) {
|
|
378
|
+
const fnCalls = fnNames.map(
|
|
379
|
+
(name) => `
|
|
380
|
+
export async function ${name}(...args: unknown[]): Promise<unknown> {
|
|
381
|
+
const res = await fetch("${endpointBase}/${name}", {
|
|
382
|
+
method: "POST",
|
|
383
|
+
headers: { "Content-Type": "application/json" },
|
|
384
|
+
body: JSON.stringify(args),
|
|
385
|
+
});
|
|
386
|
+
if (!res.ok) throw new Error(await res.text());
|
|
387
|
+
return res.json();
|
|
388
|
+
}`
|
|
389
|
+
).join("\n");
|
|
390
|
+
return `// Auto-generated client for server functions in ${routeFilePath}
|
|
391
|
+
// Do not edit.
|
|
392
|
+
|
|
393
|
+
${fnCalls}
|
|
394
|
+
`;
|
|
395
|
+
}
|
|
396
|
+
var ACTION_ROUTES = [];
|
|
397
|
+
function resetServerFunctions() {
|
|
398
|
+
ACTION_ROUTES.length = 0;
|
|
399
|
+
}
|
|
400
|
+
function registerServerFunctions(routePath, paramNames, fns) {
|
|
401
|
+
const fnMap = new Map(Object.entries(fns));
|
|
402
|
+
const existing = ACTION_ROUTES.find((e) => e.routePath === routePath);
|
|
403
|
+
if (existing) {
|
|
404
|
+
for (const [name, fn] of fnMap) {
|
|
405
|
+
existing.fns.set(name, fn);
|
|
406
|
+
}
|
|
407
|
+
} else {
|
|
408
|
+
ACTION_ROUTES.push({ routePath, paramNames, fns: fnMap });
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
function getServerFunctionHandler(csrfOptions) {
|
|
412
|
+
return async (req) => {
|
|
413
|
+
if (req.method !== "POST") return null;
|
|
414
|
+
const url = new URL(req.url);
|
|
415
|
+
if (!url.pathname.startsWith("/__x/actions/")) return null;
|
|
416
|
+
const csrfResult = checkCsrf(req, csrfOptions);
|
|
417
|
+
if (!csrfResult.ok) {
|
|
418
|
+
return new Response(`Forbidden: ${csrfResult.reason}`, { status: 403 });
|
|
419
|
+
}
|
|
420
|
+
const parts = url.pathname.replace("/__x/actions/", "").split("/");
|
|
421
|
+
if (parts.length < 1) return null;
|
|
422
|
+
const actionName = parts.pop();
|
|
423
|
+
if (!actionName) return null;
|
|
424
|
+
const concretePath = `/${parts.join("/")}`;
|
|
425
|
+
for (const entry of ACTION_ROUTES) {
|
|
426
|
+
const params = extractActionParams(entry.routePath, entry.paramNames, concretePath);
|
|
427
|
+
if (params === null) continue;
|
|
428
|
+
const fn = entry.fns.get(actionName);
|
|
429
|
+
if (!fn) return new Response("Function not found", { status: 404 });
|
|
430
|
+
let args = [];
|
|
431
|
+
try {
|
|
432
|
+
const body = await req.json();
|
|
433
|
+
args = Array.isArray(body) ? body : [body];
|
|
434
|
+
} catch {
|
|
435
|
+
return new Response("Invalid request body", { status: 400 });
|
|
436
|
+
}
|
|
437
|
+
try {
|
|
438
|
+
const result = await fn(...args);
|
|
439
|
+
return Response.json(result);
|
|
440
|
+
} catch (err) {
|
|
441
|
+
reportException(err, { route: concretePath, phase: "action" });
|
|
442
|
+
const message = err instanceof Error ? err.message : "Internal error";
|
|
443
|
+
return new Response(message, { status: 500 });
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
return new Response("Not found", { status: 404 });
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
function extractActionParams(routePath, paramNames, url) {
|
|
450
|
+
const regex = routePatternToRegex(routePath);
|
|
451
|
+
const match = url.match(regex);
|
|
452
|
+
if (!match) return null;
|
|
453
|
+
const params = {};
|
|
454
|
+
let idx = 1;
|
|
455
|
+
for (const name of paramNames) {
|
|
456
|
+
const value = match[idx];
|
|
457
|
+
if (value !== void 0) {
|
|
458
|
+
params[name] = safeDecodeURIComponent(value);
|
|
459
|
+
}
|
|
460
|
+
idx++;
|
|
461
|
+
}
|
|
462
|
+
return params;
|
|
463
|
+
}
|
|
464
|
+
function safeDecodeURIComponent(value) {
|
|
465
|
+
try {
|
|
466
|
+
return decodeURIComponent(value);
|
|
467
|
+
} catch {
|
|
468
|
+
return value;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
// src/island-bundle.ts
|
|
473
|
+
function actionsRewritePlugin(actionModules) {
|
|
474
|
+
return {
|
|
475
|
+
name: "x-actions-rewrite",
|
|
476
|
+
setup(build2) {
|
|
477
|
+
if (actionModules.size === 0) return;
|
|
478
|
+
build2.onLoad({ filter: /\.(ts|tsx)$/ }, (args) => {
|
|
479
|
+
const info = actionModules.get(args.path);
|
|
480
|
+
if (!info) return void 0;
|
|
481
|
+
const endpointBase = info.parentPath === "/" ? "/__x/actions" : `/__x/actions${info.parentPath}`;
|
|
482
|
+
const contents = generateServerFunctionClient(args.path, info.fnNames, endpointBase);
|
|
483
|
+
return { contents, loader: "ts" };
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
function generateHydrateEntry(routeAbsPath, layoutAbsPaths = []) {
|
|
489
|
+
const layoutImports = layoutAbsPaths.map((p, i) => `import * as Layout${i} from "${p}";`).join("\n");
|
|
490
|
+
const lookupParts = ["Route.islands?.[name]"];
|
|
491
|
+
for (let i = 0; i < layoutAbsPaths.length; i++) {
|
|
492
|
+
lookupParts.push(`Layout${i}.islands?.[name]`);
|
|
493
|
+
}
|
|
494
|
+
const lookup = lookupParts.join(" ?? ");
|
|
495
|
+
return `import React from "react";
|
|
496
|
+
import { hydrateRoot } from "react-dom/client";
|
|
497
|
+
import * as Route from "${routeAbsPath}";
|
|
498
|
+
${layoutImports}
|
|
499
|
+
|
|
500
|
+
function resolveIsland(name: string) {
|
|
501
|
+
return ${lookup};
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
// Islands whose render is non-deterministic (e.g. \`useState(() => ...)\` with
|
|
505
|
+
// Math.random) can't be hydrated against their SSR output. React recovers by
|
|
506
|
+
// re-rendering client-side, so the island is still fully interactive -- the
|
|
507
|
+
// mismatch is benign, so swallow the recovery so it doesn't spam the console
|
|
508
|
+
// or cascade into React's event system.
|
|
509
|
+
function onRecoverableError() {}
|
|
772
510
|
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
511
|
+
document.querySelectorAll("[data-island]").forEach((el) => {
|
|
512
|
+
const name = el.getAttribute("data-island");
|
|
513
|
+
if (!name) return;
|
|
514
|
+
const Component = resolveIsland(name);
|
|
515
|
+
if (!Component) return;
|
|
516
|
+
hydrateRoot(el, React.createElement(Component), { onRecoverableError });
|
|
517
|
+
});
|
|
518
|
+
`;
|
|
519
|
+
}
|
|
520
|
+
function generateFallbackHydration(islandNames) {
|
|
521
|
+
return `// x island hydration fallback \u2014 ${islandNames.join(", ")}
|
|
522
|
+
document.querySelectorAll("[data-island]").forEach(function(el) {
|
|
523
|
+
el.setAttribute("data-island-hydrated", "false");
|
|
524
|
+
});
|
|
525
|
+
`;
|
|
526
|
+
}
|
|
527
|
+
function hashId(str) {
|
|
528
|
+
let h = 0;
|
|
529
|
+
for (let i = 0; i < str.length; i++) {
|
|
530
|
+
h = Math.imul(31, h) + str.charCodeAt(i) | 0;
|
|
776
531
|
}
|
|
777
|
-
|
|
778
|
-
var activeReporter = noopReporter;
|
|
779
|
-
function setErrorReporter(reporter) {
|
|
780
|
-
activeReporter = reporter;
|
|
532
|
+
return Math.abs(h).toString(36);
|
|
781
533
|
}
|
|
782
|
-
function
|
|
783
|
-
return
|
|
534
|
+
function islandEntryId(routeFilePath) {
|
|
535
|
+
return `${basename(routeFilePath).replace(/\.(tsx|ts)$/, "")}-${hashId(routeFilePath)}`;
|
|
784
536
|
}
|
|
785
|
-
function
|
|
537
|
+
function wrapIslandBundle(code) {
|
|
538
|
+
return `;(function () {
|
|
539
|
+
${code}
|
|
540
|
+
})();
|
|
541
|
+
`;
|
|
542
|
+
}
|
|
543
|
+
async function buildIslandBundleInMemory(routeFilePath, layoutFilePaths, islandNames, actionModules, projectRoot) {
|
|
544
|
+
const entryId = islandEntryId(routeFilePath);
|
|
545
|
+
const scratchRoot = join3(projectRoot, ".x", "islands-tmp");
|
|
546
|
+
mkdirSync(scratchRoot, { recursive: true });
|
|
547
|
+
const scratchDir = mkdtempSync(join3(scratchRoot, "x-islands-"));
|
|
786
548
|
try {
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
549
|
+
const entryPath = join3(scratchDir, `${entryId}.tsx`);
|
|
550
|
+
writeFileSync2(entryPath, generateHydrateEntry(routeFilePath, layoutFilePaths), "utf-8");
|
|
551
|
+
const result = await Bun.build({
|
|
552
|
+
entrypoints: [entryPath],
|
|
553
|
+
target: "browser",
|
|
554
|
+
plugins: [actionsRewritePlugin(actionModules)]
|
|
555
|
+
});
|
|
556
|
+
if (!result.success) {
|
|
557
|
+
for (const log of result.logs) {
|
|
558
|
+
console.warn(` [islands] build error: ${log.message}`);
|
|
559
|
+
}
|
|
560
|
+
return wrapIslandBundle(generateFallbackHydration(islandNames));
|
|
561
|
+
}
|
|
562
|
+
const outputs = result.outputs.filter((o) => o.kind === "entry-point");
|
|
563
|
+
const built = outputs[0] ?? result.outputs[0];
|
|
564
|
+
if (!built) return wrapIslandBundle(generateFallbackHydration(islandNames));
|
|
565
|
+
const code = await built.text();
|
|
566
|
+
assertNoEnvLeakage(code, entryPath);
|
|
567
|
+
return wrapIslandBundle(code);
|
|
568
|
+
} catch (err) {
|
|
569
|
+
if (err instanceof EnvLeakageError) {
|
|
570
|
+
console.error(
|
|
571
|
+
`\x1B[1;31m\u{1F512} SECURITY: [islands] ${err.message}\x1B[0m
|
|
572
|
+
Falling back to a non-interactive hydration stub \u2014 fix the env isolation (prefix with THEXJS_PUBLIC_ or move the access server-side) before relying on this page's client behavior.`
|
|
573
|
+
);
|
|
574
|
+
return wrapIslandBundle(generateFallbackHydration(islandNames));
|
|
575
|
+
}
|
|
576
|
+
console.warn(` [islands] build failed for ${routeFilePath}:`, err);
|
|
577
|
+
return wrapIslandBundle(generateFallbackHydration(islandNames));
|
|
578
|
+
} finally {
|
|
579
|
+
rmSync(scratchDir, { recursive: true, force: true });
|
|
790
580
|
}
|
|
791
581
|
}
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
582
|
+
|
|
583
|
+
// src/render.ts
|
|
584
|
+
import { renderToReadableStream, renderToStaticMarkup, renderToString } from "react-dom/server";
|
|
585
|
+
|
|
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);
|
|
796
609
|
},
|
|
797
|
-
|
|
798
|
-
|
|
610
|
+
{ passive: true },
|
|
611
|
+
);
|
|
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;
|
|
799
649
|
}
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
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
|
+
}
|
|
655
|
+
|
|
656
|
+
function setLoading(on) {
|
|
657
|
+
document.documentElement.classList.toggle("x-nav-loading", on);
|
|
658
|
+
}
|
|
659
|
+
|
|
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);
|
|
676
|
+
}
|
|
677
|
+
cache.set(url.href, promise);
|
|
678
|
+
return promise;
|
|
679
|
+
}
|
|
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;
|
|
688
|
+
}
|
|
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);
|
|
811
714
|
});
|
|
812
|
-
|
|
715
|
+
}
|
|
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);
|
|
725
|
+
}
|
|
726
|
+
el.textContent = old.textContent;
|
|
727
|
+
old.replaceWith(el);
|
|
813
728
|
}
|
|
729
|
+
}
|
|
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);
|
|
814
734
|
};
|
|
815
|
-
}
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
}
|
|
827
|
-
|
|
828
|
-
await Promise.all(reporters.map((r) => r.flush?.()));
|
|
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();
|
|
829
748
|
}
|
|
749
|
+
});
|
|
750
|
+
es.addEventListener("hb", function () {});
|
|
751
|
+
es.onerror = function () {
|
|
752
|
+
es.close();
|
|
830
753
|
};
|
|
831
|
-
}
|
|
754
|
+
})();
|
|
755
|
+
`.trim();
|
|
832
756
|
|
|
833
|
-
// src/
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
|
|
837
|
-
var SECURE_COOKIE_FLAG = process.env.NODE_ENV === "production" ? "; Secure" : "";
|
|
838
|
-
function originFromHeader(value) {
|
|
839
|
-
if (!value) return null;
|
|
840
|
-
try {
|
|
841
|
-
return new URL(value).origin;
|
|
842
|
-
} catch {
|
|
843
|
-
return null;
|
|
844
|
-
}
|
|
757
|
+
// src/render.ts
|
|
758
|
+
function escapeHtml2(s) {
|
|
759
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
845
760
|
}
|
|
846
|
-
function
|
|
847
|
-
|
|
848
|
-
return `${url.protocol}//${url.host}`;
|
|
761
|
+
function escapeJsonForScript(s) {
|
|
762
|
+
return s.replace(/<\//g, "<\\/");
|
|
849
763
|
}
|
|
850
|
-
function
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
const allowed = new Set([selfOrigin, ...allowedOrigins].filter(Boolean));
|
|
854
|
-
const origin = originFromHeader(req.headers.get("origin"));
|
|
855
|
-
if (origin) {
|
|
856
|
-
return allowed.has(origin) ? { ok: true } : { ok: false, reason: `origin "${origin}" is not an allowed origin` };
|
|
857
|
-
}
|
|
858
|
-
const referer = originFromHeader(req.headers.get("referer"));
|
|
859
|
-
if (referer) {
|
|
860
|
-
return allowed.has(referer) ? { ok: true } : { ok: false, reason: `referer origin "${referer}" is not an allowed origin` };
|
|
861
|
-
}
|
|
862
|
-
return { ok: false, reason: "missing Origin and Referer headers on a mutating request" };
|
|
764
|
+
function buildHeadExtras(stylesheet) {
|
|
765
|
+
return stylesheet ? `
|
|
766
|
+
<link rel="stylesheet" href="${escapeHtml2(stylesheet)}" />` : "";
|
|
863
767
|
}
|
|
864
|
-
function
|
|
865
|
-
return
|
|
768
|
+
function buildNavScriptTag(clientNav) {
|
|
769
|
+
return clientNav === false ? "" : `
|
|
770
|
+
<script>${CLIENT_NAV_SCRIPT}</script>`;
|
|
866
771
|
}
|
|
867
|
-
function
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
for (const part of header.split(";")) {
|
|
871
|
-
const [key, ...rest] = part.trim().split("=");
|
|
872
|
-
if (key === name) return rest.join("=");
|
|
873
|
-
}
|
|
874
|
-
return null;
|
|
772
|
+
function buildLiveReloadTag(liveReload) {
|
|
773
|
+
return liveReload ? `
|
|
774
|
+
<script>${LIVE_RELOAD_SCRIPT}</script>` : "";
|
|
875
775
|
}
|
|
876
|
-
function
|
|
877
|
-
|
|
878
|
-
const
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
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>`;
|
|
887
793
|
}
|
|
888
|
-
function
|
|
889
|
-
|
|
890
|
-
const
|
|
891
|
-
const
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
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)
|
|
895
809
|
);
|
|
896
|
-
return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
|
|
897
810
|
}
|
|
898
|
-
function
|
|
899
|
-
|
|
900
|
-
const
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
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
|
+
);
|
|
907
827
|
}
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
const
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
const
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
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);
|
|
846
|
+
}
|
|
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();
|
|
885
|
+
}
|
|
918
886
|
});
|
|
919
|
-
if (!res.ok) throw new Error(await res.text());
|
|
920
|
-
return res.json();
|
|
921
|
-
}`
|
|
922
|
-
).join("\n");
|
|
923
|
-
return `// Auto-generated client for server functions in ${routeFilePath}
|
|
924
|
-
// Do not edit.
|
|
925
|
-
|
|
926
|
-
${fnCalls}
|
|
927
|
-
`;
|
|
928
|
-
}
|
|
929
|
-
var ACTION_ROUTES = [];
|
|
930
|
-
function resetServerFunctions() {
|
|
931
|
-
ACTION_ROUTES.length = 0;
|
|
932
887
|
}
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
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)}`);
|
|
909
|
+
}
|
|
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
|
+
}
|
|
939
943
|
}
|
|
940
|
-
} else {
|
|
941
|
-
ACTION_ROUTES.push({ routePath, paramNames, fns: fnMap });
|
|
942
944
|
}
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
if (
|
|
951
|
-
|
|
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;
|
|
952
955
|
}
|
|
953
|
-
const
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
if (!
|
|
963
|
-
|
|
964
|
-
try {
|
|
965
|
-
const body = await req.json();
|
|
966
|
-
args = Array.isArray(body) ? body : [body];
|
|
967
|
-
} catch {
|
|
968
|
-
return new Response("Invalid request body", { status: 400 });
|
|
969
|
-
}
|
|
970
|
-
try {
|
|
971
|
-
const result = await fn(...args);
|
|
972
|
-
return Response.json(result);
|
|
973
|
-
} catch (err) {
|
|
974
|
-
reportException(err, { route: concretePath, phase: "action" });
|
|
975
|
-
const message = err instanceof Error ? err.message : "Internal error";
|
|
976
|
-
return new Response(message, { status: 500 });
|
|
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);
|
|
977
967
|
}
|
|
978
968
|
}
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
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);
|
|
992
986
|
}
|
|
993
|
-
idx++;
|
|
994
987
|
}
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
try {
|
|
999
|
-
return decodeURIComponent(value);
|
|
1000
|
-
} catch {
|
|
1001
|
-
return value;
|
|
988
|
+
let contentEntries = [];
|
|
989
|
+
if (options.contentDir) {
|
|
990
|
+
contentEntries = scanContent(options.contentDir);
|
|
1002
991
|
}
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
});
|
|
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`);
|
|
1018
1007
|
}
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1008
|
+
writtenPaths.add(outPath);
|
|
1009
|
+
let islandScripts = [];
|
|
1010
|
+
if (registry.entries.length > 0) {
|
|
1011
|
+
const uniqueNames = [...new Set(registry.entries.map((e) => e.name))];
|
|
1012
|
+
islandScripts = await bundleRouteIslands(
|
|
1013
|
+
page.filePath,
|
|
1014
|
+
page.layoutFilePaths,
|
|
1015
|
+
uniqueNames,
|
|
1016
|
+
islandsDir,
|
|
1017
|
+
actionModules
|
|
1018
|
+
);
|
|
1019
|
+
console.log(
|
|
1020
|
+
` [islands] ${uniqueNames.length} island(s) on ${page.entry.routePath} -> ${islandScripts.join(", ")}`
|
|
1021
|
+
);
|
|
1022
|
+
}
|
|
1023
|
+
const finalHtml = renderStaticPage(content, { islandScripts, stylesheet: stylesheetHref });
|
|
1024
|
+
writeFileSync3(fullPath, finalHtml, "utf-8");
|
|
1025
|
+
console.log(` [static] ${page.entry.routePath} -> ${outPath}`);
|
|
1026
1026
|
}
|
|
1027
|
-
const
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
}
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1027
|
+
for (const content of contentEntries) {
|
|
1028
|
+
const registry = createIslandRegistry();
|
|
1029
|
+
const bodyHtml = renderMarkdown(content.body);
|
|
1030
|
+
const pageContent = createElement(StaticContentPage, {
|
|
1031
|
+
content,
|
|
1032
|
+
bodyHtml
|
|
1033
|
+
});
|
|
1034
|
+
const rendered = createElement(IslandProvider, { registry }, pageContent);
|
|
1035
|
+
const html = renderStaticPage(rendered, {
|
|
1036
|
+
title: content.frontmatter.title ?? content.slug,
|
|
1037
|
+
stylesheet: stylesheetHref
|
|
1038
|
+
});
|
|
1039
|
+
const outPath = content.routePath === "/" ? "/index.html" : `${content.routePath}/index.html`;
|
|
1040
|
+
const fullPath = join4(clientDir, outPath);
|
|
1041
|
+
mkdirSync2(join4(fullPath, ".."), { recursive: true });
|
|
1042
|
+
if (writtenPaths.has(outPath)) {
|
|
1043
|
+
console.warn(` [warn] collision: content ${content.routePath} overwrites existing output`);
|
|
1044
|
+
}
|
|
1045
|
+
writtenPaths.add(outPath);
|
|
1046
|
+
writeFileSync3(fullPath, html, "utf-8");
|
|
1047
|
+
console.log(` [content] ${content.routePath} -> ${outPath}`);
|
|
1048
|
+
}
|
|
1049
|
+
if (pagesDir || options.routesDir || options.contentDir) {
|
|
1050
|
+
const srvOpts = {
|
|
1051
|
+
pagesDir: pagesDir || options.routesDir || ""
|
|
1052
|
+
};
|
|
1053
|
+
if (options.apiDir) srvOpts.apiDir = options.apiDir;
|
|
1054
|
+
if (options.layoutsDir) srvOpts.layoutsDir = options.layoutsDir;
|
|
1055
|
+
if (options.actionsDir) srvOpts.actionsDir = options.actionsDir;
|
|
1056
|
+
if (options.contentDir) srvOpts.contentDir = options.contentDir;
|
|
1057
|
+
const configImportPath = options.configPath ? relativeImportPath(serverDir, options.configPath) : void 0;
|
|
1058
|
+
const serverEntry = buildServerEntry(
|
|
1059
|
+
srvOpts,
|
|
1060
|
+
configImportPath,
|
|
1061
|
+
stylesheetHref
|
|
1062
|
+
);
|
|
1063
|
+
const serverEntryPath = join4(serverDir, "index.ts");
|
|
1064
|
+
writeFileSync3(serverEntryPath, serverEntry, "utf-8");
|
|
1065
|
+
console.log(
|
|
1066
|
+
` [server] ${serverPages.length} page routes, ${apiRoutes.length} api routes -> server/index.ts`
|
|
1067
|
+
);
|
|
1064
1068
|
}
|
|
1065
|
-
|
|
1066
|
-
}
|
|
1067
|
-
function islandEntryId(routeFilePath) {
|
|
1068
|
-
return `${basename(routeFilePath).replace(/\.(tsx|ts)$/, "")}-${hashId(routeFilePath)}`;
|
|
1069
|
-
}
|
|
1070
|
-
function wrapIslandBundle(code) {
|
|
1071
|
-
return `;(function () {
|
|
1072
|
-
${code}
|
|
1073
|
-
})();
|
|
1074
|
-
`;
|
|
1069
|
+
console.log(`[x] build complete -> ${outDir}`);
|
|
1075
1070
|
}
|
|
1076
|
-
async function
|
|
1071
|
+
async function bundleRouteIslands(routeFilePath, layoutFilePaths, islandNames, islandsDir, actionModules) {
|
|
1077
1072
|
const entryId = islandEntryId(routeFilePath);
|
|
1078
|
-
const
|
|
1079
|
-
|
|
1080
|
-
const
|
|
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");
|
|
1081
1079
|
try {
|
|
1082
|
-
const entryPath = join3(scratchDir, `${entryId}.tsx`);
|
|
1083
|
-
writeFileSync2(entryPath, generateHydrateEntry(routeFilePath, layoutFilePaths), "utf-8");
|
|
1084
1080
|
const result = await Bun.build({
|
|
1085
1081
|
entrypoints: [entryPath],
|
|
1086
1082
|
target: "browser",
|
|
1087
1083
|
plugins: [actionsRewritePlugin(actionModules)]
|
|
1088
1084
|
});
|
|
1089
|
-
if (
|
|
1090
|
-
|
|
1091
|
-
|
|
1085
|
+
if (result.success) {
|
|
1086
|
+
const outputs = result.outputs.filter((o) => o.kind === "entry-point");
|
|
1087
|
+
const built = outputs[0] ?? result.outputs[0];
|
|
1088
|
+
if (!built) throw new Error("bun build produced no output");
|
|
1089
|
+
const code = await built.text();
|
|
1090
|
+
assertNoEnvLeakage(code, bundlePath);
|
|
1091
|
+
writeFileSync3(bundlePath, wrapIslandBundle(code), "utf-8");
|
|
1092
|
+
return [`/_islands/${entryId}/${entryId}.js`];
|
|
1093
|
+
}
|
|
1094
|
+
for (const log of result.logs) {
|
|
1095
|
+
console.warn(` [islands] build error: ${log.message}`);
|
|
1096
|
+
}
|
|
1097
|
+
} catch (err) {
|
|
1098
|
+
if (err instanceof EnvLeakageError) throw err;
|
|
1099
|
+
console.warn(` [islands] build failed for ${routeFilePath}:`, err);
|
|
1100
|
+
}
|
|
1101
|
+
writeFileSync3(bundlePath, wrapIslandBundle(generateFallbackHydration(islandNames)), "utf-8");
|
|
1102
|
+
return [`/_islands/${entryId}/${entryId}.js`];
|
|
1103
|
+
}
|
|
1104
|
+
function renderPageWithLayout(Component, params, layoutModules) {
|
|
1105
|
+
let content = createElement(Component, { params });
|
|
1106
|
+
for (const Layout of [...layoutModules].reverse()) {
|
|
1107
|
+
content = createElement(Layout, null, content);
|
|
1108
|
+
}
|
|
1109
|
+
return content;
|
|
1110
|
+
}
|
|
1111
|
+
function StaticContentPage({ content, bodyHtml }) {
|
|
1112
|
+
return createElement(
|
|
1113
|
+
"article",
|
|
1114
|
+
null,
|
|
1115
|
+
content.frontmatter.title ? createElement("h1", null, content.frontmatter.title) : null,
|
|
1116
|
+
createElement("div", {
|
|
1117
|
+
// biome-ignore lint/security/noDangerouslySetInnerHtml: body is markdown rendered to HTML
|
|
1118
|
+
dangerouslySetInnerHTML: { __html: bodyHtml }
|
|
1119
|
+
})
|
|
1120
|
+
);
|
|
1121
|
+
}
|
|
1122
|
+
function buildServerEntry(opts, configImportPath, stylesheetHref) {
|
|
1123
|
+
const dirKeys = ["pagesDir", "apiDir", "layoutsDir", "actionsDir", "contentDir"];
|
|
1124
|
+
const lines = [
|
|
1125
|
+
"// Auto-generated by @thexjs/core build",
|
|
1126
|
+
'import { createApp } from "@thexjs/core";'
|
|
1127
|
+
];
|
|
1128
|
+
if (configImportPath) {
|
|
1129
|
+
lines.push("", "let userConfig = {};", "try {");
|
|
1130
|
+
lines.push(` const mod = await import(${JSON.stringify(configImportPath)});`);
|
|
1131
|
+
lines.push(" userConfig = mod.default ?? {};");
|
|
1132
|
+
lines.push("} catch (err) {");
|
|
1133
|
+
lines.push(
|
|
1134
|
+
' console.warn("[x] failed to load x.config for security/observability options:", err);'
|
|
1135
|
+
);
|
|
1136
|
+
lines.push("}");
|
|
1137
|
+
}
|
|
1138
|
+
lines.push("", "const app = await createApp({");
|
|
1139
|
+
for (const key of dirKeys) {
|
|
1140
|
+
const val = opts[key];
|
|
1141
|
+
if (val) lines.push(` ${key}: ${JSON.stringify(val)},`);
|
|
1142
|
+
}
|
|
1143
|
+
if (stylesheetHref) lines.push(` stylesheetHref: ${JSON.stringify(stylesheetHref)},`);
|
|
1144
|
+
lines.push(' port: parseInt(process.env.PORT || "3000", 10),', " development: false,");
|
|
1145
|
+
if (configImportPath) {
|
|
1146
|
+
lines.push(" ...(userConfig.security ? { security: userConfig.security } : {}),");
|
|
1147
|
+
lines.push(
|
|
1148
|
+
" ...(userConfig.observability ? { observability: userConfig.observability } : {}),"
|
|
1149
|
+
);
|
|
1150
|
+
lines.push(" ...(userConfig.images ? { images: userConfig.images } : {}),");
|
|
1151
|
+
}
|
|
1152
|
+
lines.push(
|
|
1153
|
+
"});",
|
|
1154
|
+
"",
|
|
1155
|
+
"const server = Bun.serve(app);",
|
|
1156
|
+
"",
|
|
1157
|
+
"console.log(`[x] production server running at ${server.url}`);",
|
|
1158
|
+
"",
|
|
1159
|
+
"// Graceful shutdown: stop accepting new connections, flush the error",
|
|
1160
|
+
"// reporter, then exit after in-flight requests have a moment to drain.",
|
|
1161
|
+
"let shuttingDown = false;",
|
|
1162
|
+
"async function shutdown(signal: string): Promise<void> {",
|
|
1163
|
+
" if (shuttingDown) return;",
|
|
1164
|
+
" shuttingDown = true;",
|
|
1165
|
+
" console.log(`[x] received ${signal} - shutting down`);",
|
|
1166
|
+
" try {",
|
|
1167
|
+
' const { getErrorReporter } = await import("@thexjs/core");',
|
|
1168
|
+
" await getErrorReporter().flush?.();",
|
|
1169
|
+
" } catch {}",
|
|
1170
|
+
" server.stop(true);",
|
|
1171
|
+
" const exit = () => process.exit(0);",
|
|
1172
|
+
" const drainTimer = setTimeout(exit, 3000);",
|
|
1173
|
+
" drainTimer.unref?.();",
|
|
1174
|
+
"}",
|
|
1175
|
+
'process.on("SIGTERM", () => shutdown("SIGTERM"));',
|
|
1176
|
+
'process.on("SIGINT", () => shutdown("SIGINT"));'
|
|
1177
|
+
);
|
|
1178
|
+
return lines.join("\n");
|
|
1179
|
+
}
|
|
1180
|
+
function relativeImportPath(fromDir, toFile) {
|
|
1181
|
+
const rel = relative2(fromDir, toFile).replace(/\\/g, "/").replace(/\.(ts|js|mjs)$/, "");
|
|
1182
|
+
return rel.startsWith(".") ? rel : `./${rel}`;
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
// src/createApp.ts
|
|
1186
|
+
import { existsSync as existsSync2, watch } from "fs";
|
|
1187
|
+
import { join as join5, resolve, sep as sep2 } from "path";
|
|
1188
|
+
import { createElement as createElement2 } from "react";
|
|
1189
|
+
|
|
1190
|
+
// src/error-overlay.ts
|
|
1191
|
+
function escapeHtml3(s) {
|
|
1192
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
1193
|
+
}
|
|
1194
|
+
function renderErrorOverlay(error) {
|
|
1195
|
+
const message = error instanceof Error ? error.message : "Unknown error";
|
|
1196
|
+
const stack = error instanceof Error ? error.stack ?? "" : "";
|
|
1197
|
+
const frames = stack.split("\n").slice(1).map((line) => `<span class="frame">${escapeHtml3(line.trim())}</span>`).join("\n");
|
|
1198
|
+
return `<!DOCTYPE html>
|
|
1199
|
+
<html lang="en">
|
|
1200
|
+
<head>
|
|
1201
|
+
<meta charset="UTF-8" />
|
|
1202
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
1203
|
+
<title>Server Error</title>
|
|
1204
|
+
<style>
|
|
1205
|
+
* { margin: 0; padding: 0; box-sizing: border-box; }
|
|
1206
|
+
body {
|
|
1207
|
+
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
|
1208
|
+
background: #1a1a2e;
|
|
1209
|
+
color: #e0e0e0;
|
|
1210
|
+
min-height: 100vh;
|
|
1211
|
+
display: flex;
|
|
1212
|
+
flex-direction: column;
|
|
1213
|
+
}
|
|
1214
|
+
.overlay {
|
|
1215
|
+
flex: 1;
|
|
1216
|
+
padding: 40px 24px;
|
|
1217
|
+
max-width: 900px;
|
|
1218
|
+
margin: 0 auto;
|
|
1219
|
+
width: 100%;
|
|
1220
|
+
}
|
|
1221
|
+
.header { margin-bottom: 32px; }
|
|
1222
|
+
.badge {
|
|
1223
|
+
display: inline-block;
|
|
1224
|
+
background: #e74c3c;
|
|
1225
|
+
color: #fff;
|
|
1226
|
+
font-size: 11px;
|
|
1227
|
+
font-weight: 700;
|
|
1228
|
+
letter-spacing: 0.05em;
|
|
1229
|
+
text-transform: uppercase;
|
|
1230
|
+
padding: 3px 10px;
|
|
1231
|
+
border-radius: 4px;
|
|
1232
|
+
margin-bottom: 12px;
|
|
1233
|
+
}
|
|
1234
|
+
h1 {
|
|
1235
|
+
font-size: 22px;
|
|
1236
|
+
font-weight: 600;
|
|
1237
|
+
color: #f0f0f0;
|
|
1238
|
+
line-height: 1.3;
|
|
1239
|
+
}
|
|
1240
|
+
.message-box {
|
|
1241
|
+
background: #2a2a4a;
|
|
1242
|
+
border: 1px solid #3a3a5a;
|
|
1243
|
+
border-radius: 8px;
|
|
1244
|
+
padding: 20px;
|
|
1245
|
+
margin-bottom: 24px;
|
|
1246
|
+
font-size: 15px;
|
|
1247
|
+
word-break: break-word;
|
|
1248
|
+
}
|
|
1249
|
+
.message-box .label {
|
|
1250
|
+
font-size: 11px;
|
|
1251
|
+
font-weight: 600;
|
|
1252
|
+
text-transform: uppercase;
|
|
1253
|
+
letter-spacing: 0.05em;
|
|
1254
|
+
color: #888;
|
|
1255
|
+
margin-bottom: 8px;
|
|
1256
|
+
}
|
|
1257
|
+
.message-box .message {
|
|
1258
|
+
color: #ff6b6b;
|
|
1259
|
+
font-family: "SF Mono", "Fira Code", "Fira Mono", monospace;
|
|
1260
|
+
font-size: 14px;
|
|
1261
|
+
white-space: pre-wrap;
|
|
1262
|
+
}
|
|
1263
|
+
.stack-section { margin-bottom: 24px; }
|
|
1264
|
+
.stack-section .label {
|
|
1265
|
+
font-size: 11px;
|
|
1266
|
+
font-weight: 600;
|
|
1267
|
+
text-transform: uppercase;
|
|
1268
|
+
letter-spacing: 0.05em;
|
|
1269
|
+
color: #888;
|
|
1270
|
+
margin-bottom: 12px;
|
|
1271
|
+
}
|
|
1272
|
+
.frame {
|
|
1273
|
+
display: block;
|
|
1274
|
+
padding: 6px 12px;
|
|
1275
|
+
font-family: "SF Mono", "Fira Code", "Fira Mono", monospace;
|
|
1276
|
+
font-size: 12px;
|
|
1277
|
+
color: #b0b0d0;
|
|
1278
|
+
line-height: 1.6;
|
|
1279
|
+
border-left: 2px solid #3a3a5a;
|
|
1280
|
+
margin-bottom: 2px;
|
|
1281
|
+
}
|
|
1282
|
+
.frame:first-child { border-left-color: #e74c3c; }
|
|
1283
|
+
.hint {
|
|
1284
|
+
font-size: 13px;
|
|
1285
|
+
color: #888;
|
|
1286
|
+
border-top: 1px solid #3a3a5a;
|
|
1287
|
+
padding-top: 20px;
|
|
1288
|
+
margin-top: 8px;
|
|
1289
|
+
}
|
|
1290
|
+
.hint a { color: #6ab0ff; }
|
|
1291
|
+
</style>
|
|
1292
|
+
</head>
|
|
1293
|
+
<body>
|
|
1294
|
+
<div class="overlay">
|
|
1295
|
+
<div class="header">
|
|
1296
|
+
<div class="badge">Server Error</div>
|
|
1297
|
+
<h1>Unhandled Error During Render</h1>
|
|
1298
|
+
</div>
|
|
1299
|
+
<div class="message-box">
|
|
1300
|
+
<div class="label">Error</div>
|
|
1301
|
+
<div class="message">${escapeHtml3(message)}</div>
|
|
1302
|
+
</div>
|
|
1303
|
+
${stack ? `<div class="stack-section"><div class="label">Stack Trace</div>${frames}</div>` : ""}
|
|
1304
|
+
<div class="hint">
|
|
1305
|
+
Fix the error and save the file. In development mode, the server will reload automatically.
|
|
1306
|
+
</div>
|
|
1307
|
+
</div>
|
|
1308
|
+
</body>
|
|
1309
|
+
</html>`;
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
// src/images/proxy.ts
|
|
1313
|
+
var ALLOWED_CONTENT_TYPES = /* @__PURE__ */ new Set([
|
|
1314
|
+
"image/png",
|
|
1315
|
+
"image/jpeg",
|
|
1316
|
+
"image/gif",
|
|
1317
|
+
"image/webp",
|
|
1318
|
+
"image/avif",
|
|
1319
|
+
"image/x-icon"
|
|
1320
|
+
]);
|
|
1321
|
+
function createImageProxyHandler(options = {}) {
|
|
1322
|
+
const allowedHosts = new Set(options.remoteHosts ?? []);
|
|
1323
|
+
return async (req) => {
|
|
1324
|
+
const reqUrl = new URL(req.url);
|
|
1325
|
+
if (reqUrl.pathname !== "/_x/image") return null;
|
|
1326
|
+
if (req.method !== "GET" && req.method !== "HEAD") return null;
|
|
1327
|
+
const target = reqUrl.searchParams.get("url");
|
|
1328
|
+
if (!target) return new Response("missing url param", { status: 400 });
|
|
1329
|
+
let parsed;
|
|
1330
|
+
try {
|
|
1331
|
+
parsed = new URL(target);
|
|
1332
|
+
} catch {
|
|
1333
|
+
return new Response("invalid url param", { status: 400 });
|
|
1334
|
+
}
|
|
1335
|
+
const allowedUrl = (u) => (u.protocol === "http:" || u.protocol === "https:") && allowedHosts.has(u.hostname);
|
|
1336
|
+
if (!allowedUrl(parsed)) {
|
|
1337
|
+
return new Response("host not allow-listed for image proxy", { status: 403 });
|
|
1338
|
+
}
|
|
1339
|
+
const wParam = reqUrl.searchParams.get("w");
|
|
1340
|
+
const qParam = reqUrl.searchParams.get("q");
|
|
1341
|
+
if (wParam !== null) {
|
|
1342
|
+
const w = Number.parseInt(wParam, 10);
|
|
1343
|
+
if (!Number.isFinite(w) || w < 1 || w > 8192) {
|
|
1344
|
+
return new Response("invalid w param", { status: 400 });
|
|
1092
1345
|
}
|
|
1093
|
-
return wrapIslandBundle(generateFallbackHydration(islandNames));
|
|
1094
1346
|
}
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
return wrapIslandBundle(code);
|
|
1101
|
-
} catch (err) {
|
|
1102
|
-
if (err instanceof EnvLeakageError) {
|
|
1103
|
-
console.error(
|
|
1104
|
-
`\x1B[1;31m\u{1F512} SECURITY: [islands] ${err.message}\x1B[0m
|
|
1105
|
-
Falling back to a non-interactive hydration stub \u2014 fix the env isolation (prefix with THEXJS_PUBLIC_ or move the access server-side) before relying on this page's client behavior.`
|
|
1106
|
-
);
|
|
1107
|
-
return wrapIslandBundle(generateFallbackHydration(islandNames));
|
|
1347
|
+
if (qParam !== null) {
|
|
1348
|
+
const q = Number.parseInt(qParam, 10);
|
|
1349
|
+
if (!Number.isFinite(q) || q < 1 || q > 100) {
|
|
1350
|
+
return new Response("invalid q param", { status: 400 });
|
|
1351
|
+
}
|
|
1108
1352
|
}
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1353
|
+
const isRedirect = (status) => status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
|
|
1354
|
+
let upstream;
|
|
1355
|
+
try {
|
|
1356
|
+
upstream = await fetch(parsed, { redirect: "manual" });
|
|
1357
|
+
for (let hop = 0; hop < 5; hop++) {
|
|
1358
|
+
if (!isRedirect(upstream.status)) break;
|
|
1359
|
+
const location = upstream.headers.get("location");
|
|
1360
|
+
let next;
|
|
1361
|
+
try {
|
|
1362
|
+
next = new URL(location ?? "", parsed);
|
|
1363
|
+
} catch {
|
|
1364
|
+
return new Response("upstream redirect was not a valid URL", { status: 502 });
|
|
1365
|
+
}
|
|
1366
|
+
if (!allowedUrl(next)) {
|
|
1367
|
+
return new Response("upstream redirected off the allow-list", { status: 403 });
|
|
1368
|
+
}
|
|
1369
|
+
upstream = await fetch(next, { redirect: "manual" });
|
|
1370
|
+
}
|
|
1371
|
+
} catch (err) {
|
|
1372
|
+
return new Response(`upstream fetch failed: ${String(err)}`, { status: 502 });
|
|
1373
|
+
}
|
|
1374
|
+
if (isRedirect(upstream.status)) {
|
|
1375
|
+
return new Response("too many upstream redirects", { status: 502 });
|
|
1376
|
+
}
|
|
1377
|
+
if (!upstream.ok) {
|
|
1378
|
+
return new Response("upstream error", { status: 502 });
|
|
1379
|
+
}
|
|
1380
|
+
const contentType = upstream.headers.get("content-type") ?? "";
|
|
1381
|
+
const baseContentType = (contentType.split(";")[0] ?? "").trim();
|
|
1382
|
+
if (!ALLOWED_CONTENT_TYPES.has(baseContentType)) {
|
|
1383
|
+
return new Response("upstream did not return an image", { status: 502 });
|
|
1384
|
+
}
|
|
1385
|
+
return new Response(upstream.body, {
|
|
1386
|
+
status: 200,
|
|
1387
|
+
headers: {
|
|
1388
|
+
"Content-Type": contentType,
|
|
1389
|
+
// Cache aggressively client + edge side — the proxied URL is the
|
|
1390
|
+
// cache key, and remote asset URLs like this one are typically
|
|
1391
|
+
// content-hashed by the origin already.
|
|
1392
|
+
"Cache-Control": "public, max-age=86400, immutable"
|
|
1393
|
+
}
|
|
1394
|
+
});
|
|
1395
|
+
};
|
|
1114
1396
|
}
|
|
1115
1397
|
|
|
1116
1398
|
// src/middleware.ts
|
|
@@ -1130,6 +1412,39 @@ function composeMiddleware(fns, handler) {
|
|
|
1130
1412
|
};
|
|
1131
1413
|
}
|
|
1132
1414
|
|
|
1415
|
+
// src/not-found.tsx
|
|
1416
|
+
import { jsx as jsx2, jsxs } from "react/jsx-runtime";
|
|
1417
|
+
function DefaultNotFound(_props) {
|
|
1418
|
+
return /* @__PURE__ */ jsxs(
|
|
1419
|
+
"main",
|
|
1420
|
+
{
|
|
1421
|
+
style: {
|
|
1422
|
+
maxWidth: 640,
|
|
1423
|
+
margin: "4rem auto",
|
|
1424
|
+
padding: "0 1rem",
|
|
1425
|
+
fontFamily: "system-ui, -apple-system, sans-serif",
|
|
1426
|
+
textAlign: "center"
|
|
1427
|
+
},
|
|
1428
|
+
children: [
|
|
1429
|
+
/* @__PURE__ */ jsx2("h1", { style: { fontSize: "4rem", fontWeight: 700, margin: "0 0 0.5rem", color: "#e74c3c" }, children: "404" }),
|
|
1430
|
+
/* @__PURE__ */ jsx2("p", { style: { fontSize: "1.125rem", color: "#666", margin: "0 0 2rem" }, children: "This page could not be found." }),
|
|
1431
|
+
/* @__PURE__ */ jsx2(
|
|
1432
|
+
"a",
|
|
1433
|
+
{
|
|
1434
|
+
href: "/",
|
|
1435
|
+
style: {
|
|
1436
|
+
color: "#6ab0ff",
|
|
1437
|
+
textDecoration: "underline",
|
|
1438
|
+
fontSize: "0.875rem"
|
|
1439
|
+
},
|
|
1440
|
+
children: "Back to home"
|
|
1441
|
+
}
|
|
1442
|
+
)
|
|
1443
|
+
]
|
|
1444
|
+
}
|
|
1445
|
+
);
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1133
1448
|
// src/observability/health.ts
|
|
1134
1449
|
async function runChecks(checks) {
|
|
1135
1450
|
const results = {};
|
|
@@ -1525,7 +1840,7 @@ function routeMatchesForSort(entry) {
|
|
|
1525
1840
|
return isStatic ? 0 : isCatchAll ? 2 : 1;
|
|
1526
1841
|
}
|
|
1527
1842
|
function projectRootFromRoutesDir(routesDir) {
|
|
1528
|
-
return
|
|
1843
|
+
return join5(routesDir, "..", "..");
|
|
1529
1844
|
}
|
|
1530
1845
|
function resolvePublicAsset(publicDir, pathname) {
|
|
1531
1846
|
let decoded;
|
|
@@ -1534,7 +1849,7 @@ function resolvePublicAsset(publicDir, pathname) {
|
|
|
1534
1849
|
} catch {
|
|
1535
1850
|
return null;
|
|
1536
1851
|
}
|
|
1537
|
-
const target = resolve(
|
|
1852
|
+
const target = resolve(join5(publicDir, decoded));
|
|
1538
1853
|
const root = resolve(publicDir);
|
|
1539
1854
|
if (target !== root && !target.startsWith(root + sep2)) return null;
|
|
1540
1855
|
return target;
|
|
@@ -1553,9 +1868,9 @@ async function serveStaticAsset(publicDir, req) {
|
|
|
1553
1868
|
return new Response(file);
|
|
1554
1869
|
}
|
|
1555
1870
|
function wrapWithLayouts(Component, params, loaderData, layoutModules) {
|
|
1556
|
-
let content =
|
|
1871
|
+
let content = createElement2(Component, { params, loaderData });
|
|
1557
1872
|
for (const Layout of [...layoutModules].reverse()) {
|
|
1558
|
-
content =
|
|
1873
|
+
content = createElement2(Layout, null, content);
|
|
1559
1874
|
}
|
|
1560
1875
|
return content;
|
|
1561
1876
|
}
|
|
@@ -1563,11 +1878,11 @@ function renderContentPage(content, stylesheet, dev = false) {
|
|
|
1563
1878
|
const title = content.frontmatter.title ?? content.slug;
|
|
1564
1879
|
const bodyHtml = renderMarkdown(content.body);
|
|
1565
1880
|
const body = renderPage(
|
|
1566
|
-
|
|
1881
|
+
createElement2(
|
|
1567
1882
|
"article",
|
|
1568
1883
|
null,
|
|
1569
|
-
content.frontmatter.title ?
|
|
1570
|
-
|
|
1884
|
+
content.frontmatter.title ? createElement2("h1", null, content.frontmatter.title) : null,
|
|
1885
|
+
createElement2("div", {
|
|
1571
1886
|
// biome-ignore lint/security/noDangerouslySetInnerHtml: body is markdown rendered to HTML
|
|
1572
1887
|
dangerouslySetInnerHTML: { __html: bodyHtml }
|
|
1573
1888
|
})
|
|
@@ -1586,7 +1901,7 @@ async function createApp(options) {
|
|
|
1586
1901
|
const dev = options.development ?? false;
|
|
1587
1902
|
const primaryDir = options.pagesDir || options.routesDir || "src/pages";
|
|
1588
1903
|
const projectRoot = projectRootFromRoutesDir(primaryDir);
|
|
1589
|
-
const resolvedActionsDir = options.actionsDir ?? (
|
|
1904
|
+
const resolvedActionsDir = options.actionsDir ?? (existsSync2(join5(projectRoot, "src", "actions")) ? join5(projectRoot, "src", "actions") : void 0);
|
|
1590
1905
|
let handlers = [];
|
|
1591
1906
|
let contentHandlers = [];
|
|
1592
1907
|
let publicDir = null;
|
|
@@ -1640,8 +1955,8 @@ async function createApp(options) {
|
|
|
1640
1955
|
function withResponseHardening(res) {
|
|
1641
1956
|
return securityHeadersOptions === false ? res : applySecurityHeaders(res, securityHeadersOptions);
|
|
1642
1957
|
}
|
|
1643
|
-
async function renderNotFound(
|
|
1644
|
-
const content = notFoundLayout ?
|
|
1958
|
+
async function renderNotFound(_req) {
|
|
1959
|
+
const content = notFoundLayout ? createElement2(notFoundLayout, null, createElement2(notFoundComponent, { params: {} })) : createElement2(notFoundComponent, { params: {} });
|
|
1645
1960
|
const html = renderPage(content, {
|
|
1646
1961
|
title: "404 \u2014 Not Found",
|
|
1647
1962
|
stylesheet: stylesheetHref,
|
|
@@ -1703,7 +2018,7 @@ async function createApp(options) {
|
|
|
1703
2018
|
loaderData2 = result;
|
|
1704
2019
|
}
|
|
1705
2020
|
const registry2 = createIslandRegistry();
|
|
1706
|
-
const content2 =
|
|
2021
|
+
const content2 = createElement2(
|
|
1707
2022
|
IslandProvider,
|
|
1708
2023
|
{ registry: registry2 },
|
|
1709
2024
|
wrapWithLayouts(Component, ctx.params, loaderData2, layoutModules)
|
|
@@ -1745,7 +2060,7 @@ async function createApp(options) {
|
|
|
1745
2060
|
loaderData = result;
|
|
1746
2061
|
}
|
|
1747
2062
|
const registry = createIslandRegistry();
|
|
1748
|
-
const content =
|
|
2063
|
+
const content = createElement2(
|
|
1749
2064
|
IslandProvider,
|
|
1750
2065
|
{ registry },
|
|
1751
2066
|
wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
|
|
@@ -1795,9 +2110,9 @@ async function createApp(options) {
|
|
|
1795
2110
|
async function buildHandlers() {
|
|
1796
2111
|
if (options.preloaded) {
|
|
1797
2112
|
const preloaded = options.preloaded;
|
|
1798
|
-
const candidatePublicDir2 =
|
|
1799
|
-
publicDir =
|
|
1800
|
-
stylesheetHref = options.stylesheetHref ?? (publicDir &&
|
|
2113
|
+
const candidatePublicDir2 = join5(projectRoot, "public");
|
|
2114
|
+
publicDir = existsSync2(candidatePublicDir2) ? candidatePublicDir2 : null;
|
|
2115
|
+
stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync2(join5(publicDir, "styles.css")) ? "/styles.css" : void 0);
|
|
1801
2116
|
if (preloaded.notFoundComponent) notFoundComponent = preloaded.notFoundComponent;
|
|
1802
2117
|
if (preloaded.notFoundLayout) notFoundLayout = preloaded.notFoundLayout;
|
|
1803
2118
|
const loaded2 = [];
|
|
@@ -1845,14 +2160,13 @@ async function createApp(options) {
|
|
|
1845
2160
|
islandFileCache.clear();
|
|
1846
2161
|
const pagesDir = primaryDir;
|
|
1847
2162
|
const apiDir = options.apiDir;
|
|
1848
|
-
const layoutsDir = options.layoutsDir || pagesDir;
|
|
1849
2163
|
let found = scanPages(pagesDir);
|
|
1850
2164
|
const apiFound = [];
|
|
1851
|
-
if (apiDir &&
|
|
2165
|
+
if (apiDir && existsSync2(apiDir)) {
|
|
1852
2166
|
apiFound.push(...scanApiDir(apiDir));
|
|
1853
2167
|
}
|
|
1854
|
-
const legacyApiDir =
|
|
1855
|
-
if (
|
|
2168
|
+
const legacyApiDir = join5(pagesDir, "api");
|
|
2169
|
+
if (existsSync2(legacyApiDir) && legacyApiDir !== apiDir) {
|
|
1856
2170
|
apiFound.push(...scanApiDir(legacyApiDir));
|
|
1857
2171
|
}
|
|
1858
2172
|
found = found.filter((r) => !r.isApi);
|
|
@@ -1886,9 +2200,9 @@ async function createApp(options) {
|
|
|
1886
2200
|
}
|
|
1887
2201
|
}
|
|
1888
2202
|
}
|
|
1889
|
-
const candidatePublicDir =
|
|
1890
|
-
publicDir =
|
|
1891
|
-
stylesheetHref = options.stylesheetHref ?? (publicDir &&
|
|
2203
|
+
const candidatePublicDir = join5(projectRoot, "public");
|
|
2204
|
+
publicDir = existsSync2(candidatePublicDir) ? candidatePublicDir : null;
|
|
2205
|
+
stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync2(join5(publicDir, "styles.css")) ? "/styles.css" : void 0);
|
|
1892
2206
|
const notFoundEntry = scanNotFound(pagesDir);
|
|
1893
2207
|
if (notFoundEntry) {
|
|
1894
2208
|
const mod = await importDev(notFoundEntry.filePath, dev);
|
|
@@ -2048,7 +2362,7 @@ async function createApp(options) {
|
|
|
2048
2362
|
let rebuildTimeout = null;
|
|
2049
2363
|
const sseClients = /* @__PURE__ */ new Set();
|
|
2050
2364
|
try {
|
|
2051
|
-
const srcDir =
|
|
2365
|
+
const srcDir = join5(primaryDir, "..", "..", "src");
|
|
2052
2366
|
const watchDirs = [
|
|
2053
2367
|
...new Set(
|
|
2054
2368
|
[primaryDir, options.apiDir, options.layoutsDir, resolvedActionsDir, srcDir].filter(
|
|
@@ -2129,384 +2443,192 @@ data: ${data}
|
|
|
2129
2443
|
if (islandBundle !== null) return islandBundle;
|
|
2130
2444
|
const proxiedImage = await imageProxyHandler(req);
|
|
2131
2445
|
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);
|
|
2446
|
+
for (const h of handlers) {
|
|
2447
|
+
const params = extractParams(h.entry.routePath, h.entry.paramNames, url);
|
|
2448
|
+
if (params !== null) {
|
|
2449
|
+
return h.handler(req);
|
|
2450
|
+
}
|
|
2285
2451
|
}
|
|
2286
|
-
|
|
2287
|
-
|
|
2288
|
-
|
|
2289
|
-
|
|
2290
|
-
|
|
2291
|
-
|
|
2292
|
-
|
|
2293
|
-
|
|
2294
|
-
|
|
2295
|
-
|
|
2296
|
-
|
|
2297
|
-
|
|
2298
|
-
|
|
2452
|
+
for (const h of contentHandlers) {
|
|
2453
|
+
if (h.entry.routePath === url) {
|
|
2454
|
+
return h.handler(req);
|
|
2455
|
+
}
|
|
2456
|
+
}
|
|
2457
|
+
return renderNotFound(req);
|
|
2458
|
+
};
|
|
2459
|
+
const devFetchHardened = async (req, server) => withResponseHardening(await devFetchInner(req, server));
|
|
2460
|
+
const devFetchBase = loggingEnabled ? withRequestLogging(devFetchHardened) : devFetchHardened;
|
|
2461
|
+
const devFetch = metricsReporter ? withRequestMetrics(metricsReporter, devFetchBase) : devFetchBase;
|
|
2462
|
+
return {
|
|
2463
|
+
routes: {},
|
|
2464
|
+
development: true,
|
|
2465
|
+
port: options.port ?? 3e3,
|
|
2466
|
+
fetch: devFetch
|
|
2299
2467
|
};
|
|
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
2468
|
}
|
|
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`);
|
|
2469
|
+
const prodFetchInner = async (req, server) => {
|
|
2470
|
+
const url = new URL(req.url).pathname;
|
|
2471
|
+
const healthResult = await healthHandler(req);
|
|
2472
|
+
if (healthResult !== null) return healthResult;
|
|
2473
|
+
if (metricsReporter?.handleMetrics) {
|
|
2474
|
+
const metricsResult = await metricsReporter.handleMetrics(req);
|
|
2475
|
+
if (metricsResult !== null) return metricsResult;
|
|
2325
2476
|
}
|
|
2326
|
-
|
|
2327
|
-
|
|
2328
|
-
|
|
2329
|
-
|
|
2330
|
-
|
|
2331
|
-
|
|
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
|
-
);
|
|
2477
|
+
if (rateLimiter) {
|
|
2478
|
+
const limited = await rateLimitMiddleware(rateLimiter, req, server);
|
|
2479
|
+
if (limited !== null) {
|
|
2480
|
+
metricsReporter?.incr("x_rate_limit_rejections_total", 1, { method: req.method });
|
|
2481
|
+
return limited;
|
|
2482
|
+
}
|
|
2340
2483
|
}
|
|
2341
|
-
const
|
|
2342
|
-
|
|
2343
|
-
|
|
2344
|
-
|
|
2345
|
-
|
|
2346
|
-
|
|
2347
|
-
const
|
|
2348
|
-
|
|
2349
|
-
|
|
2350
|
-
|
|
2351
|
-
|
|
2352
|
-
|
|
2353
|
-
|
|
2354
|
-
|
|
2355
|
-
|
|
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`);
|
|
2484
|
+
const revalidationResult = await handleRevalidation(req);
|
|
2485
|
+
if (revalidationResult !== null) return revalidationResult;
|
|
2486
|
+
const serverFnResult = await serverFnHandler(req);
|
|
2487
|
+
if (serverFnResult !== null) return serverFnResult;
|
|
2488
|
+
const staticAsset = await serveStaticAsset(publicDir, req);
|
|
2489
|
+
if (staticAsset !== null) return staticAsset;
|
|
2490
|
+
const islandBundle = serveIslandBundle(req);
|
|
2491
|
+
if (islandBundle !== null) return islandBundle;
|
|
2492
|
+
const proxiedImage = await imageProxyHandler(req);
|
|
2493
|
+
if (proxiedImage !== null) return proxiedImage;
|
|
2494
|
+
for (const h of handlers) {
|
|
2495
|
+
const params = extractParams(h.entry.routePath, h.entry.paramNames, url);
|
|
2496
|
+
if (params !== null) {
|
|
2497
|
+
return h.handler(req);
|
|
2498
|
+
}
|
|
2362
2499
|
}
|
|
2363
|
-
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2367
|
-
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
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}`);
|
|
2500
|
+
for (const h of contentHandlers) {
|
|
2501
|
+
if (h.entry.routePath === url) {
|
|
2502
|
+
return h.handler(req);
|
|
2503
|
+
}
|
|
2504
|
+
}
|
|
2505
|
+
return renderNotFound(req);
|
|
2506
|
+
};
|
|
2507
|
+
const prodFetchHardened = async (req, server) => withResponseHardening(await prodFetchInner(req, server));
|
|
2508
|
+
const prodFetchBase = loggingEnabled ? withRequestLogging(prodFetchHardened) : prodFetchHardened;
|
|
2509
|
+
const prodFetch = metricsReporter ? withRequestMetrics(metricsReporter, prodFetchBase) : prodFetchBase;
|
|
2510
|
+
return {
|
|
2511
|
+
routes: {},
|
|
2512
|
+
development: false,
|
|
2513
|
+
port: options.port ?? 3e3,
|
|
2514
|
+
fetch: prodFetch
|
|
2515
|
+
};
|
|
2388
2516
|
}
|
|
2389
|
-
|
|
2390
|
-
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2517
|
+
|
|
2518
|
+
// src/image.tsx
|
|
2519
|
+
import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
|
|
2520
|
+
var DEV = typeof process !== "undefined" && process.env?.NODE_ENV === "development";
|
|
2521
|
+
var PROXY_PATH = "/_x/image";
|
|
2522
|
+
var SRCSET_WIDTHS = [320, 640, 750, 828, 1080, 1200, 1920, 2048, 3840];
|
|
2523
|
+
function isRemoteUrl(src) {
|
|
2524
|
+
return /^https?:\/\//i.test(src);
|
|
2525
|
+
}
|
|
2526
|
+
function proxyUrl(src, w, q) {
|
|
2527
|
+
const params = new URLSearchParams({ url: src });
|
|
2528
|
+
if (w !== void 0) params.set("w", String(w));
|
|
2529
|
+
if (q !== void 0) params.set("q", String(q));
|
|
2530
|
+
return `${PROXY_PATH}?${params.toString()}`;
|
|
2531
|
+
}
|
|
2532
|
+
function devWarn(message) {
|
|
2533
|
+
if (DEV) {
|
|
2534
|
+
console.warn(`[x/image] ${message}`);
|
|
2535
|
+
}
|
|
2536
|
+
}
|
|
2537
|
+
function buildSrcSet(src, opts = {}) {
|
|
2538
|
+
if (!isRemoteUrl(src)) return void 0;
|
|
2397
2539
|
try {
|
|
2398
|
-
const
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
|
|
2402
|
-
|
|
2403
|
-
|
|
2404
|
-
|
|
2405
|
-
|
|
2406
|
-
|
|
2407
|
-
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
|
|
2540
|
+
const hosts = new Set(opts.remoteHosts ?? []);
|
|
2541
|
+
if (!hosts.has(new URL(src).hostname)) return void 0;
|
|
2542
|
+
} catch {
|
|
2543
|
+
return void 0;
|
|
2544
|
+
}
|
|
2545
|
+
return SRCSET_WIDTHS.map((w) => `${proxyUrl(src, w, opts.quality)} ${w}w`).join(", ");
|
|
2546
|
+
}
|
|
2547
|
+
function setImageRemoteHosts(hosts) {
|
|
2548
|
+
_remoteHosts = hosts;
|
|
2549
|
+
}
|
|
2550
|
+
var _remoteHosts;
|
|
2551
|
+
function Image(props) {
|
|
2552
|
+
const {
|
|
2553
|
+
src,
|
|
2554
|
+
alt,
|
|
2555
|
+
width,
|
|
2556
|
+
height,
|
|
2557
|
+
sizes,
|
|
2558
|
+
priority = false,
|
|
2559
|
+
fill = false,
|
|
2560
|
+
placeholder = "empty",
|
|
2561
|
+
blurDataURL,
|
|
2562
|
+
quality,
|
|
2563
|
+
className,
|
|
2564
|
+
style: userStyle,
|
|
2565
|
+
children
|
|
2566
|
+
} = props;
|
|
2567
|
+
const remote = isRemoteUrl(src);
|
|
2568
|
+
if (DEV) {
|
|
2569
|
+
if (fill && (width !== void 0 || height !== void 0)) {
|
|
2570
|
+
devWarn(`both "fill" and width/height are set on "${src}" \u2014 fill ignores dimensions.`);
|
|
2571
|
+
}
|
|
2572
|
+
if (!fill && (width === void 0 || height === void 0)) {
|
|
2573
|
+
devWarn(
|
|
2574
|
+
`missing width/height on "${src}" (causes layout shift). Provide both or use "fill".`
|
|
2575
|
+
);
|
|
2411
2576
|
}
|
|
2412
|
-
|
|
2413
|
-
|
|
2577
|
+
if (remote) {
|
|
2578
|
+
const host = new URL(src).hostname;
|
|
2579
|
+
if (!_remoteHosts?.includes(host)) {
|
|
2580
|
+
devWarn(
|
|
2581
|
+
`remote src "${src}" host "${host}" is not in images.remoteHosts \u2014 the proxy will 403.`
|
|
2582
|
+
);
|
|
2583
|
+
}
|
|
2414
2584
|
}
|
|
2415
|
-
} catch (err) {
|
|
2416
|
-
if (err instanceof EnvLeakageError) throw err;
|
|
2417
|
-
console.warn(` [islands] build failed for ${routeFilePath}:`, err);
|
|
2418
2585
|
}
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2586
|
+
const resolvedSrc = remote ? proxyUrl(src, quality) : src;
|
|
2587
|
+
const baseStyle = fill ? { position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" } : { maxWidth: "100%", height: "auto" };
|
|
2588
|
+
if (!fill && width !== void 0 && height !== void 0) {
|
|
2589
|
+
baseStyle.aspectRatio = `${width} / ${height}`;
|
|
2590
|
+
}
|
|
2591
|
+
const placeholderStyle = placeholder === "blur" && blurDataURL ? {
|
|
2592
|
+
backgroundImage: `url(${blurDataURL})`,
|
|
2593
|
+
backgroundSize: "cover",
|
|
2594
|
+
backgroundPosition: "center"
|
|
2595
|
+
} : {};
|
|
2596
|
+
const imgProps = {
|
|
2597
|
+
src: resolvedSrc,
|
|
2598
|
+
sizes,
|
|
2599
|
+
className,
|
|
2600
|
+
style: { ...baseStyle, ...placeholderStyle, ...userStyle },
|
|
2601
|
+
decoding: "async"
|
|
2602
|
+
};
|
|
2603
|
+
if (fill) {
|
|
2604
|
+
imgProps.width = void 0;
|
|
2605
|
+
imgProps.height = void 0;
|
|
2606
|
+
} else {
|
|
2607
|
+
imgProps.width = width;
|
|
2608
|
+
imgProps.height = height;
|
|
2426
2609
|
}
|
|
2427
|
-
|
|
2428
|
-
|
|
2429
|
-
|
|
2430
|
-
|
|
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("}");
|
|
2610
|
+
if (priority) {
|
|
2611
|
+
imgProps.fetchPriority = "high";
|
|
2612
|
+
} else {
|
|
2613
|
+
imgProps.loading = "lazy";
|
|
2458
2614
|
}
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
const val = opts[key];
|
|
2462
|
-
if (val) lines.push(` ${key}: ${JSON.stringify(val)},`);
|
|
2615
|
+
if (remote) {
|
|
2616
|
+
imgProps.srcSet = SRCSET_WIDTHS.map((w) => `${proxyUrl(src, w, quality)} ${w}w`).join(", ");
|
|
2463
2617
|
}
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
);
|
|
2471
|
-
lines.push(" ...(userConfig.images ? { images: userConfig.images } : {}),");
|
|
2618
|
+
const img = /* @__PURE__ */ jsx3("img", { alt, ...imgProps });
|
|
2619
|
+
if (children) {
|
|
2620
|
+
return /* @__PURE__ */ jsxs2("picture", { children: [
|
|
2621
|
+
children,
|
|
2622
|
+
img
|
|
2623
|
+
] });
|
|
2472
2624
|
}
|
|
2473
|
-
|
|
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}`;
|
|
2625
|
+
return img;
|
|
2504
2626
|
}
|
|
2505
2627
|
|
|
2506
2628
|
// src/link.tsx
|
|
2507
|
-
import { jsx as
|
|
2629
|
+
import { jsx as jsx4 } from "react/jsx-runtime";
|
|
2508
2630
|
function Link({ href, children, clientNav = true, prefetch = true, ...rest }) {
|
|
2509
|
-
return /* @__PURE__ */
|
|
2631
|
+
return /* @__PURE__ */ jsx4(
|
|
2510
2632
|
"a",
|
|
2511
2633
|
{
|
|
2512
2634
|
href,
|
|
@@ -2522,14 +2644,17 @@ export {
|
|
|
2522
2644
|
DEFAULT_HISTOGRAM_BUCKETS_MS,
|
|
2523
2645
|
DefaultNotFound,
|
|
2524
2646
|
EnvLeakageError,
|
|
2647
|
+
Image,
|
|
2525
2648
|
Island,
|
|
2526
2649
|
IslandProvider,
|
|
2527
2650
|
Link,
|
|
2528
2651
|
PUBLIC_ENV_PREFIX,
|
|
2652
|
+
SRCSET_WIDTHS,
|
|
2529
2653
|
applySecurityHeaders,
|
|
2530
2654
|
assertNoEnvLeakage,
|
|
2531
2655
|
build,
|
|
2532
2656
|
buildSecurityHeaders,
|
|
2657
|
+
buildSrcSet,
|
|
2533
2658
|
checkCsrf,
|
|
2534
2659
|
combineReporters,
|
|
2535
2660
|
composeMiddleware,
|
|
@@ -2543,7 +2668,7 @@ export {
|
|
|
2543
2668
|
createRedisRateLimitStore,
|
|
2544
2669
|
createSentryReporter,
|
|
2545
2670
|
defineConfig,
|
|
2546
|
-
|
|
2671
|
+
escapeHtml,
|
|
2547
2672
|
findLayoutChain,
|
|
2548
2673
|
findLeakedEnvKeys,
|
|
2549
2674
|
findMiddlewareChain,
|
|
@@ -2573,6 +2698,7 @@ export {
|
|
|
2573
2698
|
scanPages,
|
|
2574
2699
|
scanRoutes,
|
|
2575
2700
|
setErrorReporter,
|
|
2701
|
+
setImageRemoteHosts,
|
|
2576
2702
|
verifyCsrfToken,
|
|
2577
2703
|
verifyOrigin,
|
|
2578
2704
|
withCsrfCookie,
|