@thexjs/core 1.8.3 → 1.9.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 +14 -7
- package/dist/adapter.js +6 -2
- package/dist/backpressure-05lHLY5O.d.ts +51 -0
- package/dist/{chunk-3VMZCMAF.js → chunk-ME4ES2PD.js} +76 -7
- package/dist/index.d.ts +92 -92
- package/dist/index.js +1438 -1382
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -39,7 +39,7 @@ import {
|
|
|
39
39
|
verifyOrigin,
|
|
40
40
|
withCsrfCookie,
|
|
41
41
|
writeManifest
|
|
42
|
-
} from "./chunk-
|
|
42
|
+
} from "./chunk-ME4ES2PD.js";
|
|
43
43
|
import {
|
|
44
44
|
OTEL_ERROR_STATUS_CODE,
|
|
45
45
|
REDACTED,
|
|
@@ -179,11 +179,49 @@ function withBackpressure(handler, options) {
|
|
|
179
179
|
};
|
|
180
180
|
}
|
|
181
181
|
|
|
182
|
-
// src/
|
|
183
|
-
import {
|
|
184
|
-
import { join as join2,
|
|
182
|
+
// src/createApp.ts
|
|
183
|
+
import { existsSync, watch } from "fs";
|
|
184
|
+
import { join as join2, resolve, sep as sep2 } from "path";
|
|
185
185
|
import { createElement } from "react";
|
|
186
186
|
|
|
187
|
+
// src/bounded-cache.ts
|
|
188
|
+
var BoundedCache = class {
|
|
189
|
+
entries = /* @__PURE__ */ new Map();
|
|
190
|
+
maxEntries;
|
|
191
|
+
constructor(maxEntries = 500) {
|
|
192
|
+
this.maxEntries = maxEntries;
|
|
193
|
+
}
|
|
194
|
+
get(key) {
|
|
195
|
+
const value = this.entries.get(key);
|
|
196
|
+
if (value !== void 0) {
|
|
197
|
+
this.entries.delete(key);
|
|
198
|
+
this.entries.set(key, value);
|
|
199
|
+
}
|
|
200
|
+
return value;
|
|
201
|
+
}
|
|
202
|
+
set(key, value) {
|
|
203
|
+
this.entries.delete(key);
|
|
204
|
+
this.entries.set(key, value);
|
|
205
|
+
this.evict();
|
|
206
|
+
}
|
|
207
|
+
delete(key) {
|
|
208
|
+
this.entries.delete(key);
|
|
209
|
+
}
|
|
210
|
+
clear() {
|
|
211
|
+
this.entries.clear();
|
|
212
|
+
}
|
|
213
|
+
get size() {
|
|
214
|
+
return this.entries.size;
|
|
215
|
+
}
|
|
216
|
+
evict() {
|
|
217
|
+
while (this.entries.size > this.maxEntries) {
|
|
218
|
+
const oldestKey = this.entries.keys().next().value;
|
|
219
|
+
if (oldestKey === void 0) break;
|
|
220
|
+
this.entries.delete(oldestKey);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
|
|
187
225
|
// src/content.ts
|
|
188
226
|
import { readdirSync, readFileSync, statSync } from "fs";
|
|
189
227
|
import { join, relative, sep } from "path";
|
|
@@ -316,1396 +354,1081 @@ function renderMarkdown(md) {
|
|
|
316
354
|
return html;
|
|
317
355
|
}
|
|
318
356
|
|
|
319
|
-
// src/
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
function createIslandRegistry() {
|
|
323
|
-
return { entries: [], nextId: 0 };
|
|
357
|
+
// src/error-overlay.ts
|
|
358
|
+
function escapeHtml2(s) {
|
|
359
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
324
360
|
}
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
361
|
+
function renderErrorOverlay(error) {
|
|
362
|
+
const message = error instanceof Error ? error.message : "Unknown error";
|
|
363
|
+
const stack = error instanceof Error ? error.stack ?? "" : "";
|
|
364
|
+
const frames = stack.split("\n").slice(1).map((line) => `<span class="frame">${escapeHtml2(line.trim())}</span>`).join("\n");
|
|
365
|
+
return `<!DOCTYPE html>
|
|
366
|
+
<html lang="en">
|
|
367
|
+
<head>
|
|
368
|
+
<meta charset="UTF-8" />
|
|
369
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
370
|
+
<title>Server Error</title>
|
|
371
|
+
<style>
|
|
372
|
+
* { margin: 0; padding: 0; box-sizing: border-box; }
|
|
373
|
+
body {
|
|
374
|
+
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
|
375
|
+
background: #1a1a2e;
|
|
376
|
+
color: #e0e0e0;
|
|
377
|
+
min-height: 100vh;
|
|
378
|
+
display: flex;
|
|
379
|
+
flex-direction: column;
|
|
380
|
+
}
|
|
381
|
+
.overlay {
|
|
382
|
+
flex: 1;
|
|
383
|
+
padding: 40px 24px;
|
|
384
|
+
max-width: 900px;
|
|
385
|
+
margin: 0 auto;
|
|
386
|
+
width: 100%;
|
|
387
|
+
}
|
|
388
|
+
.header { margin-bottom: 32px; }
|
|
389
|
+
.badge {
|
|
390
|
+
display: inline-block;
|
|
391
|
+
background: #e74c3c;
|
|
392
|
+
color: #fff;
|
|
393
|
+
font-size: 11px;
|
|
394
|
+
font-weight: 700;
|
|
395
|
+
letter-spacing: 0.05em;
|
|
396
|
+
text-transform: uppercase;
|
|
397
|
+
padding: 3px 10px;
|
|
398
|
+
border-radius: 4px;
|
|
399
|
+
margin-bottom: 12px;
|
|
400
|
+
}
|
|
401
|
+
h1 {
|
|
402
|
+
font-size: 22px;
|
|
403
|
+
font-weight: 600;
|
|
404
|
+
color: #f0f0f0;
|
|
405
|
+
line-height: 1.3;
|
|
406
|
+
}
|
|
407
|
+
.message-box {
|
|
408
|
+
background: #2a2a4a;
|
|
409
|
+
border: 1px solid #3a3a5a;
|
|
410
|
+
border-radius: 8px;
|
|
411
|
+
padding: 20px;
|
|
412
|
+
margin-bottom: 24px;
|
|
413
|
+
font-size: 15px;
|
|
414
|
+
word-break: break-word;
|
|
415
|
+
}
|
|
416
|
+
.message-box .label {
|
|
417
|
+
font-size: 11px;
|
|
418
|
+
font-weight: 600;
|
|
419
|
+
text-transform: uppercase;
|
|
420
|
+
letter-spacing: 0.05em;
|
|
421
|
+
color: #888;
|
|
422
|
+
margin-bottom: 8px;
|
|
423
|
+
}
|
|
424
|
+
.message-box .message {
|
|
425
|
+
color: #ff6b6b;
|
|
426
|
+
font-family: "SF Mono", "Fira Code", "Fira Mono", monospace;
|
|
427
|
+
font-size: 14px;
|
|
428
|
+
white-space: pre-wrap;
|
|
429
|
+
}
|
|
430
|
+
.stack-section { margin-bottom: 24px; }
|
|
431
|
+
.stack-section .label {
|
|
432
|
+
font-size: 11px;
|
|
433
|
+
font-weight: 600;
|
|
434
|
+
text-transform: uppercase;
|
|
435
|
+
letter-spacing: 0.05em;
|
|
436
|
+
color: #888;
|
|
437
|
+
margin-bottom: 12px;
|
|
438
|
+
}
|
|
439
|
+
.frame {
|
|
440
|
+
display: block;
|
|
441
|
+
padding: 6px 12px;
|
|
442
|
+
font-family: "SF Mono", "Fira Code", "Fira Mono", monospace;
|
|
443
|
+
font-size: 12px;
|
|
444
|
+
color: #b0b0d0;
|
|
445
|
+
line-height: 1.6;
|
|
446
|
+
border-left: 2px solid #3a3a5a;
|
|
447
|
+
margin-bottom: 2px;
|
|
448
|
+
}
|
|
449
|
+
.frame:first-child { border-left-color: #e74c3c; }
|
|
450
|
+
.hint {
|
|
451
|
+
font-size: 13px;
|
|
452
|
+
color: #888;
|
|
453
|
+
border-top: 1px solid #3a3a5a;
|
|
454
|
+
padding-top: 20px;
|
|
455
|
+
margin-top: 8px;
|
|
456
|
+
}
|
|
457
|
+
.hint a { color: #6ab0ff; }
|
|
458
|
+
</style>
|
|
459
|
+
</head>
|
|
460
|
+
<body>
|
|
461
|
+
<div class="overlay">
|
|
462
|
+
<div class="header">
|
|
463
|
+
<div class="badge">Server Error</div>
|
|
464
|
+
<h1>Unhandled Error During Render</h1>
|
|
465
|
+
</div>
|
|
466
|
+
<div class="message-box">
|
|
467
|
+
<div class="label">Error</div>
|
|
468
|
+
<div class="message">${escapeHtml2(message)}</div>
|
|
469
|
+
</div>
|
|
470
|
+
${stack ? `<div class="stack-section"><div class="label">Stack Trace</div>${frames}</div>` : ""}
|
|
471
|
+
<div class="hint">
|
|
472
|
+
Fix the error and save the file. In development mode, the server will reload automatically.
|
|
473
|
+
</div>
|
|
474
|
+
</div>
|
|
475
|
+
</body>
|
|
476
|
+
</html>`;
|
|
331
477
|
}
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
478
|
+
|
|
479
|
+
// src/images/proxy.ts
|
|
480
|
+
var DEFAULT_MAX_IMAGE_BYTES = 10 * 1024 * 1024;
|
|
481
|
+
var ALLOWED_CONTENT_TYPES = /* @__PURE__ */ new Set([
|
|
482
|
+
"image/png",
|
|
483
|
+
"image/jpeg",
|
|
484
|
+
"image/gif",
|
|
485
|
+
"image/webp",
|
|
486
|
+
"image/avif",
|
|
487
|
+
"image/x-icon"
|
|
488
|
+
]);
|
|
489
|
+
var RFC2606_RESERVED_TLD = /\.(example|test|invalid|localhost)$|^(localhost)$/;
|
|
490
|
+
var UpstreamImageTooLargeError = class extends Error {
|
|
491
|
+
maxBytes;
|
|
492
|
+
constructor(maxBytes) {
|
|
493
|
+
super(`Upstream image exceeds the ${maxBytes} byte limit`);
|
|
494
|
+
this.name = "UpstreamImageTooLargeError";
|
|
495
|
+
this.maxBytes = maxBytes;
|
|
342
496
|
}
|
|
343
|
-
|
|
497
|
+
};
|
|
498
|
+
function isIpLiteral(host) {
|
|
499
|
+
const stem = host.startsWith("[") ? host.slice(1, -1) : host;
|
|
500
|
+
return /^\d{1,3}(\.\d{1,3}){3}$/.test(stem) || stem.includes(":");
|
|
344
501
|
}
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
(function () {
|
|
352
|
-
if (window.__xNav) return;
|
|
353
|
-
window.__xNav = true;
|
|
354
|
-
|
|
355
|
-
var cache = new Map();
|
|
356
|
-
|
|
357
|
-
document.addEventListener("click", function (ev) {
|
|
358
|
-
if (ev.defaultPrevented || ev.button !== 0) return;
|
|
359
|
-
if (ev.metaKey || ev.ctrlKey || ev.shiftKey || ev.altKey) return;
|
|
360
|
-
var anchor = resolveLink(ev.target && ev.target.closest ? ev.target.closest("a[href]") : null);
|
|
361
|
-
if (!anchor) return;
|
|
362
|
-
ev.preventDefault();
|
|
363
|
-
if (anchor.href !== location.href) navigate(anchor, true);
|
|
364
|
-
});
|
|
365
|
-
|
|
366
|
-
document.addEventListener(
|
|
367
|
-
"mouseover",
|
|
368
|
-
function (ev) {
|
|
369
|
-
var anchor = resolveLink(ev.target && ev.target.closest ? ev.target.closest("a[href]") : null);
|
|
370
|
-
if (!anchor || anchor.hasAttribute("data-no-prefetch")) return;
|
|
371
|
-
prefetch(anchor);
|
|
372
|
-
},
|
|
373
|
-
{ passive: true },
|
|
374
|
-
);
|
|
375
|
-
|
|
376
|
-
document.addEventListener(
|
|
377
|
-
"focusin",
|
|
378
|
-
function (ev) {
|
|
379
|
-
var anchor = resolveLink(ev.target && ev.target.closest ? ev.target.closest("a[href]") : null);
|
|
380
|
-
if (!anchor || anchor.hasAttribute("data-no-prefetch")) return;
|
|
381
|
-
prefetch(anchor);
|
|
382
|
-
},
|
|
383
|
-
{ passive: true },
|
|
384
|
-
);
|
|
385
|
-
|
|
386
|
-
window.addEventListener("popstate", function () {
|
|
387
|
-
navigate(new URL(location.href), false);
|
|
388
|
-
});
|
|
389
|
-
|
|
390
|
-
var style = document.createElement("style");
|
|
391
|
-
style.textContent = [
|
|
392
|
-
".x-nav-loading{cursor:progress}",
|
|
393
|
-
".x-nav-loading::after{content:'';position:fixed;top:0;left:0;height:2px;width:100%;",
|
|
394
|
-
"background:var(--x-accent,#6ab0ff);z-index:9999;animation:x-nav-progress .8s ease-in-out infinite}",
|
|
395
|
-
"@keyframes x-nav-progress{0%{transform:translateX(-100%)}50%{transform:translateX(0)}100%{transform:translateX(100%)}}",
|
|
396
|
-
].join("");
|
|
397
|
-
document.head.appendChild(style);
|
|
398
|
-
|
|
399
|
-
function resolveLink(anchor) {
|
|
400
|
-
if (!anchor) return null;
|
|
401
|
-
if (anchor.hasAttribute("data-no-nav")) return null;
|
|
402
|
-
if (anchor.target && anchor.target !== "_self") return null;
|
|
403
|
-
if (anchor.hasAttribute("download")) return null;
|
|
404
|
-
var href = anchor.getAttribute("href");
|
|
405
|
-
if (!href) return null;
|
|
406
|
-
if (/^(#|mailto:|tel:|javascript:)/i.test(href)) return null;
|
|
407
|
-
var url;
|
|
408
|
-
try {
|
|
409
|
-
url = new URL(href, location.href);
|
|
410
|
-
} catch (_) {
|
|
411
|
-
return null;
|
|
412
|
-
}
|
|
413
|
-
if (url.origin !== location.origin) return null;
|
|
414
|
-
var here = new URL(location.href);
|
|
415
|
-
if (url.pathname === here.pathname && url.search === here.search && url.hash) return null;
|
|
416
|
-
return anchor;
|
|
417
|
-
}
|
|
418
|
-
|
|
419
|
-
function setLoading(on) {
|
|
420
|
-
document.documentElement.classList.toggle("x-nav-loading", on);
|
|
502
|
+
function isPrivateOrReservedAddress(host) {
|
|
503
|
+
const stem = host.startsWith("[") ? host.slice(1, -1) : host;
|
|
504
|
+
if (!stem.includes(":") && /^\d{1,3}(\.\d{1,3}){3}$/.test(stem)) {
|
|
505
|
+
const parts = stem.split(".").map((o) => Number(o));
|
|
506
|
+
if (parts.some((o) => !Number.isInteger(o) || o < 0 || o > 255)) return false;
|
|
507
|
+
return isPrivateOrReservedIPv4(parts);
|
|
421
508
|
}
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
if (
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
return res.text().then(function (html) {
|
|
428
|
-
var ct = res.headers.get("content-type") || "";
|
|
429
|
-
return { html: html, ok: res.ok, finalUrl: res.url || url.href, isHtml: ct.indexOf("text/html") !== -1 };
|
|
430
|
-
});
|
|
431
|
-
})
|
|
432
|
-
.catch(function (err) {
|
|
433
|
-
cache.delete(url.href);
|
|
434
|
-
throw err;
|
|
435
|
-
});
|
|
436
|
-
if (cache.size >= 30) {
|
|
437
|
-
var first = cache.keys().next().value;
|
|
438
|
-
if (first !== undefined) cache.delete(first);
|
|
509
|
+
if (stem.includes(":")) {
|
|
510
|
+
const v4Match = /(\d{1,3}(?:\.\d{1,3}){3})$/.exec(stem);
|
|
511
|
+
if (v4Match) {
|
|
512
|
+
const octets = (v4Match[1] ?? "").split(".").map((o) => Number(o));
|
|
513
|
+
return isPrivateOrReservedIPv4(octets);
|
|
439
514
|
}
|
|
440
|
-
cache.set(url.href, promise);
|
|
441
|
-
return promise;
|
|
442
|
-
}
|
|
443
|
-
|
|
444
|
-
function navigate(url, push) {
|
|
445
|
-
setLoading(true);
|
|
446
|
-
prefetch(url)
|
|
447
|
-
.then(function (payload) {
|
|
448
|
-
if (!payload.isHtml) {
|
|
449
|
-
location.href = url.href;
|
|
450
|
-
return;
|
|
451
|
-
}
|
|
452
|
-
var doc = new DOMParser().parseFromString(payload.html, "text/html");
|
|
453
|
-
var next = doc.getElementById("root");
|
|
454
|
-
var root = document.getElementById("root");
|
|
455
|
-
if (!next || !root) {
|
|
456
|
-
location.href = url.href;
|
|
457
|
-
return;
|
|
458
|
-
}
|
|
459
|
-
if (push) history.pushState({ xNav: true }, "", payload.finalUrl);
|
|
460
|
-
if (doc.title) document.title = doc.title;
|
|
461
|
-
if (window.__xIslandRoots) {
|
|
462
|
-
// Must stay in sync with unmountIslandRoots() \u2014 same logic, different
|
|
463
|
-
// execution context (this is an inline script, not a module import).
|
|
464
|
-
for (var i = 0; i < window.__xIslandRoots.length; i++) {
|
|
465
|
-
try { window.__xIslandRoots[i]?.unmount(); } catch (_) {}
|
|
466
|
-
}
|
|
467
|
-
window.__xIslandRoots.length = 0;
|
|
468
|
-
}
|
|
469
|
-
root.innerHTML = next.innerHTML;
|
|
470
|
-
reexecuteScripts(root);
|
|
471
|
-
if (url.hash) {
|
|
472
|
-
var target = document.getElementById(url.hash.slice(1));
|
|
473
|
-
if (target) {
|
|
474
|
-
target.scrollIntoView();
|
|
475
|
-
return;
|
|
476
|
-
}
|
|
477
|
-
}
|
|
478
|
-
window.scrollTo(0, 0);
|
|
479
|
-
})
|
|
480
|
-
.catch(function () {
|
|
481
|
-
location.href = url.href;
|
|
482
|
-
})
|
|
483
|
-
.finally(function () {
|
|
484
|
-
setLoading(false);
|
|
485
|
-
});
|
|
486
515
|
}
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
516
|
+
const groups = ipv6Groups(stem);
|
|
517
|
+
if (groups) return isPrivateOrReservedIPv6(groups);
|
|
518
|
+
return false;
|
|
519
|
+
}
|
|
520
|
+
function isPrivateOrReservedIPv4(parts) {
|
|
521
|
+
const [a = 0, b = 0, c = 0] = parts;
|
|
522
|
+
return a === 0 || a === 10 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 127 || a === 169 && b === 254 || a === 100 && b >= 64 && b <= 127 || a === 192 && b === 0 && c === 0 || a === 192 && b === 0 && c === 2 || a === 198 && (b === 18 || b === 19) || a === 198 && b === 51 && c === 100 || a === 203 && b === 0 && c === 113 || a >= 224;
|
|
523
|
+
}
|
|
524
|
+
function ipv6Groups(ip) {
|
|
525
|
+
let head = ip;
|
|
526
|
+
let tailV4 = null;
|
|
527
|
+
const lastColon = ip.lastIndexOf(":");
|
|
528
|
+
if (lastColon !== -1) {
|
|
529
|
+
const tail = ip.slice(lastColon + 1);
|
|
530
|
+
if (tail.includes(".")) {
|
|
531
|
+
const [v0 = 0, v1 = 0, v2 = 0, v3 = 0] = tail.split(".").map((o) => Number(o));
|
|
532
|
+
if (v0 > 255 || v1 > 255 || v2 > 255 || v3 > 255) {
|
|
533
|
+
return null;
|
|
496
534
|
}
|
|
497
|
-
|
|
498
|
-
|
|
535
|
+
tailV4 = [v0 * 256 + v1, v2 * 256 + v3];
|
|
536
|
+
head = ip.slice(0, lastColon);
|
|
499
537
|
}
|
|
500
538
|
}
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
(
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
if (typeof window.__xSoftReload === "function") {
|
|
516
|
-
window.__xSoftReload();
|
|
517
|
-
} else {
|
|
518
|
-
window.location.reload();
|
|
539
|
+
const doubleColon = head.indexOf("::");
|
|
540
|
+
let left = "";
|
|
541
|
+
let right = "";
|
|
542
|
+
if (doubleColon !== -1) {
|
|
543
|
+
left = head.slice(0, doubleColon);
|
|
544
|
+
right = head.slice(doubleColon + 2);
|
|
545
|
+
} else {
|
|
546
|
+
left = head;
|
|
547
|
+
}
|
|
548
|
+
const parseGroups = (s, out) => {
|
|
549
|
+
if (s === "") return true;
|
|
550
|
+
for (const part of s.split(":")) {
|
|
551
|
+
if (!/^[0-9a-fA-F]{1,4}$/.test(part)) return false;
|
|
552
|
+
out.push(Number.parseInt(part, 16));
|
|
519
553
|
}
|
|
520
|
-
|
|
521
|
-
es.addEventListener("hb", function () {});
|
|
522
|
-
es.onerror = function () {
|
|
523
|
-
es.close();
|
|
554
|
+
return true;
|
|
524
555
|
};
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
556
|
+
const l = [];
|
|
557
|
+
const r = [];
|
|
558
|
+
if (!parseGroups(left, l) || !parseGroups(right, r)) return null;
|
|
559
|
+
if (doubleColon !== -1) {
|
|
560
|
+
const zeros = 8 - l.length - r.length - (tailV4?.length ?? 0);
|
|
561
|
+
if (zeros < 1) return null;
|
|
562
|
+
return [...l, ...new Array(zeros).fill(0), ...r, ...tailV4 ?? []];
|
|
563
|
+
}
|
|
564
|
+
const all = [...l, ...tailV4 ?? [], ...r];
|
|
565
|
+
return all.length === 8 ? all : null;
|
|
531
566
|
}
|
|
532
|
-
function
|
|
533
|
-
|
|
567
|
+
function isPrivateOrReservedIPv6(groups) {
|
|
568
|
+
const [a = 0, b = 0, , , , , , last = 0] = groups;
|
|
569
|
+
return a === 0 && last === 1 || // loopback ::1
|
|
570
|
+
groups.every((g) => g === 0) || // unspecified ::
|
|
571
|
+
(a & 65024) === 64512 || // unique local fc00::/7
|
|
572
|
+
(a & 65472) === 65152 || // link-local fe80::/10
|
|
573
|
+
(a & 65280) === 65280 || // multicast ff00::/8
|
|
574
|
+
a === 8193 && b === 3512 || // documentation 2001:db8::/32
|
|
575
|
+
a === 100 && b === 65435 || // NAT64 64:ff9b::/96
|
|
576
|
+
a === 8193 && b === 16;
|
|
534
577
|
}
|
|
535
|
-
function
|
|
536
|
-
|
|
537
|
-
|
|
578
|
+
async function resolveHostDefault(hostname) {
|
|
579
|
+
if (RFC2606_RESERVED_TLD.test(hostname)) return [];
|
|
580
|
+
try {
|
|
581
|
+
const results = await Bun.dns.lookup(hostname);
|
|
582
|
+
return results.map((r) => r.address);
|
|
583
|
+
} catch {
|
|
584
|
+
return [];
|
|
585
|
+
}
|
|
538
586
|
}
|
|
539
|
-
function
|
|
540
|
-
|
|
587
|
+
function urlForIp(target, ip) {
|
|
588
|
+
const pinned = new URL(target.toString());
|
|
589
|
+
pinned.hostname = ip.includes(":") ? `[${ip}]` : ip;
|
|
590
|
+
return pinned;
|
|
541
591
|
}
|
|
542
|
-
function
|
|
543
|
-
|
|
544
|
-
|
|
592
|
+
function pinToVerifiedIp(target, verifiedIp) {
|
|
593
|
+
const init = { redirect: "manual", headers: { host: target.host } };
|
|
594
|
+
if (target.protocol === "https:") {
|
|
595
|
+
init.tls = { serverName: target.hostname };
|
|
596
|
+
}
|
|
597
|
+
return { url: urlForIp(target, verifiedIp), init };
|
|
545
598
|
}
|
|
546
|
-
function
|
|
547
|
-
|
|
548
|
-
|
|
599
|
+
async function resolveProxyTarget(target, resolveHost) {
|
|
600
|
+
if (isIpLiteral(target.hostname)) {
|
|
601
|
+
if (isPrivateOrReservedAddress(target.hostname)) {
|
|
602
|
+
return { status: "reject-literal" };
|
|
603
|
+
}
|
|
604
|
+
return { status: "ok", url: target, init: { redirect: "manual" } };
|
|
605
|
+
}
|
|
606
|
+
let ips = [];
|
|
607
|
+
try {
|
|
608
|
+
ips = await resolveHost(target.hostname);
|
|
609
|
+
} catch {
|
|
610
|
+
ips = [];
|
|
611
|
+
}
|
|
612
|
+
if (ips.some((ip) => isPrivateOrReservedAddress(ip))) {
|
|
613
|
+
return { status: "reject-dns" };
|
|
614
|
+
}
|
|
615
|
+
const verifiedIp = ips[0];
|
|
616
|
+
if (verifiedIp !== void 0) {
|
|
617
|
+
const { url, init } = pinToVerifiedIp(target, verifiedIp);
|
|
618
|
+
return { status: "ok", url, init };
|
|
619
|
+
}
|
|
620
|
+
return { status: "ok", url: target, init: { redirect: "manual" } };
|
|
549
621
|
}
|
|
550
|
-
function
|
|
551
|
-
|
|
552
|
-
const
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
}
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
const scripts = options.resolveIslandScripts ? await options.resolveIslandScripts() : options.islandScripts ?? [];
|
|
579
|
-
return buildShellHtml(body, options, scripts);
|
|
580
|
-
}
|
|
581
|
-
function buildShellHtml(body, options, islandScripts) {
|
|
582
|
-
const { islandProps } = options;
|
|
583
|
-
const title = options.title ?? "x app";
|
|
584
|
-
const nonce = options.cspNonce;
|
|
585
|
-
const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
|
|
586
|
-
const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json"${nonceAttr(nonce)}>${propsJson}</script>` : "";
|
|
587
|
-
const islandScriptsHtml = islandScripts.map((src) => `<script data-island-script src="${escapeHtml2(src)}"></script>`).join("\n ");
|
|
588
|
-
return htmlShell(
|
|
589
|
-
title,
|
|
590
|
-
buildHeadExtras(options.stylesheet),
|
|
591
|
-
propsScript,
|
|
592
|
-
islandScriptsHtml,
|
|
593
|
-
body,
|
|
594
|
-
buildNavScriptTag(options.clientNav, nonce),
|
|
595
|
-
buildLiveReloadTag(options.liveReload, nonce)
|
|
596
|
-
);
|
|
622
|
+
function enforceImageByteCount(body, maxBytes) {
|
|
623
|
+
if (body === null) return null;
|
|
624
|
+
const source = body;
|
|
625
|
+
const { readable, writable } = new TransformStream();
|
|
626
|
+
const writer = writable.getWriter();
|
|
627
|
+
let total = 0;
|
|
628
|
+
const pump = async () => {
|
|
629
|
+
const reader = source.getReader();
|
|
630
|
+
try {
|
|
631
|
+
while (true) {
|
|
632
|
+
const { done, value } = await reader.read();
|
|
633
|
+
if (done) break;
|
|
634
|
+
total += value.byteLength;
|
|
635
|
+
if (total > maxBytes) {
|
|
636
|
+
await reader.cancel().catch(() => {
|
|
637
|
+
});
|
|
638
|
+
await writer.abort(new UpstreamImageTooLargeError(maxBytes));
|
|
639
|
+
return;
|
|
640
|
+
}
|
|
641
|
+
await writer.write(value);
|
|
642
|
+
}
|
|
643
|
+
await writer.close();
|
|
644
|
+
} catch (err) {
|
|
645
|
+
await writer.abort(err);
|
|
646
|
+
}
|
|
647
|
+
};
|
|
648
|
+
void pump();
|
|
649
|
+
return readable;
|
|
597
650
|
}
|
|
598
|
-
function
|
|
599
|
-
const
|
|
600
|
-
const
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
if (
|
|
605
|
-
|
|
606
|
-
|
|
651
|
+
function createImageProxyHandler(options = {}) {
|
|
652
|
+
const allowedHosts = new Set(options.remoteHosts ?? []);
|
|
653
|
+
const maxBytes = options.maxBytes ?? DEFAULT_MAX_IMAGE_BYTES;
|
|
654
|
+
const resolveHost = options.resolveHost ?? resolveHostDefault;
|
|
655
|
+
return async (req) => {
|
|
656
|
+
const reqUrl = new URL(req.url);
|
|
657
|
+
if (reqUrl.pathname !== "/_x/image") return null;
|
|
658
|
+
if (req.method !== "GET" && req.method !== "HEAD") return null;
|
|
659
|
+
const target = reqUrl.searchParams.get("url");
|
|
660
|
+
if (!target) return new Response("missing url param", { status: 400 });
|
|
661
|
+
let parsed;
|
|
662
|
+
try {
|
|
663
|
+
parsed = new URL(target);
|
|
664
|
+
} catch {
|
|
665
|
+
return new Response("invalid url param", { status: 400 });
|
|
607
666
|
}
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
controller.close();
|
|
619
|
-
}
|
|
620
|
-
return;
|
|
667
|
+
const allowedUrl = (u) => (u.protocol === "http:" || u.protocol === "https:") && allowedHosts.has(u.hostname);
|
|
668
|
+
if (!allowedUrl(parsed)) {
|
|
669
|
+
return new Response("host not allow-listed for image proxy", { status: 403 });
|
|
670
|
+
}
|
|
671
|
+
const rejectFor = (status, hop) => {
|
|
672
|
+
if (status === "reject-literal") {
|
|
673
|
+
return new Response(
|
|
674
|
+
hop ? "upstream redirected to a private or reserved address" : "target is a private or reserved address",
|
|
675
|
+
{ status: 403 }
|
|
676
|
+
);
|
|
621
677
|
}
|
|
622
|
-
|
|
623
|
-
|
|
678
|
+
return new Response(
|
|
679
|
+
hop ? "upstream redirect resolves to a private or reserved address" : "target resolves to a private or reserved address",
|
|
680
|
+
{ status: 403 }
|
|
681
|
+
);
|
|
682
|
+
};
|
|
683
|
+
const initial = await resolveProxyTarget(parsed, resolveHost);
|
|
684
|
+
if (initial.status !== "ok") {
|
|
685
|
+
return rejectFor(initial.status, false);
|
|
624
686
|
}
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
687
|
+
const wParam = reqUrl.searchParams.get("w");
|
|
688
|
+
const qParam = reqUrl.searchParams.get("q");
|
|
689
|
+
if (wParam !== null) {
|
|
690
|
+
const w = Number.parseInt(wParam, 10);
|
|
691
|
+
if (!Number.isFinite(w) || w < 1 || w > 8192) {
|
|
692
|
+
return new Response("invalid w param", { status: 400 });
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
if (qParam !== null) {
|
|
696
|
+
const q = Number.parseInt(qParam, 10);
|
|
697
|
+
if (!Number.isFinite(q) || q < 1 || q > 100) {
|
|
698
|
+
return new Response("invalid q param", { status: 400 });
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
const isRedirect = (status) => status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
|
|
702
|
+
let upstream;
|
|
703
|
+
try {
|
|
704
|
+
upstream = await fetch(initial.url, initial.init);
|
|
705
|
+
for (let hop = 0; hop < 5; hop++) {
|
|
706
|
+
if (!isRedirect(upstream.status)) break;
|
|
707
|
+
const location = upstream.headers.get("location");
|
|
708
|
+
let next;
|
|
635
709
|
try {
|
|
636
|
-
|
|
710
|
+
next = new URL(location ?? "", parsed);
|
|
637
711
|
} catch {
|
|
712
|
+
return new Response("upstream redirect was not a valid URL", { status: 502 });
|
|
713
|
+
}
|
|
714
|
+
if (!allowedUrl(next)) {
|
|
715
|
+
return new Response("upstream redirected off the allow-list", { status: 403 });
|
|
716
|
+
}
|
|
717
|
+
const hopTarget = await resolveProxyTarget(next, resolveHost);
|
|
718
|
+
if (hopTarget.status !== "ok") {
|
|
719
|
+
return rejectFor(hopTarget.status, true);
|
|
638
720
|
}
|
|
721
|
+
upstream = await fetch(hopTarget.url, hopTarget.init);
|
|
639
722
|
}
|
|
640
|
-
}
|
|
641
|
-
|
|
642
|
-
reader.cancel(reason).catch(() => {
|
|
643
|
-
});
|
|
644
|
-
onCancel?.(reason);
|
|
723
|
+
} catch (err) {
|
|
724
|
+
return new Response(`upstream fetch failed: ${String(err)}`, { status: 502 });
|
|
645
725
|
}
|
|
646
|
-
|
|
647
|
-
}
|
|
648
|
-
async function renderStreamingPage(node, options = {}) {
|
|
649
|
-
const { islandScripts, islandProps } = options;
|
|
650
|
-
const title = escapeHtml2(options.title ?? "x app");
|
|
651
|
-
const nonce = options.cspNonce;
|
|
652
|
-
const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
|
|
653
|
-
const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json"${nonceAttr(nonce)}>${propsJson}</script>` : "";
|
|
654
|
-
const navScriptTag = buildNavScriptTag(options.clientNav, nonce);
|
|
655
|
-
const liveReloadTag = buildLiveReloadTag(options.liveReload, nonce);
|
|
656
|
-
const headExtras = buildHeadExtras(options.stylesheet);
|
|
657
|
-
const footer = `</div>${navScriptTag}
|
|
658
|
-
${liveReloadTag} </body>
|
|
659
|
-
</html>`;
|
|
660
|
-
const reactStream = await renderToReadableStream(node, {
|
|
661
|
-
onError(err) {
|
|
662
|
-
console.error("[x] render error:", err);
|
|
726
|
+
if (isRedirect(upstream.status)) {
|
|
727
|
+
return new Response("too many upstream redirects", { status: 502 });
|
|
663
728
|
}
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
...options.onRenderError ? { onRenderError: options.onRenderError } : {}
|
|
690
|
-
});
|
|
729
|
+
if (!upstream.ok) {
|
|
730
|
+
return new Response("upstream error", { status: 502 });
|
|
731
|
+
}
|
|
732
|
+
const contentType = upstream.headers.get("content-type") ?? "";
|
|
733
|
+
const baseContentType = (contentType.split(";")[0] ?? "").trim();
|
|
734
|
+
if (!ALLOWED_CONTENT_TYPES.has(baseContentType)) {
|
|
735
|
+
return new Response("upstream did not return an image", { status: 502 });
|
|
736
|
+
}
|
|
737
|
+
const contentLength = upstream.headers.get("content-length");
|
|
738
|
+
if (contentLength !== null && Number(contentLength) > maxBytes) {
|
|
739
|
+
await upstream.body?.cancel().catch(() => {
|
|
740
|
+
});
|
|
741
|
+
return new Response("upstream image exceeds the size limit", { status: 502 });
|
|
742
|
+
}
|
|
743
|
+
return new Response(enforceImageByteCount(upstream.body, maxBytes), {
|
|
744
|
+
status: 200,
|
|
745
|
+
headers: {
|
|
746
|
+
"Content-Type": contentType,
|
|
747
|
+
// Cache aggressively client + edge side — the proxied URL is the
|
|
748
|
+
// cache key, and remote asset URLs like this one are typically
|
|
749
|
+
// content-hashed by the origin already.
|
|
750
|
+
"Cache-Control": "public, max-age=86400, immutable"
|
|
751
|
+
}
|
|
752
|
+
});
|
|
753
|
+
};
|
|
691
754
|
}
|
|
692
755
|
|
|
693
|
-
// src/
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
routeEntries = scanPages(pagesDir);
|
|
717
|
-
}
|
|
718
|
-
if (apiDir && existsSync(apiDir)) {
|
|
719
|
-
routeEntries.push(...scanApiDir(apiDir));
|
|
720
|
-
}
|
|
721
|
-
const legacyApiDir = pagesDir ? join2(pagesDir, "api") : "";
|
|
722
|
-
if (legacyApiDir && existsSync(legacyApiDir) && legacyApiDir !== apiDir) {
|
|
723
|
-
routeEntries.push(...scanApiDir(legacyApiDir));
|
|
724
|
-
}
|
|
725
|
-
const actionModules = /* @__PURE__ */ new Map();
|
|
726
|
-
if (actionsDir && existsSync(actionsDir)) {
|
|
727
|
-
for (const actionFile of scanRoutes(actionsDir)) {
|
|
728
|
-
const mod = await import(actionFile.filePath);
|
|
729
|
-
const segments = actionFile.routePath.split("/").filter(Boolean);
|
|
730
|
-
const parentPath = `/${segments.slice(0, -1).join("/")}`;
|
|
731
|
-
const fnNames = [];
|
|
732
|
-
const actions = mod.actions;
|
|
733
|
-
if (actions) {
|
|
734
|
-
registerServerFunctions(parentPath, actionFile.paramNames, actions);
|
|
735
|
-
fnNames.push(...Object.keys(actions));
|
|
736
|
-
}
|
|
737
|
-
for (const [key, value] of Object.entries(mod)) {
|
|
738
|
-
if (key === "default" || key === "actions" || typeof value !== "function") continue;
|
|
739
|
-
registerServerFunctions(parentPath, actionFile.paramNames, {
|
|
740
|
-
[key]: value
|
|
741
|
-
});
|
|
742
|
-
fnNames.push(key);
|
|
743
|
-
}
|
|
744
|
-
if (fnNames.length > 0) {
|
|
745
|
-
actionModules.set(actionFile.filePath, { parentPath, fnNames });
|
|
746
|
-
}
|
|
747
|
-
}
|
|
756
|
+
// src/island.tsx
|
|
757
|
+
import { createContext, useContext } from "react";
|
|
758
|
+
import { jsx } from "react/jsx-runtime";
|
|
759
|
+
function createIslandRegistry() {
|
|
760
|
+
return { entries: [], nextId: 0 };
|
|
761
|
+
}
|
|
762
|
+
var IslandContext = createContext(null);
|
|
763
|
+
function IslandProvider({
|
|
764
|
+
registry,
|
|
765
|
+
children
|
|
766
|
+
}) {
|
|
767
|
+
return /* @__PURE__ */ jsx(IslandContext.Provider, { value: registry, children });
|
|
768
|
+
}
|
|
769
|
+
function Island({
|
|
770
|
+
name,
|
|
771
|
+
client = "idle",
|
|
772
|
+
children
|
|
773
|
+
}) {
|
|
774
|
+
const registry = useContext(IslandContext);
|
|
775
|
+
if (registry) {
|
|
776
|
+
const id = `x-island-${registry.nextId++}`;
|
|
777
|
+
registry.entries.push({ name, id });
|
|
778
|
+
return /* @__PURE__ */ jsx("div", { "data-island": name, "data-island-id": id, "data-island-client": client, children });
|
|
748
779
|
}
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
if (!Component) {
|
|
763
|
-
console.warn(`[x] ${entry.filePath} has no default export -- skipping`);
|
|
764
|
-
continue;
|
|
765
|
-
}
|
|
766
|
-
const mode = mod.mode ?? "server";
|
|
767
|
-
const layoutChain = findLayoutChain(entry.filePath, layouts, pagesDir);
|
|
768
|
-
for (const rootLayout of dedicatedLayouts) {
|
|
769
|
-
if (!layoutChain.some((l) => l.filePath === rootLayout.filePath)) {
|
|
770
|
-
layoutChain.unshift(rootLayout);
|
|
780
|
+
return /* @__PURE__ */ jsx("div", { "data-island": name, "data-island-id": "x-island-0", "data-island-client": client, children });
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
// src/middleware.ts
|
|
784
|
+
function composeMiddleware(fns, handler) {
|
|
785
|
+
return async (ctx, _next) => {
|
|
786
|
+
let index = -1;
|
|
787
|
+
const dispatch = async (i) => {
|
|
788
|
+
if (i <= index) throw new Error("next() called multiple times");
|
|
789
|
+
index = i;
|
|
790
|
+
const fn = fns[i];
|
|
791
|
+
if (fn) {
|
|
792
|
+
return fn(ctx, () => dispatch(i + 1));
|
|
771
793
|
}
|
|
772
|
-
|
|
773
|
-
const layoutModules = [];
|
|
774
|
-
for (const l of layoutChain) {
|
|
775
|
-
const layoutMod = await import(l.filePath);
|
|
776
|
-
if (layoutMod.default) layoutModules.push(layoutMod.default);
|
|
777
|
-
}
|
|
778
|
-
const page = {
|
|
779
|
-
entry,
|
|
780
|
-
filePath: entry.filePath,
|
|
781
|
-
mode,
|
|
782
|
-
Component,
|
|
783
|
-
layoutModules,
|
|
784
|
-
layoutFilePaths: layoutChain.map((l) => l.filePath)
|
|
794
|
+
return handler(ctx);
|
|
785
795
|
};
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
796
|
+
return tracePhase(
|
|
797
|
+
"x.middleware",
|
|
798
|
+
{ route: new URL(ctx.request.url).pathname },
|
|
799
|
+
() => dispatch(0)
|
|
800
|
+
);
|
|
801
|
+
};
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
// src/not-found.tsx
|
|
805
|
+
import { jsx as jsx2, jsxs } from "react/jsx-runtime";
|
|
806
|
+
function DefaultNotFound(_props) {
|
|
807
|
+
return /* @__PURE__ */ jsxs(
|
|
808
|
+
"main",
|
|
809
|
+
{
|
|
810
|
+
style: {
|
|
811
|
+
maxWidth: 640,
|
|
812
|
+
margin: "4rem auto",
|
|
813
|
+
padding: "0 1rem",
|
|
814
|
+
fontFamily: "system-ui, -apple-system, sans-serif",
|
|
815
|
+
textAlign: "center"
|
|
816
|
+
},
|
|
817
|
+
children: [
|
|
818
|
+
/* @__PURE__ */ jsx2("h1", { style: { fontSize: "4rem", fontWeight: 700, margin: "0 0 0.5rem", color: "#e74c3c" }, children: "404" }),
|
|
819
|
+
/* @__PURE__ */ jsx2("p", { style: { fontSize: "1.125rem", color: "#666", margin: "0 0 2rem" }, children: "This page could not be found." }),
|
|
820
|
+
/* @__PURE__ */ jsx2(
|
|
821
|
+
"a",
|
|
822
|
+
{
|
|
823
|
+
href: "/",
|
|
824
|
+
style: {
|
|
825
|
+
color: "#6ab0ff",
|
|
826
|
+
textDecoration: "underline",
|
|
827
|
+
fontSize: "0.875rem"
|
|
828
|
+
},
|
|
829
|
+
children: "Back to home"
|
|
830
|
+
}
|
|
831
|
+
)
|
|
832
|
+
]
|
|
790
833
|
}
|
|
791
|
-
}
|
|
792
|
-
let contentEntries = [];
|
|
793
|
-
if (options.contentDir) {
|
|
794
|
-
contentEntries = scanContent(options.contentDir);
|
|
795
|
-
}
|
|
796
|
-
console.log(
|
|
797
|
-
`[x] build: ${staticPages.length} static, ${serverPages.length} server, ${contentEntries.length} content pages`
|
|
798
834
|
);
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
);
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
// src/observability/health.ts
|
|
838
|
+
async function runChecks(checks) {
|
|
839
|
+
const results = {};
|
|
840
|
+
let allOk = true;
|
|
841
|
+
await Promise.all(
|
|
842
|
+
Object.entries(checks).map(async ([name, check]) => {
|
|
843
|
+
try {
|
|
844
|
+
const ok = await check();
|
|
845
|
+
results[name] = ok ? "ok" : "error";
|
|
846
|
+
if (!ok) allOk = false;
|
|
847
|
+
} catch {
|
|
848
|
+
results[name] = "error";
|
|
849
|
+
allOk = false;
|
|
850
|
+
}
|
|
851
|
+
})
|
|
852
|
+
);
|
|
853
|
+
return { status: allOk ? "ok" : "error", checks: results };
|
|
854
|
+
}
|
|
855
|
+
function createHealthCheckHandler(options = {}) {
|
|
856
|
+
const checks = options.checks ?? {};
|
|
857
|
+
return async (req) => {
|
|
858
|
+
const pathname = new URL(req.url).pathname;
|
|
859
|
+
if (pathname === "/healthz") {
|
|
860
|
+
return Response.json({ status: "ok" }, { status: 200 });
|
|
826
861
|
}
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
}
|
|
831
|
-
for (const content of contentEntries) {
|
|
832
|
-
const registry = createIslandRegistry();
|
|
833
|
-
const bodyHtml = renderMarkdown(content.body);
|
|
834
|
-
const pageContent = createElement(StaticContentPage, {
|
|
835
|
-
content,
|
|
836
|
-
bodyHtml
|
|
837
|
-
});
|
|
838
|
-
const rendered = createElement(IslandProvider, { registry }, pageContent);
|
|
839
|
-
const html = renderStaticPage(rendered, {
|
|
840
|
-
title: content.frontmatter.title ?? content.slug,
|
|
841
|
-
stylesheet: stylesheetHref
|
|
842
|
-
});
|
|
843
|
-
const outPath = content.routePath === "/" ? "/index.html" : `${content.routePath}/index.html`;
|
|
844
|
-
const fullPath = join2(clientDir, outPath);
|
|
845
|
-
mkdirSync(join2(fullPath, ".."), { recursive: true });
|
|
846
|
-
if (writtenPaths.has(outPath)) {
|
|
847
|
-
console.warn(` [warn] collision: content ${content.routePath} overwrites existing output`);
|
|
862
|
+
if (pathname === "/readyz") {
|
|
863
|
+
const result = await runChecks(checks);
|
|
864
|
+
return Response.json(result, { status: result.status === "ok" ? 200 : 503 });
|
|
848
865
|
}
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
console.log(` [content] ${content.routePath} -> ${outPath}`);
|
|
852
|
-
}
|
|
853
|
-
if (pagesDir || options.routesDir || options.contentDir) {
|
|
854
|
-
const srvOpts = {
|
|
855
|
-
pagesDir: pagesDir || options.routesDir || ""
|
|
856
|
-
};
|
|
857
|
-
if (options.apiDir) srvOpts.apiDir = options.apiDir;
|
|
858
|
-
if (options.layoutsDir) srvOpts.layoutsDir = options.layoutsDir;
|
|
859
|
-
if (options.actionsDir) srvOpts.actionsDir = options.actionsDir;
|
|
860
|
-
if (options.contentDir) srvOpts.contentDir = options.contentDir;
|
|
861
|
-
const configImportPath = options.configPath ? relativeImportPath(serverDir, options.configPath) : void 0;
|
|
862
|
-
const serverEntry = buildServerEntry(
|
|
863
|
-
srvOpts,
|
|
864
|
-
configImportPath,
|
|
865
|
-
stylesheetHref
|
|
866
|
-
);
|
|
867
|
-
const serverEntryPath = join2(serverDir, "index.ts");
|
|
868
|
-
writeFileSync(serverEntryPath, serverEntry, "utf-8");
|
|
869
|
-
console.log(
|
|
870
|
-
` [server] ${serverPages.length} page routes, ${apiRoutes.length} api routes -> server/index.ts`
|
|
871
|
-
);
|
|
872
|
-
}
|
|
873
|
-
console.log(`[x] build complete -> ${outDir}`);
|
|
866
|
+
return null;
|
|
867
|
+
};
|
|
874
868
|
}
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
869
|
+
|
|
870
|
+
// src/observability/logger.ts
|
|
871
|
+
function write(level, message, fields) {
|
|
872
|
+
const entry = {
|
|
873
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
874
|
+
level,
|
|
875
|
+
message: redactString(message),
|
|
876
|
+
...redactValue(fields)
|
|
877
|
+
};
|
|
878
|
+
const line = JSON.stringify(entry);
|
|
879
|
+
if (level === "error") {
|
|
880
|
+
console.error(line);
|
|
881
|
+
} else if (level === "warn") {
|
|
882
|
+
console.warn(line);
|
|
883
|
+
} else {
|
|
884
|
+
console.log(line);
|
|
879
885
|
}
|
|
880
|
-
return content;
|
|
881
886
|
}
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
887
|
+
var logger = {
|
|
888
|
+
info: (message, fields) => write("info", message, fields),
|
|
889
|
+
warn: (message, fields) => write("warn", message, fields),
|
|
890
|
+
error: (message, fields) => write("error", message, fields)
|
|
891
|
+
};
|
|
892
|
+
function withRequestLogging(handler) {
|
|
893
|
+
return async (req, server) => {
|
|
894
|
+
const start = performance.now();
|
|
895
|
+
const requestId = traceRequestId(req);
|
|
896
|
+
const route = new URL(req.url).pathname;
|
|
897
|
+
try {
|
|
898
|
+
const res = await handler(req, server);
|
|
899
|
+
const isStream = res.headers.get("content-type")?.includes("text/event-stream");
|
|
900
|
+
console.log(
|
|
901
|
+
`[x][request] ${req.method} ${route} -> ${res.status}${isStream ? " (stream opened, not closed)" : ""}`
|
|
902
|
+
);
|
|
903
|
+
write("info", isStream ? "stream opened" : "request completed", {
|
|
904
|
+
requestId,
|
|
905
|
+
route,
|
|
906
|
+
method: req.method,
|
|
907
|
+
status: res.status,
|
|
908
|
+
durationMs: Math.round(performance.now() - start)
|
|
909
|
+
});
|
|
910
|
+
if (!res.headers.has("x-request-id")) {
|
|
911
|
+
res.headers.set("x-request-id", requestId);
|
|
912
|
+
}
|
|
913
|
+
return res;
|
|
914
|
+
} catch (err) {
|
|
915
|
+
write("error", "request failed", {
|
|
916
|
+
requestId,
|
|
917
|
+
route,
|
|
918
|
+
method: req.method,
|
|
919
|
+
status: 500,
|
|
920
|
+
durationMs: Math.round(performance.now() - start),
|
|
921
|
+
// Redacted before emission — a throwing driver or app error whose
|
|
922
|
+
// message embeds a secret must never leak it into the log sink.
|
|
923
|
+
error: redactString(err instanceof Error ? err.message : String(err))
|
|
924
|
+
});
|
|
925
|
+
throw err;
|
|
926
|
+
}
|
|
927
|
+
};
|
|
892
928
|
}
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
if (configImportPath) {
|
|
900
|
-
lines.push("", "let userConfig = {};", "try {");
|
|
901
|
-
lines.push(` const mod = await import(${JSON.stringify(configImportPath)});`);
|
|
902
|
-
lines.push(" userConfig = mod.default ?? {};");
|
|
903
|
-
lines.push("} catch (err) {");
|
|
904
|
-
lines.push(
|
|
905
|
-
' console.warn("[x] failed to load x.config for security/observability options:", err);'
|
|
906
|
-
);
|
|
907
|
-
lines.push("}");
|
|
908
|
-
}
|
|
909
|
-
lines.push("", "const app = await createApp({");
|
|
910
|
-
for (const key of dirKeys) {
|
|
911
|
-
const val = opts[key];
|
|
912
|
-
if (val) lines.push(` ${key}: ${JSON.stringify(val)},`);
|
|
913
|
-
}
|
|
914
|
-
if (stylesheetHref) lines.push(` stylesheetHref: ${JSON.stringify(stylesheetHref)},`);
|
|
915
|
-
lines.push(' port: parseInt(process.env.PORT || "3000", 10),', " development: false,");
|
|
916
|
-
if (configImportPath) {
|
|
917
|
-
lines.push(" ...(userConfig.security ? { security: userConfig.security } : {}),");
|
|
918
|
-
lines.push(
|
|
919
|
-
" ...(userConfig.observability ? { observability: userConfig.observability } : {}),"
|
|
920
|
-
);
|
|
921
|
-
lines.push(" ...(userConfig.images ? { images: userConfig.images } : {}),");
|
|
929
|
+
|
|
930
|
+
// src/observability/metrics.ts
|
|
931
|
+
var noopMetrics = {
|
|
932
|
+
incr: () => {
|
|
933
|
+
},
|
|
934
|
+
observe: () => {
|
|
922
935
|
}
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
"",
|
|
930
|
-
"// Graceful shutdown: stop accepting new connections, flush the error",
|
|
931
|
-
"// reporter, then exit after in-flight requests have a moment to drain.",
|
|
932
|
-
"let shuttingDown = false;",
|
|
933
|
-
"async function shutdown(signal: string): Promise<void> {",
|
|
934
|
-
" if (shuttingDown) return;",
|
|
935
|
-
" shuttingDown = true;",
|
|
936
|
-
" console.log(`[x] received ${signal} - shutting down`);",
|
|
937
|
-
" try {",
|
|
938
|
-
' const { getErrorReporter } = await import("@thexjs/core");',
|
|
939
|
-
" await getErrorReporter().flush?.();",
|
|
940
|
-
" } catch {}",
|
|
941
|
-
" server.stop(true);",
|
|
942
|
-
" const exit = () => process.exit(0);",
|
|
943
|
-
" const drainTimer = setTimeout(exit, 3000);",
|
|
944
|
-
" drainTimer.unref?.();",
|
|
945
|
-
"}",
|
|
946
|
-
'process.on("SIGTERM", () => shutdown("SIGTERM"));',
|
|
947
|
-
'process.on("SIGINT", () => shutdown("SIGINT"));',
|
|
948
|
-
"",
|
|
949
|
-
"// Request-level errors are caught inside createApp's fetch boundary;",
|
|
950
|
-
"// anything that still escapes (a throw outside the request lifecycle,",
|
|
951
|
-
"// a rejected promise from a background sweep) is reported through the",
|
|
952
|
-
"// error reporter so the box reports instead of dying silently.",
|
|
953
|
-
'const { installProcessCrashHandlers } = await import("@thexjs/core");',
|
|
954
|
-
// Fail fast on an uncaughtException: the singleton state may be corrupted,
|
|
955
|
-
// so drain and let the orchestrator restart clean (see crash-handlers).
|
|
956
|
-
"installProcessCrashHandlers({ exitOnCrash: true });"
|
|
957
|
-
);
|
|
958
|
-
return lines.join("\n");
|
|
959
|
-
}
|
|
960
|
-
function relativeImportPath(fromDir, toFile) {
|
|
961
|
-
const rel = relative2(fromDir, toFile).replace(/\\/g, "/").replace(/\.(ts|js|mjs)$/, "");
|
|
962
|
-
return rel.startsWith(".") ? rel : `./${rel}`;
|
|
936
|
+
};
|
|
937
|
+
var DEFAULT_HISTOGRAM_BUCKETS_MS = [5, 10, 25, 50, 100, 250, 500, 1e3, 2500, 5e3, 1e4];
|
|
938
|
+
function seriesKey(name, labels) {
|
|
939
|
+
if (!labels) return name;
|
|
940
|
+
const sorted = Object.entries(labels).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${k}=${v}`);
|
|
941
|
+
return `${name}\0${sorted.join("\0")}`;
|
|
963
942
|
}
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
943
|
+
function createInMemoryMetrics(options = {}) {
|
|
944
|
+
const buckets = options.histogramBuckets ?? DEFAULT_HISTOGRAM_BUCKETS_MS;
|
|
945
|
+
const counters = /* @__PURE__ */ new Map();
|
|
946
|
+
const histograms = /* @__PURE__ */ new Map();
|
|
947
|
+
function incr(name, delta = 1, labels) {
|
|
948
|
+
const key = seriesKey(name, labels);
|
|
949
|
+
let series = counters.get(key);
|
|
950
|
+
if (!series) {
|
|
951
|
+
series = { name, labels: labels ?? {}, value: 0 };
|
|
952
|
+
counters.set(key, series);
|
|
953
|
+
}
|
|
954
|
+
series.value += delta;
|
|
976
955
|
}
|
|
977
|
-
|
|
978
|
-
const
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
956
|
+
function observe(name, value, labels) {
|
|
957
|
+
const key = seriesKey(name, labels);
|
|
958
|
+
let acc = histograms.get(key);
|
|
959
|
+
if (!acc) {
|
|
960
|
+
acc = { bucketCounts: new Array(buckets.length).fill(0), sum: 0, count: 0 };
|
|
961
|
+
histograms.set(key, acc);
|
|
962
|
+
}
|
|
963
|
+
acc.sum += value;
|
|
964
|
+
acc.count += 1;
|
|
965
|
+
for (let i = 0; i < buckets.length; i += 1) {
|
|
966
|
+
const bound = buckets[i];
|
|
967
|
+
if (bound === void 0) break;
|
|
968
|
+
if (value <= bound) {
|
|
969
|
+
for (let j = i; j < buckets.length; j += 1) {
|
|
970
|
+
acc.bucketCounts[j] = (acc.bucketCounts[j] ?? 0) + 1;
|
|
971
|
+
}
|
|
972
|
+
break;
|
|
973
|
+
}
|
|
982
974
|
}
|
|
983
|
-
return value;
|
|
984
975
|
}
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
976
|
+
function labelsFromKey(key) {
|
|
977
|
+
const [name] = key.split("\0");
|
|
978
|
+
const labelPart = name !== void 0 ? key.slice(name.length + 1) : "";
|
|
979
|
+
const labels = {};
|
|
980
|
+
if (labelPart) {
|
|
981
|
+
for (const pair of labelPart.split("\0")) {
|
|
982
|
+
const eq = pair.indexOf("=");
|
|
983
|
+
if (eq > 0) labels[pair.slice(0, eq)] = pair.slice(eq + 1);
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
return { name: name ?? key, labels };
|
|
989
987
|
}
|
|
990
|
-
|
|
991
|
-
|
|
988
|
+
function snapshot() {
|
|
989
|
+
const sortedCounters = [...counters.entries()].sort(([a], [b]) => a < b ? -1 : 1).map(([key, series]) => {
|
|
990
|
+
const { name, labels } = labelsFromKey(key);
|
|
991
|
+
return { name, labels, value: series.value };
|
|
992
|
+
});
|
|
993
|
+
const sortedHistograms = [...histograms.entries()].sort(([a], [b]) => a < b ? -1 : 1).map(([key, acc]) => {
|
|
994
|
+
const { name, labels } = labelsFromKey(key);
|
|
995
|
+
return { name, labels, bucketCounts: acc.bucketCounts, sum: acc.sum, count: acc.count };
|
|
996
|
+
});
|
|
997
|
+
return { counters: sortedCounters, histograms: sortedHistograms };
|
|
992
998
|
}
|
|
993
|
-
|
|
994
|
-
|
|
999
|
+
function renderMetrics() {
|
|
1000
|
+
const snap = snapshot();
|
|
1001
|
+
const lines = [];
|
|
1002
|
+
for (const counter of snap.counters) {
|
|
1003
|
+
lines.push(`# TYPE ${counter.name} counter`);
|
|
1004
|
+
lines.push(`${counter.name}${formatLabels(counter.labels)} ${counter.value}`);
|
|
1005
|
+
}
|
|
1006
|
+
for (const h of snap.histograms) {
|
|
1007
|
+
const labelWithLe = (le) => {
|
|
1008
|
+
const labels = { ...h.labels, le };
|
|
1009
|
+
return formatLabels(labels);
|
|
1010
|
+
};
|
|
1011
|
+
lines.push(`# TYPE ${h.name} histogram`);
|
|
1012
|
+
for (let i = 0; i < buckets.length; i += 1) {
|
|
1013
|
+
lines.push(`${h.name}_bucket${labelWithLe(String(buckets[i]))} ${h.bucketCounts[i]}`);
|
|
1014
|
+
}
|
|
1015
|
+
lines.push(`${h.name}_bucket${labelWithLe("+Inf")} ${h.count}`);
|
|
1016
|
+
lines.push(`${h.name}_sum${formatLabels(h.labels)} ${h.sum}`);
|
|
1017
|
+
lines.push(`${h.name}_count${formatLabels(h.labels)} ${h.count}`);
|
|
1018
|
+
}
|
|
1019
|
+
return `${lines.join("\n")}
|
|
1020
|
+
`;
|
|
995
1021
|
}
|
|
996
|
-
|
|
997
|
-
|
|
1022
|
+
function handleMetrics(req) {
|
|
1023
|
+
if (new URL(req.url).pathname !== "/metrics") return null;
|
|
1024
|
+
return new Response(renderMetrics(), {
|
|
1025
|
+
headers: { "Content-Type": "text/plain; version=0.0.4; charset=utf-8" }
|
|
1026
|
+
});
|
|
998
1027
|
}
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1028
|
+
return {
|
|
1029
|
+
incr,
|
|
1030
|
+
observe,
|
|
1031
|
+
snapshot,
|
|
1032
|
+
renderMetrics,
|
|
1033
|
+
handleMetrics,
|
|
1034
|
+
async flush() {
|
|
1004
1035
|
}
|
|
1005
|
-
}
|
|
1006
|
-
};
|
|
1007
|
-
|
|
1008
|
-
// src/error-overlay.ts
|
|
1009
|
-
function escapeHtml3(s) {
|
|
1010
|
-
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
1036
|
+
};
|
|
1011
1037
|
}
|
|
1012
|
-
function
|
|
1013
|
-
const
|
|
1014
|
-
const
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
<title>Server Error</title>
|
|
1022
|
-
<style>
|
|
1023
|
-
* { margin: 0; padding: 0; box-sizing: border-box; }
|
|
1024
|
-
body {
|
|
1025
|
-
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
|
1026
|
-
background: #1a1a2e;
|
|
1027
|
-
color: #e0e0e0;
|
|
1028
|
-
min-height: 100vh;
|
|
1029
|
-
display: flex;
|
|
1030
|
-
flex-direction: column;
|
|
1031
|
-
}
|
|
1032
|
-
.overlay {
|
|
1033
|
-
flex: 1;
|
|
1034
|
-
padding: 40px 24px;
|
|
1035
|
-
max-width: 900px;
|
|
1036
|
-
margin: 0 auto;
|
|
1037
|
-
width: 100%;
|
|
1038
|
-
}
|
|
1039
|
-
.header { margin-bottom: 32px; }
|
|
1040
|
-
.badge {
|
|
1041
|
-
display: inline-block;
|
|
1042
|
-
background: #e74c3c;
|
|
1043
|
-
color: #fff;
|
|
1044
|
-
font-size: 11px;
|
|
1045
|
-
font-weight: 700;
|
|
1046
|
-
letter-spacing: 0.05em;
|
|
1047
|
-
text-transform: uppercase;
|
|
1048
|
-
padding: 3px 10px;
|
|
1049
|
-
border-radius: 4px;
|
|
1050
|
-
margin-bottom: 12px;
|
|
1051
|
-
}
|
|
1052
|
-
h1 {
|
|
1053
|
-
font-size: 22px;
|
|
1054
|
-
font-weight: 600;
|
|
1055
|
-
color: #f0f0f0;
|
|
1056
|
-
line-height: 1.3;
|
|
1057
|
-
}
|
|
1058
|
-
.message-box {
|
|
1059
|
-
background: #2a2a4a;
|
|
1060
|
-
border: 1px solid #3a3a5a;
|
|
1061
|
-
border-radius: 8px;
|
|
1062
|
-
padding: 20px;
|
|
1063
|
-
margin-bottom: 24px;
|
|
1064
|
-
font-size: 15px;
|
|
1065
|
-
word-break: break-word;
|
|
1066
|
-
}
|
|
1067
|
-
.message-box .label {
|
|
1068
|
-
font-size: 11px;
|
|
1069
|
-
font-weight: 600;
|
|
1070
|
-
text-transform: uppercase;
|
|
1071
|
-
letter-spacing: 0.05em;
|
|
1072
|
-
color: #888;
|
|
1073
|
-
margin-bottom: 8px;
|
|
1074
|
-
}
|
|
1075
|
-
.message-box .message {
|
|
1076
|
-
color: #ff6b6b;
|
|
1077
|
-
font-family: "SF Mono", "Fira Code", "Fira Mono", monospace;
|
|
1078
|
-
font-size: 14px;
|
|
1079
|
-
white-space: pre-wrap;
|
|
1080
|
-
}
|
|
1081
|
-
.stack-section { margin-bottom: 24px; }
|
|
1082
|
-
.stack-section .label {
|
|
1083
|
-
font-size: 11px;
|
|
1084
|
-
font-weight: 600;
|
|
1085
|
-
text-transform: uppercase;
|
|
1086
|
-
letter-spacing: 0.05em;
|
|
1087
|
-
color: #888;
|
|
1088
|
-
margin-bottom: 12px;
|
|
1089
|
-
}
|
|
1090
|
-
.frame {
|
|
1091
|
-
display: block;
|
|
1092
|
-
padding: 6px 12px;
|
|
1093
|
-
font-family: "SF Mono", "Fira Code", "Fira Mono", monospace;
|
|
1094
|
-
font-size: 12px;
|
|
1095
|
-
color: #b0b0d0;
|
|
1096
|
-
line-height: 1.6;
|
|
1097
|
-
border-left: 2px solid #3a3a5a;
|
|
1098
|
-
margin-bottom: 2px;
|
|
1099
|
-
}
|
|
1100
|
-
.frame:first-child { border-left-color: #e74c3c; }
|
|
1101
|
-
.hint {
|
|
1102
|
-
font-size: 13px;
|
|
1103
|
-
color: #888;
|
|
1104
|
-
border-top: 1px solid #3a3a5a;
|
|
1105
|
-
padding-top: 20px;
|
|
1106
|
-
margin-top: 8px;
|
|
1107
|
-
}
|
|
1108
|
-
.hint a { color: #6ab0ff; }
|
|
1109
|
-
</style>
|
|
1110
|
-
</head>
|
|
1111
|
-
<body>
|
|
1112
|
-
<div class="overlay">
|
|
1113
|
-
<div class="header">
|
|
1114
|
-
<div class="badge">Server Error</div>
|
|
1115
|
-
<h1>Unhandled Error During Render</h1>
|
|
1116
|
-
</div>
|
|
1117
|
-
<div class="message-box">
|
|
1118
|
-
<div class="label">Error</div>
|
|
1119
|
-
<div class="message">${escapeHtml3(message)}</div>
|
|
1120
|
-
</div>
|
|
1121
|
-
${stack ? `<div class="stack-section"><div class="label">Stack Trace</div>${frames}</div>` : ""}
|
|
1122
|
-
<div class="hint">
|
|
1123
|
-
Fix the error and save the file. In development mode, the server will reload automatically.
|
|
1124
|
-
</div>
|
|
1125
|
-
</div>
|
|
1126
|
-
</body>
|
|
1127
|
-
</html>`;
|
|
1128
|
-
}
|
|
1129
|
-
|
|
1130
|
-
// src/images/proxy.ts
|
|
1131
|
-
var DEFAULT_MAX_IMAGE_BYTES = 10 * 1024 * 1024;
|
|
1132
|
-
var ALLOWED_CONTENT_TYPES = /* @__PURE__ */ new Set([
|
|
1133
|
-
"image/png",
|
|
1134
|
-
"image/jpeg",
|
|
1135
|
-
"image/gif",
|
|
1136
|
-
"image/webp",
|
|
1137
|
-
"image/avif",
|
|
1138
|
-
"image/x-icon"
|
|
1139
|
-
]);
|
|
1140
|
-
var RFC2606_RESERVED_TLD = /\.(example|test|invalid|localhost)$|^(localhost)$/;
|
|
1141
|
-
var UpstreamImageTooLargeError = class extends Error {
|
|
1142
|
-
maxBytes;
|
|
1143
|
-
constructor(maxBytes) {
|
|
1144
|
-
super(`Upstream image exceeds the ${maxBytes} byte limit`);
|
|
1145
|
-
this.name = "UpstreamImageTooLargeError";
|
|
1146
|
-
this.maxBytes = maxBytes;
|
|
1147
|
-
}
|
|
1148
|
-
};
|
|
1149
|
-
function isIpLiteral(host) {
|
|
1150
|
-
const stem = host.startsWith("[") ? host.slice(1, -1) : host;
|
|
1151
|
-
return /^\d{1,3}(\.\d{1,3}){3}$/.test(stem) || stem.includes(":");
|
|
1152
|
-
}
|
|
1153
|
-
function isPrivateOrReservedAddress(host) {
|
|
1154
|
-
const stem = host.startsWith("[") ? host.slice(1, -1) : host;
|
|
1155
|
-
if (!stem.includes(":") && /^\d{1,3}(\.\d{1,3}){3}$/.test(stem)) {
|
|
1156
|
-
const parts = stem.split(".").map((o) => Number(o));
|
|
1157
|
-
if (parts.some((o) => !Number.isInteger(o) || o < 0 || o > 255)) return false;
|
|
1158
|
-
return isPrivateOrReservedIPv4(parts);
|
|
1159
|
-
}
|
|
1160
|
-
if (stem.includes(":")) {
|
|
1161
|
-
const v4Match = /(\d{1,3}(?:\.\d{1,3}){3})$/.exec(stem);
|
|
1162
|
-
if (v4Match) {
|
|
1163
|
-
const octets = (v4Match[1] ?? "").split(".").map((o) => Number(o));
|
|
1164
|
-
return isPrivateOrReservedIPv4(octets);
|
|
1165
|
-
}
|
|
1166
|
-
}
|
|
1167
|
-
const groups = ipv6Groups(stem);
|
|
1168
|
-
if (groups) return isPrivateOrReservedIPv6(groups);
|
|
1169
|
-
return false;
|
|
1170
|
-
}
|
|
1171
|
-
function isPrivateOrReservedIPv4(parts) {
|
|
1172
|
-
const [a = 0, b = 0, c = 0] = parts;
|
|
1173
|
-
return a === 0 || a === 10 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 127 || a === 169 && b === 254 || a === 100 && b >= 64 && b <= 127 || a === 192 && b === 0 && c === 0 || a === 192 && b === 0 && c === 2 || a === 198 && (b === 18 || b === 19) || a === 198 && b === 51 && c === 100 || a === 203 && b === 0 && c === 113 || a >= 224;
|
|
1174
|
-
}
|
|
1175
|
-
function ipv6Groups(ip) {
|
|
1176
|
-
let head = ip;
|
|
1177
|
-
let tailV4 = null;
|
|
1178
|
-
const lastColon = ip.lastIndexOf(":");
|
|
1179
|
-
if (lastColon !== -1) {
|
|
1180
|
-
const tail = ip.slice(lastColon + 1);
|
|
1181
|
-
if (tail.includes(".")) {
|
|
1182
|
-
const [v0 = 0, v1 = 0, v2 = 0, v3 = 0] = tail.split(".").map((o) => Number(o));
|
|
1183
|
-
if (v0 > 255 || v1 > 255 || v2 > 255 || v3 > 255) {
|
|
1184
|
-
return null;
|
|
1185
|
-
}
|
|
1186
|
-
tailV4 = [v0 * 256 + v1, v2 * 256 + v3];
|
|
1187
|
-
head = ip.slice(0, lastColon);
|
|
1188
|
-
}
|
|
1189
|
-
}
|
|
1190
|
-
const doubleColon = head.indexOf("::");
|
|
1191
|
-
let left = "";
|
|
1192
|
-
let right = "";
|
|
1193
|
-
if (doubleColon !== -1) {
|
|
1194
|
-
left = head.slice(0, doubleColon);
|
|
1195
|
-
right = head.slice(doubleColon + 2);
|
|
1196
|
-
} else {
|
|
1197
|
-
left = head;
|
|
1198
|
-
}
|
|
1199
|
-
const parseGroups = (s, out) => {
|
|
1200
|
-
if (s === "") return true;
|
|
1201
|
-
for (const part of s.split(":")) {
|
|
1202
|
-
if (!/^[0-9a-fA-F]{1,4}$/.test(part)) return false;
|
|
1203
|
-
out.push(Number.parseInt(part, 16));
|
|
1204
|
-
}
|
|
1205
|
-
return true;
|
|
1206
|
-
};
|
|
1207
|
-
const l = [];
|
|
1208
|
-
const r = [];
|
|
1209
|
-
if (!parseGroups(left, l) || !parseGroups(right, r)) return null;
|
|
1210
|
-
if (doubleColon !== -1) {
|
|
1211
|
-
const zeros = 8 - l.length - r.length - (tailV4?.length ?? 0);
|
|
1212
|
-
if (zeros < 1) return null;
|
|
1213
|
-
return [...l, ...new Array(zeros).fill(0), ...r, ...tailV4 ?? []];
|
|
1214
|
-
}
|
|
1215
|
-
const all = [...l, ...tailV4 ?? [], ...r];
|
|
1216
|
-
return all.length === 8 ? all : null;
|
|
1217
|
-
}
|
|
1218
|
-
function isPrivateOrReservedIPv6(groups) {
|
|
1219
|
-
const [a = 0, b = 0, , , , , , last = 0] = groups;
|
|
1220
|
-
return a === 0 && last === 1 || // loopback ::1
|
|
1221
|
-
groups.every((g) => g === 0) || // unspecified ::
|
|
1222
|
-
(a & 65024) === 64512 || // unique local fc00::/7
|
|
1223
|
-
(a & 65472) === 65152 || // link-local fe80::/10
|
|
1224
|
-
(a & 65280) === 65280 || // multicast ff00::/8
|
|
1225
|
-
a === 8193 && b === 3512 || // documentation 2001:db8::/32
|
|
1226
|
-
a === 100 && b === 65435 || // NAT64 64:ff9b::/96
|
|
1227
|
-
a === 8193 && b === 16;
|
|
1228
|
-
}
|
|
1229
|
-
async function resolveHostDefault(hostname) {
|
|
1230
|
-
if (RFC2606_RESERVED_TLD.test(hostname)) return [];
|
|
1231
|
-
try {
|
|
1232
|
-
const results = await Bun.dns.lookup(hostname);
|
|
1233
|
-
return results.map((r) => r.address);
|
|
1234
|
-
} catch {
|
|
1235
|
-
return [];
|
|
1236
|
-
}
|
|
1237
|
-
}
|
|
1238
|
-
function urlForIp(target, ip) {
|
|
1239
|
-
const pinned = new URL(target.toString());
|
|
1240
|
-
pinned.hostname = ip.includes(":") ? `[${ip}]` : ip;
|
|
1241
|
-
return pinned;
|
|
1242
|
-
}
|
|
1243
|
-
function pinToVerifiedIp(target, verifiedIp) {
|
|
1244
|
-
const init = { redirect: "manual", headers: { host: target.host } };
|
|
1245
|
-
if (target.protocol === "https:") {
|
|
1246
|
-
init.tls = { serverName: target.hostname };
|
|
1247
|
-
}
|
|
1248
|
-
return { url: urlForIp(target, verifiedIp), init };
|
|
1249
|
-
}
|
|
1250
|
-
async function resolveProxyTarget(target, resolveHost) {
|
|
1251
|
-
if (isIpLiteral(target.hostname)) {
|
|
1252
|
-
if (isPrivateOrReservedAddress(target.hostname)) {
|
|
1253
|
-
return { status: "reject-literal" };
|
|
1254
|
-
}
|
|
1255
|
-
return { status: "ok", url: target, init: { redirect: "manual" } };
|
|
1256
|
-
}
|
|
1257
|
-
let ips = [];
|
|
1258
|
-
try {
|
|
1259
|
-
ips = await resolveHost(target.hostname);
|
|
1260
|
-
} catch {
|
|
1261
|
-
ips = [];
|
|
1262
|
-
}
|
|
1263
|
-
if (ips.some((ip) => isPrivateOrReservedAddress(ip))) {
|
|
1264
|
-
return { status: "reject-dns" };
|
|
1265
|
-
}
|
|
1266
|
-
const verifiedIp = ips[0];
|
|
1267
|
-
if (verifiedIp !== void 0) {
|
|
1268
|
-
const { url, init } = pinToVerifiedIp(target, verifiedIp);
|
|
1269
|
-
return { status: "ok", url, init };
|
|
1270
|
-
}
|
|
1271
|
-
return { status: "ok", url: target, init: { redirect: "manual" } };
|
|
1272
|
-
}
|
|
1273
|
-
function enforceImageByteCount(body, maxBytes) {
|
|
1274
|
-
if (body === null) return null;
|
|
1275
|
-
const source = body;
|
|
1276
|
-
const { readable, writable } = new TransformStream();
|
|
1277
|
-
const writer = writable.getWriter();
|
|
1278
|
-
let total = 0;
|
|
1279
|
-
const pump = async () => {
|
|
1280
|
-
const reader = source.getReader();
|
|
1281
|
-
try {
|
|
1282
|
-
while (true) {
|
|
1283
|
-
const { done, value } = await reader.read();
|
|
1284
|
-
if (done) break;
|
|
1285
|
-
total += value.byteLength;
|
|
1286
|
-
if (total > maxBytes) {
|
|
1287
|
-
await reader.cancel().catch(() => {
|
|
1288
|
-
});
|
|
1289
|
-
await writer.abort(new UpstreamImageTooLargeError(maxBytes));
|
|
1290
|
-
return;
|
|
1291
|
-
}
|
|
1292
|
-
await writer.write(value);
|
|
1293
|
-
}
|
|
1294
|
-
await writer.close();
|
|
1295
|
-
} catch (err) {
|
|
1296
|
-
await writer.abort(err);
|
|
1297
|
-
}
|
|
1298
|
-
};
|
|
1299
|
-
void pump();
|
|
1300
|
-
return readable;
|
|
1301
|
-
}
|
|
1302
|
-
function createImageProxyHandler(options = {}) {
|
|
1303
|
-
const allowedHosts = new Set(options.remoteHosts ?? []);
|
|
1304
|
-
const maxBytes = options.maxBytes ?? DEFAULT_MAX_IMAGE_BYTES;
|
|
1305
|
-
const resolveHost = options.resolveHost ?? resolveHostDefault;
|
|
1306
|
-
return async (req) => {
|
|
1307
|
-
const reqUrl = new URL(req.url);
|
|
1308
|
-
if (reqUrl.pathname !== "/_x/image") return null;
|
|
1309
|
-
if (req.method !== "GET" && req.method !== "HEAD") return null;
|
|
1310
|
-
const target = reqUrl.searchParams.get("url");
|
|
1311
|
-
if (!target) return new Response("missing url param", { status: 400 });
|
|
1312
|
-
let parsed;
|
|
1313
|
-
try {
|
|
1314
|
-
parsed = new URL(target);
|
|
1315
|
-
} catch {
|
|
1316
|
-
return new Response("invalid url param", { status: 400 });
|
|
1317
|
-
}
|
|
1318
|
-
const allowedUrl = (u) => (u.protocol === "http:" || u.protocol === "https:") && allowedHosts.has(u.hostname);
|
|
1319
|
-
if (!allowedUrl(parsed)) {
|
|
1320
|
-
return new Response("host not allow-listed for image proxy", { status: 403 });
|
|
1321
|
-
}
|
|
1322
|
-
const rejectFor = (status, hop) => {
|
|
1323
|
-
if (status === "reject-literal") {
|
|
1324
|
-
return new Response(
|
|
1325
|
-
hop ? "upstream redirected to a private or reserved address" : "target is a private or reserved address",
|
|
1326
|
-
{ status: 403 }
|
|
1327
|
-
);
|
|
1328
|
-
}
|
|
1329
|
-
return new Response(
|
|
1330
|
-
hop ? "upstream redirect resolves to a private or reserved address" : "target resolves to a private or reserved address",
|
|
1331
|
-
{ status: 403 }
|
|
1332
|
-
);
|
|
1333
|
-
};
|
|
1334
|
-
const initial = await resolveProxyTarget(parsed, resolveHost);
|
|
1335
|
-
if (initial.status !== "ok") {
|
|
1336
|
-
return rejectFor(initial.status, false);
|
|
1337
|
-
}
|
|
1338
|
-
const wParam = reqUrl.searchParams.get("w");
|
|
1339
|
-
const qParam = reqUrl.searchParams.get("q");
|
|
1340
|
-
if (wParam !== null) {
|
|
1341
|
-
const w = Number.parseInt(wParam, 10);
|
|
1342
|
-
if (!Number.isFinite(w) || w < 1 || w > 8192) {
|
|
1343
|
-
return new Response("invalid w param", { status: 400 });
|
|
1344
|
-
}
|
|
1345
|
-
}
|
|
1346
|
-
if (qParam !== null) {
|
|
1347
|
-
const q = Number.parseInt(qParam, 10);
|
|
1348
|
-
if (!Number.isFinite(q) || q < 1 || q > 100) {
|
|
1349
|
-
return new Response("invalid q param", { status: 400 });
|
|
1350
|
-
}
|
|
1351
|
-
}
|
|
1352
|
-
const isRedirect = (status) => status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
|
|
1353
|
-
let upstream;
|
|
1354
|
-
try {
|
|
1355
|
-
upstream = await fetch(initial.url, initial.init);
|
|
1356
|
-
for (let hop = 0; hop < 5; hop++) {
|
|
1357
|
-
if (!isRedirect(upstream.status)) break;
|
|
1358
|
-
const location = upstream.headers.get("location");
|
|
1359
|
-
let next;
|
|
1360
|
-
try {
|
|
1361
|
-
next = new URL(location ?? "", parsed);
|
|
1362
|
-
} catch {
|
|
1363
|
-
return new Response("upstream redirect was not a valid URL", { status: 502 });
|
|
1364
|
-
}
|
|
1365
|
-
if (!allowedUrl(next)) {
|
|
1366
|
-
return new Response("upstream redirected off the allow-list", { status: 403 });
|
|
1367
|
-
}
|
|
1368
|
-
const hopTarget = await resolveProxyTarget(next, resolveHost);
|
|
1369
|
-
if (hopTarget.status !== "ok") {
|
|
1370
|
-
return rejectFor(hopTarget.status, true);
|
|
1371
|
-
}
|
|
1372
|
-
upstream = await fetch(hopTarget.url, hopTarget.init);
|
|
1373
|
-
}
|
|
1374
|
-
} catch (err) {
|
|
1375
|
-
return new Response(`upstream fetch failed: ${String(err)}`, { status: 502 });
|
|
1376
|
-
}
|
|
1377
|
-
if (isRedirect(upstream.status)) {
|
|
1378
|
-
return new Response("too many upstream redirects", { status: 502 });
|
|
1379
|
-
}
|
|
1380
|
-
if (!upstream.ok) {
|
|
1381
|
-
return new Response("upstream error", { status: 502 });
|
|
1382
|
-
}
|
|
1383
|
-
const contentType = upstream.headers.get("content-type") ?? "";
|
|
1384
|
-
const baseContentType = (contentType.split(";")[0] ?? "").trim();
|
|
1385
|
-
if (!ALLOWED_CONTENT_TYPES.has(baseContentType)) {
|
|
1386
|
-
return new Response("upstream did not return an image", { status: 502 });
|
|
1387
|
-
}
|
|
1388
|
-
const contentLength = upstream.headers.get("content-length");
|
|
1389
|
-
if (contentLength !== null && Number(contentLength) > maxBytes) {
|
|
1390
|
-
await upstream.body?.cancel().catch(() => {
|
|
1391
|
-
});
|
|
1392
|
-
return new Response("upstream image exceeds the size limit", { status: 502 });
|
|
1393
|
-
}
|
|
1394
|
-
return new Response(enforceImageByteCount(upstream.body, maxBytes), {
|
|
1395
|
-
status: 200,
|
|
1396
|
-
headers: {
|
|
1397
|
-
"Content-Type": contentType,
|
|
1398
|
-
// Cache aggressively client + edge side — the proxied URL is the
|
|
1399
|
-
// cache key, and remote asset URLs like this one are typically
|
|
1400
|
-
// content-hashed by the origin already.
|
|
1401
|
-
"Cache-Control": "public, max-age=86400, immutable"
|
|
1402
|
-
}
|
|
1403
|
-
});
|
|
1404
|
-
};
|
|
1405
|
-
}
|
|
1406
|
-
|
|
1407
|
-
// src/middleware.ts
|
|
1408
|
-
function composeMiddleware(fns, handler) {
|
|
1409
|
-
return async (ctx, _next) => {
|
|
1410
|
-
let index = -1;
|
|
1411
|
-
const dispatch = async (i) => {
|
|
1412
|
-
if (i <= index) throw new Error("next() called multiple times");
|
|
1413
|
-
index = i;
|
|
1414
|
-
const fn = fns[i];
|
|
1415
|
-
if (fn) {
|
|
1416
|
-
return fn(ctx, () => dispatch(i + 1));
|
|
1038
|
+
function createOtlpMetricsReporter(meter) {
|
|
1039
|
+
const counters = /* @__PURE__ */ new Map();
|
|
1040
|
+
const histograms = /* @__PURE__ */ new Map();
|
|
1041
|
+
return {
|
|
1042
|
+
incr(name, delta, labels) {
|
|
1043
|
+
let counter = counters.get(name);
|
|
1044
|
+
if (!counter) {
|
|
1045
|
+
counter = meter.createCounter(name, { description: `Counter ${name}` });
|
|
1046
|
+
counters.set(name, counter);
|
|
1417
1047
|
}
|
|
1418
|
-
|
|
1419
|
-
}
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
};
|
|
1426
|
-
}
|
|
1427
|
-
|
|
1428
|
-
// src/not-found.tsx
|
|
1429
|
-
import { jsx as jsx2, jsxs } from "react/jsx-runtime";
|
|
1430
|
-
function DefaultNotFound(_props) {
|
|
1431
|
-
return /* @__PURE__ */ jsxs(
|
|
1432
|
-
"main",
|
|
1433
|
-
{
|
|
1434
|
-
style: {
|
|
1435
|
-
maxWidth: 640,
|
|
1436
|
-
margin: "4rem auto",
|
|
1437
|
-
padding: "0 1rem",
|
|
1438
|
-
fontFamily: "system-ui, -apple-system, sans-serif",
|
|
1439
|
-
textAlign: "center"
|
|
1440
|
-
},
|
|
1441
|
-
children: [
|
|
1442
|
-
/* @__PURE__ */ jsx2("h1", { style: { fontSize: "4rem", fontWeight: 700, margin: "0 0 0.5rem", color: "#e74c3c" }, children: "404" }),
|
|
1443
|
-
/* @__PURE__ */ jsx2("p", { style: { fontSize: "1.125rem", color: "#666", margin: "0 0 2rem" }, children: "This page could not be found." }),
|
|
1444
|
-
/* @__PURE__ */ jsx2(
|
|
1445
|
-
"a",
|
|
1446
|
-
{
|
|
1447
|
-
href: "/",
|
|
1448
|
-
style: {
|
|
1449
|
-
color: "#6ab0ff",
|
|
1450
|
-
textDecoration: "underline",
|
|
1451
|
-
fontSize: "0.875rem"
|
|
1452
|
-
},
|
|
1453
|
-
children: "Back to home"
|
|
1454
|
-
}
|
|
1455
|
-
)
|
|
1456
|
-
]
|
|
1457
|
-
}
|
|
1458
|
-
);
|
|
1459
|
-
}
|
|
1460
|
-
|
|
1461
|
-
// src/observability/health.ts
|
|
1462
|
-
async function runChecks(checks) {
|
|
1463
|
-
const results = {};
|
|
1464
|
-
let allOk = true;
|
|
1465
|
-
await Promise.all(
|
|
1466
|
-
Object.entries(checks).map(async ([name, check]) => {
|
|
1467
|
-
try {
|
|
1468
|
-
const ok = await check();
|
|
1469
|
-
results[name] = ok ? "ok" : "error";
|
|
1470
|
-
if (!ok) allOk = false;
|
|
1471
|
-
} catch {
|
|
1472
|
-
results[name] = "error";
|
|
1473
|
-
allOk = false;
|
|
1048
|
+
counter.add(delta ?? 1, labels);
|
|
1049
|
+
},
|
|
1050
|
+
observe(name, value, labels) {
|
|
1051
|
+
let histogram = histograms.get(name);
|
|
1052
|
+
if (!histogram) {
|
|
1053
|
+
histogram = meter.createHistogram(name, { description: `Histogram ${name}` });
|
|
1054
|
+
histograms.set(name, histogram);
|
|
1474
1055
|
}
|
|
1475
|
-
|
|
1476
|
-
);
|
|
1477
|
-
return { status: allOk ? "ok" : "error", checks: results };
|
|
1478
|
-
}
|
|
1479
|
-
function createHealthCheckHandler(options = {}) {
|
|
1480
|
-
const checks = options.checks ?? {};
|
|
1481
|
-
return async (req) => {
|
|
1482
|
-
const pathname = new URL(req.url).pathname;
|
|
1483
|
-
if (pathname === "/healthz") {
|
|
1484
|
-
return Response.json({ status: "ok" }, { status: 200 });
|
|
1485
|
-
}
|
|
1486
|
-
if (pathname === "/readyz") {
|
|
1487
|
-
const result = await runChecks(checks);
|
|
1488
|
-
return Response.json(result, { status: result.status === "ok" ? 200 : 503 });
|
|
1056
|
+
histogram.record(value, labels);
|
|
1489
1057
|
}
|
|
1490
|
-
return null;
|
|
1491
1058
|
};
|
|
1492
1059
|
}
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
const
|
|
1497
|
-
|
|
1498
|
-
level,
|
|
1499
|
-
message: redactString(message),
|
|
1500
|
-
...redactValue(fields)
|
|
1501
|
-
};
|
|
1502
|
-
const line = JSON.stringify(entry);
|
|
1503
|
-
if (level === "error") {
|
|
1504
|
-
console.error(line);
|
|
1505
|
-
} else if (level === "warn") {
|
|
1506
|
-
console.warn(line);
|
|
1507
|
-
} else {
|
|
1508
|
-
console.log(line);
|
|
1509
|
-
}
|
|
1060
|
+
function formatLabels(labels) {
|
|
1061
|
+
const entries = Object.entries(labels);
|
|
1062
|
+
if (entries.length === 0) return "";
|
|
1063
|
+
const escaped = entries.map(([k, v]) => `${k}="${escapeLabelValue(v)}"`).join(",");
|
|
1064
|
+
return `{${escaped}}`;
|
|
1510
1065
|
}
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
};
|
|
1516
|
-
function withRequestLogging(handler) {
|
|
1066
|
+
function escapeLabelValue(value) {
|
|
1067
|
+
return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n");
|
|
1068
|
+
}
|
|
1069
|
+
function withRequestMetrics(reporter, handler) {
|
|
1517
1070
|
return async (req, server) => {
|
|
1518
1071
|
const start = performance.now();
|
|
1519
|
-
const
|
|
1520
|
-
const route = new URL(req.url).pathname;
|
|
1072
|
+
const method = req.method;
|
|
1521
1073
|
try {
|
|
1522
1074
|
const res = await handler(req, server);
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
`[x][request] ${req.method} ${route} -> ${res.status}${isStream ? " (stream opened, not closed)" : ""}`
|
|
1526
|
-
);
|
|
1527
|
-
write("info", isStream ? "stream opened" : "request completed", {
|
|
1528
|
-
requestId,
|
|
1529
|
-
route,
|
|
1530
|
-
method: req.method,
|
|
1531
|
-
status: res.status,
|
|
1532
|
-
durationMs: Math.round(performance.now() - start)
|
|
1533
|
-
});
|
|
1534
|
-
if (!res.headers.has("x-request-id")) {
|
|
1535
|
-
res.headers.set("x-request-id", requestId);
|
|
1536
|
-
}
|
|
1075
|
+
reporter.incr("x_http_requests_total", 1, { method, status: String(res.status) });
|
|
1076
|
+
reporter.observe("x_http_request_duration_ms", performance.now() - start, { method });
|
|
1537
1077
|
return res;
|
|
1538
1078
|
} catch (err) {
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
method: req.method,
|
|
1543
|
-
status: 500,
|
|
1544
|
-
durationMs: Math.round(performance.now() - start),
|
|
1545
|
-
// Redacted before emission — a throwing driver or app error whose
|
|
1546
|
-
// message embeds a secret must never leak it into the log sink.
|
|
1547
|
-
error: redactString(err instanceof Error ? err.message : String(err))
|
|
1548
|
-
});
|
|
1079
|
+
reporter.incr("x_http_requests_total", 1, { method, status: "500" });
|
|
1080
|
+
reporter.incr("x_http_errors_total", 1, { method });
|
|
1081
|
+
reporter.observe("x_http_request_duration_ms", performance.now() - start, { method });
|
|
1549
1082
|
throw err;
|
|
1550
1083
|
}
|
|
1551
1084
|
};
|
|
1552
1085
|
}
|
|
1553
1086
|
|
|
1554
|
-
// src/
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1087
|
+
// src/render.ts
|
|
1088
|
+
import { renderToReadableStream, renderToStaticMarkup, renderToString } from "react-dom/server";
|
|
1089
|
+
|
|
1090
|
+
// src/client-nav.ts
|
|
1091
|
+
var CLIENT_NAV_SCRIPT = `
|
|
1092
|
+
(function () {
|
|
1093
|
+
if (window.__xNav) return;
|
|
1094
|
+
window.__xNav = true;
|
|
1095
|
+
|
|
1096
|
+
var cache = new Map();
|
|
1097
|
+
|
|
1098
|
+
document.addEventListener("click", function (ev) {
|
|
1099
|
+
if (ev.defaultPrevented || ev.button !== 0) return;
|
|
1100
|
+
if (ev.metaKey || ev.ctrlKey || ev.shiftKey || ev.altKey) return;
|
|
1101
|
+
var anchor = resolveLink(ev.target && ev.target.closest ? ev.target.closest("a[href]") : null);
|
|
1102
|
+
if (!anchor) return;
|
|
1103
|
+
ev.preventDefault();
|
|
1104
|
+
if (anchor.href !== location.href) navigate(anchor, true);
|
|
1105
|
+
});
|
|
1106
|
+
|
|
1107
|
+
document.addEventListener(
|
|
1108
|
+
"mouseover",
|
|
1109
|
+
function (ev) {
|
|
1110
|
+
var anchor = resolveLink(ev.target && ev.target.closest ? ev.target.closest("a[href]") : null);
|
|
1111
|
+
if (!anchor || anchor.hasAttribute("data-no-prefetch")) return;
|
|
1112
|
+
prefetch(anchor);
|
|
1113
|
+
},
|
|
1114
|
+
{ passive: true },
|
|
1115
|
+
);
|
|
1116
|
+
|
|
1117
|
+
document.addEventListener(
|
|
1118
|
+
"focusin",
|
|
1119
|
+
function (ev) {
|
|
1120
|
+
var anchor = resolveLink(ev.target && ev.target.closest ? ev.target.closest("a[href]") : null);
|
|
1121
|
+
if (!anchor || anchor.hasAttribute("data-no-prefetch")) return;
|
|
1122
|
+
prefetch(anchor);
|
|
1123
|
+
},
|
|
1124
|
+
{ passive: true },
|
|
1125
|
+
);
|
|
1126
|
+
|
|
1127
|
+
window.addEventListener("popstate", function () {
|
|
1128
|
+
navigate(new URL(location.href), false);
|
|
1129
|
+
});
|
|
1130
|
+
|
|
1131
|
+
var style = document.createElement("style");
|
|
1132
|
+
style.textContent = [
|
|
1133
|
+
".x-nav-loading{cursor:progress}",
|
|
1134
|
+
".x-nav-loading::after{content:'';position:fixed;top:0;left:0;height:2px;width:100%;",
|
|
1135
|
+
"background:var(--x-accent,#6ab0ff);z-index:9999;animation:x-nav-progress .8s ease-in-out infinite}",
|
|
1136
|
+
"@keyframes x-nav-progress{0%{transform:translateX(-100%)}50%{transform:translateX(0)}100%{transform:translateX(100%)}}",
|
|
1137
|
+
].join("");
|
|
1138
|
+
document.head.appendChild(style);
|
|
1139
|
+
|
|
1140
|
+
function resolveLink(anchor) {
|
|
1141
|
+
if (!anchor) return null;
|
|
1142
|
+
if (anchor.hasAttribute("data-no-nav")) return null;
|
|
1143
|
+
if (anchor.target && anchor.target !== "_self") return null;
|
|
1144
|
+
if (anchor.hasAttribute("download")) return null;
|
|
1145
|
+
var href = anchor.getAttribute("href");
|
|
1146
|
+
if (!href) return null;
|
|
1147
|
+
if (/^(#|mailto:|tel:|javascript:)/i.test(href)) return null;
|
|
1148
|
+
var url;
|
|
1149
|
+
try {
|
|
1150
|
+
url = new URL(href, location.href);
|
|
1151
|
+
} catch (_) {
|
|
1152
|
+
return null;
|
|
1153
|
+
}
|
|
1154
|
+
if (url.origin !== location.origin) return null;
|
|
1155
|
+
var here = new URL(location.href);
|
|
1156
|
+
if (url.pathname === here.pathname && url.search === here.search && url.hash) return null;
|
|
1157
|
+
return anchor;
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
function setLoading(on) {
|
|
1161
|
+
document.documentElement.classList.toggle("x-nav-loading", on);
|
|
1559
1162
|
}
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
if (
|
|
1575
|
-
|
|
1576
|
-
|
|
1163
|
+
|
|
1164
|
+
function prefetch(url) {
|
|
1165
|
+
if (cache.has(url.href)) return cache.get(url.href);
|
|
1166
|
+
var promise = fetch(url.href, { headers: { "X-X-Nav": "1" } })
|
|
1167
|
+
.then(function (res) {
|
|
1168
|
+
return res.text().then(function (html) {
|
|
1169
|
+
var ct = res.headers.get("content-type") || "";
|
|
1170
|
+
return { html: html, ok: res.ok, finalUrl: res.url || url.href, isHtml: ct.indexOf("text/html") !== -1 };
|
|
1171
|
+
});
|
|
1172
|
+
})
|
|
1173
|
+
.catch(function (err) {
|
|
1174
|
+
cache.delete(url.href);
|
|
1175
|
+
throw err;
|
|
1176
|
+
});
|
|
1177
|
+
if (cache.size >= 30) {
|
|
1178
|
+
var first = cache.keys().next().value;
|
|
1179
|
+
if (first !== undefined) cache.delete(first);
|
|
1577
1180
|
}
|
|
1578
|
-
|
|
1181
|
+
cache.set(url.href, promise);
|
|
1182
|
+
return promise;
|
|
1579
1183
|
}
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
acc.count += 1;
|
|
1589
|
-
for (let i = 0; i < buckets.length; i += 1) {
|
|
1590
|
-
const bound = buckets[i];
|
|
1591
|
-
if (bound === void 0) break;
|
|
1592
|
-
if (value <= bound) {
|
|
1593
|
-
for (let j = i; j < buckets.length; j += 1) {
|
|
1594
|
-
acc.bucketCounts[j] = (acc.bucketCounts[j] ?? 0) + 1;
|
|
1184
|
+
|
|
1185
|
+
function navigate(url, push) {
|
|
1186
|
+
setLoading(true);
|
|
1187
|
+
prefetch(url)
|
|
1188
|
+
.then(function (payload) {
|
|
1189
|
+
if (!payload.isHtml) {
|
|
1190
|
+
location.href = url.href;
|
|
1191
|
+
return;
|
|
1595
1192
|
}
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1193
|
+
var doc = new DOMParser().parseFromString(payload.html, "text/html");
|
|
1194
|
+
var next = doc.getElementById("root");
|
|
1195
|
+
var root = document.getElementById("root");
|
|
1196
|
+
if (!next || !root) {
|
|
1197
|
+
location.href = url.href;
|
|
1198
|
+
return;
|
|
1199
|
+
}
|
|
1200
|
+
if (push) history.pushState({ xNav: true }, "", payload.finalUrl);
|
|
1201
|
+
if (doc.title) document.title = doc.title;
|
|
1202
|
+
if (window.__xIslandRoots) {
|
|
1203
|
+
// Must stay in sync with unmountIslandRoots() \u2014 same logic, different
|
|
1204
|
+
// execution context (this is an inline script, not a module import).
|
|
1205
|
+
for (var i = 0; i < window.__xIslandRoots.length; i++) {
|
|
1206
|
+
try { window.__xIslandRoots[i]?.unmount(); } catch (_) {}
|
|
1207
|
+
}
|
|
1208
|
+
window.__xIslandRoots.length = 0;
|
|
1209
|
+
}
|
|
1210
|
+
root.innerHTML = next.innerHTML;
|
|
1211
|
+
reexecuteScripts(root);
|
|
1212
|
+
if (url.hash) {
|
|
1213
|
+
var target = document.getElementById(url.hash.slice(1));
|
|
1214
|
+
if (target) {
|
|
1215
|
+
target.scrollIntoView();
|
|
1216
|
+
return;
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
window.scrollTo(0, 0);
|
|
1220
|
+
})
|
|
1221
|
+
.catch(function () {
|
|
1222
|
+
location.href = url.href;
|
|
1223
|
+
})
|
|
1224
|
+
.finally(function () {
|
|
1225
|
+
setLoading(false);
|
|
1226
|
+
});
|
|
1599
1227
|
}
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1228
|
+
|
|
1229
|
+
function reexecuteScripts(root) {
|
|
1230
|
+
var scripts = root.querySelectorAll("script");
|
|
1231
|
+
for (var i = 0; i < scripts.length; i++) {
|
|
1232
|
+
var old = scripts[i];
|
|
1233
|
+
var el = document.createElement("script");
|
|
1234
|
+
for (var j = 0; j < old.attributes.length; j++) {
|
|
1235
|
+
var attr = old.attributes[j];
|
|
1236
|
+
el.setAttribute(attr.name, attr.value);
|
|
1608
1237
|
}
|
|
1238
|
+
el.textContent = old.textContent;
|
|
1239
|
+
old.replaceWith(el);
|
|
1609
1240
|
}
|
|
1610
|
-
return { name: name ?? key, labels };
|
|
1611
1241
|
}
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1242
|
+
|
|
1243
|
+
/** Soft reload current page without a full document reload (used by dev live-reload). */
|
|
1244
|
+
window.__xSoftReload = function () {
|
|
1245
|
+
navigate(new URL(location.href), false);
|
|
1246
|
+
};
|
|
1247
|
+
})();
|
|
1248
|
+
`.trim();
|
|
1249
|
+
|
|
1250
|
+
// src/live-reload.ts
|
|
1251
|
+
var LIVE_RELOAD_SCRIPT = `
|
|
1252
|
+
(function () {
|
|
1253
|
+
var es = new EventSource("/__x/reload");
|
|
1254
|
+
es.addEventListener("reload", function () {
|
|
1255
|
+
es.close();
|
|
1256
|
+
if (typeof window.__xSoftReload === "function") {
|
|
1257
|
+
window.__xSoftReload();
|
|
1258
|
+
} else {
|
|
1259
|
+
window.location.reload();
|
|
1629
1260
|
}
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1261
|
+
});
|
|
1262
|
+
es.addEventListener("hb", function () {});
|
|
1263
|
+
es.onerror = function () {
|
|
1264
|
+
es.close();
|
|
1265
|
+
};
|
|
1266
|
+
})();
|
|
1267
|
+
`.trim();
|
|
1268
|
+
|
|
1269
|
+
// src/render.ts
|
|
1270
|
+
function escapeHtml3(s) {
|
|
1271
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
1272
|
+
}
|
|
1273
|
+
function escapeJsonForScript(s) {
|
|
1274
|
+
return s.replace(/<\//g, "<\\/");
|
|
1275
|
+
}
|
|
1276
|
+
function buildHeadExtras(stylesheet) {
|
|
1277
|
+
return stylesheet ? `
|
|
1278
|
+
<link rel="stylesheet" href="${escapeHtml3(stylesheet)}" />` : "";
|
|
1279
|
+
}
|
|
1280
|
+
function nonceAttr(nonce) {
|
|
1281
|
+
return nonce ? ` nonce="${nonce}"` : "";
|
|
1282
|
+
}
|
|
1283
|
+
function buildNavScriptTag(clientNav, nonce) {
|
|
1284
|
+
return clientNav === false ? "" : `
|
|
1285
|
+
<script${nonceAttr(nonce)}>${CLIENT_NAV_SCRIPT}</script>`;
|
|
1286
|
+
}
|
|
1287
|
+
function buildLiveReloadTag(liveReload, nonce) {
|
|
1288
|
+
return liveReload ? `
|
|
1289
|
+
<script${nonceAttr(nonce)}>${LIVE_RELOAD_SCRIPT}</script>` : "";
|
|
1290
|
+
}
|
|
1291
|
+
function htmlShell(title, headExtras, propsScript, scripts, bodySlot, navScriptTag, liveReloadTag) {
|
|
1292
|
+
const finalScripts = scripts ?? "";
|
|
1293
|
+
const inside = `${bodySlot}${propsScript ? `
|
|
1294
|
+
${propsScript}` : ""}${finalScripts ? `
|
|
1295
|
+
${finalScripts}` : ""}`;
|
|
1296
|
+
return `<!DOCTYPE html>
|
|
1297
|
+
<html lang="en">
|
|
1298
|
+
<head>
|
|
1299
|
+
<meta charset="UTF-8" />
|
|
1300
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
1301
|
+
<title>${escapeHtml3(title)}</title>${headExtras}
|
|
1302
|
+
</head>
|
|
1303
|
+
<body>
|
|
1304
|
+
<div id="root">${inside}</div>
|
|
1305
|
+
${navScriptTag ? ` ${navScriptTag}
|
|
1306
|
+
` : ""}${liveReloadTag} </body>
|
|
1307
|
+
</html>`;
|
|
1308
|
+
}
|
|
1309
|
+
function renderPage(node, options = {}) {
|
|
1310
|
+
const body = renderToString(node);
|
|
1311
|
+
return buildShellHtml(body, options, options.islandScripts ?? []);
|
|
1312
|
+
}
|
|
1313
|
+
function renderStaticPage(node, options = {}) {
|
|
1314
|
+
const body = renderToStaticMarkup(node);
|
|
1315
|
+
return buildShellHtml(body, options, options.islandScripts ?? []);
|
|
1316
|
+
}
|
|
1317
|
+
async function renderPageOnce(node, options = {}) {
|
|
1318
|
+
const body = renderToString(node);
|
|
1319
|
+
const scripts = options.resolveIslandScripts ? await options.resolveIslandScripts() : options.islandScripts ?? [];
|
|
1320
|
+
return buildShellHtml(body, options, scripts);
|
|
1321
|
+
}
|
|
1322
|
+
function buildShellHtml(body, options, islandScripts) {
|
|
1323
|
+
const { islandProps } = options;
|
|
1324
|
+
const title = options.title ?? "x app";
|
|
1325
|
+
const nonce = options.cspNonce;
|
|
1326
|
+
const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
|
|
1327
|
+
const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json"${nonceAttr(nonce)}>${propsJson}</script>` : "";
|
|
1328
|
+
const islandScriptsHtml = islandScripts.map((src) => `<script data-island-script src="${escapeHtml3(src)}"></script>`).join("\n ");
|
|
1329
|
+
return htmlShell(
|
|
1330
|
+
title,
|
|
1331
|
+
buildHeadExtras(options.stylesheet),
|
|
1332
|
+
propsScript,
|
|
1333
|
+
islandScriptsHtml,
|
|
1334
|
+
body,
|
|
1335
|
+
buildNavScriptTag(options.clientNav, nonce),
|
|
1336
|
+
buildLiveReloadTag(options.liveReload, nonce)
|
|
1337
|
+
);
|
|
1338
|
+
}
|
|
1339
|
+
function pumpStreamingResponse(source, options) {
|
|
1340
|
+
const { header, footer, onRenderError, onCancel } = options;
|
|
1341
|
+
const reader = source.getReader();
|
|
1342
|
+
let headerSent = false;
|
|
1343
|
+
let ended = false;
|
|
1344
|
+
async function readAhead(controller) {
|
|
1345
|
+
if (!headerSent) {
|
|
1346
|
+
headerSent = true;
|
|
1347
|
+
controller.enqueue(header);
|
|
1348
|
+
}
|
|
1349
|
+
while (true) {
|
|
1350
|
+
const { done, value } = await reader.read();
|
|
1351
|
+
if (done) {
|
|
1352
|
+
if (!ended) {
|
|
1353
|
+
const footerBytes = typeof footer === "function" ? await footer() : footer;
|
|
1354
|
+
ended = true;
|
|
1355
|
+
try {
|
|
1356
|
+
controller.enqueue(footerBytes);
|
|
1357
|
+
} catch {
|
|
1358
|
+
}
|
|
1359
|
+
controller.close();
|
|
1360
|
+
}
|
|
1361
|
+
return;
|
|
1638
1362
|
}
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
lines.push(`${h.name}_count${formatLabels(h.labels)} ${h.count}`);
|
|
1363
|
+
controller.enqueue(value);
|
|
1364
|
+
if (controller.desiredSize !== null && controller.desiredSize <= 0) return;
|
|
1642
1365
|
}
|
|
1643
|
-
return `${lines.join("\n")}
|
|
1644
|
-
`;
|
|
1645
|
-
}
|
|
1646
|
-
function handleMetrics(req) {
|
|
1647
|
-
if (new URL(req.url).pathname !== "/metrics") return null;
|
|
1648
|
-
return new Response(renderMetrics(), {
|
|
1649
|
-
headers: { "Content-Type": "text/plain; version=0.0.4; charset=utf-8" }
|
|
1650
|
-
});
|
|
1651
1366
|
}
|
|
1652
|
-
return {
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
return {
|
|
1666
|
-
incr(name, delta, labels) {
|
|
1667
|
-
let counter = counters.get(name);
|
|
1668
|
-
if (!counter) {
|
|
1669
|
-
counter = meter.createCounter(name, { description: `Counter ${name}` });
|
|
1670
|
-
counters.set(name, counter);
|
|
1367
|
+
return new ReadableStream({
|
|
1368
|
+
async pull(controller) {
|
|
1369
|
+
try {
|
|
1370
|
+
await readAhead(controller);
|
|
1371
|
+
} catch (err) {
|
|
1372
|
+
if (!ended) {
|
|
1373
|
+
ended = true;
|
|
1374
|
+
onRenderError?.(err);
|
|
1375
|
+
}
|
|
1376
|
+
try {
|
|
1377
|
+
controller.error(err);
|
|
1378
|
+
} catch {
|
|
1379
|
+
}
|
|
1671
1380
|
}
|
|
1672
|
-
counter.add(delta ?? 1, labels);
|
|
1673
1381
|
},
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
histograms.set(name, histogram);
|
|
1679
|
-
}
|
|
1680
|
-
histogram.record(value, labels);
|
|
1382
|
+
cancel(reason) {
|
|
1383
|
+
reader.cancel(reason).catch(() => {
|
|
1384
|
+
});
|
|
1385
|
+
onCancel?.(reason);
|
|
1681
1386
|
}
|
|
1682
|
-
};
|
|
1683
|
-
}
|
|
1684
|
-
function formatLabels(labels) {
|
|
1685
|
-
const entries = Object.entries(labels);
|
|
1686
|
-
if (entries.length === 0) return "";
|
|
1687
|
-
const escaped = entries.map(([k, v]) => `${k}="${escapeLabelValue(v)}"`).join(",");
|
|
1688
|
-
return `{${escaped}}`;
|
|
1689
|
-
}
|
|
1690
|
-
function escapeLabelValue(value) {
|
|
1691
|
-
return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n");
|
|
1387
|
+
});
|
|
1692
1388
|
}
|
|
1693
|
-
function
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1389
|
+
async function renderStreamingPage(node, options = {}) {
|
|
1390
|
+
const { islandScripts, islandProps } = options;
|
|
1391
|
+
const title = escapeHtml3(options.title ?? "x app");
|
|
1392
|
+
const nonce = options.cspNonce;
|
|
1393
|
+
const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
|
|
1394
|
+
const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json"${nonceAttr(nonce)}>${propsJson}</script>` : "";
|
|
1395
|
+
const navScriptTag = buildNavScriptTag(options.clientNav, nonce);
|
|
1396
|
+
const liveReloadTag = buildLiveReloadTag(options.liveReload, nonce);
|
|
1397
|
+
const headExtras = buildHeadExtras(options.stylesheet);
|
|
1398
|
+
const footer = `</div>${navScriptTag}
|
|
1399
|
+
${liveReloadTag} </body>
|
|
1400
|
+
</html>`;
|
|
1401
|
+
const reactStream = await renderToReadableStream(node, {
|
|
1402
|
+
onError(err) {
|
|
1403
|
+
console.error("[x] render error:", err);
|
|
1707
1404
|
}
|
|
1708
|
-
};
|
|
1405
|
+
});
|
|
1406
|
+
const encoder = new TextEncoder();
|
|
1407
|
+
const header = `<!DOCTYPE html>
|
|
1408
|
+
<html lang="en">
|
|
1409
|
+
<head>
|
|
1410
|
+
<meta charset="UTF-8" />
|
|
1411
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
1412
|
+
<title>${title}</title>${headExtras}
|
|
1413
|
+
</head>
|
|
1414
|
+
<body>
|
|
1415
|
+
<div id="root">`;
|
|
1416
|
+
return pumpStreamingResponse(reactStream, {
|
|
1417
|
+
header: encoder.encode(header),
|
|
1418
|
+
// Lazy footer: the island script list may only be knowable after the
|
|
1419
|
+
// render completed (single-render mode), so resolve it right before the
|
|
1420
|
+
// closing tags are emitted rather than up front.
|
|
1421
|
+
footer: async () => {
|
|
1422
|
+
const scripts = islandScripts ?? await options.resolveIslandScripts?.() ?? [];
|
|
1423
|
+
const islandScriptsHtml = scripts.map((src) => `<script data-island-script src="${escapeHtml3(src)}"></script>`).join("\n ");
|
|
1424
|
+
const rootFooter = `${propsScript ? ` ${propsScript}
|
|
1425
|
+
` : ""}${islandScriptsHtml ? ` ${islandScriptsHtml}
|
|
1426
|
+
` : ""}`;
|
|
1427
|
+
return encoder.encode(`${rootFooter}
|
|
1428
|
+
${footer}`);
|
|
1429
|
+
},
|
|
1430
|
+
...options.onRenderError ? { onRenderError: options.onRenderError } : {}
|
|
1431
|
+
});
|
|
1709
1432
|
}
|
|
1710
1433
|
|
|
1711
1434
|
// src/security/headers.ts
|
|
@@ -1964,7 +1687,7 @@ function zip(as, bs) {
|
|
|
1964
1687
|
return out;
|
|
1965
1688
|
}
|
|
1966
1689
|
function projectRootFromRoutesDir(routesDir) {
|
|
1967
|
-
return
|
|
1690
|
+
return join2(routesDir, "..", "..");
|
|
1968
1691
|
}
|
|
1969
1692
|
function resolvePublicAsset(publicDir, pathname) {
|
|
1970
1693
|
let decoded;
|
|
@@ -1973,7 +1696,7 @@ function resolvePublicAsset(publicDir, pathname) {
|
|
|
1973
1696
|
} catch {
|
|
1974
1697
|
return null;
|
|
1975
1698
|
}
|
|
1976
|
-
const target = resolve(
|
|
1699
|
+
const target = resolve(join2(publicDir, decoded));
|
|
1977
1700
|
const root = resolve(publicDir);
|
|
1978
1701
|
if (target !== root && !target.startsWith(root + sep2)) return null;
|
|
1979
1702
|
return target;
|
|
@@ -1992,9 +1715,9 @@ async function serveStaticAsset(publicDir, req) {
|
|
|
1992
1715
|
return new Response(file);
|
|
1993
1716
|
}
|
|
1994
1717
|
function wrapWithLayouts(Component, params, loaderData, layoutModules) {
|
|
1995
|
-
let content =
|
|
1718
|
+
let content = createElement(Component, { params, loaderData });
|
|
1996
1719
|
for (const Layout of [...layoutModules].reverse()) {
|
|
1997
|
-
content =
|
|
1720
|
+
content = createElement(Layout, null, content);
|
|
1998
1721
|
}
|
|
1999
1722
|
return content;
|
|
2000
1723
|
}
|
|
@@ -2002,11 +1725,11 @@ function renderContentPage(content, stylesheet, dev = false, nonce) {
|
|
|
2002
1725
|
const title = content.frontmatter.title ?? content.slug;
|
|
2003
1726
|
const bodyHtml = renderMarkdown(content.body);
|
|
2004
1727
|
const body = renderPage(
|
|
2005
|
-
|
|
1728
|
+
createElement(
|
|
2006
1729
|
"article",
|
|
2007
1730
|
null,
|
|
2008
|
-
content.frontmatter.title ?
|
|
2009
|
-
|
|
1731
|
+
content.frontmatter.title ? createElement("h1", null, content.frontmatter.title) : null,
|
|
1732
|
+
createElement("div", {
|
|
2010
1733
|
// biome-ignore lint/security/noDangerouslySetInnerHtml: body is markdown rendered to HTML
|
|
2011
1734
|
dangerouslySetInnerHTML: { __html: bodyHtml }
|
|
2012
1735
|
})
|
|
@@ -2020,9 +1743,6 @@ function renderContentPage(content, stylesheet, dev = false, nonce) {
|
|
|
2020
1743
|
);
|
|
2021
1744
|
return body;
|
|
2022
1745
|
}
|
|
2023
|
-
function defineConfig(config) {
|
|
2024
|
-
return config;
|
|
2025
|
-
}
|
|
2026
1746
|
function importDev(path, dev) {
|
|
2027
1747
|
return dev ? import(`${path}?t=${Date.now()}`) : import(path);
|
|
2028
1748
|
}
|
|
@@ -2030,7 +1750,7 @@ async function createApp(options) {
|
|
|
2030
1750
|
const dev = options.development ?? false;
|
|
2031
1751
|
const primaryDir = options.pagesDir || options.routesDir || "src/pages";
|
|
2032
1752
|
const projectRoot = projectRootFromRoutesDir(primaryDir);
|
|
2033
|
-
const resolvedActionsDir = options.actionsDir ?? (
|
|
1753
|
+
const resolvedActionsDir = options.actionsDir ?? (existsSync(join2(projectRoot, "src", "actions")) ? join2(projectRoot, "src", "actions") : void 0);
|
|
2034
1754
|
let handlers = [];
|
|
2035
1755
|
let contentHandlers = [];
|
|
2036
1756
|
let publicDir = null;
|
|
@@ -2102,7 +1822,7 @@ async function createApp(options) {
|
|
|
2102
1822
|
});
|
|
2103
1823
|
}
|
|
2104
1824
|
async function renderNotFound(_req) {
|
|
2105
|
-
const content = notFoundLayout ?
|
|
1825
|
+
const content = notFoundLayout ? createElement(notFoundLayout, null, createElement(notFoundComponent, { params: {} })) : createElement(notFoundComponent, { params: {} });
|
|
2106
1826
|
const cspNonce = generateCspNonce();
|
|
2107
1827
|
const html = renderPage(content, {
|
|
2108
1828
|
title: "404 \u2014 Not Found",
|
|
@@ -2179,7 +1899,7 @@ async function createApp(options) {
|
|
|
2179
1899
|
loaderData = result2;
|
|
2180
1900
|
}
|
|
2181
1901
|
const registry = createIslandRegistry();
|
|
2182
|
-
const content =
|
|
1902
|
+
const content = createElement(
|
|
2183
1903
|
IslandProvider,
|
|
2184
1904
|
{ registry },
|
|
2185
1905
|
wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
|
|
@@ -2239,7 +1959,7 @@ async function createApp(options) {
|
|
|
2239
1959
|
loaderData = result2;
|
|
2240
1960
|
}
|
|
2241
1961
|
const registry = createIslandRegistry();
|
|
2242
|
-
const content =
|
|
1962
|
+
const content = createElement(
|
|
2243
1963
|
IslandProvider,
|
|
2244
1964
|
{ registry },
|
|
2245
1965
|
wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
|
|
@@ -2310,9 +2030,9 @@ async function createApp(options) {
|
|
|
2310
2030
|
async function buildHandlers() {
|
|
2311
2031
|
if (options.preloaded) {
|
|
2312
2032
|
const preloaded = options.preloaded;
|
|
2313
|
-
const candidatePublicDir2 =
|
|
2314
|
-
publicDir =
|
|
2315
|
-
stylesheetHref = options.stylesheetHref ?? (publicDir &&
|
|
2033
|
+
const candidatePublicDir2 = join2(projectRoot, "public");
|
|
2034
|
+
publicDir = existsSync(candidatePublicDir2) ? candidatePublicDir2 : null;
|
|
2035
|
+
stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync(join2(publicDir, "styles.css")) ? "/styles.css" : void 0);
|
|
2316
2036
|
if (preloaded.notFoundComponent) notFoundComponent = preloaded.notFoundComponent;
|
|
2317
2037
|
if (preloaded.notFoundLayout) notFoundLayout = preloaded.notFoundLayout;
|
|
2318
2038
|
const loaded2 = [];
|
|
@@ -2362,11 +2082,11 @@ async function createApp(options) {
|
|
|
2362
2082
|
const apiDir = options.apiDir;
|
|
2363
2083
|
let found = scanPages(pagesDir);
|
|
2364
2084
|
const apiFound = [];
|
|
2365
|
-
if (apiDir &&
|
|
2085
|
+
if (apiDir && existsSync(apiDir)) {
|
|
2366
2086
|
apiFound.push(...scanApiDir(apiDir));
|
|
2367
2087
|
}
|
|
2368
|
-
const legacyApiDir =
|
|
2369
|
-
if (
|
|
2088
|
+
const legacyApiDir = join2(pagesDir, "api");
|
|
2089
|
+
if (existsSync(legacyApiDir) && legacyApiDir !== apiDir) {
|
|
2370
2090
|
apiFound.push(...scanApiDir(legacyApiDir));
|
|
2371
2091
|
}
|
|
2372
2092
|
found = found.filter((r) => !r.isApi);
|
|
@@ -2400,9 +2120,9 @@ async function createApp(options) {
|
|
|
2400
2120
|
}
|
|
2401
2121
|
}
|
|
2402
2122
|
}
|
|
2403
|
-
const candidatePublicDir =
|
|
2404
|
-
publicDir =
|
|
2405
|
-
stylesheetHref = options.stylesheetHref ?? (publicDir &&
|
|
2123
|
+
const candidatePublicDir = join2(projectRoot, "public");
|
|
2124
|
+
publicDir = existsSync(candidatePublicDir) ? candidatePublicDir : null;
|
|
2125
|
+
stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync(join2(publicDir, "styles.css")) ? "/styles.css" : void 0);
|
|
2406
2126
|
const notFoundEntry = scanNotFound(pagesDir);
|
|
2407
2127
|
if (notFoundEntry) {
|
|
2408
2128
|
const mod = await importDev(notFoundEntry.filePath, dev);
|
|
@@ -2630,7 +2350,7 @@ async function createApp(options) {
|
|
|
2630
2350
|
let rebuildTimeout = null;
|
|
2631
2351
|
const sseClients = /* @__PURE__ */ new Set();
|
|
2632
2352
|
try {
|
|
2633
|
-
const srcDir =
|
|
2353
|
+
const srcDir = join2(primaryDir, "..", "..", "src");
|
|
2634
2354
|
const watchDirs = [
|
|
2635
2355
|
...new Set(
|
|
2636
2356
|
[primaryDir, options.apiDir, options.layoutsDir, resolvedActionsDir, srcDir].filter(
|
|
@@ -2743,62 +2463,398 @@ data: ${data}
|
|
|
2743
2463
|
reportException(error, { phase: "api" });
|
|
2744
2464
|
return new Response("Internal Server Error", { status: 500 });
|
|
2745
2465
|
}
|
|
2746
|
-
};
|
|
2466
|
+
};
|
|
2467
|
+
}
|
|
2468
|
+
const prodFetchInner = async (req, server) => {
|
|
2469
|
+
const url = new URL(req.url).pathname;
|
|
2470
|
+
const healthResult = await healthHandler(req);
|
|
2471
|
+
if (healthResult !== null) return healthResult;
|
|
2472
|
+
if (metricsReporter?.handleMetrics) {
|
|
2473
|
+
const metricsResult = await metricsReporter.handleMetrics(req);
|
|
2474
|
+
if (metricsResult !== null) return metricsResult;
|
|
2475
|
+
}
|
|
2476
|
+
if (rateLimiter) {
|
|
2477
|
+
const limited = await rateLimitMiddleware(rateLimiter, req, server);
|
|
2478
|
+
if (limited !== null) {
|
|
2479
|
+
metricsReporter?.incr("x_rate_limit_rejections_total", 1, { method: req.method });
|
|
2480
|
+
return limited;
|
|
2481
|
+
}
|
|
2482
|
+
}
|
|
2483
|
+
const revalidationResult = await handleRevalidation(req);
|
|
2484
|
+
if (revalidationResult !== null) return revalidationResult;
|
|
2485
|
+
const mismatchResult = await handleHydrationMismatch(req);
|
|
2486
|
+
if (mismatchResult !== null) return mismatchResult;
|
|
2487
|
+
const serverFnResult = await serverFnHandler(req);
|
|
2488
|
+
if (serverFnResult !== null) return serverFnResult;
|
|
2489
|
+
const staticAsset = await serveStaticAsset(publicDir, req);
|
|
2490
|
+
if (staticAsset !== null) return staticAsset;
|
|
2491
|
+
const islandBundle = serveIslandBundle(req);
|
|
2492
|
+
if (islandBundle !== null) return islandBundle;
|
|
2493
|
+
const proxiedImage = await imageProxyHandler(req);
|
|
2494
|
+
if (proxiedImage !== null) return proxiedImage;
|
|
2495
|
+
for (const h of handlers) {
|
|
2496
|
+
const params = extractParams(h.entry.routePath, h.entry.paramNames, url);
|
|
2497
|
+
if (params !== null) {
|
|
2498
|
+
return h.handler(req);
|
|
2499
|
+
}
|
|
2500
|
+
}
|
|
2501
|
+
for (const h of contentHandlers) {
|
|
2502
|
+
if (h.entry.routePath === url) {
|
|
2503
|
+
return h.handler(req);
|
|
2504
|
+
}
|
|
2505
|
+
}
|
|
2506
|
+
return renderNotFound(req);
|
|
2507
|
+
};
|
|
2508
|
+
const prodFetchHardened = async (req, server) => withResponseHardening(await guardFetchErrors(withBodySizeLimit(prodFetchInner), req, server));
|
|
2509
|
+
const prodFetchBase = loggingEnabled ? withRequestLogging(prodFetchHardened) : prodFetchHardened;
|
|
2510
|
+
const prodFetchTraced = withRequestTracing(prodFetchBase);
|
|
2511
|
+
const prodFetch = metricsReporter ? withRequestMetrics(metricsReporter, prodFetchTraced) : prodFetchTraced;
|
|
2512
|
+
return {
|
|
2513
|
+
routes: {},
|
|
2514
|
+
development: false,
|
|
2515
|
+
port: options.port ?? 3e3,
|
|
2516
|
+
fetch: prodFetch,
|
|
2517
|
+
error: (error) => {
|
|
2518
|
+
reportException(error, { phase: "api" });
|
|
2519
|
+
return new Response("Internal Server Error", { status: 500 });
|
|
2520
|
+
}
|
|
2521
|
+
};
|
|
2522
|
+
}
|
|
2523
|
+
|
|
2524
|
+
// src/application.ts
|
|
2525
|
+
function bypassBackpressure(req, development, hasMetricsEndpoint) {
|
|
2526
|
+
const pathname = new URL(req.url).pathname;
|
|
2527
|
+
return pathname === "/healthz" || pathname === "/readyz" || hasMetricsEndpoint && pathname === "/metrics" || pathname.startsWith("/_islands/") || development && pathname === "/__x/reload";
|
|
2528
|
+
}
|
|
2529
|
+
function saturatedResponse(error) {
|
|
2530
|
+
return new Response("Service Unavailable", {
|
|
2531
|
+
status: 503,
|
|
2532
|
+
headers: {
|
|
2533
|
+
"Content-Type": "text/plain; charset=utf-8",
|
|
2534
|
+
"Retry-After": String(error.retryAfterSeconds)
|
|
2535
|
+
}
|
|
2536
|
+
});
|
|
2537
|
+
}
|
|
2538
|
+
function defineConfig(config) {
|
|
2539
|
+
return config;
|
|
2540
|
+
}
|
|
2541
|
+
async function createApp2(options) {
|
|
2542
|
+
const { backpressure, ...baseOptions } = options;
|
|
2543
|
+
const app = await createApp(baseOptions);
|
|
2544
|
+
if (backpressure === void 0 || backpressure === false) return app;
|
|
2545
|
+
const controller = createBackpressureController(backpressure);
|
|
2546
|
+
const baseFetch = app.fetch;
|
|
2547
|
+
const metrics = options.observability?.metrics;
|
|
2548
|
+
const hasMetricsEndpoint = metrics?.handleMetrics !== void 0;
|
|
2549
|
+
const fetch2 = async (req, server) => {
|
|
2550
|
+
if (bypassBackpressure(req, app.development, hasMetricsEndpoint)) {
|
|
2551
|
+
return baseFetch(req, server);
|
|
2552
|
+
}
|
|
2553
|
+
const startedAt = performance.now();
|
|
2554
|
+
let lease;
|
|
2555
|
+
try {
|
|
2556
|
+
lease = await controller.acquire(req.signal);
|
|
2557
|
+
} catch (error) {
|
|
2558
|
+
if (error instanceof BackpressureSaturatedError) {
|
|
2559
|
+
metrics?.incr("x_backpressure_rejections_total", 1, { method: req.method });
|
|
2560
|
+
metrics?.incr("x_http_requests_total", 1, { method: req.method, status: "503" });
|
|
2561
|
+
metrics?.observe("x_http_request_duration_ms", performance.now() - startedAt, {
|
|
2562
|
+
method: req.method
|
|
2563
|
+
});
|
|
2564
|
+
return saturatedResponse(error);
|
|
2565
|
+
}
|
|
2566
|
+
if (req.signal.aborted) {
|
|
2567
|
+
metrics?.incr("x_http_requests_total", 1, { method: req.method, status: "499" });
|
|
2568
|
+
metrics?.observe("x_http_request_duration_ms", performance.now() - startedAt, {
|
|
2569
|
+
method: req.method
|
|
2570
|
+
});
|
|
2571
|
+
return new Response(null, { status: 499 });
|
|
2572
|
+
}
|
|
2573
|
+
throw error;
|
|
2574
|
+
}
|
|
2575
|
+
try {
|
|
2576
|
+
return await baseFetch(req, server);
|
|
2577
|
+
} finally {
|
|
2578
|
+
lease.release();
|
|
2579
|
+
}
|
|
2580
|
+
};
|
|
2581
|
+
return { ...app, fetch: fetch2 };
|
|
2582
|
+
}
|
|
2583
|
+
|
|
2584
|
+
// src/build.ts
|
|
2585
|
+
import { cpSync, existsSync as existsSync2, mkdirSync, writeFileSync } from "fs";
|
|
2586
|
+
import { join as join3, relative as relative2 } from "path";
|
|
2587
|
+
import { createElement as createElement2 } from "react";
|
|
2588
|
+
async function build(options) {
|
|
2589
|
+
const outDir = options.outDir ?? join3(process.cwd(), ".x");
|
|
2590
|
+
const clientDir = join3(outDir, "client");
|
|
2591
|
+
const serverDir = join3(outDir, "server");
|
|
2592
|
+
const islandsDir = join3(clientDir, "_islands");
|
|
2593
|
+
mkdirSync(clientDir, { recursive: true });
|
|
2594
|
+
mkdirSync(serverDir, { recursive: true });
|
|
2595
|
+
mkdirSync(islandsDir, { recursive: true });
|
|
2596
|
+
const pagesDir = options.pagesDir ?? options.routesDir ?? "";
|
|
2597
|
+
const apiDir = options.apiDir;
|
|
2598
|
+
const actionsDir = options.actionsDir;
|
|
2599
|
+
const layoutsDir = options.layoutsDir ?? pagesDir;
|
|
2600
|
+
const projectRoot = pagesDir ? join3(pagesDir, "..", "..") : process.cwd();
|
|
2601
|
+
const publicDir = join3(projectRoot, "public");
|
|
2602
|
+
const hasPublicDir = existsSync2(publicDir);
|
|
2603
|
+
const stylesheetHref = hasPublicDir && existsSync2(join3(publicDir, "styles.css")) ? "/styles.css" : void 0;
|
|
2604
|
+
if (hasPublicDir) {
|
|
2605
|
+
cpSync(publicDir, clientDir, { recursive: true });
|
|
2606
|
+
console.log(`[x] build: copied public/ -> ${relative2(process.cwd(), clientDir)}`);
|
|
2607
|
+
}
|
|
2608
|
+
let routeEntries = [];
|
|
2609
|
+
if (pagesDir && existsSync2(pagesDir)) {
|
|
2610
|
+
routeEntries = scanPages(pagesDir);
|
|
2611
|
+
}
|
|
2612
|
+
if (apiDir && existsSync2(apiDir)) {
|
|
2613
|
+
routeEntries.push(...scanApiDir(apiDir));
|
|
2614
|
+
}
|
|
2615
|
+
const legacyApiDir = pagesDir ? join3(pagesDir, "api") : "";
|
|
2616
|
+
if (legacyApiDir && existsSync2(legacyApiDir) && legacyApiDir !== apiDir) {
|
|
2617
|
+
routeEntries.push(...scanApiDir(legacyApiDir));
|
|
2618
|
+
}
|
|
2619
|
+
const actionModules = /* @__PURE__ */ new Map();
|
|
2620
|
+
if (actionsDir && existsSync2(actionsDir)) {
|
|
2621
|
+
for (const actionFile of scanRoutes(actionsDir)) {
|
|
2622
|
+
const mod = await import(actionFile.filePath);
|
|
2623
|
+
const segments = actionFile.routePath.split("/").filter(Boolean);
|
|
2624
|
+
const parentPath = `/${segments.slice(0, -1).join("/")}`;
|
|
2625
|
+
const fnNames = [];
|
|
2626
|
+
const actions = mod.actions;
|
|
2627
|
+
if (actions) {
|
|
2628
|
+
registerServerFunctions(parentPath, actionFile.paramNames, actions);
|
|
2629
|
+
fnNames.push(...Object.keys(actions));
|
|
2630
|
+
}
|
|
2631
|
+
for (const [key, value] of Object.entries(mod)) {
|
|
2632
|
+
if (key === "default" || key === "actions" || typeof value !== "function") continue;
|
|
2633
|
+
registerServerFunctions(parentPath, actionFile.paramNames, {
|
|
2634
|
+
[key]: value
|
|
2635
|
+
});
|
|
2636
|
+
fnNames.push(key);
|
|
2637
|
+
}
|
|
2638
|
+
if (fnNames.length > 0) {
|
|
2639
|
+
actionModules.set(actionFile.filePath, { parentPath, fnNames });
|
|
2640
|
+
}
|
|
2641
|
+
}
|
|
2747
2642
|
}
|
|
2748
|
-
const
|
|
2749
|
-
|
|
2750
|
-
|
|
2751
|
-
|
|
2752
|
-
|
|
2753
|
-
|
|
2754
|
-
|
|
2643
|
+
const dedicatedLayouts = layoutsDir && layoutsDir !== pagesDir && existsSync2(layoutsDir) ? scanLayoutsDir(layoutsDir) : [];
|
|
2644
|
+
const nestedLayouts = pagesDir && existsSync2(pagesDir) ? scanLayouts(pagesDir) : [];
|
|
2645
|
+
const layouts = [...dedicatedLayouts, ...nestedLayouts];
|
|
2646
|
+
const staticPages = [];
|
|
2647
|
+
const serverPages = [];
|
|
2648
|
+
const apiRoutes = [];
|
|
2649
|
+
for (const entry of routeEntries) {
|
|
2650
|
+
if (entry.isApi) {
|
|
2651
|
+
apiRoutes.push(entry);
|
|
2652
|
+
continue;
|
|
2755
2653
|
}
|
|
2756
|
-
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
|
|
2761
|
-
}
|
|
2654
|
+
const mod = await import(entry.filePath);
|
|
2655
|
+
const Component = mod.default;
|
|
2656
|
+
if (!Component) {
|
|
2657
|
+
console.warn(`[x] ${entry.filePath} has no default export -- skipping`);
|
|
2658
|
+
continue;
|
|
2762
2659
|
}
|
|
2763
|
-
const
|
|
2764
|
-
|
|
2765
|
-
const
|
|
2766
|
-
|
|
2767
|
-
|
|
2768
|
-
if (serverFnResult !== null) return serverFnResult;
|
|
2769
|
-
const staticAsset = await serveStaticAsset(publicDir, req);
|
|
2770
|
-
if (staticAsset !== null) return staticAsset;
|
|
2771
|
-
const islandBundle = serveIslandBundle(req);
|
|
2772
|
-
if (islandBundle !== null) return islandBundle;
|
|
2773
|
-
const proxiedImage = await imageProxyHandler(req);
|
|
2774
|
-
if (proxiedImage !== null) return proxiedImage;
|
|
2775
|
-
for (const h of handlers) {
|
|
2776
|
-
const params = extractParams(h.entry.routePath, h.entry.paramNames, url);
|
|
2777
|
-
if (params !== null) {
|
|
2778
|
-
return h.handler(req);
|
|
2660
|
+
const mode = mod.mode ?? "server";
|
|
2661
|
+
const layoutChain = findLayoutChain(entry.filePath, layouts, pagesDir);
|
|
2662
|
+
for (const rootLayout of dedicatedLayouts) {
|
|
2663
|
+
if (!layoutChain.some((l) => l.filePath === rootLayout.filePath)) {
|
|
2664
|
+
layoutChain.unshift(rootLayout);
|
|
2779
2665
|
}
|
|
2780
2666
|
}
|
|
2781
|
-
|
|
2782
|
-
|
|
2783
|
-
|
|
2784
|
-
|
|
2667
|
+
const layoutModules = [];
|
|
2668
|
+
for (const l of layoutChain) {
|
|
2669
|
+
const layoutMod = await import(l.filePath);
|
|
2670
|
+
if (layoutMod.default) layoutModules.push(layoutMod.default);
|
|
2785
2671
|
}
|
|
2786
|
-
|
|
2787
|
-
|
|
2788
|
-
|
|
2789
|
-
|
|
2790
|
-
|
|
2791
|
-
|
|
2792
|
-
|
|
2793
|
-
|
|
2794
|
-
|
|
2795
|
-
|
|
2796
|
-
|
|
2797
|
-
|
|
2798
|
-
reportException(error, { phase: "api" });
|
|
2799
|
-
return new Response("Internal Server Error", { status: 500 });
|
|
2672
|
+
const page = {
|
|
2673
|
+
entry,
|
|
2674
|
+
filePath: entry.filePath,
|
|
2675
|
+
mode,
|
|
2676
|
+
Component,
|
|
2677
|
+
layoutModules,
|
|
2678
|
+
layoutFilePaths: layoutChain.map((l) => l.filePath)
|
|
2679
|
+
};
|
|
2680
|
+
if (mode === "static") {
|
|
2681
|
+
staticPages.push(page);
|
|
2682
|
+
} else {
|
|
2683
|
+
serverPages.push(page);
|
|
2800
2684
|
}
|
|
2801
|
-
}
|
|
2685
|
+
}
|
|
2686
|
+
let contentEntries = [];
|
|
2687
|
+
if (options.contentDir) {
|
|
2688
|
+
contentEntries = scanContent(options.contentDir);
|
|
2689
|
+
}
|
|
2690
|
+
console.log(
|
|
2691
|
+
`[x] build: ${staticPages.length} static, ${serverPages.length} server, ${contentEntries.length} content pages`
|
|
2692
|
+
);
|
|
2693
|
+
const writtenPaths = /* @__PURE__ */ new Set();
|
|
2694
|
+
for (const page of staticPages) {
|
|
2695
|
+
const params = {};
|
|
2696
|
+
const registry = createIslandRegistry();
|
|
2697
|
+
const pageContent = renderPageWithLayout(page.Component, params, page.layoutModules);
|
|
2698
|
+
const content = createElement2(IslandProvider, { registry }, pageContent);
|
|
2699
|
+
const _html = renderStaticPage(content, { stylesheet: stylesheetHref });
|
|
2700
|
+
const outPath = page.entry.routePath === "/" ? "/index.html" : `${page.entry.routePath}/index.html`;
|
|
2701
|
+
const fullPath = join3(clientDir, outPath);
|
|
2702
|
+
mkdirSync(join3(fullPath, ".."), { recursive: true });
|
|
2703
|
+
if (writtenPaths.has(outPath)) {
|
|
2704
|
+
console.warn(` [warn] collision: ${page.entry.routePath} overwrites existing output`);
|
|
2705
|
+
}
|
|
2706
|
+
writtenPaths.add(outPath);
|
|
2707
|
+
let islandScripts = [];
|
|
2708
|
+
if (registry.entries.length > 0) {
|
|
2709
|
+
const uniqueNames = [...new Set(registry.entries.map((e) => e.name))];
|
|
2710
|
+
islandScripts = await bundleRouteIslandsToDisk(
|
|
2711
|
+
page.filePath,
|
|
2712
|
+
page.layoutFilePaths,
|
|
2713
|
+
uniqueNames,
|
|
2714
|
+
islandsDir,
|
|
2715
|
+
actionModules
|
|
2716
|
+
);
|
|
2717
|
+
console.log(
|
|
2718
|
+
` [islands] ${uniqueNames.length} island(s) on ${page.entry.routePath} -> ${islandScripts.join(", ")}`
|
|
2719
|
+
);
|
|
2720
|
+
}
|
|
2721
|
+
const finalHtml = renderStaticPage(content, { islandScripts, stylesheet: stylesheetHref });
|
|
2722
|
+
writeFileSync(fullPath, finalHtml, "utf-8");
|
|
2723
|
+
console.log(` [static] ${page.entry.routePath} -> ${outPath}`);
|
|
2724
|
+
}
|
|
2725
|
+
for (const content of contentEntries) {
|
|
2726
|
+
const registry = createIslandRegistry();
|
|
2727
|
+
const bodyHtml = renderMarkdown(content.body);
|
|
2728
|
+
const pageContent = createElement2(StaticContentPage, {
|
|
2729
|
+
content,
|
|
2730
|
+
bodyHtml
|
|
2731
|
+
});
|
|
2732
|
+
const rendered = createElement2(IslandProvider, { registry }, pageContent);
|
|
2733
|
+
const html = renderStaticPage(rendered, {
|
|
2734
|
+
title: content.frontmatter.title ?? content.slug,
|
|
2735
|
+
stylesheet: stylesheetHref
|
|
2736
|
+
});
|
|
2737
|
+
const outPath = content.routePath === "/" ? "/index.html" : `${content.routePath}/index.html`;
|
|
2738
|
+
const fullPath = join3(clientDir, outPath);
|
|
2739
|
+
mkdirSync(join3(fullPath, ".."), { recursive: true });
|
|
2740
|
+
if (writtenPaths.has(outPath)) {
|
|
2741
|
+
console.warn(` [warn] collision: content ${content.routePath} overwrites existing output`);
|
|
2742
|
+
}
|
|
2743
|
+
writtenPaths.add(outPath);
|
|
2744
|
+
writeFileSync(fullPath, html, "utf-8");
|
|
2745
|
+
console.log(` [content] ${content.routePath} -> ${outPath}`);
|
|
2746
|
+
}
|
|
2747
|
+
if (pagesDir || options.routesDir || options.contentDir) {
|
|
2748
|
+
const srvOpts = {
|
|
2749
|
+
pagesDir: pagesDir || options.routesDir || ""
|
|
2750
|
+
};
|
|
2751
|
+
if (options.apiDir) srvOpts.apiDir = options.apiDir;
|
|
2752
|
+
if (options.layoutsDir) srvOpts.layoutsDir = options.layoutsDir;
|
|
2753
|
+
if (options.actionsDir) srvOpts.actionsDir = options.actionsDir;
|
|
2754
|
+
if (options.contentDir) srvOpts.contentDir = options.contentDir;
|
|
2755
|
+
const configImportPath = options.configPath ? relativeImportPath(serverDir, options.configPath) : void 0;
|
|
2756
|
+
const serverEntry = buildServerEntry(
|
|
2757
|
+
srvOpts,
|
|
2758
|
+
configImportPath,
|
|
2759
|
+
stylesheetHref
|
|
2760
|
+
);
|
|
2761
|
+
const serverEntryPath = join3(serverDir, "index.ts");
|
|
2762
|
+
writeFileSync(serverEntryPath, serverEntry, "utf-8");
|
|
2763
|
+
console.log(
|
|
2764
|
+
` [server] ${serverPages.length} page routes, ${apiRoutes.length} api routes -> server/index.ts`
|
|
2765
|
+
);
|
|
2766
|
+
}
|
|
2767
|
+
console.log(`[x] build complete -> ${outDir}`);
|
|
2768
|
+
}
|
|
2769
|
+
function renderPageWithLayout(Component, params, layoutModules) {
|
|
2770
|
+
let content = createElement2(Component, { params });
|
|
2771
|
+
for (const Layout of [...layoutModules].reverse()) {
|
|
2772
|
+
content = createElement2(Layout, null, content);
|
|
2773
|
+
}
|
|
2774
|
+
return content;
|
|
2775
|
+
}
|
|
2776
|
+
function StaticContentPage({ content, bodyHtml }) {
|
|
2777
|
+
return createElement2(
|
|
2778
|
+
"article",
|
|
2779
|
+
null,
|
|
2780
|
+
content.frontmatter.title ? createElement2("h1", null, content.frontmatter.title) : null,
|
|
2781
|
+
createElement2("div", {
|
|
2782
|
+
// biome-ignore lint/security/noDangerouslySetInnerHtml: body is markdown rendered to HTML
|
|
2783
|
+
dangerouslySetInnerHTML: { __html: bodyHtml }
|
|
2784
|
+
})
|
|
2785
|
+
);
|
|
2786
|
+
}
|
|
2787
|
+
function buildServerEntry(opts, configImportPath, stylesheetHref) {
|
|
2788
|
+
const dirKeys = ["pagesDir", "apiDir", "layoutsDir", "actionsDir", "contentDir"];
|
|
2789
|
+
const lines = [
|
|
2790
|
+
"// Auto-generated by @thexjs/core build",
|
|
2791
|
+
'import { createApp } from "@thexjs/core";'
|
|
2792
|
+
];
|
|
2793
|
+
if (configImportPath) {
|
|
2794
|
+
lines.push("", "let userConfig = {};", "try {");
|
|
2795
|
+
lines.push(` const mod = await import(${JSON.stringify(configImportPath)});`);
|
|
2796
|
+
lines.push(" userConfig = mod.default ?? {};");
|
|
2797
|
+
lines.push("} catch (err) {");
|
|
2798
|
+
lines.push(' console.warn("[x] failed to load x.config runtime options:", err);');
|
|
2799
|
+
lines.push("}");
|
|
2800
|
+
}
|
|
2801
|
+
lines.push("", "const app = await createApp({");
|
|
2802
|
+
for (const key of dirKeys) {
|
|
2803
|
+
const val = opts[key];
|
|
2804
|
+
if (val) lines.push(` ${key}: ${JSON.stringify(val)},`);
|
|
2805
|
+
}
|
|
2806
|
+
if (stylesheetHref) lines.push(` stylesheetHref: ${JSON.stringify(stylesheetHref)},`);
|
|
2807
|
+
lines.push(' port: parseInt(process.env.PORT || "3000", 10),', " development: false,");
|
|
2808
|
+
if (configImportPath) {
|
|
2809
|
+
lines.push(" ...(userConfig.security ? { security: userConfig.security } : {}),");
|
|
2810
|
+
lines.push(
|
|
2811
|
+
" ...(userConfig.observability ? { observability: userConfig.observability } : {}),"
|
|
2812
|
+
);
|
|
2813
|
+
lines.push(" ...(userConfig.images ? { images: userConfig.images } : {}),");
|
|
2814
|
+
lines.push(
|
|
2815
|
+
" ...(userConfig.backpressure !== undefined ? { backpressure: userConfig.backpressure } : {}),"
|
|
2816
|
+
);
|
|
2817
|
+
}
|
|
2818
|
+
lines.push(
|
|
2819
|
+
"});",
|
|
2820
|
+
"",
|
|
2821
|
+
"const server = Bun.serve(app);",
|
|
2822
|
+
"",
|
|
2823
|
+
"console.log(`[x] production server running at ${server.url}`);",
|
|
2824
|
+
"",
|
|
2825
|
+
"// Graceful shutdown: stop accepting new connections, flush the error",
|
|
2826
|
+
"// reporter, then exit after in-flight requests have a moment to drain.",
|
|
2827
|
+
"let shuttingDown = false;",
|
|
2828
|
+
"async function shutdown(signal: string): Promise<void> {",
|
|
2829
|
+
" if (shuttingDown) return;",
|
|
2830
|
+
" shuttingDown = true;",
|
|
2831
|
+
" console.log(`[x] received ${signal} - shutting down`);",
|
|
2832
|
+
" try {",
|
|
2833
|
+
' const { getErrorReporter } = await import("@thexjs/core");',
|
|
2834
|
+
" await getErrorReporter().flush?.();",
|
|
2835
|
+
" } catch {}",
|
|
2836
|
+
" server.stop(true);",
|
|
2837
|
+
" const exit = () => process.exit(0);",
|
|
2838
|
+
" const drainTimer = setTimeout(exit, 3000);",
|
|
2839
|
+
" drainTimer.unref?.();",
|
|
2840
|
+
"}",
|
|
2841
|
+
'process.on("SIGTERM", () => shutdown("SIGTERM"));',
|
|
2842
|
+
'process.on("SIGINT", () => shutdown("SIGINT"));',
|
|
2843
|
+
"",
|
|
2844
|
+
"// Request-level errors are caught inside createApp's fetch boundary;",
|
|
2845
|
+
"// anything that still escapes (a throw outside the request lifecycle,",
|
|
2846
|
+
"// a rejected promise from a background sweep) is reported through the",
|
|
2847
|
+
"// error reporter so the box reports instead of dying silently.",
|
|
2848
|
+
'const { installProcessCrashHandlers } = await import("@thexjs/core");',
|
|
2849
|
+
// Fail fast on an uncaughtException: the singleton state may be corrupted,
|
|
2850
|
+
// so drain and let the orchestrator restart clean (see crash-handlers).
|
|
2851
|
+
"installProcessCrashHandlers({ exitOnCrash: true });"
|
|
2852
|
+
);
|
|
2853
|
+
return lines.join("\n");
|
|
2854
|
+
}
|
|
2855
|
+
function relativeImportPath(fromDir, toFile) {
|
|
2856
|
+
const rel = relative2(fromDir, toFile).replace(/\\/g, "/").replace(/\.(ts|js|mjs)$/, "");
|
|
2857
|
+
return rel.startsWith(".") ? rel : `./${rel}`;
|
|
2802
2858
|
}
|
|
2803
2859
|
|
|
2804
2860
|
// src/image.tsx
|
|
@@ -3079,7 +3135,7 @@ export {
|
|
|
3079
3135
|
combineReporters,
|
|
3080
3136
|
composeMiddleware,
|
|
3081
3137
|
configureTrustedProxy,
|
|
3082
|
-
createApp,
|
|
3138
|
+
createApp2 as createApp,
|
|
3083
3139
|
createBackpressureController,
|
|
3084
3140
|
createConsoleAuditSink,
|
|
3085
3141
|
createHealthCheckHandler,
|