@thexjs/core 0.1.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/LICENSE +21 -0
- package/dist/index.d.ts +192 -0
- package/dist/index.js +1703 -0
- package/package.json +38 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1703 @@
|
|
|
1
|
+
// src/router.ts
|
|
2
|
+
import { readdirSync, statSync, writeFileSync } from "fs";
|
|
3
|
+
import { join, relative, sep } from "path";
|
|
4
|
+
var ROUTE_FILE = /\.(tsx|ts)$/;
|
|
5
|
+
function scanPages(rootDir) {
|
|
6
|
+
return scanRoutes(rootDir).map((r) => ({ ...r, isApi: false }));
|
|
7
|
+
}
|
|
8
|
+
function scanApiDir(rootDir) {
|
|
9
|
+
return scanRoutes(rootDir).map((r) => ({
|
|
10
|
+
...r,
|
|
11
|
+
routePath: r.routePath === "/" ? "/api" : `/api${r.routePath}`,
|
|
12
|
+
isApi: true
|
|
13
|
+
}));
|
|
14
|
+
}
|
|
15
|
+
function scanRoutes(rootDir) {
|
|
16
|
+
try {
|
|
17
|
+
statSync(rootDir);
|
|
18
|
+
} catch {
|
|
19
|
+
return [];
|
|
20
|
+
}
|
|
21
|
+
const entries = [];
|
|
22
|
+
function walk(dir) {
|
|
23
|
+
for (const name of readdirSync(dir)) {
|
|
24
|
+
if (name.startsWith("_") || name.startsWith(".")) continue;
|
|
25
|
+
const full = join(dir, name);
|
|
26
|
+
const stat = statSync(full);
|
|
27
|
+
if (stat.isDirectory()) {
|
|
28
|
+
walk(full);
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
if (!ROUTE_FILE.test(name)) continue;
|
|
32
|
+
const rel = relative(rootDir, full).replace(ROUTE_FILE, "");
|
|
33
|
+
entries.push(toRouteEntry(rel, full));
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
walk(rootDir);
|
|
37
|
+
return entries;
|
|
38
|
+
}
|
|
39
|
+
function toRouteEntry(relPath, filePath) {
|
|
40
|
+
const segments = relPath.split(sep);
|
|
41
|
+
const paramNames = [];
|
|
42
|
+
const isApi = segments[0] === "api";
|
|
43
|
+
const routeSegments = segments.map((segment) => {
|
|
44
|
+
if (segment === "index") return "";
|
|
45
|
+
if (segment.startsWith("[...") && segment.endsWith("]")) {
|
|
46
|
+
const name = segment.slice(4, -1);
|
|
47
|
+
paramNames.push(name);
|
|
48
|
+
return "*";
|
|
49
|
+
}
|
|
50
|
+
if (segment.startsWith("[") && segment.endsWith("]")) {
|
|
51
|
+
const name = segment.slice(1, -1);
|
|
52
|
+
paramNames.push(name);
|
|
53
|
+
return `:${name}`;
|
|
54
|
+
}
|
|
55
|
+
return segment;
|
|
56
|
+
});
|
|
57
|
+
const joined = routeSegments.filter((s) => s.length > 0).join("/");
|
|
58
|
+
const routePath = joined.length === 0 ? "/" : `/${joined}`;
|
|
59
|
+
return { filePath, routePath, paramNames, isApi };
|
|
60
|
+
}
|
|
61
|
+
function scanLayouts(rootDir) {
|
|
62
|
+
const entries = [];
|
|
63
|
+
function walk(dir) {
|
|
64
|
+
for (const name of readdirSync(dir)) {
|
|
65
|
+
if (name.startsWith(".")) continue;
|
|
66
|
+
const full = join(dir, name);
|
|
67
|
+
const stat = statSync(full);
|
|
68
|
+
if (stat.isDirectory()) {
|
|
69
|
+
walk(full);
|
|
70
|
+
} else if (name === "_layout.tsx" || name === "_layout.ts") {
|
|
71
|
+
entries.push({ filePath: full, dirPath: dir });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
walk(rootDir);
|
|
76
|
+
return entries;
|
|
77
|
+
}
|
|
78
|
+
function scanLayoutsDir(layoutsDir) {
|
|
79
|
+
const entries = [];
|
|
80
|
+
try {
|
|
81
|
+
if (!statSync(layoutsDir).isDirectory()) return entries;
|
|
82
|
+
} catch {
|
|
83
|
+
return entries;
|
|
84
|
+
}
|
|
85
|
+
for (const name of readdirSync(layoutsDir)) {
|
|
86
|
+
if (name.startsWith(".")) continue;
|
|
87
|
+
const full = join(layoutsDir, name);
|
|
88
|
+
const stat = statSync(full);
|
|
89
|
+
if (stat.isFile() && (name.endsWith(".tsx") || name.endsWith(".ts"))) {
|
|
90
|
+
entries.push({ filePath: full, dirPath: layoutsDir });
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return entries;
|
|
94
|
+
}
|
|
95
|
+
function findLayoutChain(routeFilePath, layouts, routesDir) {
|
|
96
|
+
const routeDir = join(routeFilePath, "..");
|
|
97
|
+
const chain = [];
|
|
98
|
+
let current = routeDir;
|
|
99
|
+
while (current.startsWith(routesDir)) {
|
|
100
|
+
const layout = layouts.find((l) => l.dirPath === current);
|
|
101
|
+
if (layout) chain.unshift(layout);
|
|
102
|
+
const parent = join(current, "..");
|
|
103
|
+
if (parent === current) break;
|
|
104
|
+
current = parent;
|
|
105
|
+
}
|
|
106
|
+
return chain;
|
|
107
|
+
}
|
|
108
|
+
var NOT_FOUND_CANDIDATES = ["_404.tsx", "_404.ts"];
|
|
109
|
+
function scanNotFound(rootDir) {
|
|
110
|
+
for (const name of NOT_FOUND_CANDIDATES) {
|
|
111
|
+
const full = join(rootDir, name);
|
|
112
|
+
try {
|
|
113
|
+
statSync(full);
|
|
114
|
+
return { filePath: full };
|
|
115
|
+
} catch {
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
120
|
+
function scanMiddleware(rootDir) {
|
|
121
|
+
const entries = [];
|
|
122
|
+
function walk(dir) {
|
|
123
|
+
for (const name of readdirSync(dir)) {
|
|
124
|
+
if (name.startsWith(".")) continue;
|
|
125
|
+
const full = join(dir, name);
|
|
126
|
+
const stat = statSync(full);
|
|
127
|
+
if (stat.isDirectory()) {
|
|
128
|
+
walk(full);
|
|
129
|
+
} else if (name === "_middleware.ts" || name === "_middleware.tsx") {
|
|
130
|
+
entries.push({ filePath: full, dirPath: dir });
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
walk(rootDir);
|
|
135
|
+
return entries;
|
|
136
|
+
}
|
|
137
|
+
function findMiddlewareChain(routeFilePath, middleware, routesDir) {
|
|
138
|
+
const routeDir = join(routeFilePath, "..");
|
|
139
|
+
const chain = [];
|
|
140
|
+
let current = routeDir;
|
|
141
|
+
while (current.startsWith(routesDir)) {
|
|
142
|
+
const mw = middleware.find((m) => m.dirPath === current);
|
|
143
|
+
if (mw) chain.unshift(mw);
|
|
144
|
+
const parent = join(current, "..");
|
|
145
|
+
if (parent === current) break;
|
|
146
|
+
current = parent;
|
|
147
|
+
}
|
|
148
|
+
return chain;
|
|
149
|
+
}
|
|
150
|
+
function routePatternToRegex(routePath) {
|
|
151
|
+
const regexStr = routePath.replace(/\//g, "\\/").replace(/:(\w+)/g, "([^/]+)").replace(/\*/g, "(.+)");
|
|
152
|
+
return new RegExp(`^${regexStr}$`);
|
|
153
|
+
}
|
|
154
|
+
function extractParams(routePath, paramNames, url) {
|
|
155
|
+
const regex = routePatternToRegex(routePath);
|
|
156
|
+
const match = url.match(regex);
|
|
157
|
+
if (!match) return null;
|
|
158
|
+
const params = {};
|
|
159
|
+
let idx = 1;
|
|
160
|
+
for (const name of paramNames) {
|
|
161
|
+
const value = match[idx];
|
|
162
|
+
if (value !== void 0) {
|
|
163
|
+
params[name] = value;
|
|
164
|
+
}
|
|
165
|
+
idx++;
|
|
166
|
+
}
|
|
167
|
+
return params;
|
|
168
|
+
}
|
|
169
|
+
function generateManifestSource(routes) {
|
|
170
|
+
const routeEntries = routes.map((r) => {
|
|
171
|
+
const paramsType = r.paramNames.length === 0 ? "Record<string, never>" : `{ ${r.paramNames.map((n) => `${n}: string`).join("; ")} }`;
|
|
172
|
+
return ` "${r.routePath}": ${paramsType};`;
|
|
173
|
+
});
|
|
174
|
+
return `// Auto-generated by @thexjs/core -- do not edit
|
|
175
|
+
export type RouteMap = {
|
|
176
|
+
${routeEntries.join("\n")}
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
export function href<T extends keyof RouteMap & string>(
|
|
180
|
+
path: T,
|
|
181
|
+
...[params]: RouteMap[T] extends Record<string, never> ? [] : [RouteMap[T]]
|
|
182
|
+
): string {
|
|
183
|
+
if (!params) return path;
|
|
184
|
+
let result: string = path;
|
|
185
|
+
for (const [key, value] of Object.entries(params)) {
|
|
186
|
+
result = result.replace(new RegExp(\`:\${key}(?=/|$)\`), encodeURIComponent(String(value)));
|
|
187
|
+
}
|
|
188
|
+
result = result.replace(/\\*+$/, "");
|
|
189
|
+
return result;
|
|
190
|
+
}
|
|
191
|
+
`;
|
|
192
|
+
}
|
|
193
|
+
function writeManifest(routes, routesDir) {
|
|
194
|
+
const source = generateManifestSource(routes);
|
|
195
|
+
const manifestPath = join(routesDir, "..", "x-routes.ts");
|
|
196
|
+
writeFileSync(manifestPath, source, "utf-8");
|
|
197
|
+
return manifestPath;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// src/not-found.tsx
|
|
201
|
+
import { jsx, jsxs } from "react/jsx-runtime";
|
|
202
|
+
function DefaultNotFound(_props) {
|
|
203
|
+
return /* @__PURE__ */ jsxs(
|
|
204
|
+
"main",
|
|
205
|
+
{
|
|
206
|
+
style: {
|
|
207
|
+
maxWidth: 640,
|
|
208
|
+
margin: "4rem auto",
|
|
209
|
+
padding: "0 1rem",
|
|
210
|
+
fontFamily: "system-ui, -apple-system, sans-serif",
|
|
211
|
+
textAlign: "center"
|
|
212
|
+
},
|
|
213
|
+
children: [
|
|
214
|
+
/* @__PURE__ */ jsx("h1", { style: { fontSize: "4rem", fontWeight: 700, margin: "0 0 0.5rem", color: "#e74c3c" }, children: "404" }),
|
|
215
|
+
/* @__PURE__ */ jsx("p", { style: { fontSize: "1.125rem", color: "#666", margin: "0 0 2rem" }, children: "This page could not be found." }),
|
|
216
|
+
/* @__PURE__ */ jsx(
|
|
217
|
+
"a",
|
|
218
|
+
{
|
|
219
|
+
href: "/",
|
|
220
|
+
style: {
|
|
221
|
+
color: "#6ab0ff",
|
|
222
|
+
textDecoration: "underline",
|
|
223
|
+
fontSize: "0.875rem"
|
|
224
|
+
},
|
|
225
|
+
children: "Back to home"
|
|
226
|
+
}
|
|
227
|
+
)
|
|
228
|
+
]
|
|
229
|
+
}
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// src/render.ts
|
|
234
|
+
import { renderToReadableStream, renderToStaticMarkup, renderToString } from "react-dom/server";
|
|
235
|
+
|
|
236
|
+
// src/client-nav.ts
|
|
237
|
+
var CLIENT_NAV_SCRIPT = `(function () {
|
|
238
|
+
if (window.__xNav) return;
|
|
239
|
+
window.__xNav = true;
|
|
240
|
+
|
|
241
|
+
var cache = new Map();
|
|
242
|
+
var CACHE_LIMIT = 30;
|
|
243
|
+
|
|
244
|
+
function isEligibleLink(link) {
|
|
245
|
+
if (!link) return null;
|
|
246
|
+
if (link.hasAttribute("data-no-nav")) return null;
|
|
247
|
+
if (link.target && link.target !== "_self") return null;
|
|
248
|
+
if (link.hasAttribute("download")) return null;
|
|
249
|
+
var href = link.getAttribute("href");
|
|
250
|
+
if (!href) return null;
|
|
251
|
+
if (/^(#|mailto:|tel:|javascript:)/i.test(href)) return null;
|
|
252
|
+
|
|
253
|
+
var url;
|
|
254
|
+
try {
|
|
255
|
+
url = new URL(href, location.href);
|
|
256
|
+
} catch (e) {
|
|
257
|
+
return null;
|
|
258
|
+
}
|
|
259
|
+
if (url.origin !== location.origin) return null;
|
|
260
|
+
|
|
261
|
+
var current = new URL(location.href);
|
|
262
|
+
var samePage = url.pathname === current.pathname && url.search === current.search;
|
|
263
|
+
if (samePage && url.hash) return null;
|
|
264
|
+
|
|
265
|
+
return url;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function setLoading(isLoading) {
|
|
269
|
+
document.documentElement.classList.toggle("x-nav-loading", isLoading);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function runScripts(container) {
|
|
273
|
+
var scripts = container.querySelectorAll("script");
|
|
274
|
+
for (var i = 0; i < scripts.length; i++) {
|
|
275
|
+
var old = scripts[i];
|
|
276
|
+
var fresh = document.createElement("script");
|
|
277
|
+
for (var j = 0; j < old.attributes.length; j++) {
|
|
278
|
+
var attr = old.attributes[j];
|
|
279
|
+
fresh.setAttribute(attr.name, attr.value);
|
|
280
|
+
}
|
|
281
|
+
fresh.textContent = old.textContent;
|
|
282
|
+
old.replaceWith(fresh);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function evictIfFull() {
|
|
287
|
+
if (cache.size < CACHE_LIMIT) return;
|
|
288
|
+
var oldest = cache.keys().next().value;
|
|
289
|
+
if (oldest !== undefined) cache.delete(oldest);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function fetchPage(url) {
|
|
293
|
+
var key = url.href;
|
|
294
|
+
if (cache.has(key)) return cache.get(key);
|
|
295
|
+
var promise = fetch(url.href, { headers: { "X-X-Nav": "1" } })
|
|
296
|
+
.then(function (res) {
|
|
297
|
+
return res.text().then(function (html) {
|
|
298
|
+
var contentType = res.headers.get("content-type") || "";
|
|
299
|
+
return {
|
|
300
|
+
html: html,
|
|
301
|
+
ok: res.ok,
|
|
302
|
+
finalUrl: res.url || url.href,
|
|
303
|
+
isHtml: contentType.indexOf("text/html") !== -1,
|
|
304
|
+
};
|
|
305
|
+
});
|
|
306
|
+
})
|
|
307
|
+
.catch(function (err) {
|
|
308
|
+
cache.delete(key);
|
|
309
|
+
throw err;
|
|
310
|
+
});
|
|
311
|
+
evictIfFull();
|
|
312
|
+
cache.set(key, promise);
|
|
313
|
+
return promise;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function prefetch(url) {
|
|
317
|
+
if (cache.has(url.href)) return;
|
|
318
|
+
fetchPage(url).catch(function () {});
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function navigate(url, push) {
|
|
322
|
+
setLoading(true);
|
|
323
|
+
return fetchPage(url)
|
|
324
|
+
.then(function (entry) {
|
|
325
|
+
if (!entry.isHtml) {
|
|
326
|
+
location.href = url.href;
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
var doc = new DOMParser().parseFromString(entry.html, "text/html");
|
|
330
|
+
var newRoot = doc.getElementById("root");
|
|
331
|
+
var currentRoot = document.getElementById("root");
|
|
332
|
+
if (!newRoot || !currentRoot) {
|
|
333
|
+
location.href = url.href;
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
if (push) history.pushState({ xNav: true }, "", entry.finalUrl);
|
|
338
|
+
if (doc.title) document.title = doc.title;
|
|
339
|
+
currentRoot.innerHTML = newRoot.innerHTML;
|
|
340
|
+
runScripts(currentRoot);
|
|
341
|
+
|
|
342
|
+
if (url.hash) {
|
|
343
|
+
var target = document.getElementById(url.hash.slice(1));
|
|
344
|
+
if (target) {
|
|
345
|
+
target.scrollIntoView();
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
window.scrollTo(0, 0);
|
|
350
|
+
})
|
|
351
|
+
.catch(function () {
|
|
352
|
+
location.href = url.href;
|
|
353
|
+
})
|
|
354
|
+
.finally(function () {
|
|
355
|
+
setLoading(false);
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
document.addEventListener("click", function (event) {
|
|
360
|
+
if (event.defaultPrevented || event.button !== 0) return;
|
|
361
|
+
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
|
|
362
|
+
|
|
363
|
+
var link = event.target && event.target.closest ? event.target.closest("a[href]") : null;
|
|
364
|
+
var url = isEligibleLink(link);
|
|
365
|
+
if (!url) return;
|
|
366
|
+
|
|
367
|
+
event.preventDefault();
|
|
368
|
+
if (url.href === location.href) return;
|
|
369
|
+
navigate(url, true);
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
document.addEventListener(
|
|
373
|
+
"mouseover",
|
|
374
|
+
function (event) {
|
|
375
|
+
var link = event.target && event.target.closest ? event.target.closest("a[href]") : null;
|
|
376
|
+
var url = isEligibleLink(link);
|
|
377
|
+
if (url) prefetch(url);
|
|
378
|
+
},
|
|
379
|
+
{ passive: true },
|
|
380
|
+
);
|
|
381
|
+
|
|
382
|
+
window.addEventListener("popstate", function () {
|
|
383
|
+
navigate(new URL(location.href), false);
|
|
384
|
+
});
|
|
385
|
+
|
|
386
|
+
var style = document.createElement("style");
|
|
387
|
+
style.textContent = [
|
|
388
|
+
".x-nav-loading{cursor:progress}",
|
|
389
|
+
".x-nav-loading::after{content:'';position:fixed;top:0;left:0;height:2px;width:100%;",
|
|
390
|
+
"background:var(--x-accent,#6ab0ff);z-index:9999;animation:x-nav-progress .8s ease-in-out infinite}",
|
|
391
|
+
"@keyframes x-nav-progress{0%{transform:translateX(-100%)}50%{transform:translateX(0)}100%{transform:translateX(100%)}}",
|
|
392
|
+
].join("");
|
|
393
|
+
document.head.appendChild(style);
|
|
394
|
+
})();`;
|
|
395
|
+
|
|
396
|
+
// src/live-reload.ts
|
|
397
|
+
var LIVE_RELOAD_SCRIPT = `
|
|
398
|
+
(function(){var s=new EventSource("/__x/reload");s.addEventListener("reload",function(){s.close();window.location.reload()});s.addEventListener("hb",function(){});s.onerror=function(){s.close()}})();
|
|
399
|
+
`;
|
|
400
|
+
|
|
401
|
+
// src/render.ts
|
|
402
|
+
function escapeHtml(s) {
|
|
403
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
404
|
+
}
|
|
405
|
+
function escapeJsonForScript(s) {
|
|
406
|
+
return s.replace(/<\//g, "<\\/");
|
|
407
|
+
}
|
|
408
|
+
function buildHeadExtras(stylesheet) {
|
|
409
|
+
return stylesheet ? `
|
|
410
|
+
<link rel="stylesheet" href="${escapeHtml(stylesheet)}" />` : "";
|
|
411
|
+
}
|
|
412
|
+
function buildNavScriptTag(clientNav) {
|
|
413
|
+
return clientNav === false ? "" : `
|
|
414
|
+
<script>${CLIENT_NAV_SCRIPT}</script>`;
|
|
415
|
+
}
|
|
416
|
+
function buildLiveReloadTag(liveReload) {
|
|
417
|
+
return liveReload ? `
|
|
418
|
+
<script>${LIVE_RELOAD_SCRIPT}</script>` : "";
|
|
419
|
+
}
|
|
420
|
+
function htmlShell(title, headExtras, propsScript, scripts, bodySlot, navScriptTag, liveReloadTag) {
|
|
421
|
+
const finalScripts = scripts ?? "";
|
|
422
|
+
const inside = `${bodySlot}${propsScript ? `
|
|
423
|
+
${propsScript}` : ""}${finalScripts ? `
|
|
424
|
+
${finalScripts}` : ""}`;
|
|
425
|
+
return `<!DOCTYPE html>
|
|
426
|
+
<html lang="en">
|
|
427
|
+
<head>
|
|
428
|
+
<meta charset="UTF-8" />
|
|
429
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
430
|
+
<title>${escapeHtml(title)}</title>${headExtras}
|
|
431
|
+
</head>
|
|
432
|
+
<body>
|
|
433
|
+
<div id="root">${inside}</div>
|
|
434
|
+
${navScriptTag ? ` ${navScriptTag}
|
|
435
|
+
` : ""}${liveReloadTag} </body>
|
|
436
|
+
</html>`;
|
|
437
|
+
}
|
|
438
|
+
function renderPage(node, options = {}) {
|
|
439
|
+
const { islandScripts, islandProps } = options;
|
|
440
|
+
const title = options.title ?? "x app";
|
|
441
|
+
const body = renderToString(node);
|
|
442
|
+
const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
|
|
443
|
+
const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json">${propsJson}</script>` : "";
|
|
444
|
+
const islandScriptsHtml = islandScripts?.map((src) => `<script type="module" data-island-script src="${escapeHtml(src)}"></script>`).join("\n ");
|
|
445
|
+
return htmlShell(
|
|
446
|
+
title,
|
|
447
|
+
buildHeadExtras(options.stylesheet),
|
|
448
|
+
propsScript,
|
|
449
|
+
islandScriptsHtml,
|
|
450
|
+
body,
|
|
451
|
+
buildNavScriptTag(options.clientNav),
|
|
452
|
+
buildLiveReloadTag(options.liveReload)
|
|
453
|
+
);
|
|
454
|
+
}
|
|
455
|
+
function renderStaticPage(node, options = {}) {
|
|
456
|
+
const { islandScripts, islandProps } = options;
|
|
457
|
+
const title = options.title ?? "x app";
|
|
458
|
+
const body = renderToStaticMarkup(node);
|
|
459
|
+
const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
|
|
460
|
+
const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json">${propsJson}</script>` : "";
|
|
461
|
+
const islandScriptsHtml = islandScripts?.map((src) => `<script type="module" data-island-script src="${escapeHtml(src)}"></script>`).join("\n ");
|
|
462
|
+
return htmlShell(
|
|
463
|
+
title,
|
|
464
|
+
buildHeadExtras(options.stylesheet),
|
|
465
|
+
propsScript,
|
|
466
|
+
islandScriptsHtml,
|
|
467
|
+
body,
|
|
468
|
+
buildNavScriptTag(options.clientNav),
|
|
469
|
+
buildLiveReloadTag(options.liveReload)
|
|
470
|
+
);
|
|
471
|
+
}
|
|
472
|
+
async function renderStreamingPage(node, options = {}) {
|
|
473
|
+
const { islandScripts, islandProps } = options;
|
|
474
|
+
const title = escapeHtml(options.title ?? "x app");
|
|
475
|
+
const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
|
|
476
|
+
const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json">${propsJson}</script>` : "";
|
|
477
|
+
const islandScriptsHtml = islandScripts?.map((src) => `<script type="module" data-island-script src="${escapeHtml(src)}"></script>`).join("\n ");
|
|
478
|
+
const navScriptTag = buildNavScriptTag(options.clientNav);
|
|
479
|
+
const liveReloadTag = buildLiveReloadTag(options.liveReload);
|
|
480
|
+
const headExtras = buildHeadExtras(options.stylesheet);
|
|
481
|
+
const rootFooter = `${propsScript ? ` ${propsScript}
|
|
482
|
+
` : ""}${islandScriptsHtml ? ` ${islandScriptsHtml}
|
|
483
|
+
` : ""}`;
|
|
484
|
+
const footer = `</div>${navScriptTag}
|
|
485
|
+
${liveReloadTag} </body>
|
|
486
|
+
</html>`;
|
|
487
|
+
const reactStream = await renderToReadableStream(node, {
|
|
488
|
+
onError(err) {
|
|
489
|
+
console.error("[x] render error:", err);
|
|
490
|
+
}
|
|
491
|
+
});
|
|
492
|
+
const encoder = new TextEncoder();
|
|
493
|
+
const header = `<!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>${title}</title>${headExtras}
|
|
499
|
+
</head>
|
|
500
|
+
<body>
|
|
501
|
+
<div id="root">`;
|
|
502
|
+
return new ReadableStream({
|
|
503
|
+
async start(controller) {
|
|
504
|
+
controller.enqueue(encoder.encode(header));
|
|
505
|
+
const reader = reactStream.getReader();
|
|
506
|
+
async function pump() {
|
|
507
|
+
try {
|
|
508
|
+
const { done, value } = await reader.read();
|
|
509
|
+
if (done) {
|
|
510
|
+
controller.enqueue(encoder.encode(`${rootFooter}
|
|
511
|
+
${footer}`));
|
|
512
|
+
controller.close();
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
controller.enqueue(value);
|
|
516
|
+
await pump();
|
|
517
|
+
} catch (err) {
|
|
518
|
+
console.error("[x] stream read error:", err);
|
|
519
|
+
controller.enqueue(
|
|
520
|
+
encoder.encode(
|
|
521
|
+
`${rootFooter}<div style="color:red;padding:1em;margin:1rem">Render error: ${err instanceof Error ? err.message : "Unknown"}</div>
|
|
522
|
+
${footer}`
|
|
523
|
+
)
|
|
524
|
+
);
|
|
525
|
+
controller.close();
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
await pump();
|
|
529
|
+
}
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
// src/createApp.ts
|
|
534
|
+
import { existsSync, watch } from "fs";
|
|
535
|
+
import { join as join4, resolve, sep as sep3 } from "path";
|
|
536
|
+
import { createElement } from "react";
|
|
537
|
+
|
|
538
|
+
// src/content.ts
|
|
539
|
+
import { readFileSync, readdirSync as readdirSync2, statSync as statSync2 } from "fs";
|
|
540
|
+
import { join as join2, relative as relative2, sep as sep2 } from "path";
|
|
541
|
+
var CONTENT_FILE = /\.(md|mdx)$/;
|
|
542
|
+
function scanContent(rootDir) {
|
|
543
|
+
const entries = [];
|
|
544
|
+
function walk(dir) {
|
|
545
|
+
for (const name of readdirSync2(dir)) {
|
|
546
|
+
if (name.startsWith(".")) continue;
|
|
547
|
+
const full = join2(dir, name);
|
|
548
|
+
const stat = statSync2(full);
|
|
549
|
+
if (stat.isDirectory()) {
|
|
550
|
+
walk(full);
|
|
551
|
+
continue;
|
|
552
|
+
}
|
|
553
|
+
if (!CONTENT_FILE.test(name)) continue;
|
|
554
|
+
const raw = readFileSync(full, "utf-8");
|
|
555
|
+
const { frontmatter, body } = parseFrontmatter(raw);
|
|
556
|
+
const rel = relative2(rootDir, full).replace(CONTENT_FILE, "");
|
|
557
|
+
const slug = name.replace(CONTENT_FILE, "");
|
|
558
|
+
const routePath = toContentRoutePath(rel);
|
|
559
|
+
entries.push({ filePath: full, routePath, slug, frontmatter, body });
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
walk(rootDir);
|
|
563
|
+
return entries;
|
|
564
|
+
}
|
|
565
|
+
function toContentRoutePath(relPath) {
|
|
566
|
+
const segments = relPath.split(sep2).filter((s) => s !== "index");
|
|
567
|
+
const joined = segments.join("/");
|
|
568
|
+
return joined.length === 0 ? "/" : `/${joined}`;
|
|
569
|
+
}
|
|
570
|
+
function parseFrontmatter(raw) {
|
|
571
|
+
const trimmed = raw.trimStart();
|
|
572
|
+
if (!trimmed.startsWith("---")) {
|
|
573
|
+
return { frontmatter: {}, body: trimmed };
|
|
574
|
+
}
|
|
575
|
+
const endIndex = trimmed.indexOf("---", 3);
|
|
576
|
+
if (endIndex === -1) {
|
|
577
|
+
return { frontmatter: {}, body: trimmed };
|
|
578
|
+
}
|
|
579
|
+
const fmRaw = trimmed.slice(3, endIndex).trim();
|
|
580
|
+
const body = trimmed.slice(endIndex + 3).trimStart();
|
|
581
|
+
const frontmatter = parseYamlLines(fmRaw);
|
|
582
|
+
return { frontmatter, body };
|
|
583
|
+
}
|
|
584
|
+
function parseYamlLines(raw) {
|
|
585
|
+
const result = {};
|
|
586
|
+
for (const line of raw.split("\n")) {
|
|
587
|
+
const colon = line.indexOf(":");
|
|
588
|
+
if (colon === -1) continue;
|
|
589
|
+
const key = line.slice(0, colon).trim();
|
|
590
|
+
let value = line.slice(colon + 1).trim();
|
|
591
|
+
if (typeof value === "string" && value.startsWith('"') && value.endsWith('"')) {
|
|
592
|
+
value = value.slice(1, -1);
|
|
593
|
+
}
|
|
594
|
+
if (typeof value === "string" && value.startsWith("[")) {
|
|
595
|
+
try {
|
|
596
|
+
value = JSON.parse(value);
|
|
597
|
+
} catch {
|
|
598
|
+
value = value.slice(1, -1).split(",").map((s) => s.trim()).filter(Boolean);
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
result[key] = value;
|
|
602
|
+
}
|
|
603
|
+
return result;
|
|
604
|
+
}
|
|
605
|
+
function escapeHtml2(s) {
|
|
606
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
607
|
+
}
|
|
608
|
+
function renderMarkdown(md) {
|
|
609
|
+
const inlineCodes = [];
|
|
610
|
+
let html = md.replace(/^### (.+)$/gm, "<h3>$1</h3>").replace(/^## (.+)$/gm, "<h2>$1</h2>").replace(/^# (.+)$/gm, "<h1>$1</h1>").replace(
|
|
611
|
+
/`{3}(\w*)\n([\s\S]*?)`{3}/gm,
|
|
612
|
+
(_m, _lang, code) => `<pre><code>${escapeHtml2(code.trim())}</code></pre>`
|
|
613
|
+
).replace(/`([^`]+)`/g, (_m, code) => {
|
|
614
|
+
inlineCodes.push(code);
|
|
615
|
+
return `__X_CODE_${inlineCodes.length - 1}__`;
|
|
616
|
+
}).replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>").replace(/\*([^*]+)\*/g, "<em>$1</em>").replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>').replace(/__X_CODE_(\d+)__/g, (_m, i) => `<code>${inlineCodes[Number.parseInt(i)]}</code>`);
|
|
617
|
+
const blocks = html.split(/\n\n+/);
|
|
618
|
+
html = blocks.map((b) => {
|
|
619
|
+
const t = b.trim();
|
|
620
|
+
if (!t) return "";
|
|
621
|
+
if (t.startsWith("<h") || t.startsWith("<pre") || t.startsWith("<ul") || t.startsWith("<ol"))
|
|
622
|
+
return t;
|
|
623
|
+
return `<p>${t}</p>`;
|
|
624
|
+
}).join("\n");
|
|
625
|
+
return html;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
// src/error-overlay.ts
|
|
629
|
+
function escapeHtml3(s) {
|
|
630
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
631
|
+
}
|
|
632
|
+
function renderErrorOverlay(error) {
|
|
633
|
+
const message = error instanceof Error ? error.message : "Unknown error";
|
|
634
|
+
const stack = error instanceof Error ? error.stack ?? "" : "";
|
|
635
|
+
const frames = stack.split("\n").slice(1).map((line) => `<span class="frame">${escapeHtml3(line.trim())}</span>`).join("\n");
|
|
636
|
+
return `<!DOCTYPE html>
|
|
637
|
+
<html lang="en">
|
|
638
|
+
<head>
|
|
639
|
+
<meta charset="UTF-8" />
|
|
640
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
641
|
+
<title>Server Error</title>
|
|
642
|
+
<style>
|
|
643
|
+
* { margin: 0; padding: 0; box-sizing: border-box; }
|
|
644
|
+
body {
|
|
645
|
+
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
|
646
|
+
background: #1a1a2e;
|
|
647
|
+
color: #e0e0e0;
|
|
648
|
+
min-height: 100vh;
|
|
649
|
+
display: flex;
|
|
650
|
+
flex-direction: column;
|
|
651
|
+
}
|
|
652
|
+
.overlay {
|
|
653
|
+
flex: 1;
|
|
654
|
+
padding: 40px 24px;
|
|
655
|
+
max-width: 900px;
|
|
656
|
+
margin: 0 auto;
|
|
657
|
+
width: 100%;
|
|
658
|
+
}
|
|
659
|
+
.header { margin-bottom: 32px; }
|
|
660
|
+
.badge {
|
|
661
|
+
display: inline-block;
|
|
662
|
+
background: #e74c3c;
|
|
663
|
+
color: #fff;
|
|
664
|
+
font-size: 11px;
|
|
665
|
+
font-weight: 700;
|
|
666
|
+
letter-spacing: 0.05em;
|
|
667
|
+
text-transform: uppercase;
|
|
668
|
+
padding: 3px 10px;
|
|
669
|
+
border-radius: 4px;
|
|
670
|
+
margin-bottom: 12px;
|
|
671
|
+
}
|
|
672
|
+
h1 {
|
|
673
|
+
font-size: 22px;
|
|
674
|
+
font-weight: 600;
|
|
675
|
+
color: #f0f0f0;
|
|
676
|
+
line-height: 1.3;
|
|
677
|
+
}
|
|
678
|
+
.message-box {
|
|
679
|
+
background: #2a2a4a;
|
|
680
|
+
border: 1px solid #3a3a5a;
|
|
681
|
+
border-radius: 8px;
|
|
682
|
+
padding: 20px;
|
|
683
|
+
margin-bottom: 24px;
|
|
684
|
+
font-size: 15px;
|
|
685
|
+
word-break: break-word;
|
|
686
|
+
}
|
|
687
|
+
.message-box .label {
|
|
688
|
+
font-size: 11px;
|
|
689
|
+
font-weight: 600;
|
|
690
|
+
text-transform: uppercase;
|
|
691
|
+
letter-spacing: 0.05em;
|
|
692
|
+
color: #888;
|
|
693
|
+
margin-bottom: 8px;
|
|
694
|
+
}
|
|
695
|
+
.message-box .message {
|
|
696
|
+
color: #ff6b6b;
|
|
697
|
+
font-family: "SF Mono", "Fira Code", "Fira Mono", monospace;
|
|
698
|
+
font-size: 14px;
|
|
699
|
+
white-space: pre-wrap;
|
|
700
|
+
}
|
|
701
|
+
.stack-section { margin-bottom: 24px; }
|
|
702
|
+
.stack-section .label {
|
|
703
|
+
font-size: 11px;
|
|
704
|
+
font-weight: 600;
|
|
705
|
+
text-transform: uppercase;
|
|
706
|
+
letter-spacing: 0.05em;
|
|
707
|
+
color: #888;
|
|
708
|
+
margin-bottom: 12px;
|
|
709
|
+
}
|
|
710
|
+
.frame {
|
|
711
|
+
display: block;
|
|
712
|
+
padding: 6px 12px;
|
|
713
|
+
font-family: "SF Mono", "Fira Code", "Fira Mono", monospace;
|
|
714
|
+
font-size: 12px;
|
|
715
|
+
color: #b0b0d0;
|
|
716
|
+
line-height: 1.6;
|
|
717
|
+
border-left: 2px solid #3a3a5a;
|
|
718
|
+
margin-bottom: 2px;
|
|
719
|
+
}
|
|
720
|
+
.frame:first-child { border-left-color: #e74c3c; }
|
|
721
|
+
.hint {
|
|
722
|
+
font-size: 13px;
|
|
723
|
+
color: #888;
|
|
724
|
+
border-top: 1px solid #3a3a5a;
|
|
725
|
+
padding-top: 20px;
|
|
726
|
+
margin-top: 8px;
|
|
727
|
+
}
|
|
728
|
+
.hint a { color: #6ab0ff; }
|
|
729
|
+
</style>
|
|
730
|
+
</head>
|
|
731
|
+
<body>
|
|
732
|
+
<div class="overlay">
|
|
733
|
+
<div class="header">
|
|
734
|
+
<div class="badge">Server Error</div>
|
|
735
|
+
<h1>Unhandled Error During Render</h1>
|
|
736
|
+
</div>
|
|
737
|
+
<div class="message-box">
|
|
738
|
+
<div class="label">Error</div>
|
|
739
|
+
<div class="message">${escapeHtml3(message)}</div>
|
|
740
|
+
</div>
|
|
741
|
+
${stack ? `<div class="stack-section"><div class="label">Stack Trace</div>${frames}</div>` : ""}
|
|
742
|
+
<div class="hint">
|
|
743
|
+
Fix the error and save the file. In development mode, the server will reload automatically.
|
|
744
|
+
</div>
|
|
745
|
+
</div>
|
|
746
|
+
</body>
|
|
747
|
+
</html>`;
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
// src/middleware.ts
|
|
751
|
+
function composeMiddleware(fns, handler) {
|
|
752
|
+
return async (ctx, _next) => {
|
|
753
|
+
let index = -1;
|
|
754
|
+
const dispatch = async (i) => {
|
|
755
|
+
if (i <= index) throw new Error("next() called multiple times");
|
|
756
|
+
index = i;
|
|
757
|
+
const fn = fns[i];
|
|
758
|
+
if (fn) {
|
|
759
|
+
return fn(ctx, () => dispatch(i + 1));
|
|
760
|
+
}
|
|
761
|
+
return handler(ctx);
|
|
762
|
+
};
|
|
763
|
+
return dispatch(0);
|
|
764
|
+
};
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
// src/server-functions.ts
|
|
768
|
+
import { writeFileSync as writeFileSync2 } from "fs";
|
|
769
|
+
import { join as join3 } from "path";
|
|
770
|
+
function generateServerFunctionClient(routeFilePath, fnNames, endpointBase) {
|
|
771
|
+
const fnCalls = fnNames.map(
|
|
772
|
+
(name) => `
|
|
773
|
+
export async function ${name}(...args: unknown[]): Promise<unknown> {
|
|
774
|
+
const res = await fetch("${endpointBase}/${name}", {
|
|
775
|
+
method: "POST",
|
|
776
|
+
headers: { "Content-Type": "application/json" },
|
|
777
|
+
body: JSON.stringify(args),
|
|
778
|
+
});
|
|
779
|
+
if (!res.ok) throw new Error(await res.text());
|
|
780
|
+
return res.json();
|
|
781
|
+
}`
|
|
782
|
+
).join("\n");
|
|
783
|
+
return `// Auto-generated client for server functions in ${routeFilePath}
|
|
784
|
+
// Do not edit.
|
|
785
|
+
|
|
786
|
+
${fnCalls}
|
|
787
|
+
`;
|
|
788
|
+
}
|
|
789
|
+
var ACTION_ROUTES = [];
|
|
790
|
+
function resetServerFunctions() {
|
|
791
|
+
ACTION_ROUTES.length = 0;
|
|
792
|
+
}
|
|
793
|
+
function registerServerFunctions(routePath, paramNames, fns) {
|
|
794
|
+
const fnMap = new Map(Object.entries(fns));
|
|
795
|
+
const existing = ACTION_ROUTES.find((e) => e.routePath === routePath);
|
|
796
|
+
if (existing) {
|
|
797
|
+
for (const [name, fn] of fnMap) {
|
|
798
|
+
existing.fns.set(name, fn);
|
|
799
|
+
}
|
|
800
|
+
} else {
|
|
801
|
+
ACTION_ROUTES.push({ routePath, paramNames, fns: fnMap });
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
function getServerFunctionHandler() {
|
|
805
|
+
return async (req) => {
|
|
806
|
+
if (req.method !== "POST") return null;
|
|
807
|
+
const url = new URL(req.url);
|
|
808
|
+
if (!url.pathname.startsWith("/__x/actions/")) return null;
|
|
809
|
+
const parts = url.pathname.replace("/__x/actions/", "").split("/");
|
|
810
|
+
if (parts.length < 2) return null;
|
|
811
|
+
const actionName = parts.pop();
|
|
812
|
+
if (!actionName) return null;
|
|
813
|
+
const concretePath = `/${parts.join("/")}`;
|
|
814
|
+
for (const entry of ACTION_ROUTES) {
|
|
815
|
+
const params = extractActionParams(entry.routePath, entry.paramNames, concretePath);
|
|
816
|
+
if (params === null) continue;
|
|
817
|
+
const fn = entry.fns.get(actionName);
|
|
818
|
+
if (!fn) return new Response("Function not found", { status: 404 });
|
|
819
|
+
let args = [];
|
|
820
|
+
try {
|
|
821
|
+
const body = await req.json();
|
|
822
|
+
args = Array.isArray(body) ? body : [body];
|
|
823
|
+
} catch {
|
|
824
|
+
return new Response("Invalid request body", { status: 400 });
|
|
825
|
+
}
|
|
826
|
+
try {
|
|
827
|
+
const result = await fn(...args);
|
|
828
|
+
return Response.json(result);
|
|
829
|
+
} catch (err) {
|
|
830
|
+
const message = err instanceof Error ? err.message : "Internal error";
|
|
831
|
+
return new Response(message, { status: 500 });
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
return new Response("Not found", { status: 404 });
|
|
835
|
+
};
|
|
836
|
+
}
|
|
837
|
+
function extractActionParams(routePath, paramNames, url) {
|
|
838
|
+
const regex = routePatternToRegex(routePath);
|
|
839
|
+
const match = url.match(regex);
|
|
840
|
+
if (!match) return null;
|
|
841
|
+
const params = {};
|
|
842
|
+
let idx = 1;
|
|
843
|
+
for (const name of paramNames) {
|
|
844
|
+
const value = match[idx];
|
|
845
|
+
if (value !== void 0) {
|
|
846
|
+
params[name] = value;
|
|
847
|
+
}
|
|
848
|
+
idx++;
|
|
849
|
+
}
|
|
850
|
+
return params;
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
// src/createApp.ts
|
|
854
|
+
var HTTP_METHODS = /* @__PURE__ */ new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);
|
|
855
|
+
function projectRootFromRoutesDir(routesDir) {
|
|
856
|
+
return join4(routesDir, "..", "..");
|
|
857
|
+
}
|
|
858
|
+
function resolvePublicAsset(publicDir, pathname) {
|
|
859
|
+
let decoded;
|
|
860
|
+
try {
|
|
861
|
+
decoded = decodeURIComponent(pathname);
|
|
862
|
+
} catch {
|
|
863
|
+
return null;
|
|
864
|
+
}
|
|
865
|
+
const target = resolve(join4(publicDir, decoded));
|
|
866
|
+
const root = resolve(publicDir);
|
|
867
|
+
if (target !== root && !target.startsWith(root + sep3)) return null;
|
|
868
|
+
return target;
|
|
869
|
+
}
|
|
870
|
+
async function serveStaticAsset(publicDir, req) {
|
|
871
|
+
if (!publicDir) return null;
|
|
872
|
+
if (req.method !== "GET" && req.method !== "HEAD") return null;
|
|
873
|
+
const pathname = new URL(req.url).pathname;
|
|
874
|
+
if (pathname === "/" || pathname.endsWith("/")) return null;
|
|
875
|
+
const filePath = resolvePublicAsset(publicDir, pathname);
|
|
876
|
+
if (!filePath) return null;
|
|
877
|
+
const file = Bun.file(filePath);
|
|
878
|
+
if (!await file.exists()) return null;
|
|
879
|
+
return new Response(file);
|
|
880
|
+
}
|
|
881
|
+
function wrapWithLayouts(Component, params, loaderData, layoutModules) {
|
|
882
|
+
let content = createElement(Component, { params, loaderData });
|
|
883
|
+
for (const Layout of [...layoutModules].reverse()) {
|
|
884
|
+
content = createElement(Layout, null, content);
|
|
885
|
+
}
|
|
886
|
+
return content;
|
|
887
|
+
}
|
|
888
|
+
function renderContentPage(content, stylesheet, dev = false) {
|
|
889
|
+
const title = content.frontmatter.title ?? content.slug;
|
|
890
|
+
const bodyHtml = renderMarkdown(content.body);
|
|
891
|
+
const body = renderPage(
|
|
892
|
+
createElement(
|
|
893
|
+
"article",
|
|
894
|
+
null,
|
|
895
|
+
content.frontmatter.title ? createElement("h1", null, content.frontmatter.title) : null,
|
|
896
|
+
createElement("div", {
|
|
897
|
+
// biome-ignore lint/security/noDangerouslySetInnerHtml: body is markdown rendered to HTML
|
|
898
|
+
dangerouslySetInnerHTML: { __html: bodyHtml }
|
|
899
|
+
})
|
|
900
|
+
),
|
|
901
|
+
{ title, stylesheet, liveReload: dev }
|
|
902
|
+
);
|
|
903
|
+
return body;
|
|
904
|
+
}
|
|
905
|
+
function defineConfig(config) {
|
|
906
|
+
return config;
|
|
907
|
+
}
|
|
908
|
+
function importDev(path, dev) {
|
|
909
|
+
return dev ? import(`${path}?t=${Date.now()}`) : import(path);
|
|
910
|
+
}
|
|
911
|
+
async function createApp(options) {
|
|
912
|
+
const dev = options.development ?? false;
|
|
913
|
+
const primaryDir = options.pagesDir || options.routesDir || "src/pages";
|
|
914
|
+
let handlers = [];
|
|
915
|
+
let contentHandlers = [];
|
|
916
|
+
let publicDir = null;
|
|
917
|
+
let stylesheetHref;
|
|
918
|
+
let notFoundComponent = DefaultNotFound;
|
|
919
|
+
let notFoundLayout;
|
|
920
|
+
const serverFnHandler = getServerFunctionHandler();
|
|
921
|
+
const staticCache = /* @__PURE__ */ new Map();
|
|
922
|
+
async function renderNotFound(req) {
|
|
923
|
+
const content = notFoundLayout ? createElement(notFoundLayout, null, createElement(notFoundComponent, { params: {} })) : createElement(notFoundComponent, { params: {} });
|
|
924
|
+
const html = renderPage(content, {
|
|
925
|
+
title: "404 \u2014 Not Found",
|
|
926
|
+
stylesheet: stylesheetHref,
|
|
927
|
+
liveReload: dev
|
|
928
|
+
});
|
|
929
|
+
return new Response(html, {
|
|
930
|
+
status: 404,
|
|
931
|
+
headers: { "Content-Type": "text/html; charset=utf-8" }
|
|
932
|
+
});
|
|
933
|
+
}
|
|
934
|
+
async function buildHandlers() {
|
|
935
|
+
resetServerFunctions();
|
|
936
|
+
const pagesDir = primaryDir;
|
|
937
|
+
const apiDir = options.apiDir;
|
|
938
|
+
const layoutsDir = options.layoutsDir || pagesDir;
|
|
939
|
+
let found = scanPages(pagesDir);
|
|
940
|
+
const apiFound = [];
|
|
941
|
+
if (apiDir && existsSync(apiDir)) {
|
|
942
|
+
apiFound.push(...scanApiDir(apiDir));
|
|
943
|
+
}
|
|
944
|
+
const legacyApiDir = join4(pagesDir, "api");
|
|
945
|
+
if (existsSync(legacyApiDir) && legacyApiDir !== apiDir) {
|
|
946
|
+
apiFound.push(...scanApiDir(legacyApiDir));
|
|
947
|
+
}
|
|
948
|
+
found = found.filter((r) => !r.isApi);
|
|
949
|
+
found.push(...apiFound);
|
|
950
|
+
const dedicatedLayouts = options.layoutsDir ? scanLayoutsDir(options.layoutsDir) : [];
|
|
951
|
+
const nestedLayouts = scanLayouts(pagesDir);
|
|
952
|
+
const layouts = [...dedicatedLayouts, ...nestedLayouts];
|
|
953
|
+
const middlewareEntries = scanMiddleware(pagesDir);
|
|
954
|
+
if (options.actionsDir) {
|
|
955
|
+
const actionFiles = scanRoutes(options.actionsDir);
|
|
956
|
+
for (const actionFile of actionFiles) {
|
|
957
|
+
const mod = await importDev(actionFile.filePath, dev);
|
|
958
|
+
const segments = actionFile.routePath.split("/").filter(Boolean);
|
|
959
|
+
const fileName = segments[segments.length - 1] ?? "";
|
|
960
|
+
const parentPath = fileName === "index" || !fileName ? actionFile.routePath : `/${segments.slice(0, -1).join("/")}`;
|
|
961
|
+
const actions = mod.actions;
|
|
962
|
+
if (actions) {
|
|
963
|
+
registerServerFunctions(parentPath, actionFile.paramNames, actions);
|
|
964
|
+
}
|
|
965
|
+
for (const [key, value] of Object.entries(mod)) {
|
|
966
|
+
if (key === "default" || key === "actions" || typeof value !== "function") continue;
|
|
967
|
+
registerServerFunctions(parentPath, actionFile.paramNames, {
|
|
968
|
+
[key]: value
|
|
969
|
+
});
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
const projectRoot = projectRootFromRoutesDir(pagesDir);
|
|
974
|
+
const candidatePublicDir = join4(projectRoot, "public");
|
|
975
|
+
publicDir = existsSync(candidatePublicDir) ? candidatePublicDir : null;
|
|
976
|
+
stylesheetHref = publicDir && existsSync(join4(publicDir, "styles.css")) ? "/styles.css" : void 0;
|
|
977
|
+
const notFoundEntry = scanNotFound(pagesDir);
|
|
978
|
+
if (notFoundEntry) {
|
|
979
|
+
const mod = await importDev(notFoundEntry.filePath, dev);
|
|
980
|
+
notFoundComponent = mod.default ?? DefaultNotFound;
|
|
981
|
+
} else {
|
|
982
|
+
notFoundComponent = DefaultNotFound;
|
|
983
|
+
}
|
|
984
|
+
const rootLayout = layouts.find((l) => l.dirPath === pagesDir);
|
|
985
|
+
if (rootLayout) {
|
|
986
|
+
const layoutMod = await importDev(rootLayout.filePath, dev);
|
|
987
|
+
notFoundLayout = layoutMod.default;
|
|
988
|
+
} else {
|
|
989
|
+
notFoundLayout = void 0;
|
|
990
|
+
}
|
|
991
|
+
if (options.development) {
|
|
992
|
+
writeManifest(found, pagesDir);
|
|
993
|
+
}
|
|
994
|
+
const loaded = [];
|
|
995
|
+
for (const route of found) {
|
|
996
|
+
const mod = await importDev(route.filePath, dev);
|
|
997
|
+
if (route.isApi) {
|
|
998
|
+
const methodHandlers = {};
|
|
999
|
+
for (const method of HTTP_METHODS) {
|
|
1000
|
+
if (typeof mod[method] === "function") {
|
|
1001
|
+
methodHandlers[method] = mod[method];
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
const actions2 = mod.actions;
|
|
1005
|
+
if (actions2) {
|
|
1006
|
+
registerServerFunctions(route.routePath, route.paramNames, actions2);
|
|
1007
|
+
}
|
|
1008
|
+
loaded.push({
|
|
1009
|
+
entry: route,
|
|
1010
|
+
mode: "server",
|
|
1011
|
+
revalidate: void 0,
|
|
1012
|
+
handler: async (req) => {
|
|
1013
|
+
try {
|
|
1014
|
+
const method = req.method;
|
|
1015
|
+
const handlerFn = methodHandlers[method];
|
|
1016
|
+
if (handlerFn) {
|
|
1017
|
+
const result = await handlerFn(req);
|
|
1018
|
+
if (result instanceof Response) return result;
|
|
1019
|
+
if (result === void 0 || result === null) {
|
|
1020
|
+
return new Response("OK", { status: 200 });
|
|
1021
|
+
}
|
|
1022
|
+
return Response.json(result);
|
|
1023
|
+
}
|
|
1024
|
+
return new Response(`Method ${method} not allowed`, { status: 405 });
|
|
1025
|
+
} catch (err) {
|
|
1026
|
+
console.error("[x] API handler error:", err);
|
|
1027
|
+
if (options.development) {
|
|
1028
|
+
return new Response(renderErrorOverlay(err), {
|
|
1029
|
+
status: 500,
|
|
1030
|
+
headers: { "Content-Type": "text/html; charset=utf-8" }
|
|
1031
|
+
});
|
|
1032
|
+
}
|
|
1033
|
+
return new Response("Internal server error", { status: 500 });
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
});
|
|
1037
|
+
continue;
|
|
1038
|
+
}
|
|
1039
|
+
const actions = mod.actions;
|
|
1040
|
+
if (actions) {
|
|
1041
|
+
registerServerFunctions(route.routePath, route.paramNames, actions);
|
|
1042
|
+
}
|
|
1043
|
+
const Component = mod.default;
|
|
1044
|
+
if (!Component) {
|
|
1045
|
+
if (!actions) {
|
|
1046
|
+
console.warn(`[x] ${route.filePath} has no default export -- skipping`);
|
|
1047
|
+
}
|
|
1048
|
+
continue;
|
|
1049
|
+
}
|
|
1050
|
+
const mode = mod.mode ?? "server";
|
|
1051
|
+
const loader = mod.loader;
|
|
1052
|
+
const routeMiddleware = mod.middleware;
|
|
1053
|
+
const revalidate = mod.revalidate;
|
|
1054
|
+
const layoutChain = findLayoutChain(route.filePath, layouts, pagesDir);
|
|
1055
|
+
for (const rootLayout2 of dedicatedLayouts) {
|
|
1056
|
+
if (!layoutChain.some((l) => l.filePath === rootLayout2.filePath)) {
|
|
1057
|
+
layoutChain.unshift(rootLayout2);
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
const layoutModules = [];
|
|
1061
|
+
for (const l of layoutChain) {
|
|
1062
|
+
const layoutMod = await importDev(l.filePath, dev);
|
|
1063
|
+
if (layoutMod.default) layoutModules.push(layoutMod.default);
|
|
1064
|
+
}
|
|
1065
|
+
const mwChain = findMiddlewareChain(route.filePath, middlewareEntries, pagesDir);
|
|
1066
|
+
const middlewareModules = [];
|
|
1067
|
+
for (const m of mwChain) {
|
|
1068
|
+
const mwMod = await importDev(m.filePath, dev);
|
|
1069
|
+
if (typeof mwMod.middleware === "function") {
|
|
1070
|
+
middlewareModules.push(mwMod.middleware);
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
if (routeMiddleware) {
|
|
1074
|
+
middlewareModules.push(routeMiddleware);
|
|
1075
|
+
}
|
|
1076
|
+
loaded.push({
|
|
1077
|
+
entry: route,
|
|
1078
|
+
mode,
|
|
1079
|
+
revalidate,
|
|
1080
|
+
handler: async (req) => {
|
|
1081
|
+
try {
|
|
1082
|
+
const params = extractParams(route.routePath, route.paramNames, new URL(req.url).pathname) ?? {};
|
|
1083
|
+
const baseHandler = async (ctx) => {
|
|
1084
|
+
let loaderData = {};
|
|
1085
|
+
if (loader) {
|
|
1086
|
+
const result = await loader(ctx);
|
|
1087
|
+
if (result instanceof Response) return result;
|
|
1088
|
+
loaderData = result;
|
|
1089
|
+
}
|
|
1090
|
+
if (mode === "server") {
|
|
1091
|
+
const content2 = wrapWithLayouts(Component, ctx.params, loaderData, layoutModules);
|
|
1092
|
+
const stream = await renderStreamingPage(content2, {
|
|
1093
|
+
stylesheet: stylesheetHref,
|
|
1094
|
+
liveReload: dev
|
|
1095
|
+
});
|
|
1096
|
+
return new Response(stream, {
|
|
1097
|
+
headers: { "Content-Type": "text/html; charset=utf-8" }
|
|
1098
|
+
});
|
|
1099
|
+
}
|
|
1100
|
+
const cached = staticCache.get(route.routePath);
|
|
1101
|
+
const revalidateSeconds = revalidate ?? 0;
|
|
1102
|
+
if (revalidateSeconds > 0 && cached && Date.now() - cached.timestamp < revalidateSeconds * 1e3) {
|
|
1103
|
+
return new Response(cached.html, {
|
|
1104
|
+
headers: { "Content-Type": "text/html; charset=utf-8", "X-Revalidated": "hit" }
|
|
1105
|
+
});
|
|
1106
|
+
}
|
|
1107
|
+
const content = wrapWithLayouts(Component, ctx.params, loaderData, layoutModules);
|
|
1108
|
+
const html = renderPage(content, { stylesheet: stylesheetHref, liveReload: dev });
|
|
1109
|
+
if (revalidateSeconds > 0) {
|
|
1110
|
+
staticCache.set(route.routePath, { html, timestamp: Date.now() });
|
|
1111
|
+
}
|
|
1112
|
+
return new Response(html, {
|
|
1113
|
+
headers: {
|
|
1114
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
1115
|
+
"X-Revalidated": revalidateSeconds > 0 ? "miss" : "none"
|
|
1116
|
+
}
|
|
1117
|
+
});
|
|
1118
|
+
};
|
|
1119
|
+
if (middlewareModules.length > 0) {
|
|
1120
|
+
const composed = composeMiddleware(middlewareModules, baseHandler);
|
|
1121
|
+
return composed(
|
|
1122
|
+
{ params, request: req },
|
|
1123
|
+
async () => new Response("Not found", { status: 404 })
|
|
1124
|
+
);
|
|
1125
|
+
}
|
|
1126
|
+
return baseHandler({ params, request: req });
|
|
1127
|
+
} catch (err) {
|
|
1128
|
+
console.error("[x] route handler error:", err);
|
|
1129
|
+
if (options.development) {
|
|
1130
|
+
return new Response(renderErrorOverlay(err), {
|
|
1131
|
+
status: 500,
|
|
1132
|
+
headers: { "Content-Type": "text/html; charset=utf-8" }
|
|
1133
|
+
});
|
|
1134
|
+
}
|
|
1135
|
+
return new Response("Internal server error", { status: 500 });
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
});
|
|
1139
|
+
}
|
|
1140
|
+
handlers = loaded;
|
|
1141
|
+
if (options.contentDir) {
|
|
1142
|
+
const content = scanContent(options.contentDir);
|
|
1143
|
+
const loadedContent = content.map((entry) => ({
|
|
1144
|
+
entry,
|
|
1145
|
+
handler: async () => {
|
|
1146
|
+
const html = renderContentPage(entry, stylesheetHref, dev);
|
|
1147
|
+
return new Response(html, {
|
|
1148
|
+
headers: { "Content-Type": "text/html; charset=utf-8" }
|
|
1149
|
+
});
|
|
1150
|
+
}
|
|
1151
|
+
}));
|
|
1152
|
+
contentHandlers = loadedContent;
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
await buildHandlers();
|
|
1156
|
+
async function handleRevalidation(req) {
|
|
1157
|
+
if (new URL(req.url).pathname !== "/__x/revalidate") return null;
|
|
1158
|
+
if (req.method !== "POST") return new Response("Method not allowed", { status: 405 });
|
|
1159
|
+
const body = await req.json();
|
|
1160
|
+
if (body.path) {
|
|
1161
|
+
staticCache.delete(body.path);
|
|
1162
|
+
return new Response(`Revalidated: ${body.path}`);
|
|
1163
|
+
}
|
|
1164
|
+
staticCache.clear();
|
|
1165
|
+
return new Response("Revalidated all");
|
|
1166
|
+
}
|
|
1167
|
+
if (options.development) {
|
|
1168
|
+
let notifyClients2 = function() {
|
|
1169
|
+
for (const send of sseClients) {
|
|
1170
|
+
try {
|
|
1171
|
+
send("reload", "");
|
|
1172
|
+
} catch {
|
|
1173
|
+
sseClients.delete(send);
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
}, scheduleRebuild2 = function() {
|
|
1177
|
+
if (rebuildTimeout) clearTimeout(rebuildTimeout);
|
|
1178
|
+
rebuildTimeout = setTimeout(async () => {
|
|
1179
|
+
try {
|
|
1180
|
+
const oldPaths = new Set(handlers.map((h) => h.entry.filePath));
|
|
1181
|
+
await buildHandlers();
|
|
1182
|
+
const newPaths = new Set(handlers.map((h) => h.entry.filePath));
|
|
1183
|
+
const added = [...newPaths].filter((p) => !oldPaths.has(p));
|
|
1184
|
+
const removed = [...oldPaths].filter((p) => !newPaths.has(p));
|
|
1185
|
+
if (added.length > 0) {
|
|
1186
|
+
for (const p of added) console.log(`[x] route added: ${p.replace(primaryDir, "")}`);
|
|
1187
|
+
}
|
|
1188
|
+
if (removed.length > 0) {
|
|
1189
|
+
for (const p of removed) console.log(`[x] route removed: ${p.replace(primaryDir, "")}`);
|
|
1190
|
+
}
|
|
1191
|
+
if (added.length > 0 || removed.length > 0) {
|
|
1192
|
+
console.log(
|
|
1193
|
+
`[x] route tree rebuilt (${handlers.length} routes, ${contentHandlers.length} content)`
|
|
1194
|
+
);
|
|
1195
|
+
}
|
|
1196
|
+
notifyClients2();
|
|
1197
|
+
} catch {
|
|
1198
|
+
if (options.development) {
|
|
1199
|
+
console.warn("[x] rebuild skipped: routes directory may have changed");
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
}, 200);
|
|
1203
|
+
};
|
|
1204
|
+
var notifyClients = notifyClients2, scheduleRebuild = scheduleRebuild2;
|
|
1205
|
+
let rebuildTimeout = null;
|
|
1206
|
+
const sseClients = /* @__PURE__ */ new Set();
|
|
1207
|
+
try {
|
|
1208
|
+
const srcDir = join4(primaryDir, "..", "..", "src");
|
|
1209
|
+
const watchDirs = [
|
|
1210
|
+
...new Set(
|
|
1211
|
+
[primaryDir, options.apiDir, options.layoutsDir, options.actionsDir, srcDir].filter(
|
|
1212
|
+
Boolean
|
|
1213
|
+
)
|
|
1214
|
+
)
|
|
1215
|
+
];
|
|
1216
|
+
for (const dir of watchDirs) {
|
|
1217
|
+
watch(dir, { recursive: true }, (_eventType, filename) => {
|
|
1218
|
+
if (!filename) return;
|
|
1219
|
+
const name = typeof filename === "string" ? filename : filename.toString();
|
|
1220
|
+
if (name.startsWith(".") || name.startsWith("_")) return;
|
|
1221
|
+
if (name === "x-routes.ts") return;
|
|
1222
|
+
if (!/\.(tsx|ts|css)$/.test(name)) return;
|
|
1223
|
+
scheduleRebuild2();
|
|
1224
|
+
});
|
|
1225
|
+
}
|
|
1226
|
+
} catch {
|
|
1227
|
+
console.warn("[x] file watching not available on this platform");
|
|
1228
|
+
}
|
|
1229
|
+
const devFetch = async (req) => {
|
|
1230
|
+
const url = new URL(req.url).pathname;
|
|
1231
|
+
if (url === "/__x/reload") {
|
|
1232
|
+
const body = new ReadableStream({
|
|
1233
|
+
start(controller) {
|
|
1234
|
+
const encoder = new TextEncoder();
|
|
1235
|
+
controller.enqueue(encoder.encode("event: hb\ndata: \n\n"));
|
|
1236
|
+
const send = (event, data) => {
|
|
1237
|
+
controller.enqueue(encoder.encode(`event: ${event}
|
|
1238
|
+
data: ${data}
|
|
1239
|
+
|
|
1240
|
+
`));
|
|
1241
|
+
};
|
|
1242
|
+
sseClients.add(send);
|
|
1243
|
+
req.signal.addEventListener("abort", () => sseClients.delete(send));
|
|
1244
|
+
}
|
|
1245
|
+
});
|
|
1246
|
+
return new Response(body, {
|
|
1247
|
+
headers: {
|
|
1248
|
+
"Content-Type": "text/event-stream",
|
|
1249
|
+
"Cache-Control": "no-cache",
|
|
1250
|
+
Connection: "keep-alive"
|
|
1251
|
+
}
|
|
1252
|
+
});
|
|
1253
|
+
}
|
|
1254
|
+
const revalidationResult = await handleRevalidation(req);
|
|
1255
|
+
if (revalidationResult !== null) return revalidationResult;
|
|
1256
|
+
const serverFnResult = await serverFnHandler(req);
|
|
1257
|
+
if (serverFnResult !== null) return serverFnResult;
|
|
1258
|
+
const staticAsset = await serveStaticAsset(publicDir, req);
|
|
1259
|
+
if (staticAsset !== null) return staticAsset;
|
|
1260
|
+
for (const h of handlers) {
|
|
1261
|
+
const params = extractParams(h.entry.routePath, h.entry.paramNames, url);
|
|
1262
|
+
if (params !== null) {
|
|
1263
|
+
return h.handler(req);
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
for (const h of contentHandlers) {
|
|
1267
|
+
if (h.entry.routePath === url) {
|
|
1268
|
+
return h.handler(req);
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
return renderNotFound(req);
|
|
1272
|
+
};
|
|
1273
|
+
return {
|
|
1274
|
+
routes: {},
|
|
1275
|
+
development: true,
|
|
1276
|
+
port: options.port ?? 3e3,
|
|
1277
|
+
fetch: devFetch
|
|
1278
|
+
};
|
|
1279
|
+
}
|
|
1280
|
+
const prodFetch = async (req) => {
|
|
1281
|
+
const url = new URL(req.url).pathname;
|
|
1282
|
+
const revalidationResult = await handleRevalidation(req);
|
|
1283
|
+
if (revalidationResult !== null) return revalidationResult;
|
|
1284
|
+
const serverFnResult = await serverFnHandler(req);
|
|
1285
|
+
if (serverFnResult !== null) return serverFnResult;
|
|
1286
|
+
const staticAsset = await serveStaticAsset(publicDir, req);
|
|
1287
|
+
if (staticAsset !== null) return staticAsset;
|
|
1288
|
+
for (const h of handlers) {
|
|
1289
|
+
const params = extractParams(h.entry.routePath, h.entry.paramNames, url);
|
|
1290
|
+
if (params !== null) {
|
|
1291
|
+
return h.handler(req);
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
for (const h of contentHandlers) {
|
|
1295
|
+
if (h.entry.routePath === url) {
|
|
1296
|
+
return h.handler(req);
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
1299
|
+
return renderNotFound(req);
|
|
1300
|
+
};
|
|
1301
|
+
return {
|
|
1302
|
+
routes: {},
|
|
1303
|
+
development: false,
|
|
1304
|
+
port: options.port ?? 3e3,
|
|
1305
|
+
fetch: prodFetch
|
|
1306
|
+
};
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
// src/build.ts
|
|
1310
|
+
import { existsSync as existsSync2, mkdirSync, writeFileSync as writeFileSync3 } from "fs";
|
|
1311
|
+
import { basename, join as join5, relative as relative3 } from "path";
|
|
1312
|
+
import { createElement as createElement2 } from "react";
|
|
1313
|
+
|
|
1314
|
+
// src/island.tsx
|
|
1315
|
+
import { createContext, useContext } from "react";
|
|
1316
|
+
import { jsx as jsx2 } from "react/jsx-runtime";
|
|
1317
|
+
function createIslandRegistry() {
|
|
1318
|
+
return { entries: [] };
|
|
1319
|
+
}
|
|
1320
|
+
var IslandContext = createContext(null);
|
|
1321
|
+
function IslandProvider({
|
|
1322
|
+
registry,
|
|
1323
|
+
children
|
|
1324
|
+
}) {
|
|
1325
|
+
return /* @__PURE__ */ jsx2(IslandContext.Provider, { value: registry, children });
|
|
1326
|
+
}
|
|
1327
|
+
var islandCounter = 0;
|
|
1328
|
+
function Island({
|
|
1329
|
+
name,
|
|
1330
|
+
client = "idle",
|
|
1331
|
+
children
|
|
1332
|
+
}) {
|
|
1333
|
+
const registry = useContext(IslandContext);
|
|
1334
|
+
const id = `x-island-${islandCounter++}`;
|
|
1335
|
+
if (registry) {
|
|
1336
|
+
registry.entries.push({ name, id });
|
|
1337
|
+
}
|
|
1338
|
+
return /* @__PURE__ */ jsx2("div", { "data-island": name, "data-island-id": id, "data-island-client": client, children });
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
// src/build.ts
|
|
1342
|
+
async function build(options) {
|
|
1343
|
+
const outDir = options.outDir ?? join5(process.cwd(), ".x");
|
|
1344
|
+
const clientDir = join5(outDir, "client");
|
|
1345
|
+
const serverDir = join5(outDir, "server");
|
|
1346
|
+
const islandsDir = join5(clientDir, "_islands");
|
|
1347
|
+
mkdirSync(clientDir, { recursive: true });
|
|
1348
|
+
mkdirSync(serverDir, { recursive: true });
|
|
1349
|
+
mkdirSync(islandsDir, { recursive: true });
|
|
1350
|
+
const pagesDir = options.pagesDir ?? options.routesDir ?? "";
|
|
1351
|
+
const apiDir = options.apiDir;
|
|
1352
|
+
const actionsDir = options.actionsDir;
|
|
1353
|
+
const layoutsDir = options.layoutsDir ?? pagesDir;
|
|
1354
|
+
let routeEntries = [];
|
|
1355
|
+
if (pagesDir && existsSync2(pagesDir)) {
|
|
1356
|
+
routeEntries = scanPages(pagesDir);
|
|
1357
|
+
}
|
|
1358
|
+
if (apiDir && existsSync2(apiDir)) {
|
|
1359
|
+
routeEntries.push(...scanApiDir(apiDir));
|
|
1360
|
+
}
|
|
1361
|
+
const legacyApiDir = pagesDir ? join5(pagesDir, "api") : "";
|
|
1362
|
+
if (legacyApiDir && existsSync2(legacyApiDir) && legacyApiDir !== apiDir) {
|
|
1363
|
+
routeEntries.push(...scanApiDir(legacyApiDir));
|
|
1364
|
+
}
|
|
1365
|
+
if (actionsDir && existsSync2(actionsDir)) {
|
|
1366
|
+
for (const actionFile of scanRoutes(actionsDir)) {
|
|
1367
|
+
const mod = await import(actionFile.filePath);
|
|
1368
|
+
const segments = actionFile.routePath.split("/").filter(Boolean);
|
|
1369
|
+
const parentPath = `/${segments.slice(0, -1).join("/")}`;
|
|
1370
|
+
const actions = mod.actions;
|
|
1371
|
+
if (actions) registerServerFunctions(parentPath, actionFile.paramNames, actions);
|
|
1372
|
+
for (const [key, value] of Object.entries(mod)) {
|
|
1373
|
+
if (key === "default" || key === "actions" || typeof value !== "function") continue;
|
|
1374
|
+
registerServerFunctions(parentPath, actionFile.paramNames, {
|
|
1375
|
+
[key]: value
|
|
1376
|
+
});
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
const dedicatedLayouts = layoutsDir && layoutsDir !== pagesDir && existsSync2(layoutsDir) ? scanLayoutsDir(layoutsDir) : [];
|
|
1381
|
+
const nestedLayouts = pagesDir && existsSync2(pagesDir) ? scanLayouts(pagesDir) : [];
|
|
1382
|
+
const layouts = [...dedicatedLayouts, ...nestedLayouts];
|
|
1383
|
+
const staticPages = [];
|
|
1384
|
+
const serverPages = [];
|
|
1385
|
+
const apiRoutes = [];
|
|
1386
|
+
for (const entry of routeEntries) {
|
|
1387
|
+
if (entry.isApi) {
|
|
1388
|
+
apiRoutes.push(entry);
|
|
1389
|
+
continue;
|
|
1390
|
+
}
|
|
1391
|
+
const mod = await import(entry.filePath);
|
|
1392
|
+
const Component = mod.default;
|
|
1393
|
+
if (!Component) {
|
|
1394
|
+
console.warn(`[x] ${entry.filePath} has no default export -- skipping`);
|
|
1395
|
+
continue;
|
|
1396
|
+
}
|
|
1397
|
+
const mode = mod.mode ?? "server";
|
|
1398
|
+
const layoutChain = findLayoutChain(entry.filePath, layouts, pagesDir);
|
|
1399
|
+
for (const rootLayout of dedicatedLayouts) {
|
|
1400
|
+
if (!layoutChain.some((l) => l.filePath === rootLayout.filePath)) {
|
|
1401
|
+
layoutChain.unshift(rootLayout);
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
const layoutModules = [];
|
|
1405
|
+
for (const l of layoutChain) {
|
|
1406
|
+
const layoutMod = await import(l.filePath);
|
|
1407
|
+
if (layoutMod.default) layoutModules.push(layoutMod.default);
|
|
1408
|
+
}
|
|
1409
|
+
const page = { entry, filePath: entry.filePath, mode, Component, layoutModules };
|
|
1410
|
+
if (mode === "static") {
|
|
1411
|
+
staticPages.push(page);
|
|
1412
|
+
} else {
|
|
1413
|
+
serverPages.push(page);
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
1416
|
+
let contentEntries = [];
|
|
1417
|
+
if (options.contentDir) {
|
|
1418
|
+
contentEntries = scanContent(options.contentDir);
|
|
1419
|
+
}
|
|
1420
|
+
console.log(
|
|
1421
|
+
`[x] build: ${staticPages.length} static, ${serverPages.length} server, ${contentEntries.length} content pages`
|
|
1422
|
+
);
|
|
1423
|
+
const writtenPaths = /* @__PURE__ */ new Set();
|
|
1424
|
+
for (const page of staticPages) {
|
|
1425
|
+
const params = {};
|
|
1426
|
+
const registry = createIslandRegistry();
|
|
1427
|
+
const pageContent = renderPageWithLayout(page.Component, params, page.layoutModules);
|
|
1428
|
+
const content = createElement2(IslandProvider, { registry }, pageContent);
|
|
1429
|
+
const html = renderStaticPage(content);
|
|
1430
|
+
const outPath = page.entry.routePath === "/" ? "/index.html" : `${page.entry.routePath}/index.html`;
|
|
1431
|
+
const fullPath = join5(clientDir, outPath);
|
|
1432
|
+
mkdirSync(join5(fullPath, ".."), { recursive: true });
|
|
1433
|
+
if (writtenPaths.has(outPath)) {
|
|
1434
|
+
console.warn(` [warn] collision: ${page.entry.routePath} overwrites existing output`);
|
|
1435
|
+
}
|
|
1436
|
+
writtenPaths.add(outPath);
|
|
1437
|
+
let islandScripts = [];
|
|
1438
|
+
if (registry.entries.length > 0) {
|
|
1439
|
+
const uniqueNames = [...new Set(registry.entries.map((e) => e.name))];
|
|
1440
|
+
islandScripts = await bundleRouteIslands(page.filePath, uniqueNames, islandsDir);
|
|
1441
|
+
console.log(
|
|
1442
|
+
` [islands] ${uniqueNames.length} island(s) on ${page.entry.routePath} -> ${islandScripts.join(", ")}`
|
|
1443
|
+
);
|
|
1444
|
+
}
|
|
1445
|
+
const finalHtml = renderStaticPage(content, { islandScripts });
|
|
1446
|
+
writeFileSync3(fullPath, finalHtml, "utf-8");
|
|
1447
|
+
console.log(` [static] ${page.entry.routePath} -> ${outPath}`);
|
|
1448
|
+
}
|
|
1449
|
+
for (const content of contentEntries) {
|
|
1450
|
+
const registry = createIslandRegistry();
|
|
1451
|
+
const bodyHtml = renderMarkdown(content.body);
|
|
1452
|
+
const pageContent = createElement2(StaticContentPage, {
|
|
1453
|
+
content,
|
|
1454
|
+
bodyHtml
|
|
1455
|
+
});
|
|
1456
|
+
const rendered = createElement2(IslandProvider, { registry }, pageContent);
|
|
1457
|
+
const html = renderStaticPage(rendered, {
|
|
1458
|
+
title: content.frontmatter.title ?? content.slug
|
|
1459
|
+
});
|
|
1460
|
+
const outPath = content.routePath === "/" ? "/index.html" : `${content.routePath}/index.html`;
|
|
1461
|
+
const fullPath = join5(clientDir, outPath);
|
|
1462
|
+
mkdirSync(join5(fullPath, ".."), { recursive: true });
|
|
1463
|
+
if (writtenPaths.has(outPath)) {
|
|
1464
|
+
console.warn(` [warn] collision: content ${content.routePath} overwrites existing output`);
|
|
1465
|
+
}
|
|
1466
|
+
writtenPaths.add(outPath);
|
|
1467
|
+
writeFileSync3(fullPath, html, "utf-8");
|
|
1468
|
+
console.log(` [content] ${content.routePath} -> ${outPath}`);
|
|
1469
|
+
}
|
|
1470
|
+
if (serverPages.length > 0 || apiRoutes.length > 0) {
|
|
1471
|
+
const srvOpts = {
|
|
1472
|
+
pagesDir: pagesDir || options.routesDir || ""
|
|
1473
|
+
};
|
|
1474
|
+
if (options.apiDir) srvOpts.apiDir = options.apiDir;
|
|
1475
|
+
if (options.layoutsDir) srvOpts.layoutsDir = options.layoutsDir;
|
|
1476
|
+
if (options.actionsDir) srvOpts.actionsDir = options.actionsDir;
|
|
1477
|
+
if (options.contentDir) srvOpts.contentDir = options.contentDir;
|
|
1478
|
+
const serverEntry = buildServerEntry(
|
|
1479
|
+
srvOpts
|
|
1480
|
+
);
|
|
1481
|
+
const serverEntryPath = join5(serverDir, "index.ts");
|
|
1482
|
+
writeFileSync3(serverEntryPath, serverEntry, "utf-8");
|
|
1483
|
+
console.log(
|
|
1484
|
+
` [server] ${serverPages.length} page routes, ${apiRoutes.length} api routes -> server/index.ts`
|
|
1485
|
+
);
|
|
1486
|
+
}
|
|
1487
|
+
console.log(`[x] build complete -> ${outDir}`);
|
|
1488
|
+
}
|
|
1489
|
+
async function bundleRouteIslands(routeFilePath, islandNames, islandsDir) {
|
|
1490
|
+
const entryId = `${basename(routeFilePath).replace(/\.(tsx|ts)$/, "")}-${hash(routeFilePath)}`;
|
|
1491
|
+
const outdir = join5(islandsDir, entryId);
|
|
1492
|
+
mkdirSync(outdir, { recursive: true });
|
|
1493
|
+
const bundlePath = join5(outdir, `${entryId}.js`);
|
|
1494
|
+
const routeRel = join5(relative3(outdir, join5(routeFilePath, "..")), basename(routeFilePath));
|
|
1495
|
+
const hydrateEntry = generateHydrateEntry(routeRel, islandNames);
|
|
1496
|
+
const entryPath = join5(outdir, `${entryId}.tsx`);
|
|
1497
|
+
writeFileSync3(entryPath, hydrateEntry, "utf-8");
|
|
1498
|
+
const result = Bun.spawnSync([
|
|
1499
|
+
"bun",
|
|
1500
|
+
"build",
|
|
1501
|
+
"--target=browser",
|
|
1502
|
+
"--external",
|
|
1503
|
+
"react",
|
|
1504
|
+
"--external",
|
|
1505
|
+
"react-dom",
|
|
1506
|
+
"--outdir",
|
|
1507
|
+
outdir,
|
|
1508
|
+
entryPath
|
|
1509
|
+
]);
|
|
1510
|
+
if (result.success) {
|
|
1511
|
+
return [`/_islands/${entryId}/${entryId}.js`];
|
|
1512
|
+
}
|
|
1513
|
+
writeFileSync3(bundlePath, generateFallbackHydration(islandNames), "utf-8");
|
|
1514
|
+
return [`/_islands/${entryId}/${entryId}.js`];
|
|
1515
|
+
}
|
|
1516
|
+
function generateHydrateEntry(routeRelPath, islandNames) {
|
|
1517
|
+
return `import * as Route from "${routeRelPath}";
|
|
1518
|
+
|
|
1519
|
+
document.querySelectorAll("[data-island]").forEach((el) => {
|
|
1520
|
+
const name = el.getAttribute("data-island");
|
|
1521
|
+
if (!name) return;
|
|
1522
|
+
const Component = Route.islands?.[name];
|
|
1523
|
+
if (!Component) return;
|
|
1524
|
+
const root = ReactDOM.hydrateRoot(el, React.createElement(Component));
|
|
1525
|
+
});
|
|
1526
|
+
`;
|
|
1527
|
+
}
|
|
1528
|
+
function generateFallbackHydration(islandNames) {
|
|
1529
|
+
return `// x island hydration fallback \u2014 ${islandNames.join(", ")}
|
|
1530
|
+
document.querySelectorAll("[data-island]").forEach(function(el) {
|
|
1531
|
+
el.setAttribute("data-island-hydrated", "false");
|
|
1532
|
+
});
|
|
1533
|
+
`;
|
|
1534
|
+
}
|
|
1535
|
+
function renderPageWithLayout(Component, params, layoutModules) {
|
|
1536
|
+
let content = createElement2(Component, { params });
|
|
1537
|
+
for (const Layout of layoutModules) {
|
|
1538
|
+
content = createElement2(Layout, null, content);
|
|
1539
|
+
}
|
|
1540
|
+
return content;
|
|
1541
|
+
}
|
|
1542
|
+
function StaticContentPage({
|
|
1543
|
+
content,
|
|
1544
|
+
bodyHtml
|
|
1545
|
+
}) {
|
|
1546
|
+
return createElement2(
|
|
1547
|
+
"article",
|
|
1548
|
+
null,
|
|
1549
|
+
content.frontmatter.title ? createElement2("h1", null, content.frontmatter.title) : null,
|
|
1550
|
+
createElement2("div", {
|
|
1551
|
+
// biome-ignore lint/security/noDangerouslySetInnerHtml: body is markdown rendered to HTML
|
|
1552
|
+
dangerouslySetInnerHTML: { __html: bodyHtml }
|
|
1553
|
+
})
|
|
1554
|
+
);
|
|
1555
|
+
}
|
|
1556
|
+
function buildServerEntry(opts) {
|
|
1557
|
+
const dirKeys = ["pagesDir", "apiDir", "layoutsDir", "actionsDir", "contentDir"];
|
|
1558
|
+
const lines = [
|
|
1559
|
+
"// Auto-generated by @thexjs/core build",
|
|
1560
|
+
'import { createApp } from "@thexjs/core";',
|
|
1561
|
+
"",
|
|
1562
|
+
"const app = await createApp({"
|
|
1563
|
+
];
|
|
1564
|
+
for (const key of dirKeys) {
|
|
1565
|
+
const val = opts[key];
|
|
1566
|
+
if (val) lines.push(` ${key}: ${JSON.stringify(val)},`);
|
|
1567
|
+
}
|
|
1568
|
+
lines.push(
|
|
1569
|
+
' port: parseInt(process.env.PORT || "3000", 10),',
|
|
1570
|
+
" development: false,",
|
|
1571
|
+
"});",
|
|
1572
|
+
"",
|
|
1573
|
+
"const server = Bun.serve(app);",
|
|
1574
|
+
"",
|
|
1575
|
+
"console.log(`[x] production server running at ${server.url}`);"
|
|
1576
|
+
);
|
|
1577
|
+
return lines.join("\n");
|
|
1578
|
+
}
|
|
1579
|
+
function hash(str) {
|
|
1580
|
+
let h = 0;
|
|
1581
|
+
for (let i = 0; i < str.length; i++) {
|
|
1582
|
+
h = Math.imul(31, h) + str.charCodeAt(i) | 0;
|
|
1583
|
+
}
|
|
1584
|
+
return Math.abs(h).toString(36);
|
|
1585
|
+
}
|
|
1586
|
+
|
|
1587
|
+
// src/data/sqlite.ts
|
|
1588
|
+
import { Database } from "bun:sqlite";
|
|
1589
|
+
function connectSQLite(options) {
|
|
1590
|
+
const db = new Database(options?.path ?? "data/dev.db");
|
|
1591
|
+
if (options?.wal !== false) {
|
|
1592
|
+
db.run("PRAGMA journal_mode = WAL");
|
|
1593
|
+
}
|
|
1594
|
+
if (options?.foreignKeys !== false) {
|
|
1595
|
+
db.run("PRAGMA foreign_keys = ON");
|
|
1596
|
+
}
|
|
1597
|
+
return db;
|
|
1598
|
+
}
|
|
1599
|
+
|
|
1600
|
+
// src/data/postgres.ts
|
|
1601
|
+
function connectPostgres(options) {
|
|
1602
|
+
const url = options?.url ?? process.env.DATABASE_URL;
|
|
1603
|
+
if (!url) {
|
|
1604
|
+
throw new Error(
|
|
1605
|
+
"DATABASE_URL is required \u2014 set it via options.url or the DATABASE_URL environment variable"
|
|
1606
|
+
);
|
|
1607
|
+
}
|
|
1608
|
+
return Bun.sql(url);
|
|
1609
|
+
}
|
|
1610
|
+
|
|
1611
|
+
// src/data/migrate.ts
|
|
1612
|
+
import { readFileSync as readFileSync2, readdirSync as readdirSync3 } from "fs";
|
|
1613
|
+
import { join as join6 } from "path";
|
|
1614
|
+
function runSQLiteMigrations(db, migrationsDir) {
|
|
1615
|
+
db.run(`CREATE TABLE IF NOT EXISTS _x_migrations (
|
|
1616
|
+
name TEXT PRIMARY KEY,
|
|
1617
|
+
applied_at TEXT DEFAULT (datetime('now'))
|
|
1618
|
+
)`);
|
|
1619
|
+
const stmt = db.prepare("SELECT name FROM _x_migrations");
|
|
1620
|
+
const applied = new Set(stmt.all().map((r) => r.name));
|
|
1621
|
+
let files;
|
|
1622
|
+
try {
|
|
1623
|
+
files = readdirSync3(migrationsDir).filter((f) => f.endsWith(".sql")).sort();
|
|
1624
|
+
} catch {
|
|
1625
|
+
return { applied: [], skipped: [] };
|
|
1626
|
+
}
|
|
1627
|
+
const result = { applied: [], skipped: [] };
|
|
1628
|
+
for (const file of files) {
|
|
1629
|
+
if (applied.has(file)) {
|
|
1630
|
+
result.skipped.push(file);
|
|
1631
|
+
continue;
|
|
1632
|
+
}
|
|
1633
|
+
const sql = readFileSync2(join6(migrationsDir, file), "utf-8");
|
|
1634
|
+
db.run(sql);
|
|
1635
|
+
db.run("INSERT INTO _x_migrations (name) VALUES (?1)", [file]);
|
|
1636
|
+
console.log(`[x] migration applied: ${file}`);
|
|
1637
|
+
result.applied.push(file);
|
|
1638
|
+
}
|
|
1639
|
+
return result;
|
|
1640
|
+
}
|
|
1641
|
+
async function runPostgresMigrations(client, migrationsDir) {
|
|
1642
|
+
await client.unsafe(`CREATE TABLE IF NOT EXISTS _x_migrations (
|
|
1643
|
+
name TEXT PRIMARY KEY,
|
|
1644
|
+
applied_at TIMESTAMP DEFAULT NOW()
|
|
1645
|
+
)`);
|
|
1646
|
+
const rows = await client.unsafe("SELECT name FROM _x_migrations");
|
|
1647
|
+
const applied = new Set(rows.map((r) => r.name));
|
|
1648
|
+
let files;
|
|
1649
|
+
try {
|
|
1650
|
+
files = readdirSync3(migrationsDir).filter((f) => f.endsWith(".sql")).sort();
|
|
1651
|
+
} catch {
|
|
1652
|
+
return { applied: [], skipped: [] };
|
|
1653
|
+
}
|
|
1654
|
+
const result = { applied: [], skipped: [] };
|
|
1655
|
+
for (const file of files) {
|
|
1656
|
+
if (applied.has(file)) {
|
|
1657
|
+
result.skipped.push(file);
|
|
1658
|
+
continue;
|
|
1659
|
+
}
|
|
1660
|
+
const raw = readFileSync2(join6(migrationsDir, file), "utf-8");
|
|
1661
|
+
await client.unsafe(raw);
|
|
1662
|
+
await client.unsafe(`INSERT INTO _x_migrations (name) VALUES ('${file}')`);
|
|
1663
|
+
console.log(`[x] migration applied: ${file}`);
|
|
1664
|
+
result.applied.push(file);
|
|
1665
|
+
}
|
|
1666
|
+
return result;
|
|
1667
|
+
}
|
|
1668
|
+
export {
|
|
1669
|
+
CLIENT_NAV_SCRIPT,
|
|
1670
|
+
DefaultNotFound,
|
|
1671
|
+
Island,
|
|
1672
|
+
IslandProvider,
|
|
1673
|
+
build,
|
|
1674
|
+
composeMiddleware,
|
|
1675
|
+
connectPostgres,
|
|
1676
|
+
connectSQLite,
|
|
1677
|
+
createApp,
|
|
1678
|
+
defineConfig,
|
|
1679
|
+
escapeHtml2 as escapeHtml,
|
|
1680
|
+
findLayoutChain,
|
|
1681
|
+
findMiddlewareChain,
|
|
1682
|
+
generateManifestSource,
|
|
1683
|
+
generateServerFunctionClient,
|
|
1684
|
+
getServerFunctionHandler,
|
|
1685
|
+
registerServerFunctions,
|
|
1686
|
+
renderErrorOverlay,
|
|
1687
|
+
renderMarkdown,
|
|
1688
|
+
renderPage,
|
|
1689
|
+
renderStaticPage,
|
|
1690
|
+
renderStreamingPage,
|
|
1691
|
+
resetServerFunctions,
|
|
1692
|
+
runPostgresMigrations,
|
|
1693
|
+
runSQLiteMigrations,
|
|
1694
|
+
scanApiDir,
|
|
1695
|
+
scanContent,
|
|
1696
|
+
scanLayouts,
|
|
1697
|
+
scanLayoutsDir,
|
|
1698
|
+
scanMiddleware,
|
|
1699
|
+
scanNotFound,
|
|
1700
|
+
scanPages,
|
|
1701
|
+
scanRoutes,
|
|
1702
|
+
writeManifest
|
|
1703
|
+
};
|