@teyik0/furin 0.1.0-alpha.7 → 0.1.0-alpha.9
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/static.d.ts +3 -0
- package/dist/build/client.d.ts +3 -3
- package/dist/build/compile-entry.d.ts +4 -4
- package/dist/build/entry-template.d.ts +2 -2
- package/dist/build/hydrate.d.ts +6 -2
- package/dist/build/index.d.ts +1 -1
- package/dist/build/index.js +1491 -78
- package/dist/build/types.d.ts +26 -3
- package/dist/cli/index.js +1525 -91
- package/dist/client.d.ts +18 -11
- package/dist/config.d.ts +33 -2
- package/dist/config.js +6 -1
- package/dist/context-logger.d.ts +26 -0
- package/dist/dev-page-plugin.d.ts +77 -0
- package/dist/furin.js +459 -69
- package/dist/link.d.ts +31 -3
- package/dist/link.js +198 -51
- package/dist/render/assemble.d.ts +4 -2
- package/dist/render/index.d.ts +1 -1
- package/dist/render/loaders.d.ts +1 -1
- package/dist/render/shell.d.ts +4 -1
- package/dist/router.d.ts +11 -0
- package/dist/router.js +942 -41
- package/package.json +6 -5
- package/src/adapter/bun.ts +20 -0
- package/src/adapter/static.ts +341 -0
- package/src/build/client.ts +21 -11
- package/src/build/compile-entry.ts +5 -3
- package/src/build/entry-template.ts +2 -2
- package/src/build/hydrate.ts +37 -9
- package/src/build/index.ts +56 -21
- package/src/build/scan-server.ts +43 -21
- package/src/build/types.ts +28 -3
- package/src/cli/index.ts +13 -5
- package/src/client.ts +19 -25
- package/src/config.ts +35 -1
- package/src/context-logger.ts +71 -0
- package/src/dev-page-plugin.ts +339 -4
- package/src/furin.ts +6 -2
- package/src/link.tsx +355 -64
- package/src/plugin/index.ts +2 -2
- package/src/render/assemble.ts +4 -2
- package/src/render/index.ts +67 -23
- package/src/render/loaders.ts +81 -36
- package/src/render/shell.ts +11 -4
- package/src/router.ts +55 -6
package/dist/cli/index.js
CHANGED
|
@@ -2,13 +2,13 @@
|
|
|
2
2
|
// @bun
|
|
3
3
|
|
|
4
4
|
// src/cli/index.ts
|
|
5
|
-
import { existsSync as
|
|
6
|
-
import { resolve as
|
|
5
|
+
import { existsSync as existsSync9 } from "fs";
|
|
6
|
+
import { resolve as resolve5 } from "path";
|
|
7
7
|
import { parseArgs } from "util";
|
|
8
8
|
|
|
9
9
|
// src/build/index.ts
|
|
10
|
-
import { existsSync as
|
|
11
|
-
import { join as
|
|
10
|
+
import { existsSync as existsSync7, writeFileSync as writeFileSync6 } from "fs";
|
|
11
|
+
import { join as join8, relative as relative4, resolve as resolve3 } from "path";
|
|
12
12
|
|
|
13
13
|
// src/adapter/bun.ts
|
|
14
14
|
import { existsSync as existsSync4, rmSync as rmSync2, writeFileSync as writeFileSync4 } from "fs";
|
|
@@ -1377,15 +1377,107 @@ function transformForClient(code, filename) {
|
|
|
1377
1377
|
}
|
|
1378
1378
|
|
|
1379
1379
|
// src/render/shell.ts
|
|
1380
|
+
function extractTitle(meta) {
|
|
1381
|
+
if (!meta) {
|
|
1382
|
+
return;
|
|
1383
|
+
}
|
|
1384
|
+
for (const entry of meta) {
|
|
1385
|
+
if ("title" in entry) {
|
|
1386
|
+
return entry.title;
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
return;
|
|
1390
|
+
}
|
|
1391
|
+
function isMetaTag(entry) {
|
|
1392
|
+
return !(("title" in entry) || ("charSet" in entry) || ("script:ld+json" in entry) || ("tagName" in entry));
|
|
1393
|
+
}
|
|
1380
1394
|
function escapeHtml(str) {
|
|
1381
1395
|
return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
1382
1396
|
}
|
|
1397
|
+
function safeJson(value) {
|
|
1398
|
+
return JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
|
|
1399
|
+
}
|
|
1400
|
+
function renderAttrs(obj) {
|
|
1401
|
+
return Object.entries(obj).filter(([, v]) => v !== undefined).map(([k, v]) => `${k}="${escapeHtml(String(v))}"`).join(" ");
|
|
1402
|
+
}
|
|
1403
|
+
function buildMetaParts(meta) {
|
|
1404
|
+
const parts = [];
|
|
1405
|
+
const title = extractTitle(meta);
|
|
1406
|
+
if (title) {
|
|
1407
|
+
parts.push(`<title>${escapeHtml(title)}</title>`);
|
|
1408
|
+
}
|
|
1409
|
+
for (const m of meta) {
|
|
1410
|
+
if (isMetaTag(m)) {
|
|
1411
|
+
parts.push(`<meta ${renderAttrs(m)} />`);
|
|
1412
|
+
}
|
|
1413
|
+
if ("script:ld+json" in m) {
|
|
1414
|
+
parts.push(`<script type="application/ld+json">${safeJson(m["script:ld+json"])}</script>`);
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
return parts;
|
|
1418
|
+
}
|
|
1419
|
+
function buildLinkParts(links) {
|
|
1420
|
+
return links.map((link) => `<link ${renderAttrs(link)} />`);
|
|
1421
|
+
}
|
|
1422
|
+
function buildScriptParts(scripts) {
|
|
1423
|
+
return scripts.map((script) => {
|
|
1424
|
+
const { children, ...rest } = script;
|
|
1425
|
+
const attrs = renderAttrs(rest);
|
|
1426
|
+
if (children) {
|
|
1427
|
+
return `<script ${attrs}>${children}</script>`;
|
|
1428
|
+
}
|
|
1429
|
+
return `<script ${attrs}></script>`;
|
|
1430
|
+
});
|
|
1431
|
+
}
|
|
1432
|
+
function buildStyleParts(styles) {
|
|
1433
|
+
return styles.map((style) => {
|
|
1434
|
+
const typeAttr = style.type ? ` type="${escapeHtml(style.type)}"` : "";
|
|
1435
|
+
return `<style${typeAttr}>${style.children}</style>`;
|
|
1436
|
+
});
|
|
1437
|
+
}
|
|
1438
|
+
function buildHeadInjection(headData) {
|
|
1439
|
+
const parts = [];
|
|
1440
|
+
if (headData?.meta) {
|
|
1441
|
+
parts.push(...buildMetaParts(headData.meta));
|
|
1442
|
+
}
|
|
1443
|
+
if (headData?.links) {
|
|
1444
|
+
parts.push(...buildLinkParts(headData.links));
|
|
1445
|
+
}
|
|
1446
|
+
if (headData?.scripts) {
|
|
1447
|
+
parts.push(...buildScriptParts(headData.scripts));
|
|
1448
|
+
}
|
|
1449
|
+
if (headData?.styles) {
|
|
1450
|
+
parts.push(...buildStyleParts(headData.styles));
|
|
1451
|
+
}
|
|
1452
|
+
return parts.length > 0 ? `
|
|
1453
|
+
${parts.join(`
|
|
1454
|
+
`)}
|
|
1455
|
+
` : "";
|
|
1456
|
+
}
|
|
1383
1457
|
var THEME_INIT_SCRIPT = `<script>try{var __t=localStorage.getItem("furin-theme");` + `document.documentElement.classList.add(__t==="light"?"light":"dark")}` + `catch(e){document.documentElement.classList.add("dark")}</script>`;
|
|
1384
|
-
function
|
|
1458
|
+
function generateIndexHtml() {
|
|
1459
|
+
return `<!DOCTYPE html>
|
|
1460
|
+
<html lang="en">
|
|
1461
|
+
<head>
|
|
1462
|
+
<meta charset="UTF-8">
|
|
1463
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
1464
|
+
${THEME_INIT_SCRIPT}
|
|
1465
|
+
<!--ssr-head-->
|
|
1466
|
+
</head>
|
|
1467
|
+
<body>
|
|
1468
|
+
<div id="root"><!--ssr-outlet--></div>
|
|
1469
|
+
<script type="module" src="./_hydrate.tsx"></script>
|
|
1470
|
+
</body>
|
|
1471
|
+
</html>
|
|
1472
|
+
`;
|
|
1473
|
+
}
|
|
1474
|
+
function generateProdIndexHtml(entryChunk, cssChunks, buildId, faviconHref) {
|
|
1385
1475
|
const cssLinks = cssChunks.map((c) => ` <link rel="stylesheet" crossorigin href="${c}">`).join(`
|
|
1386
1476
|
`);
|
|
1387
1477
|
const scriptTag = `<script type="module" crossorigin src="${entryChunk}"></script>`;
|
|
1388
1478
|
const buildIdMeta = buildId ? ` <meta name="furin-build-id" content="${escapeHtml(buildId)}">
|
|
1479
|
+
` : "";
|
|
1480
|
+
const faviconLink = faviconHref ? ` <link rel="icon" href="${escapeHtml(faviconHref)}">
|
|
1389
1481
|
` : "";
|
|
1390
1482
|
return `<!DOCTYPE html>
|
|
1391
1483
|
<html lang="en">
|
|
@@ -1393,7 +1485,7 @@ function generateProdIndexHtml(entryChunk, cssChunks, buildId) {
|
|
|
1393
1485
|
<meta charset="UTF-8">
|
|
1394
1486
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
1395
1487
|
${THEME_INIT_SCRIPT}
|
|
1396
|
-
${buildIdMeta}${cssLinks ? `${cssLinks}
|
|
1488
|
+
${buildIdMeta}${faviconLink}${cssLinks ? `${cssLinks}
|
|
1397
1489
|
` : ""} <!--ssr-head-->
|
|
1398
1490
|
</head>
|
|
1399
1491
|
<body>
|
|
@@ -1405,28 +1497,33 @@ ${buildIdMeta}${cssLinks ? `${cssLinks}
|
|
|
1405
1497
|
}
|
|
1406
1498
|
|
|
1407
1499
|
// src/build/hydrate.ts
|
|
1408
|
-
function generateHydrateEntry(routes, rootLayout) {
|
|
1500
|
+
function generateHydrateEntry(routes, rootLayout, basePath) {
|
|
1409
1501
|
const routeEntries = [];
|
|
1410
1502
|
for (const route of routes) {
|
|
1411
1503
|
const resolvedPage = route.path.replace(/\\/g, "/");
|
|
1412
1504
|
const regexPattern = route.pattern.replace(/:[^/]+/g, "([^/]+)").replace(/\*/g, "(.*)");
|
|
1413
1505
|
routeEntries.push(` { pattern: "${route.pattern}", regex: new RegExp("^${regexPattern}$"), load: () => import("${resolvedPage}") }`);
|
|
1414
1506
|
}
|
|
1507
|
+
const basePathLiteral = JSON.stringify(basePath);
|
|
1508
|
+
const pathnameExpr = basePath ? `(() => { const p = window.location.pathname; const b = ${basePathLiteral}; return (p.startsWith(b) && (p.length === b.length || p[b.length] === "/")) ? p.slice(b.length) || "/" : p; })()` : "window.location.pathname";
|
|
1509
|
+
const logEndpoint = basePath ? `${JSON.stringify(basePath)} + "/_furin/ingest"` : `"/_furin/ingest"`;
|
|
1510
|
+
const basePathProp = basePath ? `
|
|
1511
|
+
basePath: ${basePathLiteral},` : "";
|
|
1415
1512
|
return `import { hydrateRoot, createRoot } from "react-dom/client";
|
|
1416
1513
|
import { createElement } from "react";
|
|
1417
1514
|
import { initLogger, log } from "evlog";
|
|
1418
|
-
import {
|
|
1515
|
+
import { createHttpLogDrain } from "evlog/http";
|
|
1419
1516
|
import { RouterProvider } from "@teyik0/furin/link";
|
|
1420
1517
|
import { route as root } from "${rootLayout.replace(/\\/g, "/")}";
|
|
1421
1518
|
|
|
1422
|
-
initLogger({ drain:
|
|
1519
|
+
initLogger({ drain: createHttpLogDrain({ drain: { endpoint: ${logEndpoint} } }) });
|
|
1423
1520
|
|
|
1424
1521
|
const routes = [
|
|
1425
1522
|
${routeEntries.join(`,
|
|
1426
1523
|
`)}
|
|
1427
1524
|
];
|
|
1428
1525
|
|
|
1429
|
-
const pathname =
|
|
1526
|
+
const pathname = ${pathnameExpr};
|
|
1430
1527
|
const _match = routes.find((r) => r.regex.test(pathname));
|
|
1431
1528
|
|
|
1432
1529
|
// Eagerly load only the current page module for initial hydration.
|
|
@@ -1446,7 +1543,7 @@ const _match = routes.find((r) => r.regex.test(pathname));
|
|
|
1446
1543
|
routes,
|
|
1447
1544
|
root,
|
|
1448
1545
|
initialMatch: match,
|
|
1449
|
-
initialData: loaderData
|
|
1546
|
+
initialData: loaderData,${basePathProp}
|
|
1450
1547
|
} as any);
|
|
1451
1548
|
|
|
1452
1549
|
if (import.meta.hot) {
|
|
@@ -1535,7 +1632,7 @@ function buildTargetManifest(rootDir, buildRoot, target, serverEntry) {
|
|
|
1535
1632
|
// src/build/client.ts
|
|
1536
1633
|
var TS_FILE_FILTER = /\.(tsx|ts)$/;
|
|
1537
1634
|
var REACT_IMPORT_RE = /import\s+React\b/;
|
|
1538
|
-
async function buildClient(routes, { outDir, rootLayout, plugins }) {
|
|
1635
|
+
async function buildClient(routes, { outDir, rootLayout, plugins, publicPath, basePath }) {
|
|
1539
1636
|
const clientDir = join2(outDir, "client");
|
|
1540
1637
|
if (!existsSync2(outDir)) {
|
|
1541
1638
|
mkdirSync2(outDir, { recursive: true });
|
|
@@ -1543,7 +1640,7 @@ async function buildClient(routes, { outDir, rootLayout, plugins }) {
|
|
|
1543
1640
|
if (!existsSync2(clientDir)) {
|
|
1544
1641
|
mkdirSync2(clientDir, { recursive: true });
|
|
1545
1642
|
}
|
|
1546
|
-
const hydrateCode = generateHydrateEntry(routes, rootLayout);
|
|
1643
|
+
const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath);
|
|
1547
1644
|
const hydratePath = join2(outDir, "_hydrate.tsx");
|
|
1548
1645
|
writeFileSync(hydratePath, hydrateCode);
|
|
1549
1646
|
console.log("[furin] Building production client bundle\u2026");
|
|
@@ -1587,7 +1684,7 @@ ${transformed}`;
|
|
|
1587
1684
|
entry: "[dir]/[name]-[hash].[ext]",
|
|
1588
1685
|
chunk: "[name]-[hash].[ext]"
|
|
1589
1686
|
},
|
|
1590
|
-
publicPath
|
|
1687
|
+
publicPath,
|
|
1591
1688
|
plugins: plugins ? [...plugins, transformPlugin] : [transformPlugin],
|
|
1592
1689
|
alias: {
|
|
1593
1690
|
"@teyik0/furin/client": CLIENT_MODULE_PATH,
|
|
@@ -1606,8 +1703,14 @@ ${transformed}`;
|
|
|
1606
1703
|
if (!entryOutput) {
|
|
1607
1704
|
throw new Error("[furin] client build did not emit entry chunk");
|
|
1608
1705
|
}
|
|
1609
|
-
|
|
1610
|
-
|
|
1706
|
+
let publicPrefix;
|
|
1707
|
+
if (publicPath === "") {
|
|
1708
|
+
publicPrefix = "";
|
|
1709
|
+
} else {
|
|
1710
|
+
publicPrefix = publicPath.endsWith("/") ? publicPath : `${publicPath}/`;
|
|
1711
|
+
}
|
|
1712
|
+
const entryChunk = `${publicPrefix}${basename(entryOutput.path)}`;
|
|
1713
|
+
const cssChunks = cssOutputs.map((o) => `${publicPrefix}${basename(o.path)}`);
|
|
1611
1714
|
console.log("[furin] Production client build complete");
|
|
1612
1715
|
return { entryChunk, cssChunks };
|
|
1613
1716
|
}
|
|
@@ -1792,7 +1895,9 @@ async function buildBunTarget(routes, rootDir, buildRoot, rootPath, serverEntry,
|
|
|
1792
1895
|
const { entryChunk, cssChunks } = await buildClient(routes, {
|
|
1793
1896
|
outDir: targetDir,
|
|
1794
1897
|
rootLayout: rootPath,
|
|
1795
|
-
plugins: options.plugins
|
|
1898
|
+
plugins: options.plugins,
|
|
1899
|
+
publicPath: "/_client/",
|
|
1900
|
+
basePath: ""
|
|
1796
1901
|
});
|
|
1797
1902
|
const buildFingerprint = await createBuildFingerprint(entryChunk, cssChunks, routes, rootPath, serverEntry);
|
|
1798
1903
|
const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
|
|
@@ -1822,8 +1927,18 @@ async function buildBunTarget(routes, rootDir, buildRoot, rootPath, serverEntry,
|
|
|
1822
1927
|
compile: { outfile },
|
|
1823
1928
|
minify: true,
|
|
1824
1929
|
sourcemap: "linked",
|
|
1930
|
+
define: { "process.env.NODE_ENV": JSON.stringify("production") },
|
|
1825
1931
|
plugins: options.plugins
|
|
1826
1932
|
});
|
|
1933
|
+
if (process.platform === "darwin") {
|
|
1934
|
+
Bun.spawnSync(["codesign", "--remove-signature", outfile]);
|
|
1935
|
+
const sign = Bun.spawnSync(["codesign", "-f", "-s", "-", outfile]);
|
|
1936
|
+
if (sign.exitCode !== 0) {
|
|
1937
|
+
console.warn(`[furin] Warning: codesign failed (exit ${sign.exitCode}). ` + `The binary may be killed by Gatekeeper on macOS. Run manually:
|
|
1938
|
+
` + ` codesign --remove-signature ${outfile}
|
|
1939
|
+
` + ` codesign -f -s - ${outfile}`);
|
|
1940
|
+
}
|
|
1941
|
+
}
|
|
1827
1942
|
console.log(`[furin] Server binary: ${outfile}`);
|
|
1828
1943
|
targetManifest.serverPath = toPosixPath(join5(targetManifest.targetDir, "server"));
|
|
1829
1944
|
if (options.compile === "embed") {
|
|
@@ -1861,9 +1976,1305 @@ async function buildBunTarget(routes, rootDir, buildRoot, rootPath, serverEntry,
|
|
|
1861
1976
|
return targetManifest;
|
|
1862
1977
|
}
|
|
1863
1978
|
|
|
1979
|
+
// src/adapter/static.ts
|
|
1980
|
+
import { cpSync as cpSync2, existsSync as existsSync5, rmSync as rmSync3, writeFileSync as writeFileSync5 } from "fs";
|
|
1981
|
+
import { dirname as dirname3, isAbsolute, join as join6, relative as relative3, resolve as resolve2, sep } from "path";
|
|
1982
|
+
|
|
1983
|
+
// src/render/assemble.ts
|
|
1984
|
+
function resolvePath(pattern, params) {
|
|
1985
|
+
let path = pattern;
|
|
1986
|
+
for (const [key, val] of Object.entries(params ?? {})) {
|
|
1987
|
+
path = path.replace(key === "*" ? "*" : `:${key}`, val);
|
|
1988
|
+
}
|
|
1989
|
+
return path;
|
|
1990
|
+
}
|
|
1991
|
+
async function streamToString(stream) {
|
|
1992
|
+
const reader = stream.getReader();
|
|
1993
|
+
const decoder = new TextDecoder;
|
|
1994
|
+
let html = "";
|
|
1995
|
+
for (;; ) {
|
|
1996
|
+
const { done, value } = await reader.read();
|
|
1997
|
+
if (done) {
|
|
1998
|
+
break;
|
|
1999
|
+
}
|
|
2000
|
+
html += decoder.decode(value, { stream: true });
|
|
2001
|
+
}
|
|
2002
|
+
html += decoder.decode();
|
|
2003
|
+
return html;
|
|
2004
|
+
}
|
|
2005
|
+
function splitTemplate(template) {
|
|
2006
|
+
const [headPre, afterHead = ""] = template.split("<!--ssr-head-->");
|
|
2007
|
+
const [bodyPre, bodyPost = ""] = afterHead.split("<!--ssr-outlet-->");
|
|
2008
|
+
return { headPre, bodyPre, bodyPost };
|
|
2009
|
+
}
|
|
2010
|
+
function assembleHTML(template, headData, reactHtml, data) {
|
|
2011
|
+
const { headPre, bodyPre, bodyPost } = splitTemplate(template);
|
|
2012
|
+
const dataScript = data ? `<script id="__FURIN_DATA__" type="application/json">${safeJson(data)}</script>` : "";
|
|
2013
|
+
let injectedBodyPost = bodyPost;
|
|
2014
|
+
if (dataScript) {
|
|
2015
|
+
injectedBodyPost = bodyPost.includes("</body>") ? bodyPost.replace("</body>", `${dataScript}</body>`) : bodyPost + dataScript;
|
|
2016
|
+
}
|
|
2017
|
+
return headPre + headData + bodyPre + reactHtml + injectedBodyPost;
|
|
2018
|
+
}
|
|
2019
|
+
|
|
2020
|
+
// src/render/index.ts
|
|
2021
|
+
import { createElement as createElement2 } from "react";
|
|
2022
|
+
import { renderToReadableStream } from "react-dom/server";
|
|
2023
|
+
// ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/utils.mjs
|
|
2024
|
+
function formatDuration(ms) {
|
|
2025
|
+
if (ms < 1000)
|
|
2026
|
+
return `${Math.round(ms)}ms`;
|
|
2027
|
+
return `${(ms / 1000).toFixed(2)}s`;
|
|
2028
|
+
}
|
|
2029
|
+
function isClient() {
|
|
2030
|
+
return typeof window !== "undefined";
|
|
2031
|
+
}
|
|
2032
|
+
function isDev() {
|
|
2033
|
+
if (typeof process !== "undefined")
|
|
2034
|
+
return true;
|
|
2035
|
+
if (typeof window !== "undefined")
|
|
2036
|
+
return true;
|
|
2037
|
+
return false;
|
|
2038
|
+
}
|
|
2039
|
+
function detectEnvironment() {
|
|
2040
|
+
const env = typeof process !== "undefined" ? process.env : {};
|
|
2041
|
+
const defaultEnvironment = isDev() ? "development" : "production";
|
|
2042
|
+
return {
|
|
2043
|
+
environment: env.NODE_ENV || defaultEnvironment,
|
|
2044
|
+
service: env.SERVICE_NAME || "app",
|
|
2045
|
+
version: env.APP_VERSION,
|
|
2046
|
+
commitHash: env.COMMIT_SHA || env.GITHUB_SHA || env.VERCEL_GIT_COMMIT_SHA || env.CF_PAGES_COMMIT_SHA,
|
|
2047
|
+
region: env.VERCEL_REGION || env.AWS_REGION || env.FLY_REGION || env.CF_REGION
|
|
2048
|
+
};
|
|
2049
|
+
}
|
|
2050
|
+
var LEVEL_ORDER = {
|
|
2051
|
+
debug: 0,
|
|
2052
|
+
info: 1,
|
|
2053
|
+
warn: 2,
|
|
2054
|
+
error: 3
|
|
2055
|
+
};
|
|
2056
|
+
function isLevelEnabled(level, minLevel) {
|
|
2057
|
+
return LEVEL_ORDER[level] >= LEVEL_ORDER[minLevel];
|
|
2058
|
+
}
|
|
2059
|
+
function getConsoleMethod(level) {
|
|
2060
|
+
return level;
|
|
2061
|
+
}
|
|
2062
|
+
var colors = {
|
|
2063
|
+
reset: "\x1B[0m",
|
|
2064
|
+
bold: "\x1B[1m",
|
|
2065
|
+
dim: "\x1B[2m",
|
|
2066
|
+
red: "\x1B[31m",
|
|
2067
|
+
green: "\x1B[32m",
|
|
2068
|
+
yellow: "\x1B[33m",
|
|
2069
|
+
blue: "\x1B[34m",
|
|
2070
|
+
magenta: "\x1B[35m",
|
|
2071
|
+
cyan: "\x1B[36m",
|
|
2072
|
+
white: "\x1B[37m",
|
|
2073
|
+
gray: "\x1B[90m"
|
|
2074
|
+
};
|
|
2075
|
+
var levelColorMap = {
|
|
2076
|
+
error: colors.red,
|
|
2077
|
+
warn: colors.yellow,
|
|
2078
|
+
info: colors.cyan,
|
|
2079
|
+
debug: colors.gray
|
|
2080
|
+
};
|
|
2081
|
+
function getLevelColor(level) {
|
|
2082
|
+
return levelColorMap[level] ?? colors.white;
|
|
2083
|
+
}
|
|
2084
|
+
var cssColors = {
|
|
2085
|
+
dim: "color: #6b7280",
|
|
2086
|
+
red: "color: #ef4444; font-weight: bold",
|
|
2087
|
+
green: "color: #22c55e",
|
|
2088
|
+
yellow: "color: #f59e0b; font-weight: bold",
|
|
2089
|
+
cyan: "color: #06b6d4; font-weight: bold",
|
|
2090
|
+
gray: "color: #6b7280; font-weight: bold",
|
|
2091
|
+
reset: "color: inherit; font-weight: normal"
|
|
2092
|
+
};
|
|
2093
|
+
var cssLevelColorMap = {
|
|
2094
|
+
error: cssColors.red,
|
|
2095
|
+
warn: cssColors.yellow,
|
|
2096
|
+
info: cssColors.cyan,
|
|
2097
|
+
debug: cssColors.gray
|
|
2098
|
+
};
|
|
2099
|
+
function getCssLevelColor(level) {
|
|
2100
|
+
return cssLevelColorMap[level] ?? cssColors.reset;
|
|
2101
|
+
}
|
|
2102
|
+
function escapeFormatString(str) {
|
|
2103
|
+
return str.replace(/%/g, "%%");
|
|
2104
|
+
}
|
|
2105
|
+
var patternCache = /* @__PURE__ */ new Map;
|
|
2106
|
+
function matchesPattern(path, pattern) {
|
|
2107
|
+
let regex = patternCache.get(pattern);
|
|
2108
|
+
if (!regex) {
|
|
2109
|
+
const regexPattern = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "{{GLOBSTAR}}").replace(/\*/g, "[^/]*").replace(/{{GLOBSTAR}}/g, ".*").replace(/\?/g, "[^/]");
|
|
2110
|
+
regex = new RegExp(`^${regexPattern}$`);
|
|
2111
|
+
patternCache.set(pattern, regex);
|
|
2112
|
+
}
|
|
2113
|
+
return regex.test(path);
|
|
2114
|
+
}
|
|
2115
|
+
|
|
2116
|
+
// ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/logger-DnobymUQ.mjs
|
|
2117
|
+
var DEFAULT_REPLACEMENT = "[REDACTED]";
|
|
2118
|
+
var builtinPatterns = {
|
|
2119
|
+
creditCard: {
|
|
2120
|
+
pattern: /\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,
|
|
2121
|
+
mask: (m) => `****${m.replace(/[\s-]/g, "").slice(-4)}`
|
|
2122
|
+
},
|
|
2123
|
+
email: {
|
|
2124
|
+
pattern: /[\w.+-]+@[\w-]+\.[\w.]+/g,
|
|
2125
|
+
mask: (m) => {
|
|
2126
|
+
if (m.indexOf("@") < 1)
|
|
2127
|
+
return "***@***";
|
|
2128
|
+
const tld = m.slice(m.lastIndexOf("."));
|
|
2129
|
+
return `${m[0]}***@***${tld}`;
|
|
2130
|
+
}
|
|
2131
|
+
},
|
|
2132
|
+
ipv4: {
|
|
2133
|
+
pattern: /\b(?!0\.0\.0\.0\b)(?!127\.0\.0\.1\b)\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,
|
|
2134
|
+
mask: (m) => `***.***.***.${m.split(".").pop()}`
|
|
2135
|
+
},
|
|
2136
|
+
phone: {
|
|
2137
|
+
pattern: /(?:\+\d{1,3}[\s.-]?)?\(?\d{1,4}\)?[\s.-]?\d{2,4}[\s.-]?\d{2,4}[\s.-]?\d{2,4}\b/g,
|
|
2138
|
+
mask: (m) => {
|
|
2139
|
+
const digits = m.replace(/[^\d]/g, "");
|
|
2140
|
+
if (m.startsWith("+") && digits.length > 4) {
|
|
2141
|
+
const ccMatch = m.match(/^\+\d{1,3}/);
|
|
2142
|
+
return `${ccMatch ? ccMatch[0] : "+"}******${digits.slice(-2)}`;
|
|
2143
|
+
}
|
|
2144
|
+
if (digits.length > 2)
|
|
2145
|
+
return `${"*".repeat(digits.length - 2)}${digits.slice(-2)}`;
|
|
2146
|
+
return "***";
|
|
2147
|
+
}
|
|
2148
|
+
},
|
|
2149
|
+
jwt: {
|
|
2150
|
+
pattern: /\beyJ[\w-]*\.[\w-]*\.[\w-]*\b/g,
|
|
2151
|
+
mask: () => "eyJ***.***"
|
|
2152
|
+
},
|
|
2153
|
+
bearer: {
|
|
2154
|
+
pattern: /\bBearer\s+[\w\-.~+/]{8,}=*/gi,
|
|
2155
|
+
mask: () => "Bearer ***"
|
|
2156
|
+
},
|
|
2157
|
+
iban: {
|
|
2158
|
+
pattern: /\b[A-Z]{2}\d{2}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}\b/g,
|
|
2159
|
+
mask: (m) => {
|
|
2160
|
+
const clean = m.replace(/[\s-]/g, "");
|
|
2161
|
+
return `${clean.slice(0, 4)}****${clean.slice(-3)}`;
|
|
2162
|
+
}
|
|
2163
|
+
}
|
|
2164
|
+
};
|
|
2165
|
+
function resolveRedactConfig(input) {
|
|
2166
|
+
if (input === undefined || input === false)
|
|
2167
|
+
return;
|
|
2168
|
+
if (input === true)
|
|
2169
|
+
return { _maskers: allBuiltinMaskers() };
|
|
2170
|
+
if (input.builtins === false)
|
|
2171
|
+
return input;
|
|
2172
|
+
const maskers = Array.isArray(input.builtins) ? input.builtins.map((name) => builtinPatterns[name]).filter(Boolean).map((b) => [cloneRegex(b.pattern), b.mask]) : allBuiltinMaskers();
|
|
2173
|
+
return {
|
|
2174
|
+
...input,
|
|
2175
|
+
_maskers: maskers
|
|
2176
|
+
};
|
|
2177
|
+
}
|
|
2178
|
+
function allBuiltinMaskers() {
|
|
2179
|
+
return Object.values(builtinPatterns).map((b) => [cloneRegex(b.pattern), b.mask]);
|
|
2180
|
+
}
|
|
2181
|
+
function cloneRegex(re) {
|
|
2182
|
+
return new RegExp(re.source, re.flags);
|
|
2183
|
+
}
|
|
2184
|
+
function redactEvent(event, config) {
|
|
2185
|
+
const replacement = config.replacement ?? DEFAULT_REPLACEMENT;
|
|
2186
|
+
if (config.paths?.length)
|
|
2187
|
+
for (const path of config.paths)
|
|
2188
|
+
redactPath(event, path.split("."), replacement);
|
|
2189
|
+
if (config._maskers?.length)
|
|
2190
|
+
applyMaskersToTree(event, config._maskers);
|
|
2191
|
+
if (config.patterns?.length)
|
|
2192
|
+
redactPatterns(event, config.patterns, replacement);
|
|
2193
|
+
}
|
|
2194
|
+
function redactPath(obj, segments, replacement) {
|
|
2195
|
+
let current = obj;
|
|
2196
|
+
for (let i = 0;i < segments.length - 1; i++) {
|
|
2197
|
+
if (current === null || current === undefined || typeof current !== "object")
|
|
2198
|
+
return;
|
|
2199
|
+
current = current[segments[i]];
|
|
2200
|
+
}
|
|
2201
|
+
if (current === null || current === undefined || typeof current !== "object")
|
|
2202
|
+
return;
|
|
2203
|
+
const leaf = segments[segments.length - 1];
|
|
2204
|
+
if (leaf in current)
|
|
2205
|
+
current[leaf] = replacement;
|
|
2206
|
+
}
|
|
2207
|
+
function redactPatterns(obj, patterns, replacement) {
|
|
2208
|
+
if (obj === null || obj === undefined)
|
|
2209
|
+
return;
|
|
2210
|
+
if (Array.isArray(obj)) {
|
|
2211
|
+
for (let i = 0;i < obj.length; i++)
|
|
2212
|
+
if (typeof obj[i] === "string")
|
|
2213
|
+
obj[i] = applyPatterns(obj[i], patterns, replacement);
|
|
2214
|
+
else if (typeof obj[i] === "object")
|
|
2215
|
+
redactPatterns(obj[i], patterns, replacement);
|
|
2216
|
+
return;
|
|
2217
|
+
}
|
|
2218
|
+
if (typeof obj === "object") {
|
|
2219
|
+
const record = obj;
|
|
2220
|
+
for (const key in record) {
|
|
2221
|
+
const val = record[key];
|
|
2222
|
+
if (typeof val === "string")
|
|
2223
|
+
record[key] = applyPatterns(val, patterns, replacement);
|
|
2224
|
+
else if (typeof val === "object")
|
|
2225
|
+
redactPatterns(val, patterns, replacement);
|
|
2226
|
+
}
|
|
2227
|
+
}
|
|
2228
|
+
}
|
|
2229
|
+
function applyPatterns(value, patterns, replacement) {
|
|
2230
|
+
let result = value;
|
|
2231
|
+
for (const pattern of patterns) {
|
|
2232
|
+
pattern.lastIndex = 0;
|
|
2233
|
+
result = result.replace(pattern, replacement);
|
|
2234
|
+
}
|
|
2235
|
+
return result;
|
|
2236
|
+
}
|
|
2237
|
+
function applyMaskersToTree(obj, maskers) {
|
|
2238
|
+
if (obj === null || obj === undefined)
|
|
2239
|
+
return;
|
|
2240
|
+
if (Array.isArray(obj)) {
|
|
2241
|
+
for (let i = 0;i < obj.length; i++)
|
|
2242
|
+
if (typeof obj[i] === "string")
|
|
2243
|
+
obj[i] = applyMaskers(obj[i], maskers);
|
|
2244
|
+
else if (typeof obj[i] === "object")
|
|
2245
|
+
applyMaskersToTree(obj[i], maskers);
|
|
2246
|
+
return;
|
|
2247
|
+
}
|
|
2248
|
+
if (typeof obj === "object") {
|
|
2249
|
+
const record = obj;
|
|
2250
|
+
for (const key in record) {
|
|
2251
|
+
const val = record[key];
|
|
2252
|
+
if (typeof val === "string")
|
|
2253
|
+
record[key] = applyMaskers(val, maskers);
|
|
2254
|
+
else if (typeof val === "object")
|
|
2255
|
+
applyMaskersToTree(val, maskers);
|
|
2256
|
+
}
|
|
2257
|
+
}
|
|
2258
|
+
}
|
|
2259
|
+
function applyMaskers(value, maskers) {
|
|
2260
|
+
let result = value;
|
|
2261
|
+
for (const [pattern, mask] of maskers) {
|
|
2262
|
+
pattern.lastIndex = 0;
|
|
2263
|
+
result = result.replace(pattern, mask);
|
|
2264
|
+
}
|
|
2265
|
+
return result;
|
|
2266
|
+
}
|
|
2267
|
+
function isPlainObject(val) {
|
|
2268
|
+
return val !== null && typeof val === "object" && !Array.isArray(val);
|
|
2269
|
+
}
|
|
2270
|
+
var _tsDate = /* @__PURE__ */ new Date;
|
|
2271
|
+
function isoNow() {
|
|
2272
|
+
_tsDate.setTime(Date.now());
|
|
2273
|
+
return _tsDate.toISOString();
|
|
2274
|
+
}
|
|
2275
|
+
var POST_EMIT_FORK_HINT = "For intentional background work tied to this request, use log.fork('label', fn) when your integration supports it (see https://evlog.dev).";
|
|
2276
|
+
function warnPostEmit(method, detail) {
|
|
2277
|
+
console.warn(`[evlog] ${method} called after the wide event was emitted \u2014 ${detail} This data will not appear in observability. ${POST_EMIT_FORK_HINT}`);
|
|
2278
|
+
}
|
|
2279
|
+
function mergeInto(target, source) {
|
|
2280
|
+
for (const key in source) {
|
|
2281
|
+
const sourceVal = source[key];
|
|
2282
|
+
if (sourceVal === undefined || sourceVal === null)
|
|
2283
|
+
continue;
|
|
2284
|
+
const targetVal = target[key];
|
|
2285
|
+
if (isPlainObject(sourceVal) && isPlainObject(targetVal))
|
|
2286
|
+
mergeInto(targetVal, sourceVal);
|
|
2287
|
+
else if (Array.isArray(targetVal) && Array.isArray(sourceVal))
|
|
2288
|
+
target[key] = [...targetVal, ...sourceVal];
|
|
2289
|
+
else
|
|
2290
|
+
target[key] = sourceVal;
|
|
2291
|
+
}
|
|
2292
|
+
}
|
|
2293
|
+
var globalEnv = {
|
|
2294
|
+
service: "app",
|
|
2295
|
+
environment: "development"
|
|
2296
|
+
};
|
|
2297
|
+
var globalPretty = isDev();
|
|
2298
|
+
var globalSampling = {};
|
|
2299
|
+
var globalStringify = true;
|
|
2300
|
+
var globalDrain;
|
|
2301
|
+
var globalRedact;
|
|
2302
|
+
var globalEnabled = true;
|
|
2303
|
+
var globalSilent = false;
|
|
2304
|
+
var globalMinLevel = "debug";
|
|
2305
|
+
function initLogger(config = {}) {
|
|
2306
|
+
globalEnabled = config.enabled ?? true;
|
|
2307
|
+
const detected = detectEnvironment();
|
|
2308
|
+
globalEnv = {
|
|
2309
|
+
service: config.env?.service ?? detected.service ?? "app",
|
|
2310
|
+
environment: config.env?.environment ?? detected.environment ?? "development",
|
|
2311
|
+
version: config.env?.version ?? detected.version,
|
|
2312
|
+
commitHash: config.env?.commitHash ?? detected.commitHash,
|
|
2313
|
+
region: config.env?.region ?? detected.region
|
|
2314
|
+
};
|
|
2315
|
+
globalPretty = config.pretty ?? isDev();
|
|
2316
|
+
globalSampling = config.sampling ?? {};
|
|
2317
|
+
globalStringify = config.stringify ?? true;
|
|
2318
|
+
globalDrain = config.drain;
|
|
2319
|
+
globalRedact = resolveRedactConfig(config.redact ?? !isDev());
|
|
2320
|
+
globalSilent = config.silent ?? false;
|
|
2321
|
+
globalMinLevel = config.minLevel ?? "debug";
|
|
2322
|
+
if (globalSilent && !globalDrain && !config._suppressDrainWarning)
|
|
2323
|
+
console.warn("[evlog] silent mode is enabled but no drain is configured. Events will be built and sampled but not output anywhere. Set a drain via initLogger({ drain }) or a framework hook (evlog:drain).");
|
|
2324
|
+
}
|
|
2325
|
+
function shouldSample(level) {
|
|
2326
|
+
const { rates } = globalSampling;
|
|
2327
|
+
if (!rates)
|
|
2328
|
+
return true;
|
|
2329
|
+
const percentage = level === "error" && rates.error === undefined ? 100 : rates[level] ?? 100;
|
|
2330
|
+
if (percentage <= 0)
|
|
2331
|
+
return false;
|
|
2332
|
+
if (percentage >= 100)
|
|
2333
|
+
return true;
|
|
2334
|
+
return Math.random() * 100 < percentage;
|
|
2335
|
+
}
|
|
2336
|
+
function shouldKeep(ctx) {
|
|
2337
|
+
const { keep } = globalSampling;
|
|
2338
|
+
if (!keep?.length)
|
|
2339
|
+
return false;
|
|
2340
|
+
return keep.some((condition) => {
|
|
2341
|
+
if (condition.status !== undefined && ctx.status !== undefined && ctx.status >= condition.status)
|
|
2342
|
+
return true;
|
|
2343
|
+
if (condition.duration !== undefined && ctx.duration !== undefined && ctx.duration >= condition.duration)
|
|
2344
|
+
return true;
|
|
2345
|
+
if (condition.path && ctx.path && matchesPattern(ctx.path, condition.path))
|
|
2346
|
+
return true;
|
|
2347
|
+
return false;
|
|
2348
|
+
});
|
|
2349
|
+
}
|
|
2350
|
+
function emitWideEvent(level, event, deferDrain = false, ownsEvent = false) {
|
|
2351
|
+
if (!globalEnabled)
|
|
2352
|
+
return null;
|
|
2353
|
+
if (!ownsEvent) {
|
|
2354
|
+
if (!isLevelEnabled(level, globalMinLevel))
|
|
2355
|
+
return null;
|
|
2356
|
+
if (!shouldSample(level))
|
|
2357
|
+
return null;
|
|
2358
|
+
}
|
|
2359
|
+
let formatted;
|
|
2360
|
+
if (ownsEvent) {
|
|
2361
|
+
event.timestamp = isoNow();
|
|
2362
|
+
event.level = level;
|
|
2363
|
+
if (event.service === undefined)
|
|
2364
|
+
event.service = globalEnv.service;
|
|
2365
|
+
if (event.environment === undefined)
|
|
2366
|
+
event.environment = globalEnv.environment;
|
|
2367
|
+
if (globalEnv.version !== undefined && event.version === undefined)
|
|
2368
|
+
event.version = globalEnv.version;
|
|
2369
|
+
if (globalEnv.commitHash !== undefined && event.commitHash === undefined)
|
|
2370
|
+
event.commitHash = globalEnv.commitHash;
|
|
2371
|
+
if (globalEnv.region !== undefined && event.region === undefined)
|
|
2372
|
+
event.region = globalEnv.region;
|
|
2373
|
+
formatted = event;
|
|
2374
|
+
} else
|
|
2375
|
+
formatted = {
|
|
2376
|
+
timestamp: isoNow(),
|
|
2377
|
+
level,
|
|
2378
|
+
...globalEnv,
|
|
2379
|
+
...event
|
|
2380
|
+
};
|
|
2381
|
+
if (globalRedact)
|
|
2382
|
+
redactEvent(formatted, globalRedact);
|
|
2383
|
+
if (!globalSilent)
|
|
2384
|
+
if (globalPretty)
|
|
2385
|
+
prettyPrintWideEvent(formatted);
|
|
2386
|
+
else if (globalStringify)
|
|
2387
|
+
console[getConsoleMethod(level)](JSON.stringify(formatted));
|
|
2388
|
+
else
|
|
2389
|
+
console[getConsoleMethod(level)](formatted);
|
|
2390
|
+
if (globalDrain && !deferDrain)
|
|
2391
|
+
Promise.resolve(globalDrain({ event: formatted })).catch((err) => {
|
|
2392
|
+
console.error("[evlog] drain failed:", err);
|
|
2393
|
+
});
|
|
2394
|
+
return formatted;
|
|
2395
|
+
}
|
|
2396
|
+
function emitTaggedLog(level, tag, message) {
|
|
2397
|
+
if (!globalEnabled)
|
|
2398
|
+
return;
|
|
2399
|
+
if (globalPretty && !globalSilent) {
|
|
2400
|
+
if (!isLevelEnabled(level, globalMinLevel))
|
|
2401
|
+
return;
|
|
2402
|
+
if (!shouldSample(level))
|
|
2403
|
+
return;
|
|
2404
|
+
if (isClient()) {
|
|
2405
|
+
const levelColor = getCssLevelColor(level);
|
|
2406
|
+
const timestamp = isoNow().slice(11, 23);
|
|
2407
|
+
console.log(`%c${timestamp}%c %c[${escapeFormatString(tag)}]%c ${escapeFormatString(message)}`, cssColors.dim, cssColors.reset, levelColor, cssColors.reset);
|
|
2408
|
+
} else {
|
|
2409
|
+
const color = getLevelColor(level);
|
|
2410
|
+
const timestamp = isoNow().slice(11, 23);
|
|
2411
|
+
console.log(`${colors.dim}${timestamp}${colors.reset} ${color}[${tag}]${colors.reset} ${message}`);
|
|
2412
|
+
}
|
|
2413
|
+
return;
|
|
2414
|
+
}
|
|
2415
|
+
emitWideEvent(level, {
|
|
2416
|
+
tag,
|
|
2417
|
+
message
|
|
2418
|
+
});
|
|
2419
|
+
}
|
|
2420
|
+
function formatValue(value) {
|
|
2421
|
+
if (value === null || value === undefined)
|
|
2422
|
+
return String(value);
|
|
2423
|
+
if (typeof value === "object") {
|
|
2424
|
+
const pairs = [];
|
|
2425
|
+
for (const [k, v] of Object.entries(value))
|
|
2426
|
+
if (v !== undefined && v !== null)
|
|
2427
|
+
if (typeof v === "object")
|
|
2428
|
+
pairs.push(`${k}=${JSON.stringify(v)}`);
|
|
2429
|
+
else
|
|
2430
|
+
pairs.push(`${k}=${v}`);
|
|
2431
|
+
return pairs.join(" ");
|
|
2432
|
+
}
|
|
2433
|
+
return String(value);
|
|
2434
|
+
}
|
|
2435
|
+
function formatCost(cost) {
|
|
2436
|
+
if (cost < 0.01)
|
|
2437
|
+
return `$${cost.toFixed(6)}`;
|
|
2438
|
+
if (cost < 1)
|
|
2439
|
+
return `$${cost.toFixed(4)}`;
|
|
2440
|
+
return `$${cost.toFixed(2)}`;
|
|
2441
|
+
}
|
|
2442
|
+
function buildAIEntries(ai) {
|
|
2443
|
+
const entries = [];
|
|
2444
|
+
const headerParts = [];
|
|
2445
|
+
if (ai.model) {
|
|
2446
|
+
let m = String(ai.model);
|
|
2447
|
+
if (ai.provider)
|
|
2448
|
+
m += ` (${ai.provider})`;
|
|
2449
|
+
headerParts.push(m);
|
|
2450
|
+
}
|
|
2451
|
+
if (ai.calls)
|
|
2452
|
+
headerParts.push(`${ai.calls} call${ai.calls > 1 ? "s" : ""}`);
|
|
2453
|
+
if (ai.steps && ai.steps > 1)
|
|
2454
|
+
headerParts.push(`${ai.steps} steps`);
|
|
2455
|
+
entries.push({
|
|
2456
|
+
key: "ai",
|
|
2457
|
+
value: headerParts.join(" \xB7 ")
|
|
2458
|
+
});
|
|
2459
|
+
const inputTokens = ai.inputTokens;
|
|
2460
|
+
const outputTokens = ai.outputTokens;
|
|
2461
|
+
const totalTokens = ai.totalTokens;
|
|
2462
|
+
if (inputTokens !== undefined && outputTokens !== undefined) {
|
|
2463
|
+
let tokLine = `${inputTokens} in \u2192 ${outputTokens} out`;
|
|
2464
|
+
if (totalTokens)
|
|
2465
|
+
tokLine += ` (${totalTokens} total)`;
|
|
2466
|
+
const extras = [];
|
|
2467
|
+
if (ai.cacheReadTokens)
|
|
2468
|
+
extras.push(`${ai.cacheReadTokens} cache read`);
|
|
2469
|
+
if (ai.cacheWriteTokens)
|
|
2470
|
+
extras.push(`${ai.cacheWriteTokens} cache write`);
|
|
2471
|
+
if (ai.reasoningTokens)
|
|
2472
|
+
extras.push(`${ai.reasoningTokens} reasoning`);
|
|
2473
|
+
if (extras.length)
|
|
2474
|
+
tokLine += ` \xB7 ${extras.join(" \xB7 ")}`;
|
|
2475
|
+
entries.push({
|
|
2476
|
+
key: "ai.tokens",
|
|
2477
|
+
value: tokLine
|
|
2478
|
+
});
|
|
2479
|
+
}
|
|
2480
|
+
const msFirst = ai.msToFirstChunk;
|
|
2481
|
+
const msFinish = ai.msToFinish;
|
|
2482
|
+
const tps = ai.tokensPerSecond;
|
|
2483
|
+
if (msFirst !== undefined || msFinish !== undefined) {
|
|
2484
|
+
const parts = [];
|
|
2485
|
+
if (msFirst !== undefined)
|
|
2486
|
+
parts.push(`${formatDuration(msFirst)} to first chunk`);
|
|
2487
|
+
if (msFinish !== undefined)
|
|
2488
|
+
parts.push(`${formatDuration(msFinish)} total`);
|
|
2489
|
+
let streamLine = parts.join(" \u2192 ");
|
|
2490
|
+
if (tps)
|
|
2491
|
+
streamLine += ` \xB7 ${tps} tok/s`;
|
|
2492
|
+
entries.push({
|
|
2493
|
+
key: "ai.streaming",
|
|
2494
|
+
value: streamLine
|
|
2495
|
+
});
|
|
2496
|
+
}
|
|
2497
|
+
if (ai.estimatedCost !== undefined)
|
|
2498
|
+
entries.push({
|
|
2499
|
+
key: "ai.cost",
|
|
2500
|
+
value: formatCost(ai.estimatedCost)
|
|
2501
|
+
});
|
|
2502
|
+
if (ai.totalDurationMs !== undefined)
|
|
2503
|
+
entries.push({
|
|
2504
|
+
key: "ai.totalDuration",
|
|
2505
|
+
value: formatDuration(ai.totalDurationMs)
|
|
2506
|
+
});
|
|
2507
|
+
const toolCalls = ai.toolCalls;
|
|
2508
|
+
const tools = ai.tools;
|
|
2509
|
+
const hasInputs = toolCalls?.length ? typeof toolCalls[0] === "object" : false;
|
|
2510
|
+
if (tools?.length) {
|
|
2511
|
+
const children = tools.map((t, idx) => {
|
|
2512
|
+
const mark = t.success ? "\u2713" : "\u2717";
|
|
2513
|
+
let line = `${t.name} ${formatDuration(t.durationMs)} ${mark}`;
|
|
2514
|
+
if (t.error)
|
|
2515
|
+
line += ` ${t.error}`;
|
|
2516
|
+
if (hasInputs && toolCalls && idx < toolCalls.length) {
|
|
2517
|
+
const tc = toolCalls[idx];
|
|
2518
|
+
const inputStr = typeof tc.input === "string" ? tc.input : JSON.stringify(tc.input);
|
|
2519
|
+
const truncated = inputStr.length > 100 ? `${inputStr.slice(0, 100)}\u2026` : inputStr;
|
|
2520
|
+
line += ` ${truncated}`;
|
|
2521
|
+
}
|
|
2522
|
+
return line;
|
|
2523
|
+
});
|
|
2524
|
+
entries.push({
|
|
2525
|
+
key: "ai.tools",
|
|
2526
|
+
value: "",
|
|
2527
|
+
children
|
|
2528
|
+
});
|
|
2529
|
+
} else if (toolCalls?.length)
|
|
2530
|
+
if (hasInputs) {
|
|
2531
|
+
const children = toolCalls.map((tc) => {
|
|
2532
|
+
const inputStr = typeof tc.input === "string" ? tc.input : JSON.stringify(tc.input);
|
|
2533
|
+
const truncated = inputStr.length > 100 ? `${inputStr.slice(0, 100)}\u2026` : inputStr;
|
|
2534
|
+
return `${tc.name}(${truncated})`;
|
|
2535
|
+
});
|
|
2536
|
+
entries.push({
|
|
2537
|
+
key: "ai.tools",
|
|
2538
|
+
value: "",
|
|
2539
|
+
children
|
|
2540
|
+
});
|
|
2541
|
+
} else
|
|
2542
|
+
entries.push({
|
|
2543
|
+
key: "ai.tools",
|
|
2544
|
+
value: toolCalls.join(", ")
|
|
2545
|
+
});
|
|
2546
|
+
const stepsUsage = ai.stepsUsage;
|
|
2547
|
+
if (stepsUsage?.length) {
|
|
2548
|
+
const allSameModel = stepsUsage.every((s) => s.model === stepsUsage[0].model);
|
|
2549
|
+
const children = stepsUsage.map((s) => {
|
|
2550
|
+
let line = `${allSameModel ? "" : `${s.model} `}${s.inputTokens} in \u2192 ${s.outputTokens} out`;
|
|
2551
|
+
const stepTools = s.toolCalls;
|
|
2552
|
+
if (stepTools?.length)
|
|
2553
|
+
line += ` [${stepTools.join(", ")}]`;
|
|
2554
|
+
return line;
|
|
2555
|
+
});
|
|
2556
|
+
entries.push({
|
|
2557
|
+
key: "ai.steps",
|
|
2558
|
+
value: "",
|
|
2559
|
+
children
|
|
2560
|
+
});
|
|
2561
|
+
} else if (ai.steps && ai.steps > 1)
|
|
2562
|
+
entries.push({
|
|
2563
|
+
key: "ai.steps",
|
|
2564
|
+
value: String(ai.steps)
|
|
2565
|
+
});
|
|
2566
|
+
const embedding = ai.embedding;
|
|
2567
|
+
if (embedding) {
|
|
2568
|
+
const parts = [];
|
|
2569
|
+
if (embedding.model)
|
|
2570
|
+
parts.push(String(embedding.model));
|
|
2571
|
+
parts.push(`${embedding.tokens} tokens`);
|
|
2572
|
+
if (embedding.dimensions)
|
|
2573
|
+
parts.push(`${embedding.dimensions}d`);
|
|
2574
|
+
if (embedding.count)
|
|
2575
|
+
parts.push(`${embedding.count} items`);
|
|
2576
|
+
entries.push({
|
|
2577
|
+
key: "ai.embedding",
|
|
2578
|
+
value: parts.join(" \xB7 ")
|
|
2579
|
+
});
|
|
2580
|
+
}
|
|
2581
|
+
if (ai.finishReason)
|
|
2582
|
+
entries.push({
|
|
2583
|
+
key: "ai.finishReason",
|
|
2584
|
+
value: String(ai.finishReason)
|
|
2585
|
+
});
|
|
2586
|
+
if (ai.error)
|
|
2587
|
+
entries.push({
|
|
2588
|
+
key: "ai.error",
|
|
2589
|
+
value: String(ai.error)
|
|
2590
|
+
});
|
|
2591
|
+
if (ai.responseId)
|
|
2592
|
+
entries.push({
|
|
2593
|
+
key: "ai.responseId",
|
|
2594
|
+
value: String(ai.responseId)
|
|
2595
|
+
});
|
|
2596
|
+
return entries;
|
|
2597
|
+
}
|
|
2598
|
+
function prettyPrintWideEvent(event) {
|
|
2599
|
+
const { timestamp, level, service, environment, version, ...rest } = event;
|
|
2600
|
+
const ts = timestamp.slice(11, 23);
|
|
2601
|
+
const browser = isClient();
|
|
2602
|
+
const parts = [];
|
|
2603
|
+
const styles = [];
|
|
2604
|
+
if (browser) {
|
|
2605
|
+
const lc = getCssLevelColor(level);
|
|
2606
|
+
parts.push(`%c${ts}%c %c${level.toUpperCase()}%c %c[${escapeFormatString(String(service))}]%c`);
|
|
2607
|
+
styles.push(cssColors.dim, cssColors.reset, lc, cssColors.reset, cssColors.cyan, cssColors.reset);
|
|
2608
|
+
} else {
|
|
2609
|
+
const lc = getLevelColor(level);
|
|
2610
|
+
parts.push(`${colors.dim}${ts}${colors.reset} ${lc}${level.toUpperCase()}${colors.reset} ${colors.cyan}[${service}]${colors.reset}`);
|
|
2611
|
+
}
|
|
2612
|
+
if (rest.method && rest.path) {
|
|
2613
|
+
parts.push(browser ? ` ${escapeFormatString(String(rest.method))} ${escapeFormatString(String(rest.path))}` : ` ${rest.method} ${rest.path}`);
|
|
2614
|
+
delete rest.method;
|
|
2615
|
+
delete rest.path;
|
|
2616
|
+
}
|
|
2617
|
+
if (rest.status) {
|
|
2618
|
+
const sc = browser ? rest.status >= 400 ? cssColors.red : cssColors.green : rest.status >= 400 ? colors.red : colors.green;
|
|
2619
|
+
if (browser) {
|
|
2620
|
+
parts.push(` %c${rest.status}%c`);
|
|
2621
|
+
styles.push(sc, cssColors.reset);
|
|
2622
|
+
} else
|
|
2623
|
+
parts.push(` ${sc}${rest.status}${colors.reset}`);
|
|
2624
|
+
delete rest.status;
|
|
2625
|
+
}
|
|
2626
|
+
if (rest.duration) {
|
|
2627
|
+
if (browser) {
|
|
2628
|
+
parts.push(` %c${escapeFormatString(`in ${rest.duration}`)}%c`);
|
|
2629
|
+
styles.push(cssColors.dim, cssColors.reset);
|
|
2630
|
+
} else
|
|
2631
|
+
parts.push(` ${colors.dim}in ${rest.duration}${colors.reset}`);
|
|
2632
|
+
delete rest.duration;
|
|
2633
|
+
}
|
|
2634
|
+
console.log(parts.join(""), ...styles);
|
|
2635
|
+
const aiData = rest.ai;
|
|
2636
|
+
if (aiData && typeof aiData === "object")
|
|
2637
|
+
delete rest.ai;
|
|
2638
|
+
const restEntries = Object.entries(rest).filter(([_, v]) => v !== undefined);
|
|
2639
|
+
const aiEntries = aiData ? buildAIEntries(aiData) : [];
|
|
2640
|
+
const allEntries = [...restEntries.map(([key, value]) => ({
|
|
2641
|
+
key,
|
|
2642
|
+
value: formatValue(value)
|
|
2643
|
+
})), ...aiEntries];
|
|
2644
|
+
for (let i = 0;i < allEntries.length; i++) {
|
|
2645
|
+
const entry = allEntries[i];
|
|
2646
|
+
const hasChildren = entry.children && entry.children.length > 0;
|
|
2647
|
+
const prefix = i === allEntries.length - 1 && !hasChildren ? "\u2514\u2500" : "\u251C\u2500";
|
|
2648
|
+
if (browser) {
|
|
2649
|
+
const val = entry.value ? ` ${escapeFormatString(entry.value)}` : "";
|
|
2650
|
+
console.log(` %c${prefix}%c %c${escapeFormatString(entry.key)}:%c${val}`, cssColors.dim, cssColors.reset, cssColors.cyan, cssColors.reset);
|
|
2651
|
+
} else {
|
|
2652
|
+
const val = entry.value ? ` ${entry.value}` : "";
|
|
2653
|
+
console.log(` ${colors.dim}${prefix}${colors.reset} ${colors.cyan}${entry.key}:${colors.reset}${val}`);
|
|
2654
|
+
}
|
|
2655
|
+
if (hasChildren) {
|
|
2656
|
+
const connector = i === allEntries.length - 1 ? " " : "\u2502";
|
|
2657
|
+
for (let j = 0;j < entry.children.length; j++) {
|
|
2658
|
+
const child = entry.children[j];
|
|
2659
|
+
const childPrefix = j === entry.children.length - 1 ? "\u2514\u2500" : "\u251C\u2500";
|
|
2660
|
+
if (browser)
|
|
2661
|
+
console.log(` %c${connector} ${childPrefix}%c ${escapeFormatString(child)}`, cssColors.dim, cssColors.reset);
|
|
2662
|
+
else
|
|
2663
|
+
console.log(` ${colors.dim}${connector} ${childPrefix}${colors.reset} ${child}`);
|
|
2664
|
+
}
|
|
2665
|
+
}
|
|
2666
|
+
}
|
|
2667
|
+
}
|
|
2668
|
+
function createLogMethod(level) {
|
|
2669
|
+
return function logMethod(tagOrEvent, message) {
|
|
2670
|
+
if (typeof tagOrEvent === "string" && message !== undefined)
|
|
2671
|
+
emitTaggedLog(level, tagOrEvent, message);
|
|
2672
|
+
else if (typeof tagOrEvent === "object")
|
|
2673
|
+
emitWideEvent(level, tagOrEvent);
|
|
2674
|
+
else
|
|
2675
|
+
emitTaggedLog(level, "log", String(tagOrEvent));
|
|
2676
|
+
};
|
|
2677
|
+
}
|
|
2678
|
+
var _log = {
|
|
2679
|
+
info: createLogMethod("info"),
|
|
2680
|
+
error: createLogMethod("error"),
|
|
2681
|
+
warn: createLogMethod("warn"),
|
|
2682
|
+
debug: createLogMethod("debug")
|
|
2683
|
+
};
|
|
2684
|
+
var noopLogger = {
|
|
2685
|
+
set() {},
|
|
2686
|
+
error() {},
|
|
2687
|
+
info() {},
|
|
2688
|
+
warn() {},
|
|
2689
|
+
emit() {
|
|
2690
|
+
return null;
|
|
2691
|
+
},
|
|
2692
|
+
getContext() {
|
|
2693
|
+
return {};
|
|
2694
|
+
}
|
|
2695
|
+
};
|
|
2696
|
+
function createLogger(initialContext = {}, internalOptions) {
|
|
2697
|
+
if (!globalEnabled)
|
|
2698
|
+
return noopLogger;
|
|
2699
|
+
const deferDrain = internalOptions?._deferDrain ?? false;
|
|
2700
|
+
const startTime = Date.now();
|
|
2701
|
+
const context = { ...initialContext };
|
|
2702
|
+
let hasError = false;
|
|
2703
|
+
let hasWarn = false;
|
|
2704
|
+
let emitted = false;
|
|
2705
|
+
function addLog(level, message) {
|
|
2706
|
+
if (!Array.isArray(context.requestLogs))
|
|
2707
|
+
context.requestLogs = [];
|
|
2708
|
+
context.requestLogs.push({
|
|
2709
|
+
level,
|
|
2710
|
+
message,
|
|
2711
|
+
timestamp: isoNow()
|
|
2712
|
+
});
|
|
2713
|
+
}
|
|
2714
|
+
return {
|
|
2715
|
+
set(data) {
|
|
2716
|
+
if (emitted) {
|
|
2717
|
+
const keys = Object.keys(data);
|
|
2718
|
+
warnPostEmit("log.set()", `Keys dropped: ${keys.length ? keys.join(", ") : "(empty)"}.`);
|
|
2719
|
+
return;
|
|
2720
|
+
}
|
|
2721
|
+
mergeInto(context, data);
|
|
2722
|
+
},
|
|
2723
|
+
error(error, errorContext) {
|
|
2724
|
+
if (emitted) {
|
|
2725
|
+
warnPostEmit("log.error()", `Keys dropped: ${(errorContext ? [...Object.keys(errorContext), "error"] : ["error"]).join(", ")}.`);
|
|
2726
|
+
return;
|
|
2727
|
+
}
|
|
2728
|
+
hasError = true;
|
|
2729
|
+
const err = typeof error === "string" ? new Error(error) : error;
|
|
2730
|
+
if (errorContext)
|
|
2731
|
+
mergeInto(context, errorContext);
|
|
2732
|
+
const errorObj = {
|
|
2733
|
+
name: err.name,
|
|
2734
|
+
message: err.message,
|
|
2735
|
+
stack: err.stack
|
|
2736
|
+
};
|
|
2737
|
+
const errRecord = err;
|
|
2738
|
+
for (const k of [
|
|
2739
|
+
"status",
|
|
2740
|
+
"statusText",
|
|
2741
|
+
"statusCode",
|
|
2742
|
+
"statusMessage",
|
|
2743
|
+
"data",
|
|
2744
|
+
"cause",
|
|
2745
|
+
"internal"
|
|
2746
|
+
])
|
|
2747
|
+
if (k in err)
|
|
2748
|
+
errorObj[k] = errRecord[k];
|
|
2749
|
+
if (isPlainObject(context.error))
|
|
2750
|
+
mergeInto(context.error, errorObj);
|
|
2751
|
+
else
|
|
2752
|
+
context.error = errorObj;
|
|
2753
|
+
},
|
|
2754
|
+
info(message, infoContext) {
|
|
2755
|
+
if (emitted) {
|
|
2756
|
+
warnPostEmit("log.info()", `Keys dropped: ${(infoContext ? ["message", ...Object.keys(infoContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
|
|
2757
|
+
return;
|
|
2758
|
+
}
|
|
2759
|
+
addLog("info", message);
|
|
2760
|
+
if (infoContext) {
|
|
2761
|
+
const { requestLogs: _, ...rest } = infoContext;
|
|
2762
|
+
mergeInto(context, rest);
|
|
2763
|
+
}
|
|
2764
|
+
},
|
|
2765
|
+
warn(message, warnContext) {
|
|
2766
|
+
if (emitted) {
|
|
2767
|
+
warnPostEmit("log.warn()", `Keys dropped: ${(warnContext ? ["message", ...Object.keys(warnContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
|
|
2768
|
+
return;
|
|
2769
|
+
}
|
|
2770
|
+
hasWarn = true;
|
|
2771
|
+
addLog("warn", message);
|
|
2772
|
+
if (warnContext) {
|
|
2773
|
+
const { requestLogs: _, ...rest } = warnContext;
|
|
2774
|
+
mergeInto(context, rest);
|
|
2775
|
+
}
|
|
2776
|
+
},
|
|
2777
|
+
emit(overrides) {
|
|
2778
|
+
if (emitted) {
|
|
2779
|
+
warnPostEmit("log.emit()", "Ignoring duplicate emit.");
|
|
2780
|
+
return null;
|
|
2781
|
+
}
|
|
2782
|
+
const durationMs = Date.now() - startTime;
|
|
2783
|
+
const level = hasError ? "error" : hasWarn ? "warn" : "info";
|
|
2784
|
+
let forceKeep = false;
|
|
2785
|
+
if (overrides?._forceKeep)
|
|
2786
|
+
forceKeep = true;
|
|
2787
|
+
else if (globalSampling.keep?.length)
|
|
2788
|
+
forceKeep = shouldKeep({
|
|
2789
|
+
status: overrides?.status ?? context.status,
|
|
2790
|
+
duration: durationMs,
|
|
2791
|
+
path: context.path,
|
|
2792
|
+
method: context.method,
|
|
2793
|
+
context
|
|
2794
|
+
});
|
|
2795
|
+
if (!forceKeep && !shouldSample(level)) {
|
|
2796
|
+
emitted = true;
|
|
2797
|
+
return null;
|
|
2798
|
+
}
|
|
2799
|
+
if (overrides) {
|
|
2800
|
+
const obj = overrides;
|
|
2801
|
+
for (const key in obj)
|
|
2802
|
+
if (key !== "_forceKeep")
|
|
2803
|
+
context[key] = obj[key];
|
|
2804
|
+
}
|
|
2805
|
+
context.duration = formatDuration(durationMs);
|
|
2806
|
+
const wide = emitWideEvent(level, context, deferDrain, true);
|
|
2807
|
+
emitted = true;
|
|
2808
|
+
return wide;
|
|
2809
|
+
},
|
|
2810
|
+
getContext() {
|
|
2811
|
+
return { ...context };
|
|
2812
|
+
}
|
|
2813
|
+
};
|
|
2814
|
+
}
|
|
2815
|
+
if (typeof __EVLOG_CONFIG__ !== "undefined")
|
|
2816
|
+
initLogger(__EVLOG_CONFIG__);
|
|
2817
|
+
// src/link.tsx
|
|
2818
|
+
import {
|
|
2819
|
+
createContext,
|
|
2820
|
+
createElement,
|
|
2821
|
+
useCallback,
|
|
2822
|
+
useContext,
|
|
2823
|
+
useEffect,
|
|
2824
|
+
useRef,
|
|
2825
|
+
useState
|
|
2826
|
+
} from "react";
|
|
2827
|
+
var RouterContext = createContext(null);
|
|
2828
|
+
|
|
2829
|
+
// src/render/cache.ts
|
|
2830
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
2831
|
+
var MAX_SSG_CACHE_SIZE = 1000;
|
|
2832
|
+
var isrCache = new Map;
|
|
2833
|
+
var ssgCache = new Map;
|
|
2834
|
+
function evictOldest(map, maxSize) {
|
|
2835
|
+
if (map.size > maxSize) {
|
|
2836
|
+
const oldest = map.keys().next().value;
|
|
2837
|
+
if (oldest !== undefined) {
|
|
2838
|
+
map.delete(oldest);
|
|
2839
|
+
}
|
|
2840
|
+
}
|
|
2841
|
+
}
|
|
2842
|
+
function getSSGCache(key) {
|
|
2843
|
+
const entry = ssgCache.get(key);
|
|
2844
|
+
if (entry !== undefined) {
|
|
2845
|
+
ssgCache.delete(key);
|
|
2846
|
+
ssgCache.set(key, entry);
|
|
2847
|
+
}
|
|
2848
|
+
return entry;
|
|
2849
|
+
}
|
|
2850
|
+
function setSSGCache(key, entry) {
|
|
2851
|
+
ssgCache.delete(key);
|
|
2852
|
+
ssgCache.set(key, entry);
|
|
2853
|
+
evictOldest(ssgCache, MAX_SSG_CACHE_SIZE);
|
|
2854
|
+
}
|
|
2855
|
+
var _requestInvalidationScope = new AsyncLocalStorage;
|
|
2856
|
+
var _globalPendingInvalidations = new Set;
|
|
2857
|
+
|
|
2858
|
+
// src/render/element.tsx
|
|
2859
|
+
import { jsxDEV } from "react/jsx-dev-runtime";
|
|
2860
|
+
function buildElement(route, data, rootLayout) {
|
|
2861
|
+
const Component = route.page.component;
|
|
2862
|
+
let element = /* @__PURE__ */ jsxDEV(Component, {
|
|
2863
|
+
...data
|
|
2864
|
+
}, undefined, false, undefined, this);
|
|
2865
|
+
for (let i = route.routeChain.length - 1;i >= 1; i--) {
|
|
2866
|
+
const routeEntry = route.routeChain[i];
|
|
2867
|
+
if (routeEntry?.layout) {
|
|
2868
|
+
const Layout = routeEntry.layout;
|
|
2869
|
+
element = /* @__PURE__ */ jsxDEV(Layout, {
|
|
2870
|
+
...data,
|
|
2871
|
+
children: element
|
|
2872
|
+
}, undefined, false, undefined, this);
|
|
2873
|
+
}
|
|
2874
|
+
}
|
|
2875
|
+
if (rootLayout.layout) {
|
|
2876
|
+
const RootLayoutComponent = rootLayout.layout;
|
|
2877
|
+
element = /* @__PURE__ */ jsxDEV(RootLayoutComponent, {
|
|
2878
|
+
...data,
|
|
2879
|
+
children: element
|
|
2880
|
+
}, undefined, false, undefined, this);
|
|
2881
|
+
}
|
|
2882
|
+
return element;
|
|
2883
|
+
}
|
|
2884
|
+
|
|
2885
|
+
// src/context-logger.ts
|
|
2886
|
+
import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
|
|
2887
|
+
|
|
2888
|
+
// ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/elysia/index.mjs
|
|
2889
|
+
import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
|
|
2890
|
+
import { Elysia } from "elysia";
|
|
2891
|
+
var storage = new AsyncLocalStorage2;
|
|
2892
|
+
var activeLoggers = /* @__PURE__ */ new WeakSet;
|
|
2893
|
+
function useLogger2() {
|
|
2894
|
+
const logger = storage.getStore();
|
|
2895
|
+
if (!logger || !activeLoggers.has(logger))
|
|
2896
|
+
throw new Error("[evlog] useLogger() was called outside of an evlog plugin context. Make sure app.use(evlog()) is registered before your routes.");
|
|
2897
|
+
return logger;
|
|
2898
|
+
}
|
|
2899
|
+
|
|
2900
|
+
// src/context-logger.ts
|
|
2901
|
+
var noopLogger2 = {
|
|
2902
|
+
set: () => {},
|
|
2903
|
+
error: () => {},
|
|
2904
|
+
info: () => {},
|
|
2905
|
+
warn: () => {},
|
|
2906
|
+
emit: () => null,
|
|
2907
|
+
getContext: () => ({}),
|
|
2908
|
+
fork: (_label, fn) => fn()
|
|
2909
|
+
};
|
|
2910
|
+
var syntheticRenderStorage = new AsyncLocalStorage3;
|
|
2911
|
+
function useLogger3() {
|
|
2912
|
+
try {
|
|
2913
|
+
return useLogger2();
|
|
2914
|
+
} catch {
|
|
2915
|
+
return syntheticRenderStorage.getStore() ?? noopLogger2;
|
|
2916
|
+
}
|
|
2917
|
+
}
|
|
2918
|
+
async function runInSyntheticRenderScope(fn, initialContext) {
|
|
2919
|
+
const logger = createLogger(initialContext);
|
|
2920
|
+
try {
|
|
2921
|
+
const result = await syntheticRenderStorage.run(logger, () => Promise.resolve(fn()));
|
|
2922
|
+
logger.emit();
|
|
2923
|
+
return result;
|
|
2924
|
+
} catch (err) {
|
|
2925
|
+
logger.error(err instanceof Error ? err : new Error(String(err)));
|
|
2926
|
+
logger.emit();
|
|
2927
|
+
throw err;
|
|
2928
|
+
}
|
|
2929
|
+
}
|
|
2930
|
+
|
|
2931
|
+
// src/render/loaders.ts
|
|
2932
|
+
function createLoaderCtx(ctx, accumulatedParentPromise) {
|
|
2933
|
+
const cache = new Map;
|
|
2934
|
+
return new Proxy(ctx, {
|
|
2935
|
+
get(target, prop) {
|
|
2936
|
+
if (typeof prop !== "string") {
|
|
2937
|
+
return Reflect.get(target, prop);
|
|
2938
|
+
}
|
|
2939
|
+
if (prop === "then" || prop === "catch" || prop === "finally" || prop === "toJSON") {
|
|
2940
|
+
return Reflect.get(target, prop);
|
|
2941
|
+
}
|
|
2942
|
+
if (Object.hasOwn(target, prop)) {
|
|
2943
|
+
return target[prop];
|
|
2944
|
+
}
|
|
2945
|
+
let entry = cache.get(prop);
|
|
2946
|
+
if (!entry) {
|
|
2947
|
+
entry = accumulatedParentPromise.then((data) => data[prop]);
|
|
2948
|
+
cache.set(prop, entry);
|
|
2949
|
+
}
|
|
2950
|
+
return entry;
|
|
2951
|
+
}
|
|
2952
|
+
});
|
|
2953
|
+
}
|
|
2954
|
+
async function runLoaders(route, ctx, _rootLayout) {
|
|
2955
|
+
try {
|
|
2956
|
+
const ctxRecord = { ...ctx, log: useLogger3() };
|
|
2957
|
+
const loaderMap = new Map;
|
|
2958
|
+
let accumulatedParentPromise = Promise.resolve({});
|
|
2959
|
+
for (const r of route.routeChain) {
|
|
2960
|
+
const parentAccum = accumulatedParentPromise;
|
|
2961
|
+
if (r.loader) {
|
|
2962
|
+
const loaderCtx = createLoaderCtx(ctxRecord, parentAccum);
|
|
2963
|
+
const loaderPromise = Promise.resolve(r.loader(loaderCtx)).then((res) => res ?? {});
|
|
2964
|
+
loaderMap.set(r, loaderPromise);
|
|
2965
|
+
accumulatedParentPromise = Promise.all([parentAccum, loaderPromise]).then(([acc, own]) => ({
|
|
2966
|
+
...acc,
|
|
2967
|
+
...own
|
|
2968
|
+
}));
|
|
2969
|
+
accumulatedParentPromise.catch(() => {});
|
|
2970
|
+
}
|
|
2971
|
+
}
|
|
2972
|
+
const pageCtx = createLoaderCtx(ctxRecord, accumulatedParentPromise);
|
|
2973
|
+
const pagePromise = route.page?.loader ? Promise.resolve(route.page.loader(pageCtx)).then((r) => r ?? {}) : Promise.resolve({});
|
|
2974
|
+
const results = await Promise.all([...loaderMap.values(), pagePromise]);
|
|
2975
|
+
const data = Object.assign({}, ...results);
|
|
2976
|
+
const headers = {};
|
|
2977
|
+
Object.assign(headers, ctx.set.headers);
|
|
2978
|
+
return { type: "data", data, headers };
|
|
2979
|
+
} catch (err) {
|
|
2980
|
+
if (err instanceof Response) {
|
|
2981
|
+
return { type: "redirect", response: err };
|
|
2982
|
+
}
|
|
2983
|
+
throw err;
|
|
2984
|
+
}
|
|
2985
|
+
}
|
|
2986
|
+
|
|
2987
|
+
// src/render/template.ts
|
|
2988
|
+
import { readFileSync } from "fs";
|
|
2989
|
+
var _prodTemplatePath = null;
|
|
2990
|
+
var _prodTemplateContent = null;
|
|
2991
|
+
var _devTemplateCache = null;
|
|
2992
|
+
var DEV_TEMPLATE_TTL_MS = 1000;
|
|
2993
|
+
async function getDevTemplate(origin) {
|
|
2994
|
+
if (_devTemplateCache && Date.now() - _devTemplateCache.ts < DEV_TEMPLATE_TTL_MS) {
|
|
2995
|
+
return _devTemplateCache.html;
|
|
2996
|
+
}
|
|
2997
|
+
const r = await fetch(`${origin}/_bun_hmr_entry`);
|
|
2998
|
+
if (!r.ok) {
|
|
2999
|
+
throw new Error(`/_bun_hmr_entry returned ${r.status}`);
|
|
3000
|
+
}
|
|
3001
|
+
const html = await r.text();
|
|
3002
|
+
_devTemplateCache = { html, ts: Date.now() };
|
|
3003
|
+
return html;
|
|
3004
|
+
}
|
|
3005
|
+
function setProductionTemplateContent(content) {
|
|
3006
|
+
_prodTemplatePath = null;
|
|
3007
|
+
_prodTemplateContent = content;
|
|
3008
|
+
}
|
|
3009
|
+
function getProductionTemplate() {
|
|
3010
|
+
if (_prodTemplateContent !== null) {
|
|
3011
|
+
return _prodTemplateContent;
|
|
3012
|
+
}
|
|
3013
|
+
if (!_prodTemplatePath) {
|
|
3014
|
+
return null;
|
|
3015
|
+
}
|
|
3016
|
+
try {
|
|
3017
|
+
_prodTemplateContent = readFileSync(_prodTemplatePath, "utf8");
|
|
3018
|
+
return _prodTemplateContent;
|
|
3019
|
+
} catch {
|
|
3020
|
+
return null;
|
|
3021
|
+
}
|
|
3022
|
+
}
|
|
3023
|
+
// src/runtime-env.ts
|
|
3024
|
+
var IS_DEV = true;
|
|
3025
|
+
|
|
3026
|
+
// src/render/index.ts
|
|
3027
|
+
async function prepareRender(route, ctx, root, basePath) {
|
|
3028
|
+
const loaderStart = Date.now();
|
|
3029
|
+
const loaderResult = await runLoaders(route, ctx, root.route);
|
|
3030
|
+
const loader_ms = Date.now() - loaderStart;
|
|
3031
|
+
if (loaderResult.type === "redirect") {
|
|
3032
|
+
return loaderResult.response;
|
|
3033
|
+
}
|
|
3034
|
+
const { data, headers } = loaderResult;
|
|
3035
|
+
const componentProps = {
|
|
3036
|
+
...data,
|
|
3037
|
+
params: ctx.params,
|
|
3038
|
+
query: ctx.query,
|
|
3039
|
+
path: ctx.path
|
|
3040
|
+
};
|
|
3041
|
+
const headData = buildHeadInjection(route.page?.head?.(componentProps));
|
|
3042
|
+
const prodTemplate = getProductionTemplate();
|
|
3043
|
+
const template = prodTemplate ?? (IS_DEV ? await getDevTemplate(new URL(ctx.request.url).origin) : generateIndexHtml());
|
|
3044
|
+
let element = buildElement(route, componentProps, root.route);
|
|
3045
|
+
if (basePath !== undefined) {
|
|
3046
|
+
const ssrContext = {
|
|
3047
|
+
basePath,
|
|
3048
|
+
currentHref: ctx.path,
|
|
3049
|
+
navigate: () => Promise.resolve(),
|
|
3050
|
+
prefetch: () => {},
|
|
3051
|
+
invalidatePrefetch: () => {},
|
|
3052
|
+
refresh: () => Promise.resolve(),
|
|
3053
|
+
isNavigating: false,
|
|
3054
|
+
defaultPreload: "intent",
|
|
3055
|
+
defaultPreloadDelay: 50,
|
|
3056
|
+
defaultPreloadStaleTime: 30000
|
|
3057
|
+
};
|
|
3058
|
+
element = createElement2(RouterContext.Provider, { value: ssrContext }, element);
|
|
3059
|
+
}
|
|
3060
|
+
return { componentProps, element, headData, headers, loader_ms, template };
|
|
3061
|
+
}
|
|
3062
|
+
async function renderForPath(route, params, root, origin, basePath) {
|
|
3063
|
+
const resolvedPath = resolvePath(route.pattern, params);
|
|
3064
|
+
const ctx = {
|
|
3065
|
+
params,
|
|
3066
|
+
query: {},
|
|
3067
|
+
request: new Request(`${origin}${resolvedPath}`),
|
|
3068
|
+
headers: {},
|
|
3069
|
+
cookie: {},
|
|
3070
|
+
redirect: (url, status = 302) => new Response(null, { status, headers: { Location: url } }),
|
|
3071
|
+
set: { headers: {} },
|
|
3072
|
+
path: resolvedPath
|
|
3073
|
+
};
|
|
3074
|
+
const prepared = await runInSyntheticRenderScope(() => prepareRender(route, ctx, root, basePath), { route: route.pattern });
|
|
3075
|
+
if (prepared instanceof Response) {
|
|
3076
|
+
throw prepared;
|
|
3077
|
+
}
|
|
3078
|
+
const { componentProps, element, headData, headers, template } = prepared;
|
|
3079
|
+
const stream = await renderToReadableStream(element);
|
|
3080
|
+
await stream.allReady;
|
|
3081
|
+
const reactHtml = await streamToString(stream);
|
|
3082
|
+
return {
|
|
3083
|
+
html: assembleHTML(template, headData, reactHtml, componentProps),
|
|
3084
|
+
headers
|
|
3085
|
+
};
|
|
3086
|
+
}
|
|
3087
|
+
async function prerenderSSG(route, params, root, origin = "http://localhost:3000", basePath) {
|
|
3088
|
+
const resolvedPath = resolvePath(route.pattern, params);
|
|
3089
|
+
const cached = getSSGCache(resolvedPath);
|
|
3090
|
+
if (cached && !IS_DEV) {
|
|
3091
|
+
return cached;
|
|
3092
|
+
}
|
|
3093
|
+
let result;
|
|
3094
|
+
try {
|
|
3095
|
+
result = await renderForPath(route, params, root, origin, basePath);
|
|
3096
|
+
} catch (err) {
|
|
3097
|
+
if (err instanceof Response) {
|
|
3098
|
+
return err;
|
|
3099
|
+
}
|
|
3100
|
+
throw err;
|
|
3101
|
+
}
|
|
3102
|
+
const entry = { html: result.html, cachedAt: Date.now() };
|
|
3103
|
+
if (!IS_DEV) {
|
|
3104
|
+
setSSGCache(resolvedPath, entry);
|
|
3105
|
+
}
|
|
3106
|
+
return entry;
|
|
3107
|
+
}
|
|
3108
|
+
var pendingRevalidations = new Set;
|
|
3109
|
+
|
|
3110
|
+
// src/adapter/static.ts
|
|
3111
|
+
var STATIC_CONCURRENCY = 4;
|
|
3112
|
+
var DYNAMIC_SEGMENT_RE = /\/:[^/]+|\/\*/;
|
|
3113
|
+
var TRAILING_SLASHES_RE = /\/+$/;
|
|
3114
|
+
function pathToOutputFile(urlPath, outDir) {
|
|
3115
|
+
const normalizedOutDir = resolve2(outDir);
|
|
3116
|
+
if (urlPath === "/" || urlPath === "") {
|
|
3117
|
+
return join6(normalizedOutDir, "index.html");
|
|
3118
|
+
}
|
|
3119
|
+
const resolved = resolve2(normalizedOutDir, urlPath.slice(1), "index.html");
|
|
3120
|
+
if (!resolved.startsWith(`${normalizedOutDir}${sep}`)) {
|
|
3121
|
+
throw new Error(`[furin] static: unsafe output path detected for URL "${urlPath}" \u2014 path traversal via ".." is not allowed.`);
|
|
3122
|
+
}
|
|
3123
|
+
return resolved;
|
|
3124
|
+
}
|
|
3125
|
+
async function prerenderAndWrite(route, params, root, outDir, renderedRoutes, skippedRoutes, basePath) {
|
|
3126
|
+
const urlPath = resolvePath(route.pattern, params);
|
|
3127
|
+
const outputFile = pathToOutputFile(urlPath, outDir);
|
|
3128
|
+
try {
|
|
3129
|
+
const entry = await prerenderSSG(route, params, root, "http://localhost", basePath);
|
|
3130
|
+
if (entry instanceof Response) {
|
|
3131
|
+
console.warn(`[furin] static: route "${route.pattern}" loader returned a redirect \u2014 skipping.`);
|
|
3132
|
+
return;
|
|
3133
|
+
}
|
|
3134
|
+
ensureDir(dirname3(outputFile));
|
|
3135
|
+
writeFileSync5(outputFile, entry.html);
|
|
3136
|
+
renderedRoutes.push(urlPath);
|
|
3137
|
+
console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(outputFile)}`);
|
|
3138
|
+
} catch (err) {
|
|
3139
|
+
console.error(`[furin] static: prerender failed for "${route.pattern}" (params: ${JSON.stringify(params)}):`, err);
|
|
3140
|
+
skippedRoutes.push(urlPath);
|
|
3141
|
+
}
|
|
3142
|
+
}
|
|
3143
|
+
function collectSsgRoutes(routes, onSSR, skippedRoutes) {
|
|
3144
|
+
const nonSsg = routes.filter((r) => r.mode !== "ssg");
|
|
3145
|
+
if (nonSsg.length === 0) {
|
|
3146
|
+
return routes;
|
|
3147
|
+
}
|
|
3148
|
+
if (onSSR === "error") {
|
|
3149
|
+
const list = nonSsg.map((r) => ` \u2022 ${r.pattern} (mode: ${r.mode})`).join(`
|
|
3150
|
+
`);
|
|
3151
|
+
throw new Error(`[furin] Cannot produce a static export: the following routes are not SSG and cannot be pre-rendered.
|
|
3152
|
+
` + `Either change their mode to "ssg", remove them, or set \`onSSR: "skip"\` in your static config.
|
|
3153
|
+
|
|
3154
|
+
` + `${list}`);
|
|
3155
|
+
}
|
|
3156
|
+
for (const r of nonSsg) {
|
|
3157
|
+
console.warn(`[furin] static: skipping route "${r.pattern}" (mode=${r.mode}) \u2014 not statically exportable.`);
|
|
3158
|
+
skippedRoutes.push(r.pattern);
|
|
3159
|
+
}
|
|
3160
|
+
return routes.filter((r) => r.mode === "ssg");
|
|
3161
|
+
}
|
|
3162
|
+
async function buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRoutes, basePath) {
|
|
3163
|
+
const tasks = [];
|
|
3164
|
+
for (const route of ssgRoutes) {
|
|
3165
|
+
if (!DYNAMIC_SEGMENT_RE.test(route.pattern)) {
|
|
3166
|
+
tasks.push(() => prerenderAndWrite(route, {}, root, outDir, renderedRoutes, skippedRoutes, basePath));
|
|
3167
|
+
continue;
|
|
3168
|
+
}
|
|
3169
|
+
if (!route.page.staticParams) {
|
|
3170
|
+
console.warn(`[furin] static: skipping dynamic route "${route.pattern}" \u2014 no staticParams() defined.`);
|
|
3171
|
+
skippedRoutes.push(route.pattern);
|
|
3172
|
+
continue;
|
|
3173
|
+
}
|
|
3174
|
+
try {
|
|
3175
|
+
const paramSets = await route.page.staticParams() ?? [];
|
|
3176
|
+
for (const params of paramSets) {
|
|
3177
|
+
tasks.push(() => prerenderAndWrite(route, params, root, outDir, renderedRoutes, skippedRoutes, basePath));
|
|
3178
|
+
}
|
|
3179
|
+
} catch (err) {
|
|
3180
|
+
console.error(`[furin] static: staticParams() failed for "${route.pattern}":`, err);
|
|
3181
|
+
skippedRoutes.push(route.pattern);
|
|
3182
|
+
}
|
|
3183
|
+
}
|
|
3184
|
+
return tasks;
|
|
3185
|
+
}
|
|
3186
|
+
async function runWithConcurrency(tasks, concurrency) {
|
|
3187
|
+
const queue = [...tasks];
|
|
3188
|
+
const workerCount = Math.min(concurrency, Math.max(queue.length, 1));
|
|
3189
|
+
await Promise.all(Array.from({ length: workerCount }, async () => {
|
|
3190
|
+
while (queue.length > 0) {
|
|
3191
|
+
await queue.shift()?.();
|
|
3192
|
+
}
|
|
3193
|
+
}));
|
|
3194
|
+
}
|
|
3195
|
+
async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
|
|
3196
|
+
const staticConfig = options.staticConfig ?? {};
|
|
3197
|
+
const rawBasePath = staticConfig.basePath ?? "";
|
|
3198
|
+
let basePath;
|
|
3199
|
+
if (rawBasePath === "/" || rawBasePath === "") {
|
|
3200
|
+
basePath = "";
|
|
3201
|
+
} else if (rawBasePath.endsWith("/")) {
|
|
3202
|
+
basePath = rawBasePath.replace(TRAILING_SLASHES_RE, "");
|
|
3203
|
+
} else {
|
|
3204
|
+
basePath = rawBasePath;
|
|
3205
|
+
}
|
|
3206
|
+
if (basePath && !basePath.startsWith("/")) {
|
|
3207
|
+
throw new Error(`[furin] static: basePath must start with "/" (received "${rawBasePath}"). ` + `Use "" for root deployments or "/sub-path" for sub-path deployments.`);
|
|
3208
|
+
}
|
|
3209
|
+
const outDir = resolve2(rootDir, staticConfig.outDir ?? "dist");
|
|
3210
|
+
const normalizedRoot = resolve2(rootDir);
|
|
3211
|
+
const normalizedBuildRoot = resolve2(buildRoot);
|
|
3212
|
+
if (outDir === normalizedRoot || outDir === normalizedBuildRoot || outDir === "/" || outDir === ".") {
|
|
3213
|
+
throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
|
|
3214
|
+
}
|
|
3215
|
+
function isOutsideOutDir(target) {
|
|
3216
|
+
const rel = relative3(outDir, target);
|
|
3217
|
+
return rel.startsWith("..") || isAbsolute(rel);
|
|
3218
|
+
}
|
|
3219
|
+
if (!(isOutsideOutDir(normalizedRoot) && isOutsideOutDir(normalizedBuildRoot))) {
|
|
3220
|
+
throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
|
|
3221
|
+
}
|
|
3222
|
+
const onSSR = staticConfig.onSSR ?? "error";
|
|
3223
|
+
const publicPath = basePath ? `${basePath}/_client/` : "/_client/";
|
|
3224
|
+
const renderedRoutes = [];
|
|
3225
|
+
const skippedRoutes = [];
|
|
3226
|
+
const ssgRoutes = collectSsgRoutes(routes, onSSR, skippedRoutes);
|
|
3227
|
+
rmSync3(outDir, { force: true, recursive: true });
|
|
3228
|
+
ensureDir(outDir);
|
|
3229
|
+
const targetDir = join6(buildRoot, "static");
|
|
3230
|
+
rmSync3(targetDir, { force: true, recursive: true });
|
|
3231
|
+
ensureDir(targetDir);
|
|
3232
|
+
const { entryChunk, cssChunks } = await buildClient(ssgRoutes, {
|
|
3233
|
+
outDir: targetDir,
|
|
3234
|
+
rootLayout: root.path,
|
|
3235
|
+
plugins: options.plugins,
|
|
3236
|
+
publicPath,
|
|
3237
|
+
basePath
|
|
3238
|
+
});
|
|
3239
|
+
const publicFavicon = join6(rootDir, "public", "favicon.ico");
|
|
3240
|
+
const faviconHref = existsSync5(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
|
|
3241
|
+
const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref);
|
|
3242
|
+
setProductionTemplateContent(shellHtml);
|
|
3243
|
+
const publicSrcDir = join6(rootDir, "public");
|
|
3244
|
+
if (existsSync5(publicSrcDir)) {
|
|
3245
|
+
cpSync2(publicSrcDir, outDir, { recursive: true });
|
|
3246
|
+
}
|
|
3247
|
+
const clientSrcDir = join6(targetDir, "client");
|
|
3248
|
+
if (existsSync5(clientSrcDir)) {
|
|
3249
|
+
cpSync2(clientSrcDir, join6(outDir, "_client"), { recursive: true });
|
|
3250
|
+
}
|
|
3251
|
+
const tasks = await buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRoutes, basePath);
|
|
3252
|
+
const afterQueueCount = skippedRoutes.length;
|
|
3253
|
+
await runWithConcurrency(tasks, STATIC_CONCURRENCY);
|
|
3254
|
+
if (onSSR === "error" && skippedRoutes.length > afterQueueCount) {
|
|
3255
|
+
const failed = skippedRoutes.slice(afterQueueCount);
|
|
3256
|
+
const list = failed.map((r) => ` \u2022 ${r}`).join(`
|
|
3257
|
+
`);
|
|
3258
|
+
throw new Error(`[furin] static: ${failed.length} route(s) failed to pre-render:
|
|
3259
|
+
${list}
|
|
3260
|
+
` + `Set \`onSSR: "skip"\` in your static config to suppress this error.`);
|
|
3261
|
+
}
|
|
3262
|
+
writeFileSync5(join6(outDir, "404.html"), shellHtml);
|
|
3263
|
+
console.log("[furin] static: wrote 404.html (SPA shell fallback)");
|
|
3264
|
+
rmSync3(targetDir, { force: true, recursive: true });
|
|
3265
|
+
console.log(`[furin] static: export complete \u2192 ${toPosixPath(outDir)}` + ` (${renderedRoutes.length} rendered, ${skippedRoutes.length} skipped)`);
|
|
3266
|
+
return {
|
|
3267
|
+
basePath,
|
|
3268
|
+
generatedAt: new Date().toISOString(),
|
|
3269
|
+
outDir: toPosixPath(outDir),
|
|
3270
|
+
renderedRoutes,
|
|
3271
|
+
skippedRoutes
|
|
3272
|
+
};
|
|
3273
|
+
}
|
|
3274
|
+
|
|
1864
3275
|
// src/config.ts
|
|
1865
3276
|
import { t } from "elysia";
|
|
1866
|
-
var BUILD_TARGETS = ["bun", "node", "vercel", "cloudflare"];
|
|
3277
|
+
var BUILD_TARGETS = ["bun", "node", "vercel", "cloudflare", "static"];
|
|
1867
3278
|
var buildTargetSchema = t.Union(BUILD_TARGETS.map((v) => t.Literal(v)));
|
|
1868
3279
|
var compileTargetSchema = t.Union([t.Literal("server"), t.Literal("embed")]);
|
|
1869
3280
|
var configSchema = t.Object({
|
|
@@ -1873,14 +3284,19 @@ var configSchema = t.Object({
|
|
|
1873
3284
|
targets: t.Optional(t.Array(buildTargetSchema)),
|
|
1874
3285
|
bun: t.Optional(t.Object({
|
|
1875
3286
|
compile: t.Optional(compileTargetSchema)
|
|
3287
|
+
})),
|
|
3288
|
+
static: t.Optional(t.Object({
|
|
3289
|
+
basePath: t.Optional(t.String()),
|
|
3290
|
+
outDir: t.Optional(t.String()),
|
|
3291
|
+
onSSR: t.Optional(t.Union([t.Literal("error"), t.Literal("skip")]))
|
|
1876
3292
|
}))
|
|
1877
3293
|
});
|
|
1878
3294
|
|
|
1879
3295
|
// src/router.ts
|
|
1880
|
-
import { existsSync as
|
|
3296
|
+
import { existsSync as existsSync6 } from "fs";
|
|
1881
3297
|
import { readdir } from "fs/promises";
|
|
1882
|
-
import { join as
|
|
1883
|
-
import { Elysia } from "elysia";
|
|
3298
|
+
import { join as join7, parse } from "path";
|
|
3299
|
+
import { Elysia as Elysia2, t as t2 } from "elysia";
|
|
1884
3300
|
|
|
1885
3301
|
// src/internal.ts
|
|
1886
3302
|
var _compileCtx = null;
|
|
@@ -1888,24 +3304,6 @@ function getCompileContext() {
|
|
|
1888
3304
|
return _compileCtx;
|
|
1889
3305
|
}
|
|
1890
3306
|
|
|
1891
|
-
// src/render/index.ts
|
|
1892
|
-
import { renderToReadableStream } from "react-dom/server";
|
|
1893
|
-
|
|
1894
|
-
// src/render/cache.ts
|
|
1895
|
-
import { AsyncLocalStorage } from "async_hooks";
|
|
1896
|
-
var isrCache = new Map;
|
|
1897
|
-
var ssgCache = new Map;
|
|
1898
|
-
var _requestInvalidationScope = new AsyncLocalStorage;
|
|
1899
|
-
var _globalPendingInvalidations = new Set;
|
|
1900
|
-
|
|
1901
|
-
// src/render/element.tsx
|
|
1902
|
-
import { jsxDEV } from "react/jsx-dev-runtime";
|
|
1903
|
-
// src/runtime-env.ts
|
|
1904
|
-
var IS_DEV = true;
|
|
1905
|
-
|
|
1906
|
-
// src/render/index.ts
|
|
1907
|
-
var pendingRevalidations = new Set;
|
|
1908
|
-
|
|
1909
3307
|
// src/utils.ts
|
|
1910
3308
|
function isFurinPage(value) {
|
|
1911
3309
|
return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_PAGE";
|
|
@@ -1956,7 +3354,7 @@ async function scanPages(pagesDir) {
|
|
|
1956
3354
|
async function scanRootLayout(pagesDir) {
|
|
1957
3355
|
const rootPath = `${pagesDir}/root.tsx`;
|
|
1958
3356
|
const ctx = getCompileContext();
|
|
1959
|
-
if (!(
|
|
3357
|
+
if (!(existsSync6(rootPath) || ctx?.modules[rootPath])) {
|
|
1960
3358
|
throw new Error("[furin] root.tsx: not found.");
|
|
1961
3359
|
}
|
|
1962
3360
|
const mod = ctx?.modules[rootPath] ?? await import(rootPath);
|
|
@@ -2026,10 +3424,11 @@ async function buildDevRoute(absolutePath, relativePath, root) {
|
|
|
2026
3424
|
routeChain
|
|
2027
3425
|
};
|
|
2028
3426
|
}
|
|
3427
|
+
var TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
|
|
2029
3428
|
async function collectPageFilePaths(dir) {
|
|
2030
3429
|
const files = [];
|
|
2031
3430
|
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
2032
|
-
const absolutePath =
|
|
3431
|
+
const absolutePath = join7(dir, entry.name);
|
|
2033
3432
|
if (entry.isDirectory()) {
|
|
2034
3433
|
files.push(...await collectPageFilePaths(absolutePath));
|
|
2035
3434
|
continue;
|
|
@@ -2077,10 +3476,10 @@ function filePathToPattern(path) {
|
|
|
2077
3476
|
}
|
|
2078
3477
|
|
|
2079
3478
|
// src/build/scan-server.ts
|
|
2080
|
-
import { readFileSync } from "fs";
|
|
3479
|
+
import { readFileSync as readFileSync2 } from "fs";
|
|
2081
3480
|
import { parseSync as parseSync2 } from "oxc-parser";
|
|
2082
3481
|
function scanFurinInstances(serverEntryPath) {
|
|
2083
|
-
const code =
|
|
3482
|
+
const code = readFileSync2(serverEntryPath, "utf8");
|
|
2084
3483
|
const { program, errors } = parseSync2(serverEntryPath, code);
|
|
2085
3484
|
if (errors.length > 0) {
|
|
2086
3485
|
return [];
|
|
@@ -2089,26 +3488,28 @@ function scanFurinInstances(serverEntryPath) {
|
|
|
2089
3488
|
walkNode(program, results);
|
|
2090
3489
|
return results;
|
|
2091
3490
|
}
|
|
2092
|
-
|
|
2093
|
-
|
|
3491
|
+
var SKIP_KEYS = new Set(["type", "start", "end"]);
|
|
3492
|
+
function checkFurinCall(node, out) {
|
|
3493
|
+
const callee = node.callee;
|
|
3494
|
+
const args = node.arguments;
|
|
3495
|
+
const isFurinCall = callee?.type === "Identifier" && callee.name === "furin";
|
|
3496
|
+
if (!(isFurinCall && Array.isArray(args)) || args.length === 0) {
|
|
3497
|
+
return;
|
|
3498
|
+
}
|
|
3499
|
+
const firstArg = args[0];
|
|
3500
|
+
if (firstArg?.type !== "ObjectExpression") {
|
|
2094
3501
|
return;
|
|
2095
|
-
if (node.type === "CallExpression") {
|
|
2096
|
-
const callee = node.callee;
|
|
2097
|
-
const args = node.arguments;
|
|
2098
|
-
const isFurinCall = callee?.type === "Identifier" && callee.name === "furin";
|
|
2099
|
-
if (isFurinCall && Array.isArray(args) && args.length > 0) {
|
|
2100
|
-
const firstArg = args[0];
|
|
2101
|
-
if (firstArg?.type === "ObjectExpression") {
|
|
2102
|
-
const pagesDir = extractStringProperty(firstArg, "pagesDir");
|
|
2103
|
-
if (pagesDir !== null) {
|
|
2104
|
-
out.push(pagesDir);
|
|
2105
|
-
}
|
|
2106
|
-
}
|
|
2107
|
-
}
|
|
2108
3502
|
}
|
|
3503
|
+
const pagesDir = extractStringProperty(firstArg, "pagesDir");
|
|
3504
|
+
if (pagesDir !== null) {
|
|
3505
|
+
out.push(pagesDir);
|
|
3506
|
+
}
|
|
3507
|
+
}
|
|
3508
|
+
function walkChildren(node, out) {
|
|
2109
3509
|
for (const key of Object.keys(node)) {
|
|
2110
|
-
if (key
|
|
3510
|
+
if (SKIP_KEYS.has(key)) {
|
|
2111
3511
|
continue;
|
|
3512
|
+
}
|
|
2112
3513
|
const child = node[key];
|
|
2113
3514
|
if (Array.isArray(child)) {
|
|
2114
3515
|
for (const item of child) {
|
|
@@ -2121,18 +3522,30 @@ function walkNode(node, out) {
|
|
|
2121
3522
|
}
|
|
2122
3523
|
}
|
|
2123
3524
|
}
|
|
3525
|
+
function walkNode(node, out) {
|
|
3526
|
+
if (!node || typeof node !== "object") {
|
|
3527
|
+
return;
|
|
3528
|
+
}
|
|
3529
|
+
if (node.type === "CallExpression") {
|
|
3530
|
+
checkFurinCall(node, out);
|
|
3531
|
+
}
|
|
3532
|
+
walkChildren(node, out);
|
|
3533
|
+
}
|
|
2124
3534
|
function extractStringProperty(obj, propName) {
|
|
2125
3535
|
const properties = obj.properties;
|
|
2126
|
-
if (!Array.isArray(properties))
|
|
3536
|
+
if (!Array.isArray(properties)) {
|
|
2127
3537
|
return null;
|
|
3538
|
+
}
|
|
2128
3539
|
for (const prop of properties) {
|
|
2129
|
-
if (prop.type !== "Property")
|
|
3540
|
+
if (prop.type !== "Property") {
|
|
2130
3541
|
continue;
|
|
3542
|
+
}
|
|
2131
3543
|
const key = prop.key;
|
|
2132
3544
|
const value = prop.value;
|
|
2133
3545
|
const keyMatches = key.type === "Identifier" && key.name === propName || key.type === "Literal" && key.value === propName;
|
|
2134
|
-
if (!keyMatches)
|
|
3546
|
+
if (!keyMatches) {
|
|
2135
3547
|
continue;
|
|
3548
|
+
}
|
|
2136
3549
|
if (value?.type === "Literal" && typeof value.value === "string") {
|
|
2137
3550
|
return value.value;
|
|
2138
3551
|
}
|
|
@@ -2142,33 +3555,46 @@ function extractStringProperty(obj, propName) {
|
|
|
2142
3555
|
}
|
|
2143
3556
|
|
|
2144
3557
|
// src/build/index.ts
|
|
2145
|
-
var IMPLEMENTED_TARGETS = ["bun"];
|
|
3558
|
+
var IMPLEMENTED_TARGETS = ["bun", "static"];
|
|
2146
3559
|
var BUILD_OUTPUT_DIR = ".furin/build";
|
|
2147
3560
|
function resolvePagesDirFromServer(serverEntry, rootDir) {
|
|
2148
|
-
if (!serverEntry)
|
|
3561
|
+
if (!serverEntry) {
|
|
2149
3562
|
return null;
|
|
3563
|
+
}
|
|
2150
3564
|
const detected = scanFurinInstances(serverEntry);
|
|
2151
|
-
if (detected.length === 0)
|
|
3565
|
+
if (detected.length === 0) {
|
|
2152
3566
|
return null;
|
|
2153
|
-
|
|
3567
|
+
}
|
|
3568
|
+
return resolve3(rootDir, detected[0]);
|
|
2154
3569
|
}
|
|
2155
3570
|
async function buildApp(options) {
|
|
2156
|
-
const rootDir =
|
|
2157
|
-
const buildRoot =
|
|
3571
|
+
const rootDir = resolve3(options.rootDir ?? process.cwd());
|
|
3572
|
+
const buildRoot = join8(rootDir, BUILD_OUTPUT_DIR);
|
|
2158
3573
|
const serverEntry = (() => {
|
|
3574
|
+
if (options.target === "static") {
|
|
3575
|
+
return null;
|
|
3576
|
+
}
|
|
2159
3577
|
if (options.serverEntry) {
|
|
2160
|
-
const resolved =
|
|
2161
|
-
if (
|
|
3578
|
+
const resolved = resolve3(rootDir, options.serverEntry);
|
|
3579
|
+
if (existsSync7(resolved)) {
|
|
2162
3580
|
return resolved;
|
|
3581
|
+
}
|
|
2163
3582
|
}
|
|
2164
|
-
const
|
|
2165
|
-
if (!
|
|
3583
|
+
const entry = resolve3(rootDir, "src/server.ts");
|
|
3584
|
+
if (!existsSync7(entry)) {
|
|
2166
3585
|
throw new Error("[furin] Entrypoint server.ts not found");
|
|
2167
3586
|
}
|
|
2168
|
-
return
|
|
3587
|
+
return entry;
|
|
2169
3588
|
})();
|
|
3589
|
+
for (const plugin of options.plugins ?? []) {
|
|
3590
|
+
try {
|
|
3591
|
+
Bun.plugin(plugin);
|
|
3592
|
+
} catch (err) {
|
|
3593
|
+
console.debug("[furin] Skipped build-only plugin at runtime:", err);
|
|
3594
|
+
}
|
|
3595
|
+
}
|
|
2170
3596
|
const rawPagesDir = options.pagesDir ?? resolvePagesDirFromServer(serverEntry, rootDir) ?? "src/pages";
|
|
2171
|
-
const pagesDir =
|
|
3597
|
+
const pagesDir = resolve3(rootDir, rawPagesDir);
|
|
2172
3598
|
const requestedTargets = options.target === "all" ? [...IMPLEMENTED_TARGETS] : [options.target].map((target) => {
|
|
2173
3599
|
if (!BUILD_TARGETS.includes(target)) {
|
|
2174
3600
|
throw new Error(`[furin] Unsupported build target "${target}"`);
|
|
@@ -2181,9 +3607,9 @@ async function buildApp(options) {
|
|
|
2181
3607
|
version: 1,
|
|
2182
3608
|
generatedAt: new Date().toISOString(),
|
|
2183
3609
|
rootDir: toPosixPath(rootDir),
|
|
2184
|
-
pagesDir: toPosixPath(
|
|
2185
|
-
rootPath: toPosixPath(
|
|
2186
|
-
serverEntry: serverEntry ? toPosixPath(
|
|
3610
|
+
pagesDir: toPosixPath(relative4(rootDir, pagesDir)),
|
|
3611
|
+
rootPath: toPosixPath(relative4(rootDir, root.path)),
|
|
3612
|
+
serverEntry: serverEntry ? toPosixPath(relative4(rootDir, serverEntry)) : null,
|
|
2187
3613
|
routes: routes.map((route) => toBuildRouteManifestEntry(route, rootDir)),
|
|
2188
3614
|
targets: {}
|
|
2189
3615
|
};
|
|
@@ -2192,6 +3618,9 @@ async function buildApp(options) {
|
|
|
2192
3618
|
case "bun":
|
|
2193
3619
|
manifest.targets.bun = await buildBunTarget(routes, rootDir, buildRoot, root.path, serverEntry, options);
|
|
2194
3620
|
break;
|
|
3621
|
+
case "static":
|
|
3622
|
+
manifest.targets.static = await buildStaticTarget(routes, rootDir, buildRoot, root, options);
|
|
3623
|
+
break;
|
|
2195
3624
|
case "node":
|
|
2196
3625
|
case "vercel":
|
|
2197
3626
|
case "cloudflare":
|
|
@@ -2200,7 +3629,7 @@ async function buildApp(options) {
|
|
|
2200
3629
|
throw new Error(`[furin] Unsupported build target "${target}"`);
|
|
2201
3630
|
}
|
|
2202
3631
|
}
|
|
2203
|
-
|
|
3632
|
+
writeFileSync6(join8(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
|
|
2204
3633
|
`);
|
|
2205
3634
|
return {
|
|
2206
3635
|
manifest,
|
|
@@ -2209,8 +3638,8 @@ async function buildApp(options) {
|
|
|
2209
3638
|
}
|
|
2210
3639
|
|
|
2211
3640
|
// src/cli/config.ts
|
|
2212
|
-
import { existsSync as
|
|
2213
|
-
import { resolve as
|
|
3641
|
+
import { existsSync as existsSync8 } from "fs";
|
|
3642
|
+
import { resolve as resolve4 } from "path";
|
|
2214
3643
|
import { pathToFileURL } from "url";
|
|
2215
3644
|
import { TypeCompiler } from "elysia/type-system";
|
|
2216
3645
|
var compiledConfigSchema = TypeCompiler.Compile(configSchema);
|
|
@@ -2220,13 +3649,13 @@ var DEFAULT_CONFIG_FILENAMES = [
|
|
|
2220
3649
|
"furin.config.mjs"
|
|
2221
3650
|
];
|
|
2222
3651
|
async function loadCliConfig(cwd, explicitConfigPath) {
|
|
2223
|
-
const rootDir =
|
|
2224
|
-
const configPath = explicitConfigPath ?
|
|
3652
|
+
const rootDir = resolve4(cwd);
|
|
3653
|
+
const configPath = explicitConfigPath ? resolve4(rootDir, explicitConfigPath) : DEFAULT_CONFIG_FILENAMES.map((filename) => resolve4(rootDir, filename)).find((path) => existsSync8(path));
|
|
2225
3654
|
if (!configPath) {
|
|
2226
3655
|
return {
|
|
2227
3656
|
configPath: null,
|
|
2228
3657
|
rootDir,
|
|
2229
|
-
pagesDir:
|
|
3658
|
+
pagesDir: resolve4(rootDir, "src/pages")
|
|
2230
3659
|
};
|
|
2231
3660
|
}
|
|
2232
3661
|
const imported = await import(pathToFileURL(configPath).href);
|
|
@@ -2239,13 +3668,13 @@ async function loadCliConfig(cwd, explicitConfigPath) {
|
|
|
2239
3668
|
const [firstError] = compiledConfigSchema.Errors(configToValidate);
|
|
2240
3669
|
throw new Error(`[furin] Invalid config at ${configPath}: ${firstError?.message ?? "unknown error"} (path: ${firstError?.path ?? "/"})`);
|
|
2241
3670
|
}
|
|
2242
|
-
const resolvedRootDir =
|
|
3671
|
+
const resolvedRootDir = resolve4(rootDir, configToValidate.rootDir ?? ".");
|
|
2243
3672
|
return {
|
|
2244
3673
|
...configToValidate,
|
|
2245
3674
|
plugins,
|
|
2246
3675
|
configPath,
|
|
2247
3676
|
rootDir: resolvedRootDir,
|
|
2248
|
-
pagesDir:
|
|
3677
|
+
pagesDir: resolve4(resolvedRootDir, configToValidate.pagesDir ?? "src/pages")
|
|
2249
3678
|
};
|
|
2250
3679
|
}
|
|
2251
3680
|
|
|
@@ -2296,11 +3725,15 @@ if (command === "build") {
|
|
|
2296
3725
|
bail(`Unsupported build target "${target}". Valid: ${BUILD_TARGETS.join(", ")}, all`);
|
|
2297
3726
|
}
|
|
2298
3727
|
const config = await loadCliConfig(process.cwd(), values.config);
|
|
2299
|
-
const
|
|
2300
|
-
|
|
2301
|
-
const
|
|
2302
|
-
|
|
2303
|
-
|
|
3728
|
+
const isStaticTarget = target === "static";
|
|
3729
|
+
const resolvedServerEntry = isStaticTarget ? undefined : (() => {
|
|
3730
|
+
const entry = resolve5(config.rootDir, config.serverEntry ?? "src/server.ts");
|
|
3731
|
+
if (!existsSync9(entry)) {
|
|
3732
|
+
const expected = config.serverEntry ?? "src/server.ts";
|
|
3733
|
+
throw new Error(`[furin] Entrypoint ${expected} not found`);
|
|
3734
|
+
}
|
|
3735
|
+
return entry;
|
|
3736
|
+
})();
|
|
2304
3737
|
log(`Building Furin for ${target}\u2026`);
|
|
2305
3738
|
const result = await buildApp({
|
|
2306
3739
|
target,
|
|
@@ -2308,7 +3741,8 @@ if (command === "build") {
|
|
|
2308
3741
|
rootDir: config.rootDir,
|
|
2309
3742
|
pagesDir: values.pagesDir ?? config.pagesDir,
|
|
2310
3743
|
serverEntry: resolvedServerEntry,
|
|
2311
|
-
plugins: config.plugins
|
|
3744
|
+
plugins: config.plugins,
|
|
3745
|
+
staticConfig: config.static
|
|
2312
3746
|
});
|
|
2313
3747
|
const built = Object.keys(result.targets).join(", ") || "none";
|
|
2314
3748
|
log(`Done: ${built} \u2192 .furin/build`);
|