@teyik0/furin 0.1.0-alpha.6 → 0.1.0-alpha.8
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 +668 -90
- package/dist/build/types.d.ts +26 -3
- package/dist/cli/index.d.ts +1 -0
- package/dist/cli/index.js +704 -103
- package/dist/client.d.ts +22 -15
- package/dist/config.d.ts +33 -2
- package/dist/config.js +6 -1
- package/dist/dev-page-plugin.d.ts +77 -0
- package/dist/furin.js +771 -81
- package/dist/link.d.ts +31 -3
- package/dist/link.js +511 -62
- package/dist/render/index.d.ts +1 -1
- package/dist/render/loaders.d.ts +1 -1
- package/dist/router.js +84 -24
- package/package.json +9 -10
- package/src/adapter/bun.ts +31 -7
- package/src/adapter/static.ts +337 -0
- package/src/build/client.ts +28 -11
- package/src/build/compile-entry.ts +5 -3
- package/src/build/entry-template.ts +9 -5
- package/src/build/hydrate.ts +40 -10
- package/src/build/index.ts +56 -21
- package/src/build/scan-server.ts +43 -21
- package/src/build/shared.ts +7 -3
- package/src/build/types.ts +28 -3
- package/src/cli/index.ts +14 -5
- package/src/client.ts +26 -31
- package/src/config.ts +35 -1
- package/src/dev-page-plugin.ts +339 -4
- package/src/furin.ts +6 -2
- package/src/link.tsx +268 -62
- package/src/plugin/index.ts +2 -2
- package/src/render/index.ts +64 -24
- package/src/render/loaders.ts +77 -36
- package/src/render/shell.ts +2 -2
- package/src/router.ts +11 -1
package/dist/cli/index.js
CHANGED
|
@@ -1,16 +1,19 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
1
2
|
// @bun
|
|
3
|
+
|
|
2
4
|
// src/cli/index.ts
|
|
3
|
-
import { existsSync as
|
|
4
|
-
import { resolve as
|
|
5
|
+
import { existsSync as existsSync9 } from "fs";
|
|
6
|
+
import { resolve as resolve5 } from "path";
|
|
5
7
|
import { parseArgs } from "util";
|
|
6
8
|
|
|
7
9
|
// src/build/index.ts
|
|
8
|
-
import { existsSync as
|
|
9
|
-
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";
|
|
10
12
|
|
|
11
13
|
// src/adapter/bun.ts
|
|
12
14
|
import { existsSync as existsSync4, rmSync as rmSync2, writeFileSync as writeFileSync4 } from "fs";
|
|
13
|
-
import { join as join5, resolve
|
|
15
|
+
import { dirname as dirname2, join as join5, resolve } from "path";
|
|
16
|
+
import { fileURLToPath } from "url";
|
|
14
17
|
|
|
15
18
|
// src/build/client.ts
|
|
16
19
|
import { existsSync as existsSync2, mkdirSync as mkdirSync2, writeFileSync } from "fs";
|
|
@@ -1374,10 +1377,100 @@ function transformForClient(code, filename) {
|
|
|
1374
1377
|
}
|
|
1375
1378
|
|
|
1376
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
|
+
}
|
|
1377
1394
|
function escapeHtml(str) {
|
|
1378
1395
|
return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
1379
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
|
+
}
|
|
1380
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>`;
|
|
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
|
+
}
|
|
1381
1474
|
function generateProdIndexHtml(entryChunk, cssChunks, buildId) {
|
|
1382
1475
|
const cssLinks = cssChunks.map((c) => ` <link rel="stylesheet" crossorigin href="${c}">`).join(`
|
|
1383
1476
|
`);
|
|
@@ -1402,28 +1495,33 @@ ${buildIdMeta}${cssLinks ? `${cssLinks}
|
|
|
1402
1495
|
}
|
|
1403
1496
|
|
|
1404
1497
|
// src/build/hydrate.ts
|
|
1405
|
-
function generateHydrateEntry(routes, rootLayout) {
|
|
1498
|
+
function generateHydrateEntry(routes, rootLayout, basePath) {
|
|
1406
1499
|
const routeEntries = [];
|
|
1407
1500
|
for (const route of routes) {
|
|
1408
1501
|
const resolvedPage = route.path.replace(/\\/g, "/");
|
|
1409
1502
|
const regexPattern = route.pattern.replace(/:[^/]+/g, "([^/]+)").replace(/\*/g, "(.*)");
|
|
1410
1503
|
routeEntries.push(` { pattern: "${route.pattern}", regex: new RegExp("^${regexPattern}$"), load: () => import("${resolvedPage}") }`);
|
|
1411
1504
|
}
|
|
1505
|
+
const basePathLiteral = JSON.stringify(basePath);
|
|
1506
|
+
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";
|
|
1507
|
+
const logEndpoint = basePath ? `${JSON.stringify(basePath)} + "/_furin/ingest"` : `"/_furin/ingest"`;
|
|
1508
|
+
const basePathProp = basePath ? `
|
|
1509
|
+
basePath: ${basePathLiteral},` : "";
|
|
1412
1510
|
return `import { hydrateRoot, createRoot } from "react-dom/client";
|
|
1413
1511
|
import { createElement } from "react";
|
|
1414
1512
|
import { initLogger, log } from "evlog";
|
|
1415
|
-
import {
|
|
1513
|
+
import { createHttpLogDrain } from "evlog/http";
|
|
1416
1514
|
import { RouterProvider } from "@teyik0/furin/link";
|
|
1417
1515
|
import { route as root } from "${rootLayout.replace(/\\/g, "/")}";
|
|
1418
1516
|
|
|
1419
|
-
initLogger({ drain:
|
|
1517
|
+
initLogger({ drain: createHttpLogDrain({ drain: { endpoint: ${logEndpoint} } }) });
|
|
1420
1518
|
|
|
1421
1519
|
const routes = [
|
|
1422
1520
|
${routeEntries.join(`,
|
|
1423
1521
|
`)}
|
|
1424
1522
|
];
|
|
1425
1523
|
|
|
1426
|
-
const pathname =
|
|
1524
|
+
const pathname = ${pathnameExpr};
|
|
1427
1525
|
const _match = routes.find((r) => r.regex.test(pathname));
|
|
1428
1526
|
|
|
1429
1527
|
// Eagerly load only the current page module for initial hydration.
|
|
@@ -1443,7 +1541,7 @@ const _match = routes.find((r) => r.regex.test(pathname));
|
|
|
1443
1541
|
routes,
|
|
1444
1542
|
root,
|
|
1445
1543
|
initialMatch: match,
|
|
1446
|
-
initialData: loaderData
|
|
1544
|
+
initialData: loaderData,${basePathProp}
|
|
1447
1545
|
} as any);
|
|
1448
1546
|
|
|
1449
1547
|
if (import.meta.hot) {
|
|
@@ -1468,15 +1566,17 @@ const _match = routes.find((r) => r.regex.test(pathname));
|
|
|
1468
1566
|
} else {
|
|
1469
1567
|
log.error({ action: "hydrate_no_match", pathname });
|
|
1470
1568
|
}
|
|
1471
|
-
})()
|
|
1569
|
+
})().catch((err: unknown) => {
|
|
1570
|
+
log.error({ action: "hydrate_failed", pathname, error: String(err) });
|
|
1571
|
+
});
|
|
1472
1572
|
`;
|
|
1473
1573
|
}
|
|
1474
1574
|
|
|
1475
1575
|
// src/build/shared.ts
|
|
1476
1576
|
import { cpSync, existsSync, mkdirSync, readdirSync, rmSync } from "fs";
|
|
1477
|
-
import { join, relative
|
|
1478
|
-
var CLIENT_MODULE_PATH =
|
|
1479
|
-
var LINK_MODULE_PATH =
|
|
1577
|
+
import { join, relative } from "path";
|
|
1578
|
+
var CLIENT_MODULE_PATH = new URL(import.meta.resolve("@teyik0/furin/client")).pathname;
|
|
1579
|
+
var LINK_MODULE_PATH = new URL(import.meta.resolve("@teyik0/furin/link")).pathname;
|
|
1480
1580
|
function ensureDir(path) {
|
|
1481
1581
|
if (!existsSync(path)) {
|
|
1482
1582
|
mkdirSync(path, { recursive: true });
|
|
@@ -1530,7 +1630,7 @@ function buildTargetManifest(rootDir, buildRoot, target, serverEntry) {
|
|
|
1530
1630
|
// src/build/client.ts
|
|
1531
1631
|
var TS_FILE_FILTER = /\.(tsx|ts)$/;
|
|
1532
1632
|
var REACT_IMPORT_RE = /import\s+React\b/;
|
|
1533
|
-
async function buildClient(routes, { outDir, rootLayout, plugins }) {
|
|
1633
|
+
async function buildClient(routes, { outDir, rootLayout, plugins, publicPath, basePath }) {
|
|
1534
1634
|
const clientDir = join2(outDir, "client");
|
|
1535
1635
|
if (!existsSync2(outDir)) {
|
|
1536
1636
|
mkdirSync2(outDir, { recursive: true });
|
|
@@ -1538,7 +1638,7 @@ async function buildClient(routes, { outDir, rootLayout, plugins }) {
|
|
|
1538
1638
|
if (!existsSync2(clientDir)) {
|
|
1539
1639
|
mkdirSync2(clientDir, { recursive: true });
|
|
1540
1640
|
}
|
|
1541
|
-
const hydrateCode = generateHydrateEntry(routes, rootLayout);
|
|
1641
|
+
const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath);
|
|
1542
1642
|
const hydratePath = join2(outDir, "_hydrate.tsx");
|
|
1543
1643
|
writeFileSync(hydratePath, hydrateCode);
|
|
1544
1644
|
console.log("[furin] Building production client bundle\u2026");
|
|
@@ -1578,7 +1678,11 @@ ${transformed}`;
|
|
|
1578
1678
|
splitting: true,
|
|
1579
1679
|
minify: true,
|
|
1580
1680
|
sourcemap: "linked",
|
|
1581
|
-
|
|
1681
|
+
naming: {
|
|
1682
|
+
entry: "[dir]/[name]-[hash].[ext]",
|
|
1683
|
+
chunk: "[name]-[hash].[ext]"
|
|
1684
|
+
},
|
|
1685
|
+
publicPath,
|
|
1582
1686
|
plugins: plugins ? [...plugins, transformPlugin] : [transformPlugin],
|
|
1583
1687
|
alias: {
|
|
1584
1688
|
"@teyik0/furin/client": CLIENT_MODULE_PATH,
|
|
@@ -1597,8 +1701,14 @@ ${transformed}`;
|
|
|
1597
1701
|
if (!entryOutput) {
|
|
1598
1702
|
throw new Error("[furin] client build did not emit entry chunk");
|
|
1599
1703
|
}
|
|
1600
|
-
|
|
1601
|
-
|
|
1704
|
+
let publicPrefix;
|
|
1705
|
+
if (publicPath === "") {
|
|
1706
|
+
publicPrefix = "";
|
|
1707
|
+
} else {
|
|
1708
|
+
publicPrefix = publicPath.endsWith("/") ? publicPath : `${publicPath}/`;
|
|
1709
|
+
}
|
|
1710
|
+
const entryChunk = `${publicPrefix}${basename(entryOutput.path)}`;
|
|
1711
|
+
const cssChunks = cssOutputs.map((o) => `${publicPrefix}${basename(o.path)}`);
|
|
1602
1712
|
console.log("[furin] Production client build complete");
|
|
1603
1713
|
return { entryChunk, cssChunks };
|
|
1604
1714
|
}
|
|
@@ -1608,9 +1718,10 @@ import { existsSync as existsSync3, writeFileSync as writeFileSync2 } from "fs";
|
|
|
1608
1718
|
import { join as join3, relative as relative2 } from "path";
|
|
1609
1719
|
|
|
1610
1720
|
// src/build/entry-template.ts
|
|
1611
|
-
import {
|
|
1612
|
-
var
|
|
1613
|
-
var
|
|
1721
|
+
import { dirname } from "path";
|
|
1722
|
+
var _pkgSrcDir = dirname(new URL(import.meta.resolve("@teyik0/furin")).pathname);
|
|
1723
|
+
var INTERNAL_MODULE_PATH = `${_pkgSrcDir}/internal.ts`;
|
|
1724
|
+
var RUNTIME_ENV_MODULE_PATH = `${_pkgSrcDir}/runtime-env.ts`;
|
|
1614
1725
|
function buildEntrySource(options) {
|
|
1615
1726
|
const { buildId, headerComment, rootPath, routes, serverEntry } = options;
|
|
1616
1727
|
let { extraImports, extraContext } = options;
|
|
@@ -1742,13 +1853,14 @@ function generateServerRoutesEntry(options) {
|
|
|
1742
1853
|
}
|
|
1743
1854
|
|
|
1744
1855
|
// src/adapter/bun.ts
|
|
1856
|
+
var _pkgSrcDir2 = dirname2(fileURLToPath(import.meta.resolve("@teyik0/furin")));
|
|
1745
1857
|
var BUILD_ID_INPUT_PATHS = [
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1858
|
+
`${_pkgSrcDir2}/build/compile-entry.ts`,
|
|
1859
|
+
`${_pkgSrcDir2}/build/entry-template.ts`,
|
|
1860
|
+
`${_pkgSrcDir2}/build/server-routes-entry.ts`,
|
|
1861
|
+
`${_pkgSrcDir2}/render/index.ts`,
|
|
1862
|
+
`${_pkgSrcDir2}/render/shell.ts`,
|
|
1863
|
+
`${_pkgSrcDir2}/router.ts`
|
|
1752
1864
|
];
|
|
1753
1865
|
async function createBuildFingerprint(entryChunk, cssChunks, routes, rootPath, serverEntry) {
|
|
1754
1866
|
const fingerprintPaths = new Set([rootPath, ...routes.map((route) => route.path)]);
|
|
@@ -1775,13 +1887,15 @@ async function buildBunTarget(routes, rootDir, buildRoot, rootPath, serverEntry,
|
|
|
1775
1887
|
}
|
|
1776
1888
|
const target = "bun";
|
|
1777
1889
|
const targetManifest = buildTargetManifest(rootDir, buildRoot, target, serverEntry);
|
|
1778
|
-
const targetDir =
|
|
1890
|
+
const targetDir = resolve(rootDir, targetManifest.targetDir);
|
|
1779
1891
|
rmSync2(targetDir, { force: true, recursive: true });
|
|
1780
1892
|
ensureDir(targetDir);
|
|
1781
1893
|
const { entryChunk, cssChunks } = await buildClient(routes, {
|
|
1782
1894
|
outDir: targetDir,
|
|
1783
1895
|
rootLayout: rootPath,
|
|
1784
|
-
plugins: options.plugins
|
|
1896
|
+
plugins: options.plugins,
|
|
1897
|
+
publicPath: "/_client/",
|
|
1898
|
+
basePath: ""
|
|
1785
1899
|
});
|
|
1786
1900
|
const buildFingerprint = await createBuildFingerprint(entryChunk, cssChunks, routes, rootPath, serverEntry);
|
|
1787
1901
|
const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
|
|
@@ -1811,8 +1925,18 @@ async function buildBunTarget(routes, rootDir, buildRoot, rootPath, serverEntry,
|
|
|
1811
1925
|
compile: { outfile },
|
|
1812
1926
|
minify: true,
|
|
1813
1927
|
sourcemap: "linked",
|
|
1928
|
+
define: { "process.env.NODE_ENV": JSON.stringify("production") },
|
|
1814
1929
|
plugins: options.plugins
|
|
1815
1930
|
});
|
|
1931
|
+
if (process.platform === "darwin") {
|
|
1932
|
+
Bun.spawnSync(["codesign", "--remove-signature", outfile]);
|
|
1933
|
+
const sign = Bun.spawnSync(["codesign", "-f", "-s", "-", outfile]);
|
|
1934
|
+
if (sign.exitCode !== 0) {
|
|
1935
|
+
console.warn(`[furin] Warning: codesign failed (exit ${sign.exitCode}). ` + `The binary may be killed by Gatekeeper on macOS. Run manually:
|
|
1936
|
+
` + ` codesign --remove-signature ${outfile}
|
|
1937
|
+
` + ` codesign -f -s - ${outfile}`);
|
|
1938
|
+
}
|
|
1939
|
+
}
|
|
1816
1940
|
console.log(`[furin] Server binary: ${outfile}`);
|
|
1817
1941
|
targetManifest.serverPath = toPosixPath(join5(targetManifest.targetDir, "server"));
|
|
1818
1942
|
if (options.compile === "embed") {
|
|
@@ -1850,9 +1974,464 @@ async function buildBunTarget(routes, rootDir, buildRoot, rootPath, serverEntry,
|
|
|
1850
1974
|
return targetManifest;
|
|
1851
1975
|
}
|
|
1852
1976
|
|
|
1977
|
+
// src/adapter/static.ts
|
|
1978
|
+
import { cpSync as cpSync2, existsSync as existsSync5, rmSync as rmSync3, writeFileSync as writeFileSync5 } from "fs";
|
|
1979
|
+
import { dirname as dirname3, isAbsolute, join as join6, relative as relative3, resolve as resolve2, sep } from "path";
|
|
1980
|
+
|
|
1981
|
+
// src/render/assemble.ts
|
|
1982
|
+
function resolvePath(pattern, params) {
|
|
1983
|
+
let path = pattern;
|
|
1984
|
+
for (const [key, val] of Object.entries(params ?? {})) {
|
|
1985
|
+
path = path.replace(key === "*" ? "*" : `:${key}`, val);
|
|
1986
|
+
}
|
|
1987
|
+
return path;
|
|
1988
|
+
}
|
|
1989
|
+
async function streamToString(stream) {
|
|
1990
|
+
const reader = stream.getReader();
|
|
1991
|
+
const decoder = new TextDecoder;
|
|
1992
|
+
let html = "";
|
|
1993
|
+
for (;; ) {
|
|
1994
|
+
const { done, value } = await reader.read();
|
|
1995
|
+
if (done) {
|
|
1996
|
+
break;
|
|
1997
|
+
}
|
|
1998
|
+
html += decoder.decode(value, { stream: true });
|
|
1999
|
+
}
|
|
2000
|
+
html += decoder.decode();
|
|
2001
|
+
return html;
|
|
2002
|
+
}
|
|
2003
|
+
function splitTemplate(template) {
|
|
2004
|
+
const [headPre, afterHead = ""] = template.split("<!--ssr-head-->");
|
|
2005
|
+
const [bodyPre, bodyPost = ""] = afterHead.split("<!--ssr-outlet-->");
|
|
2006
|
+
return { headPre, bodyPre, bodyPost };
|
|
2007
|
+
}
|
|
2008
|
+
function assembleHTML(template, headData, reactHtml, data) {
|
|
2009
|
+
const { headPre, bodyPre, bodyPost } = splitTemplate(template);
|
|
2010
|
+
const dataScript = data ? `<script id="__FURIN_DATA__" type="application/json">${safeJson(data)}</script>` : "";
|
|
2011
|
+
let injectedBodyPost = bodyPost;
|
|
2012
|
+
if (dataScript) {
|
|
2013
|
+
injectedBodyPost = bodyPost.includes("</body>") ? bodyPost.replace("</body>", `${dataScript}</body>`) : bodyPost + dataScript;
|
|
2014
|
+
}
|
|
2015
|
+
return headPre + headData + bodyPre + reactHtml + injectedBodyPost;
|
|
2016
|
+
}
|
|
2017
|
+
|
|
2018
|
+
// src/render/index.ts
|
|
2019
|
+
import { createElement as createElement2 } from "react";
|
|
2020
|
+
import { renderToReadableStream } from "react-dom/server";
|
|
2021
|
+
|
|
2022
|
+
// src/link.tsx
|
|
2023
|
+
import {
|
|
2024
|
+
createContext,
|
|
2025
|
+
createElement,
|
|
2026
|
+
useCallback,
|
|
2027
|
+
useContext,
|
|
2028
|
+
useEffect,
|
|
2029
|
+
useRef,
|
|
2030
|
+
useState
|
|
2031
|
+
} from "react";
|
|
2032
|
+
var RouterContext = createContext(null);
|
|
2033
|
+
|
|
2034
|
+
// src/render/cache.ts
|
|
2035
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
2036
|
+
var MAX_SSG_CACHE_SIZE = 1000;
|
|
2037
|
+
var isrCache = new Map;
|
|
2038
|
+
var ssgCache = new Map;
|
|
2039
|
+
function evictOldest(map, maxSize) {
|
|
2040
|
+
if (map.size > maxSize) {
|
|
2041
|
+
const oldest = map.keys().next().value;
|
|
2042
|
+
if (oldest !== undefined) {
|
|
2043
|
+
map.delete(oldest);
|
|
2044
|
+
}
|
|
2045
|
+
}
|
|
2046
|
+
}
|
|
2047
|
+
function getSSGCache(key) {
|
|
2048
|
+
const entry = ssgCache.get(key);
|
|
2049
|
+
if (entry !== undefined) {
|
|
2050
|
+
ssgCache.delete(key);
|
|
2051
|
+
ssgCache.set(key, entry);
|
|
2052
|
+
}
|
|
2053
|
+
return entry;
|
|
2054
|
+
}
|
|
2055
|
+
function setSSGCache(key, entry) {
|
|
2056
|
+
ssgCache.delete(key);
|
|
2057
|
+
ssgCache.set(key, entry);
|
|
2058
|
+
evictOldest(ssgCache, MAX_SSG_CACHE_SIZE);
|
|
2059
|
+
}
|
|
2060
|
+
var _requestInvalidationScope = new AsyncLocalStorage;
|
|
2061
|
+
var _globalPendingInvalidations = new Set;
|
|
2062
|
+
|
|
2063
|
+
// src/render/element.tsx
|
|
2064
|
+
import { jsxDEV } from "react/jsx-dev-runtime";
|
|
2065
|
+
function buildElement(route, data, rootLayout) {
|
|
2066
|
+
const Component = route.page.component;
|
|
2067
|
+
let element = /* @__PURE__ */ jsxDEV(Component, {
|
|
2068
|
+
...data
|
|
2069
|
+
}, undefined, false, undefined, this);
|
|
2070
|
+
for (let i = route.routeChain.length - 1;i >= 1; i--) {
|
|
2071
|
+
const routeEntry = route.routeChain[i];
|
|
2072
|
+
if (routeEntry?.layout) {
|
|
2073
|
+
const Layout = routeEntry.layout;
|
|
2074
|
+
element = /* @__PURE__ */ jsxDEV(Layout, {
|
|
2075
|
+
...data,
|
|
2076
|
+
children: element
|
|
2077
|
+
}, undefined, false, undefined, this);
|
|
2078
|
+
}
|
|
2079
|
+
}
|
|
2080
|
+
if (rootLayout.layout) {
|
|
2081
|
+
const RootLayoutComponent = rootLayout.layout;
|
|
2082
|
+
element = /* @__PURE__ */ jsxDEV(RootLayoutComponent, {
|
|
2083
|
+
...data,
|
|
2084
|
+
children: element
|
|
2085
|
+
}, undefined, false, undefined, this);
|
|
2086
|
+
}
|
|
2087
|
+
return element;
|
|
2088
|
+
}
|
|
2089
|
+
|
|
2090
|
+
// src/render/loaders.ts
|
|
2091
|
+
function createLoaderCtx(ctx, accumulatedParentPromise) {
|
|
2092
|
+
const cache = new Map;
|
|
2093
|
+
return new Proxy(ctx, {
|
|
2094
|
+
get(target, prop) {
|
|
2095
|
+
if (typeof prop !== "string") {
|
|
2096
|
+
return Reflect.get(target, prop);
|
|
2097
|
+
}
|
|
2098
|
+
if (prop === "then" || prop === "catch" || prop === "finally" || prop === "toJSON") {
|
|
2099
|
+
return Reflect.get(target, prop);
|
|
2100
|
+
}
|
|
2101
|
+
if (Object.hasOwn(target, prop)) {
|
|
2102
|
+
return target[prop];
|
|
2103
|
+
}
|
|
2104
|
+
let entry = cache.get(prop);
|
|
2105
|
+
if (!entry) {
|
|
2106
|
+
entry = accumulatedParentPromise.then((data) => data[prop]);
|
|
2107
|
+
cache.set(prop, entry);
|
|
2108
|
+
}
|
|
2109
|
+
return entry;
|
|
2110
|
+
}
|
|
2111
|
+
});
|
|
2112
|
+
}
|
|
2113
|
+
async function runLoaders(route, ctx, _rootLayout) {
|
|
2114
|
+
try {
|
|
2115
|
+
const ctxRecord = ctx;
|
|
2116
|
+
const loaderMap = new Map;
|
|
2117
|
+
let accumulatedParentPromise = Promise.resolve({});
|
|
2118
|
+
for (const r of route.routeChain) {
|
|
2119
|
+
const parentAccum = accumulatedParentPromise;
|
|
2120
|
+
if (r.loader) {
|
|
2121
|
+
const loaderCtx = createLoaderCtx(ctxRecord, parentAccum);
|
|
2122
|
+
const loaderPromise = Promise.resolve(r.loader(loaderCtx)).then((res) => res ?? {});
|
|
2123
|
+
loaderMap.set(r, loaderPromise);
|
|
2124
|
+
accumulatedParentPromise = Promise.all([parentAccum, loaderPromise]).then(([acc, own]) => ({
|
|
2125
|
+
...acc,
|
|
2126
|
+
...own
|
|
2127
|
+
}));
|
|
2128
|
+
accumulatedParentPromise.catch(() => {});
|
|
2129
|
+
}
|
|
2130
|
+
}
|
|
2131
|
+
const pageCtx = createLoaderCtx(ctxRecord, accumulatedParentPromise);
|
|
2132
|
+
const pagePromise = route.page?.loader ? Promise.resolve(route.page.loader(pageCtx)).then((r) => r ?? {}) : Promise.resolve({});
|
|
2133
|
+
const results = await Promise.all([...loaderMap.values(), pagePromise]);
|
|
2134
|
+
const data = Object.assign({}, ...results);
|
|
2135
|
+
const headers = {};
|
|
2136
|
+
Object.assign(headers, ctx.set.headers);
|
|
2137
|
+
return { type: "data", data, headers };
|
|
2138
|
+
} catch (err) {
|
|
2139
|
+
if (err instanceof Response) {
|
|
2140
|
+
return { type: "redirect", response: err };
|
|
2141
|
+
}
|
|
2142
|
+
throw err;
|
|
2143
|
+
}
|
|
2144
|
+
}
|
|
2145
|
+
|
|
2146
|
+
// src/render/template.ts
|
|
2147
|
+
import { readFileSync } from "fs";
|
|
2148
|
+
var _prodTemplatePath = null;
|
|
2149
|
+
var _prodTemplateContent = null;
|
|
2150
|
+
var _devTemplateCache = null;
|
|
2151
|
+
var DEV_TEMPLATE_TTL_MS = 1000;
|
|
2152
|
+
async function getDevTemplate(origin) {
|
|
2153
|
+
if (_devTemplateCache && Date.now() - _devTemplateCache.ts < DEV_TEMPLATE_TTL_MS) {
|
|
2154
|
+
return _devTemplateCache.html;
|
|
2155
|
+
}
|
|
2156
|
+
const r = await fetch(`${origin}/_bun_hmr_entry`);
|
|
2157
|
+
if (!r.ok) {
|
|
2158
|
+
throw new Error(`/_bun_hmr_entry returned ${r.status}`);
|
|
2159
|
+
}
|
|
2160
|
+
const html = await r.text();
|
|
2161
|
+
_devTemplateCache = { html, ts: Date.now() };
|
|
2162
|
+
return html;
|
|
2163
|
+
}
|
|
2164
|
+
function setProductionTemplateContent(content) {
|
|
2165
|
+
_prodTemplatePath = null;
|
|
2166
|
+
_prodTemplateContent = content;
|
|
2167
|
+
}
|
|
2168
|
+
function getProductionTemplate() {
|
|
2169
|
+
if (_prodTemplateContent !== null) {
|
|
2170
|
+
return _prodTemplateContent;
|
|
2171
|
+
}
|
|
2172
|
+
if (!_prodTemplatePath) {
|
|
2173
|
+
return null;
|
|
2174
|
+
}
|
|
2175
|
+
try {
|
|
2176
|
+
_prodTemplateContent = readFileSync(_prodTemplatePath, "utf8");
|
|
2177
|
+
return _prodTemplateContent;
|
|
2178
|
+
} catch {
|
|
2179
|
+
return null;
|
|
2180
|
+
}
|
|
2181
|
+
}
|
|
2182
|
+
// src/runtime-env.ts
|
|
2183
|
+
var IS_DEV = true;
|
|
2184
|
+
|
|
2185
|
+
// src/render/index.ts
|
|
2186
|
+
async function prepareRender(route, ctx, root, basePath) {
|
|
2187
|
+
const loaderStart = Date.now();
|
|
2188
|
+
const loaderResult = await runLoaders(route, ctx, root.route);
|
|
2189
|
+
const loader_ms = Date.now() - loaderStart;
|
|
2190
|
+
if (loaderResult.type === "redirect") {
|
|
2191
|
+
return loaderResult.response;
|
|
2192
|
+
}
|
|
2193
|
+
const { data, headers } = loaderResult;
|
|
2194
|
+
const componentProps = {
|
|
2195
|
+
...data,
|
|
2196
|
+
params: ctx.params,
|
|
2197
|
+
query: ctx.query,
|
|
2198
|
+
path: ctx.path
|
|
2199
|
+
};
|
|
2200
|
+
const headData = buildHeadInjection(route.page?.head?.(componentProps));
|
|
2201
|
+
const prodTemplate = getProductionTemplate();
|
|
2202
|
+
const template = prodTemplate ?? (IS_DEV ? await getDevTemplate(new URL(ctx.request.url).origin) : generateIndexHtml());
|
|
2203
|
+
let element = buildElement(route, componentProps, root.route);
|
|
2204
|
+
if (basePath !== undefined) {
|
|
2205
|
+
const ssrContext = {
|
|
2206
|
+
basePath,
|
|
2207
|
+
currentHref: ctx.path,
|
|
2208
|
+
navigate: () => Promise.resolve(),
|
|
2209
|
+
prefetch: () => {},
|
|
2210
|
+
invalidatePrefetch: () => {},
|
|
2211
|
+
refresh: () => Promise.resolve(),
|
|
2212
|
+
isNavigating: false,
|
|
2213
|
+
defaultPreload: "intent",
|
|
2214
|
+
defaultPreloadDelay: 50,
|
|
2215
|
+
defaultPreloadStaleTime: 30000
|
|
2216
|
+
};
|
|
2217
|
+
element = createElement2(RouterContext.Provider, { value: ssrContext }, element);
|
|
2218
|
+
}
|
|
2219
|
+
return { componentProps, element, headData, headers, loader_ms, template };
|
|
2220
|
+
}
|
|
2221
|
+
async function renderForPath(route, params, root, origin, basePath) {
|
|
2222
|
+
const resolvedPath = resolvePath(route.pattern, params);
|
|
2223
|
+
const ctx = {
|
|
2224
|
+
params,
|
|
2225
|
+
query: {},
|
|
2226
|
+
request: new Request(`${origin}${resolvedPath}`),
|
|
2227
|
+
headers: {},
|
|
2228
|
+
cookie: {},
|
|
2229
|
+
redirect: (url, status = 302) => new Response(null, { status, headers: { Location: url } }),
|
|
2230
|
+
set: { headers: {} },
|
|
2231
|
+
path: resolvedPath
|
|
2232
|
+
};
|
|
2233
|
+
const prepared = await prepareRender(route, ctx, root, basePath);
|
|
2234
|
+
if (prepared instanceof Response) {
|
|
2235
|
+
throw prepared;
|
|
2236
|
+
}
|
|
2237
|
+
const { componentProps, element, headData, headers, template } = prepared;
|
|
2238
|
+
const stream = await renderToReadableStream(element);
|
|
2239
|
+
await stream.allReady;
|
|
2240
|
+
const reactHtml = await streamToString(stream);
|
|
2241
|
+
return {
|
|
2242
|
+
html: assembleHTML(template, headData, reactHtml, componentProps),
|
|
2243
|
+
headers
|
|
2244
|
+
};
|
|
2245
|
+
}
|
|
2246
|
+
async function prerenderSSG(route, params, root, origin = "http://localhost:3000", basePath) {
|
|
2247
|
+
const resolvedPath = resolvePath(route.pattern, params);
|
|
2248
|
+
const cached = getSSGCache(resolvedPath);
|
|
2249
|
+
if (cached && !IS_DEV) {
|
|
2250
|
+
return cached;
|
|
2251
|
+
}
|
|
2252
|
+
let result;
|
|
2253
|
+
try {
|
|
2254
|
+
result = await renderForPath(route, params, root, origin, basePath);
|
|
2255
|
+
} catch (err) {
|
|
2256
|
+
if (err instanceof Response) {
|
|
2257
|
+
return err;
|
|
2258
|
+
}
|
|
2259
|
+
throw err;
|
|
2260
|
+
}
|
|
2261
|
+
const entry = { html: result.html, cachedAt: Date.now() };
|
|
2262
|
+
if (!IS_DEV) {
|
|
2263
|
+
setSSGCache(resolvedPath, entry);
|
|
2264
|
+
}
|
|
2265
|
+
return entry;
|
|
2266
|
+
}
|
|
2267
|
+
var pendingRevalidations = new Set;
|
|
2268
|
+
|
|
2269
|
+
// src/adapter/static.ts
|
|
2270
|
+
var STATIC_CONCURRENCY = 4;
|
|
2271
|
+
var DYNAMIC_SEGMENT_RE = /\/:[^/]+|\/\*/;
|
|
2272
|
+
var TRAILING_SLASHES_RE = /\/+$/;
|
|
2273
|
+
function pathToOutputFile(urlPath, outDir) {
|
|
2274
|
+
const normalizedOutDir = resolve2(outDir);
|
|
2275
|
+
if (urlPath === "/" || urlPath === "") {
|
|
2276
|
+
return join6(normalizedOutDir, "index.html");
|
|
2277
|
+
}
|
|
2278
|
+
const resolved = resolve2(normalizedOutDir, urlPath.slice(1), "index.html");
|
|
2279
|
+
if (!resolved.startsWith(`${normalizedOutDir}${sep}`)) {
|
|
2280
|
+
throw new Error(`[furin] static: unsafe output path detected for URL "${urlPath}" \u2014 path traversal via ".." is not allowed.`);
|
|
2281
|
+
}
|
|
2282
|
+
return resolved;
|
|
2283
|
+
}
|
|
2284
|
+
async function prerenderAndWrite(route, params, root, outDir, renderedRoutes, skippedRoutes, basePath) {
|
|
2285
|
+
const urlPath = resolvePath(route.pattern, params);
|
|
2286
|
+
const outputFile = pathToOutputFile(urlPath, outDir);
|
|
2287
|
+
try {
|
|
2288
|
+
const entry = await prerenderSSG(route, params, root, "http://localhost", basePath);
|
|
2289
|
+
if (entry instanceof Response) {
|
|
2290
|
+
console.warn(`[furin] static: route "${route.pattern}" loader returned a redirect \u2014 skipping.`);
|
|
2291
|
+
return;
|
|
2292
|
+
}
|
|
2293
|
+
ensureDir(dirname3(outputFile));
|
|
2294
|
+
writeFileSync5(outputFile, entry.html);
|
|
2295
|
+
renderedRoutes.push(urlPath);
|
|
2296
|
+
console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(outputFile)}`);
|
|
2297
|
+
} catch (err) {
|
|
2298
|
+
console.error(`[furin] static: prerender failed for "${route.pattern}" (params: ${JSON.stringify(params)}):`, err);
|
|
2299
|
+
skippedRoutes.push(urlPath);
|
|
2300
|
+
}
|
|
2301
|
+
}
|
|
2302
|
+
function collectSsgRoutes(routes, onSSR, skippedRoutes) {
|
|
2303
|
+
const nonSsg = routes.filter((r) => r.mode !== "ssg");
|
|
2304
|
+
if (nonSsg.length === 0) {
|
|
2305
|
+
return routes;
|
|
2306
|
+
}
|
|
2307
|
+
if (onSSR === "error") {
|
|
2308
|
+
const list = nonSsg.map((r) => ` \u2022 ${r.pattern} (mode: ${r.mode})`).join(`
|
|
2309
|
+
`);
|
|
2310
|
+
throw new Error(`[furin] Cannot produce a static export: the following routes are not SSG and cannot be pre-rendered.
|
|
2311
|
+
` + `Either change their mode to "ssg", remove them, or set \`onSSR: "skip"\` in your static config.
|
|
2312
|
+
|
|
2313
|
+
` + `${list}`);
|
|
2314
|
+
}
|
|
2315
|
+
for (const r of nonSsg) {
|
|
2316
|
+
console.warn(`[furin] static: skipping route "${r.pattern}" (mode=${r.mode}) \u2014 not statically exportable.`);
|
|
2317
|
+
skippedRoutes.push(r.pattern);
|
|
2318
|
+
}
|
|
2319
|
+
return routes.filter((r) => r.mode === "ssg");
|
|
2320
|
+
}
|
|
2321
|
+
async function buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRoutes, basePath) {
|
|
2322
|
+
const tasks = [];
|
|
2323
|
+
for (const route of ssgRoutes) {
|
|
2324
|
+
if (!DYNAMIC_SEGMENT_RE.test(route.pattern)) {
|
|
2325
|
+
tasks.push(() => prerenderAndWrite(route, {}, root, outDir, renderedRoutes, skippedRoutes, basePath));
|
|
2326
|
+
continue;
|
|
2327
|
+
}
|
|
2328
|
+
if (!route.page.staticParams) {
|
|
2329
|
+
console.warn(`[furin] static: skipping dynamic route "${route.pattern}" \u2014 no staticParams() defined.`);
|
|
2330
|
+
skippedRoutes.push(route.pattern);
|
|
2331
|
+
continue;
|
|
2332
|
+
}
|
|
2333
|
+
try {
|
|
2334
|
+
const paramSets = await route.page.staticParams() ?? [];
|
|
2335
|
+
for (const params of paramSets) {
|
|
2336
|
+
tasks.push(() => prerenderAndWrite(route, params, root, outDir, renderedRoutes, skippedRoutes, basePath));
|
|
2337
|
+
}
|
|
2338
|
+
} catch (err) {
|
|
2339
|
+
console.error(`[furin] static: staticParams() failed for "${route.pattern}":`, err);
|
|
2340
|
+
skippedRoutes.push(route.pattern);
|
|
2341
|
+
}
|
|
2342
|
+
}
|
|
2343
|
+
return tasks;
|
|
2344
|
+
}
|
|
2345
|
+
async function runWithConcurrency(tasks, concurrency) {
|
|
2346
|
+
const queue = [...tasks];
|
|
2347
|
+
const workerCount = Math.min(concurrency, Math.max(queue.length, 1));
|
|
2348
|
+
await Promise.all(Array.from({ length: workerCount }, async () => {
|
|
2349
|
+
while (queue.length > 0) {
|
|
2350
|
+
await queue.shift()?.();
|
|
2351
|
+
}
|
|
2352
|
+
}));
|
|
2353
|
+
}
|
|
2354
|
+
async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
|
|
2355
|
+
const staticConfig = options.staticConfig ?? {};
|
|
2356
|
+
const rawBasePath = staticConfig.basePath ?? "";
|
|
2357
|
+
let basePath;
|
|
2358
|
+
if (rawBasePath === "/" || rawBasePath === "") {
|
|
2359
|
+
basePath = "";
|
|
2360
|
+
} else if (rawBasePath.endsWith("/")) {
|
|
2361
|
+
basePath = rawBasePath.replace(TRAILING_SLASHES_RE, "");
|
|
2362
|
+
} else {
|
|
2363
|
+
basePath = rawBasePath;
|
|
2364
|
+
}
|
|
2365
|
+
if (basePath && !basePath.startsWith("/")) {
|
|
2366
|
+
throw new Error(`[furin] static: basePath must start with "/" (received "${rawBasePath}"). ` + `Use "" for root deployments or "/sub-path" for sub-path deployments.`);
|
|
2367
|
+
}
|
|
2368
|
+
const outDir = resolve2(rootDir, staticConfig.outDir ?? "dist");
|
|
2369
|
+
const normalizedRoot = resolve2(rootDir);
|
|
2370
|
+
const normalizedBuildRoot = resolve2(buildRoot);
|
|
2371
|
+
if (outDir === normalizedRoot || outDir === normalizedBuildRoot || outDir === "/" || outDir === ".") {
|
|
2372
|
+
throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
|
|
2373
|
+
}
|
|
2374
|
+
function isOutsideOutDir(target) {
|
|
2375
|
+
const rel = relative3(outDir, target);
|
|
2376
|
+
return rel.startsWith("..") || isAbsolute(rel);
|
|
2377
|
+
}
|
|
2378
|
+
if (!(isOutsideOutDir(normalizedRoot) && isOutsideOutDir(normalizedBuildRoot))) {
|
|
2379
|
+
throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
|
|
2380
|
+
}
|
|
2381
|
+
const onSSR = staticConfig.onSSR ?? "error";
|
|
2382
|
+
const publicPath = basePath ? `${basePath}/_client/` : "/_client/";
|
|
2383
|
+
const renderedRoutes = [];
|
|
2384
|
+
const skippedRoutes = [];
|
|
2385
|
+
const ssgRoutes = collectSsgRoutes(routes, onSSR, skippedRoutes);
|
|
2386
|
+
rmSync3(outDir, { force: true, recursive: true });
|
|
2387
|
+
ensureDir(outDir);
|
|
2388
|
+
const targetDir = join6(buildRoot, "static");
|
|
2389
|
+
rmSync3(targetDir, { force: true, recursive: true });
|
|
2390
|
+
ensureDir(targetDir);
|
|
2391
|
+
const { entryChunk, cssChunks } = await buildClient(ssgRoutes, {
|
|
2392
|
+
outDir: targetDir,
|
|
2393
|
+
rootLayout: root.path,
|
|
2394
|
+
plugins: options.plugins,
|
|
2395
|
+
publicPath,
|
|
2396
|
+
basePath
|
|
2397
|
+
});
|
|
2398
|
+
const shellHtml = generateProdIndexHtml(entryChunk, cssChunks);
|
|
2399
|
+
setProductionTemplateContent(shellHtml);
|
|
2400
|
+
const publicSrcDir = join6(rootDir, "public");
|
|
2401
|
+
if (existsSync5(publicSrcDir)) {
|
|
2402
|
+
cpSync2(publicSrcDir, outDir, { recursive: true });
|
|
2403
|
+
}
|
|
2404
|
+
const clientSrcDir = join6(targetDir, "client");
|
|
2405
|
+
if (existsSync5(clientSrcDir)) {
|
|
2406
|
+
cpSync2(clientSrcDir, join6(outDir, "_client"), { recursive: true });
|
|
2407
|
+
}
|
|
2408
|
+
const tasks = await buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRoutes, basePath);
|
|
2409
|
+
const afterQueueCount = skippedRoutes.length;
|
|
2410
|
+
await runWithConcurrency(tasks, STATIC_CONCURRENCY);
|
|
2411
|
+
if (onSSR === "error" && skippedRoutes.length > afterQueueCount) {
|
|
2412
|
+
const failed = skippedRoutes.slice(afterQueueCount);
|
|
2413
|
+
const list = failed.map((r) => ` \u2022 ${r}`).join(`
|
|
2414
|
+
`);
|
|
2415
|
+
throw new Error(`[furin] static: ${failed.length} route(s) failed to pre-render:
|
|
2416
|
+
${list}
|
|
2417
|
+
` + `Set \`onSSR: "skip"\` in your static config to suppress this error.`);
|
|
2418
|
+
}
|
|
2419
|
+
writeFileSync5(join6(outDir, "404.html"), shellHtml);
|
|
2420
|
+
console.log("[furin] static: wrote 404.html (SPA shell fallback)");
|
|
2421
|
+
rmSync3(targetDir, { force: true, recursive: true });
|
|
2422
|
+
console.log(`[furin] static: export complete \u2192 ${toPosixPath(outDir)}` + ` (${renderedRoutes.length} rendered, ${skippedRoutes.length} skipped)`);
|
|
2423
|
+
return {
|
|
2424
|
+
basePath,
|
|
2425
|
+
generatedAt: new Date().toISOString(),
|
|
2426
|
+
outDir: toPosixPath(outDir),
|
|
2427
|
+
renderedRoutes,
|
|
2428
|
+
skippedRoutes
|
|
2429
|
+
};
|
|
2430
|
+
}
|
|
2431
|
+
|
|
1853
2432
|
// src/config.ts
|
|
1854
2433
|
import { t } from "elysia";
|
|
1855
|
-
var BUILD_TARGETS = ["bun", "node", "vercel", "cloudflare"];
|
|
2434
|
+
var BUILD_TARGETS = ["bun", "node", "vercel", "cloudflare", "static"];
|
|
1856
2435
|
var buildTargetSchema = t.Union(BUILD_TARGETS.map((v) => t.Literal(v)));
|
|
1857
2436
|
var compileTargetSchema = t.Union([t.Literal("server"), t.Literal("embed")]);
|
|
1858
2437
|
var configSchema = t.Object({
|
|
@@ -1862,13 +2441,18 @@ var configSchema = t.Object({
|
|
|
1862
2441
|
targets: t.Optional(t.Array(buildTargetSchema)),
|
|
1863
2442
|
bun: t.Optional(t.Object({
|
|
1864
2443
|
compile: t.Optional(compileTargetSchema)
|
|
2444
|
+
})),
|
|
2445
|
+
static: t.Optional(t.Object({
|
|
2446
|
+
basePath: t.Optional(t.String()),
|
|
2447
|
+
outDir: t.Optional(t.String()),
|
|
2448
|
+
onSSR: t.Optional(t.Union([t.Literal("error"), t.Literal("skip")]))
|
|
1865
2449
|
}))
|
|
1866
2450
|
});
|
|
1867
2451
|
|
|
1868
2452
|
// src/router.ts
|
|
1869
|
-
import { existsSync as
|
|
2453
|
+
import { existsSync as existsSync6 } from "fs";
|
|
1870
2454
|
import { readdir } from "fs/promises";
|
|
1871
|
-
import { join as
|
|
2455
|
+
import { join as join7, parse } from "path";
|
|
1872
2456
|
import { Elysia } from "elysia";
|
|
1873
2457
|
|
|
1874
2458
|
// src/internal.ts
|
|
@@ -1877,24 +2461,6 @@ function getCompileContext() {
|
|
|
1877
2461
|
return _compileCtx;
|
|
1878
2462
|
}
|
|
1879
2463
|
|
|
1880
|
-
// src/render/index.ts
|
|
1881
|
-
import { renderToReadableStream } from "react-dom/server";
|
|
1882
|
-
|
|
1883
|
-
// src/render/cache.ts
|
|
1884
|
-
import { AsyncLocalStorage } from "async_hooks";
|
|
1885
|
-
var isrCache = new Map;
|
|
1886
|
-
var ssgCache = new Map;
|
|
1887
|
-
var _requestInvalidationScope = new AsyncLocalStorage;
|
|
1888
|
-
var _globalPendingInvalidations = new Set;
|
|
1889
|
-
|
|
1890
|
-
// src/render/element.tsx
|
|
1891
|
-
import { jsxDEV } from "react/jsx-dev-runtime";
|
|
1892
|
-
// src/runtime-env.ts
|
|
1893
|
-
var IS_DEV = true;
|
|
1894
|
-
|
|
1895
|
-
// src/render/index.ts
|
|
1896
|
-
var pendingRevalidations = new Set;
|
|
1897
|
-
|
|
1898
2464
|
// src/utils.ts
|
|
1899
2465
|
function isFurinPage(value) {
|
|
1900
2466
|
return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_PAGE";
|
|
@@ -1945,7 +2511,7 @@ async function scanPages(pagesDir) {
|
|
|
1945
2511
|
async function scanRootLayout(pagesDir) {
|
|
1946
2512
|
const rootPath = `${pagesDir}/root.tsx`;
|
|
1947
2513
|
const ctx = getCompileContext();
|
|
1948
|
-
if (!(
|
|
2514
|
+
if (!(existsSync6(rootPath) || ctx?.modules[rootPath])) {
|
|
1949
2515
|
throw new Error("[furin] root.tsx: not found.");
|
|
1950
2516
|
}
|
|
1951
2517
|
const mod = ctx?.modules[rootPath] ?? await import(rootPath);
|
|
@@ -2018,7 +2584,7 @@ async function buildDevRoute(absolutePath, relativePath, root) {
|
|
|
2018
2584
|
async function collectPageFilePaths(dir) {
|
|
2019
2585
|
const files = [];
|
|
2020
2586
|
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
2021
|
-
const absolutePath =
|
|
2587
|
+
const absolutePath = join7(dir, entry.name);
|
|
2022
2588
|
if (entry.isDirectory()) {
|
|
2023
2589
|
files.push(...await collectPageFilePaths(absolutePath));
|
|
2024
2590
|
continue;
|
|
@@ -2066,10 +2632,10 @@ function filePathToPattern(path) {
|
|
|
2066
2632
|
}
|
|
2067
2633
|
|
|
2068
2634
|
// src/build/scan-server.ts
|
|
2069
|
-
import { readFileSync } from "fs";
|
|
2635
|
+
import { readFileSync as readFileSync2 } from "fs";
|
|
2070
2636
|
import { parseSync as parseSync2 } from "oxc-parser";
|
|
2071
2637
|
function scanFurinInstances(serverEntryPath) {
|
|
2072
|
-
const code =
|
|
2638
|
+
const code = readFileSync2(serverEntryPath, "utf8");
|
|
2073
2639
|
const { program, errors } = parseSync2(serverEntryPath, code);
|
|
2074
2640
|
if (errors.length > 0) {
|
|
2075
2641
|
return [];
|
|
@@ -2078,26 +2644,28 @@ function scanFurinInstances(serverEntryPath) {
|
|
|
2078
2644
|
walkNode(program, results);
|
|
2079
2645
|
return results;
|
|
2080
2646
|
}
|
|
2081
|
-
|
|
2082
|
-
|
|
2647
|
+
var SKIP_KEYS = new Set(["type", "start", "end"]);
|
|
2648
|
+
function checkFurinCall(node, out) {
|
|
2649
|
+
const callee = node.callee;
|
|
2650
|
+
const args = node.arguments;
|
|
2651
|
+
const isFurinCall = callee?.type === "Identifier" && callee.name === "furin";
|
|
2652
|
+
if (!(isFurinCall && Array.isArray(args)) || args.length === 0) {
|
|
2083
2653
|
return;
|
|
2084
|
-
if (node.type === "CallExpression") {
|
|
2085
|
-
const callee = node.callee;
|
|
2086
|
-
const args = node.arguments;
|
|
2087
|
-
const isFurinCall = callee?.type === "Identifier" && callee.name === "furin";
|
|
2088
|
-
if (isFurinCall && Array.isArray(args) && args.length > 0) {
|
|
2089
|
-
const firstArg = args[0];
|
|
2090
|
-
if (firstArg?.type === "ObjectExpression") {
|
|
2091
|
-
const pagesDir = extractStringProperty(firstArg, "pagesDir");
|
|
2092
|
-
if (pagesDir !== null) {
|
|
2093
|
-
out.push(pagesDir);
|
|
2094
|
-
}
|
|
2095
|
-
}
|
|
2096
|
-
}
|
|
2097
2654
|
}
|
|
2655
|
+
const firstArg = args[0];
|
|
2656
|
+
if (firstArg?.type !== "ObjectExpression") {
|
|
2657
|
+
return;
|
|
2658
|
+
}
|
|
2659
|
+
const pagesDir = extractStringProperty(firstArg, "pagesDir");
|
|
2660
|
+
if (pagesDir !== null) {
|
|
2661
|
+
out.push(pagesDir);
|
|
2662
|
+
}
|
|
2663
|
+
}
|
|
2664
|
+
function walkChildren(node, out) {
|
|
2098
2665
|
for (const key of Object.keys(node)) {
|
|
2099
|
-
if (key
|
|
2666
|
+
if (SKIP_KEYS.has(key)) {
|
|
2100
2667
|
continue;
|
|
2668
|
+
}
|
|
2101
2669
|
const child = node[key];
|
|
2102
2670
|
if (Array.isArray(child)) {
|
|
2103
2671
|
for (const item of child) {
|
|
@@ -2110,18 +2678,30 @@ function walkNode(node, out) {
|
|
|
2110
2678
|
}
|
|
2111
2679
|
}
|
|
2112
2680
|
}
|
|
2681
|
+
function walkNode(node, out) {
|
|
2682
|
+
if (!node || typeof node !== "object") {
|
|
2683
|
+
return;
|
|
2684
|
+
}
|
|
2685
|
+
if (node.type === "CallExpression") {
|
|
2686
|
+
checkFurinCall(node, out);
|
|
2687
|
+
}
|
|
2688
|
+
walkChildren(node, out);
|
|
2689
|
+
}
|
|
2113
2690
|
function extractStringProperty(obj, propName) {
|
|
2114
2691
|
const properties = obj.properties;
|
|
2115
|
-
if (!Array.isArray(properties))
|
|
2692
|
+
if (!Array.isArray(properties)) {
|
|
2116
2693
|
return null;
|
|
2694
|
+
}
|
|
2117
2695
|
for (const prop of properties) {
|
|
2118
|
-
if (prop.type !== "Property")
|
|
2696
|
+
if (prop.type !== "Property") {
|
|
2119
2697
|
continue;
|
|
2698
|
+
}
|
|
2120
2699
|
const key = prop.key;
|
|
2121
2700
|
const value = prop.value;
|
|
2122
2701
|
const keyMatches = key.type === "Identifier" && key.name === propName || key.type === "Literal" && key.value === propName;
|
|
2123
|
-
if (!keyMatches)
|
|
2702
|
+
if (!keyMatches) {
|
|
2124
2703
|
continue;
|
|
2704
|
+
}
|
|
2125
2705
|
if (value?.type === "Literal" && typeof value.value === "string") {
|
|
2126
2706
|
return value.value;
|
|
2127
2707
|
}
|
|
@@ -2131,33 +2711,46 @@ function extractStringProperty(obj, propName) {
|
|
|
2131
2711
|
}
|
|
2132
2712
|
|
|
2133
2713
|
// src/build/index.ts
|
|
2134
|
-
var IMPLEMENTED_TARGETS = ["bun"];
|
|
2714
|
+
var IMPLEMENTED_TARGETS = ["bun", "static"];
|
|
2135
2715
|
var BUILD_OUTPUT_DIR = ".furin/build";
|
|
2136
2716
|
function resolvePagesDirFromServer(serverEntry, rootDir) {
|
|
2137
|
-
if (!serverEntry)
|
|
2717
|
+
if (!serverEntry) {
|
|
2138
2718
|
return null;
|
|
2719
|
+
}
|
|
2139
2720
|
const detected = scanFurinInstances(serverEntry);
|
|
2140
|
-
if (detected.length === 0)
|
|
2721
|
+
if (detected.length === 0) {
|
|
2141
2722
|
return null;
|
|
2142
|
-
|
|
2723
|
+
}
|
|
2724
|
+
return resolve3(rootDir, detected[0]);
|
|
2143
2725
|
}
|
|
2144
2726
|
async function buildApp(options) {
|
|
2145
|
-
const rootDir =
|
|
2146
|
-
const buildRoot =
|
|
2727
|
+
const rootDir = resolve3(options.rootDir ?? process.cwd());
|
|
2728
|
+
const buildRoot = join8(rootDir, BUILD_OUTPUT_DIR);
|
|
2147
2729
|
const serverEntry = (() => {
|
|
2730
|
+
if (options.target === "static") {
|
|
2731
|
+
return null;
|
|
2732
|
+
}
|
|
2148
2733
|
if (options.serverEntry) {
|
|
2149
|
-
const resolved =
|
|
2150
|
-
if (
|
|
2734
|
+
const resolved = resolve3(rootDir, options.serverEntry);
|
|
2735
|
+
if (existsSync7(resolved)) {
|
|
2151
2736
|
return resolved;
|
|
2737
|
+
}
|
|
2152
2738
|
}
|
|
2153
|
-
const
|
|
2154
|
-
if (!
|
|
2739
|
+
const entry = resolve3(rootDir, "src/server.ts");
|
|
2740
|
+
if (!existsSync7(entry)) {
|
|
2155
2741
|
throw new Error("[furin] Entrypoint server.ts not found");
|
|
2156
2742
|
}
|
|
2157
|
-
return
|
|
2743
|
+
return entry;
|
|
2158
2744
|
})();
|
|
2745
|
+
for (const plugin of options.plugins ?? []) {
|
|
2746
|
+
try {
|
|
2747
|
+
Bun.plugin(plugin);
|
|
2748
|
+
} catch (err) {
|
|
2749
|
+
console.debug("[furin] Skipped build-only plugin at runtime:", err);
|
|
2750
|
+
}
|
|
2751
|
+
}
|
|
2159
2752
|
const rawPagesDir = options.pagesDir ?? resolvePagesDirFromServer(serverEntry, rootDir) ?? "src/pages";
|
|
2160
|
-
const pagesDir =
|
|
2753
|
+
const pagesDir = resolve3(rootDir, rawPagesDir);
|
|
2161
2754
|
const requestedTargets = options.target === "all" ? [...IMPLEMENTED_TARGETS] : [options.target].map((target) => {
|
|
2162
2755
|
if (!BUILD_TARGETS.includes(target)) {
|
|
2163
2756
|
throw new Error(`[furin] Unsupported build target "${target}"`);
|
|
@@ -2170,9 +2763,9 @@ async function buildApp(options) {
|
|
|
2170
2763
|
version: 1,
|
|
2171
2764
|
generatedAt: new Date().toISOString(),
|
|
2172
2765
|
rootDir: toPosixPath(rootDir),
|
|
2173
|
-
pagesDir: toPosixPath(
|
|
2174
|
-
rootPath: toPosixPath(
|
|
2175
|
-
serverEntry: serverEntry ? toPosixPath(
|
|
2766
|
+
pagesDir: toPosixPath(relative4(rootDir, pagesDir)),
|
|
2767
|
+
rootPath: toPosixPath(relative4(rootDir, root.path)),
|
|
2768
|
+
serverEntry: serverEntry ? toPosixPath(relative4(rootDir, serverEntry)) : null,
|
|
2176
2769
|
routes: routes.map((route) => toBuildRouteManifestEntry(route, rootDir)),
|
|
2177
2770
|
targets: {}
|
|
2178
2771
|
};
|
|
@@ -2181,6 +2774,9 @@ async function buildApp(options) {
|
|
|
2181
2774
|
case "bun":
|
|
2182
2775
|
manifest.targets.bun = await buildBunTarget(routes, rootDir, buildRoot, root.path, serverEntry, options);
|
|
2183
2776
|
break;
|
|
2777
|
+
case "static":
|
|
2778
|
+
manifest.targets.static = await buildStaticTarget(routes, rootDir, buildRoot, root, options);
|
|
2779
|
+
break;
|
|
2184
2780
|
case "node":
|
|
2185
2781
|
case "vercel":
|
|
2186
2782
|
case "cloudflare":
|
|
@@ -2189,7 +2785,7 @@ async function buildApp(options) {
|
|
|
2189
2785
|
throw new Error(`[furin] Unsupported build target "${target}"`);
|
|
2190
2786
|
}
|
|
2191
2787
|
}
|
|
2192
|
-
|
|
2788
|
+
writeFileSync6(join8(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
|
|
2193
2789
|
`);
|
|
2194
2790
|
return {
|
|
2195
2791
|
manifest,
|
|
@@ -2198,8 +2794,8 @@ async function buildApp(options) {
|
|
|
2198
2794
|
}
|
|
2199
2795
|
|
|
2200
2796
|
// src/cli/config.ts
|
|
2201
|
-
import { existsSync as
|
|
2202
|
-
import { resolve as
|
|
2797
|
+
import { existsSync as existsSync8 } from "fs";
|
|
2798
|
+
import { resolve as resolve4 } from "path";
|
|
2203
2799
|
import { pathToFileURL } from "url";
|
|
2204
2800
|
import { TypeCompiler } from "elysia/type-system";
|
|
2205
2801
|
var compiledConfigSchema = TypeCompiler.Compile(configSchema);
|
|
@@ -2209,13 +2805,13 @@ var DEFAULT_CONFIG_FILENAMES = [
|
|
|
2209
2805
|
"furin.config.mjs"
|
|
2210
2806
|
];
|
|
2211
2807
|
async function loadCliConfig(cwd, explicitConfigPath) {
|
|
2212
|
-
const rootDir =
|
|
2213
|
-
const configPath = explicitConfigPath ?
|
|
2808
|
+
const rootDir = resolve4(cwd);
|
|
2809
|
+
const configPath = explicitConfigPath ? resolve4(rootDir, explicitConfigPath) : DEFAULT_CONFIG_FILENAMES.map((filename) => resolve4(rootDir, filename)).find((path) => existsSync8(path));
|
|
2214
2810
|
if (!configPath) {
|
|
2215
2811
|
return {
|
|
2216
2812
|
configPath: null,
|
|
2217
2813
|
rootDir,
|
|
2218
|
-
pagesDir:
|
|
2814
|
+
pagesDir: resolve4(rootDir, "src/pages")
|
|
2219
2815
|
};
|
|
2220
2816
|
}
|
|
2221
2817
|
const imported = await import(pathToFileURL(configPath).href);
|
|
@@ -2228,13 +2824,13 @@ async function loadCliConfig(cwd, explicitConfigPath) {
|
|
|
2228
2824
|
const [firstError] = compiledConfigSchema.Errors(configToValidate);
|
|
2229
2825
|
throw new Error(`[furin] Invalid config at ${configPath}: ${firstError?.message ?? "unknown error"} (path: ${firstError?.path ?? "/"})`);
|
|
2230
2826
|
}
|
|
2231
|
-
const resolvedRootDir =
|
|
2827
|
+
const resolvedRootDir = resolve4(rootDir, configToValidate.rootDir ?? ".");
|
|
2232
2828
|
return {
|
|
2233
2829
|
...configToValidate,
|
|
2234
2830
|
plugins,
|
|
2235
2831
|
configPath,
|
|
2236
2832
|
rootDir: resolvedRootDir,
|
|
2237
|
-
pagesDir:
|
|
2833
|
+
pagesDir: resolve4(resolvedRootDir, configToValidate.pagesDir ?? "src/pages")
|
|
2238
2834
|
};
|
|
2239
2835
|
}
|
|
2240
2836
|
|
|
@@ -2285,11 +2881,15 @@ if (command === "build") {
|
|
|
2285
2881
|
bail(`Unsupported build target "${target}". Valid: ${BUILD_TARGETS.join(", ")}, all`);
|
|
2286
2882
|
}
|
|
2287
2883
|
const config = await loadCliConfig(process.cwd(), values.config);
|
|
2288
|
-
const
|
|
2289
|
-
|
|
2290
|
-
const
|
|
2291
|
-
|
|
2292
|
-
|
|
2884
|
+
const isStaticTarget = target === "static";
|
|
2885
|
+
const resolvedServerEntry = isStaticTarget ? undefined : (() => {
|
|
2886
|
+
const entry = resolve5(config.rootDir, config.serverEntry ?? "src/server.ts");
|
|
2887
|
+
if (!existsSync9(entry)) {
|
|
2888
|
+
const expected = config.serverEntry ?? "src/server.ts";
|
|
2889
|
+
throw new Error(`[furin] Entrypoint ${expected} not found`);
|
|
2890
|
+
}
|
|
2891
|
+
return entry;
|
|
2892
|
+
})();
|
|
2293
2893
|
log(`Building Furin for ${target}\u2026`);
|
|
2294
2894
|
const result = await buildApp({
|
|
2295
2895
|
target,
|
|
@@ -2297,7 +2897,8 @@ if (command === "build") {
|
|
|
2297
2897
|
rootDir: config.rootDir,
|
|
2298
2898
|
pagesDir: values.pagesDir ?? config.pagesDir,
|
|
2299
2899
|
serverEntry: resolvedServerEntry,
|
|
2300
|
-
plugins: config.plugins
|
|
2900
|
+
plugins: config.plugins,
|
|
2901
|
+
staticConfig: config.static
|
|
2301
2902
|
});
|
|
2302
2903
|
const built = Object.keys(result.targets).join(", ") || "none";
|
|
2303
2904
|
log(`Done: ${built} \u2192 .furin/build`);
|