@teyik0/furin 0.1.0-alpha.7 → 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 +644 -75
- package/dist/build/types.d.ts +26 -3
- package/dist/cli/index.js +678 -88
- package/dist/client.d.ts +15 -11
- 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 +395 -63
- package/dist/link.d.ts +31 -3
- package/dist/link.js +138 -50
- 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 +6 -5
- package/src/adapter/bun.ts +20 -0
- package/src/adapter/static.ts +337 -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 +16 -25
- 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
|
@@ -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,10 +1377,100 @@ 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>`;
|
|
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
|
+
}
|
|
1384
1474
|
function generateProdIndexHtml(entryChunk, cssChunks, buildId) {
|
|
1385
1475
|
const cssLinks = cssChunks.map((c) => ` <link rel="stylesheet" crossorigin href="${c}">`).join(`
|
|
1386
1476
|
`);
|
|
@@ -1405,28 +1495,33 @@ ${buildIdMeta}${cssLinks ? `${cssLinks}
|
|
|
1405
1495
|
}
|
|
1406
1496
|
|
|
1407
1497
|
// src/build/hydrate.ts
|
|
1408
|
-
function generateHydrateEntry(routes, rootLayout) {
|
|
1498
|
+
function generateHydrateEntry(routes, rootLayout, basePath) {
|
|
1409
1499
|
const routeEntries = [];
|
|
1410
1500
|
for (const route of routes) {
|
|
1411
1501
|
const resolvedPage = route.path.replace(/\\/g, "/");
|
|
1412
1502
|
const regexPattern = route.pattern.replace(/:[^/]+/g, "([^/]+)").replace(/\*/g, "(.*)");
|
|
1413
1503
|
routeEntries.push(` { pattern: "${route.pattern}", regex: new RegExp("^${regexPattern}$"), load: () => import("${resolvedPage}") }`);
|
|
1414
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},` : "";
|
|
1415
1510
|
return `import { hydrateRoot, createRoot } from "react-dom/client";
|
|
1416
1511
|
import { createElement } from "react";
|
|
1417
1512
|
import { initLogger, log } from "evlog";
|
|
1418
|
-
import {
|
|
1513
|
+
import { createHttpLogDrain } from "evlog/http";
|
|
1419
1514
|
import { RouterProvider } from "@teyik0/furin/link";
|
|
1420
1515
|
import { route as root } from "${rootLayout.replace(/\\/g, "/")}";
|
|
1421
1516
|
|
|
1422
|
-
initLogger({ drain:
|
|
1517
|
+
initLogger({ drain: createHttpLogDrain({ drain: { endpoint: ${logEndpoint} } }) });
|
|
1423
1518
|
|
|
1424
1519
|
const routes = [
|
|
1425
1520
|
${routeEntries.join(`,
|
|
1426
1521
|
`)}
|
|
1427
1522
|
];
|
|
1428
1523
|
|
|
1429
|
-
const pathname =
|
|
1524
|
+
const pathname = ${pathnameExpr};
|
|
1430
1525
|
const _match = routes.find((r) => r.regex.test(pathname));
|
|
1431
1526
|
|
|
1432
1527
|
// Eagerly load only the current page module for initial hydration.
|
|
@@ -1446,7 +1541,7 @@ const _match = routes.find((r) => r.regex.test(pathname));
|
|
|
1446
1541
|
routes,
|
|
1447
1542
|
root,
|
|
1448
1543
|
initialMatch: match,
|
|
1449
|
-
initialData: loaderData
|
|
1544
|
+
initialData: loaderData,${basePathProp}
|
|
1450
1545
|
} as any);
|
|
1451
1546
|
|
|
1452
1547
|
if (import.meta.hot) {
|
|
@@ -1535,7 +1630,7 @@ function buildTargetManifest(rootDir, buildRoot, target, serverEntry) {
|
|
|
1535
1630
|
// src/build/client.ts
|
|
1536
1631
|
var TS_FILE_FILTER = /\.(tsx|ts)$/;
|
|
1537
1632
|
var REACT_IMPORT_RE = /import\s+React\b/;
|
|
1538
|
-
async function buildClient(routes, { outDir, rootLayout, plugins }) {
|
|
1633
|
+
async function buildClient(routes, { outDir, rootLayout, plugins, publicPath, basePath }) {
|
|
1539
1634
|
const clientDir = join2(outDir, "client");
|
|
1540
1635
|
if (!existsSync2(outDir)) {
|
|
1541
1636
|
mkdirSync2(outDir, { recursive: true });
|
|
@@ -1543,7 +1638,7 @@ async function buildClient(routes, { outDir, rootLayout, plugins }) {
|
|
|
1543
1638
|
if (!existsSync2(clientDir)) {
|
|
1544
1639
|
mkdirSync2(clientDir, { recursive: true });
|
|
1545
1640
|
}
|
|
1546
|
-
const hydrateCode = generateHydrateEntry(routes, rootLayout);
|
|
1641
|
+
const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath);
|
|
1547
1642
|
const hydratePath = join2(outDir, "_hydrate.tsx");
|
|
1548
1643
|
writeFileSync(hydratePath, hydrateCode);
|
|
1549
1644
|
console.log("[furin] Building production client bundle\u2026");
|
|
@@ -1587,7 +1682,7 @@ ${transformed}`;
|
|
|
1587
1682
|
entry: "[dir]/[name]-[hash].[ext]",
|
|
1588
1683
|
chunk: "[name]-[hash].[ext]"
|
|
1589
1684
|
},
|
|
1590
|
-
publicPath
|
|
1685
|
+
publicPath,
|
|
1591
1686
|
plugins: plugins ? [...plugins, transformPlugin] : [transformPlugin],
|
|
1592
1687
|
alias: {
|
|
1593
1688
|
"@teyik0/furin/client": CLIENT_MODULE_PATH,
|
|
@@ -1606,8 +1701,14 @@ ${transformed}`;
|
|
|
1606
1701
|
if (!entryOutput) {
|
|
1607
1702
|
throw new Error("[furin] client build did not emit entry chunk");
|
|
1608
1703
|
}
|
|
1609
|
-
|
|
1610
|
-
|
|
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)}`);
|
|
1611
1712
|
console.log("[furin] Production client build complete");
|
|
1612
1713
|
return { entryChunk, cssChunks };
|
|
1613
1714
|
}
|
|
@@ -1792,7 +1893,9 @@ async function buildBunTarget(routes, rootDir, buildRoot, rootPath, serverEntry,
|
|
|
1792
1893
|
const { entryChunk, cssChunks } = await buildClient(routes, {
|
|
1793
1894
|
outDir: targetDir,
|
|
1794
1895
|
rootLayout: rootPath,
|
|
1795
|
-
plugins: options.plugins
|
|
1896
|
+
plugins: options.plugins,
|
|
1897
|
+
publicPath: "/_client/",
|
|
1898
|
+
basePath: ""
|
|
1796
1899
|
});
|
|
1797
1900
|
const buildFingerprint = await createBuildFingerprint(entryChunk, cssChunks, routes, rootPath, serverEntry);
|
|
1798
1901
|
const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
|
|
@@ -1822,8 +1925,18 @@ async function buildBunTarget(routes, rootDir, buildRoot, rootPath, serverEntry,
|
|
|
1822
1925
|
compile: { outfile },
|
|
1823
1926
|
minify: true,
|
|
1824
1927
|
sourcemap: "linked",
|
|
1928
|
+
define: { "process.env.NODE_ENV": JSON.stringify("production") },
|
|
1825
1929
|
plugins: options.plugins
|
|
1826
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
|
+
}
|
|
1827
1940
|
console.log(`[furin] Server binary: ${outfile}`);
|
|
1828
1941
|
targetManifest.serverPath = toPosixPath(join5(targetManifest.targetDir, "server"));
|
|
1829
1942
|
if (options.compile === "embed") {
|
|
@@ -1861,9 +1974,464 @@ async function buildBunTarget(routes, rootDir, buildRoot, rootPath, serverEntry,
|
|
|
1861
1974
|
return targetManifest;
|
|
1862
1975
|
}
|
|
1863
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
|
+
|
|
1864
2432
|
// src/config.ts
|
|
1865
2433
|
import { t } from "elysia";
|
|
1866
|
-
var BUILD_TARGETS = ["bun", "node", "vercel", "cloudflare"];
|
|
2434
|
+
var BUILD_TARGETS = ["bun", "node", "vercel", "cloudflare", "static"];
|
|
1867
2435
|
var buildTargetSchema = t.Union(BUILD_TARGETS.map((v) => t.Literal(v)));
|
|
1868
2436
|
var compileTargetSchema = t.Union([t.Literal("server"), t.Literal("embed")]);
|
|
1869
2437
|
var configSchema = t.Object({
|
|
@@ -1873,13 +2441,18 @@ var configSchema = t.Object({
|
|
|
1873
2441
|
targets: t.Optional(t.Array(buildTargetSchema)),
|
|
1874
2442
|
bun: t.Optional(t.Object({
|
|
1875
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")]))
|
|
1876
2449
|
}))
|
|
1877
2450
|
});
|
|
1878
2451
|
|
|
1879
2452
|
// src/router.ts
|
|
1880
|
-
import { existsSync as
|
|
2453
|
+
import { existsSync as existsSync6 } from "fs";
|
|
1881
2454
|
import { readdir } from "fs/promises";
|
|
1882
|
-
import { join as
|
|
2455
|
+
import { join as join7, parse } from "path";
|
|
1883
2456
|
import { Elysia } from "elysia";
|
|
1884
2457
|
|
|
1885
2458
|
// src/internal.ts
|
|
@@ -1888,24 +2461,6 @@ function getCompileContext() {
|
|
|
1888
2461
|
return _compileCtx;
|
|
1889
2462
|
}
|
|
1890
2463
|
|
|
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
2464
|
// src/utils.ts
|
|
1910
2465
|
function isFurinPage(value) {
|
|
1911
2466
|
return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_PAGE";
|
|
@@ -1956,7 +2511,7 @@ async function scanPages(pagesDir) {
|
|
|
1956
2511
|
async function scanRootLayout(pagesDir) {
|
|
1957
2512
|
const rootPath = `${pagesDir}/root.tsx`;
|
|
1958
2513
|
const ctx = getCompileContext();
|
|
1959
|
-
if (!(
|
|
2514
|
+
if (!(existsSync6(rootPath) || ctx?.modules[rootPath])) {
|
|
1960
2515
|
throw new Error("[furin] root.tsx: not found.");
|
|
1961
2516
|
}
|
|
1962
2517
|
const mod = ctx?.modules[rootPath] ?? await import(rootPath);
|
|
@@ -2029,7 +2584,7 @@ async function buildDevRoute(absolutePath, relativePath, root) {
|
|
|
2029
2584
|
async function collectPageFilePaths(dir) {
|
|
2030
2585
|
const files = [];
|
|
2031
2586
|
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
2032
|
-
const absolutePath =
|
|
2587
|
+
const absolutePath = join7(dir, entry.name);
|
|
2033
2588
|
if (entry.isDirectory()) {
|
|
2034
2589
|
files.push(...await collectPageFilePaths(absolutePath));
|
|
2035
2590
|
continue;
|
|
@@ -2077,10 +2632,10 @@ function filePathToPattern(path) {
|
|
|
2077
2632
|
}
|
|
2078
2633
|
|
|
2079
2634
|
// src/build/scan-server.ts
|
|
2080
|
-
import { readFileSync } from "fs";
|
|
2635
|
+
import { readFileSync as readFileSync2 } from "fs";
|
|
2081
2636
|
import { parseSync as parseSync2 } from "oxc-parser";
|
|
2082
2637
|
function scanFurinInstances(serverEntryPath) {
|
|
2083
|
-
const code =
|
|
2638
|
+
const code = readFileSync2(serverEntryPath, "utf8");
|
|
2084
2639
|
const { program, errors } = parseSync2(serverEntryPath, code);
|
|
2085
2640
|
if (errors.length > 0) {
|
|
2086
2641
|
return [];
|
|
@@ -2089,26 +2644,28 @@ function scanFurinInstances(serverEntryPath) {
|
|
|
2089
2644
|
walkNode(program, results);
|
|
2090
2645
|
return results;
|
|
2091
2646
|
}
|
|
2092
|
-
|
|
2093
|
-
|
|
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) {
|
|
2094
2653
|
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
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) {
|
|
2109
2665
|
for (const key of Object.keys(node)) {
|
|
2110
|
-
if (key
|
|
2666
|
+
if (SKIP_KEYS.has(key)) {
|
|
2111
2667
|
continue;
|
|
2668
|
+
}
|
|
2112
2669
|
const child = node[key];
|
|
2113
2670
|
if (Array.isArray(child)) {
|
|
2114
2671
|
for (const item of child) {
|
|
@@ -2121,18 +2678,30 @@ function walkNode(node, out) {
|
|
|
2121
2678
|
}
|
|
2122
2679
|
}
|
|
2123
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
|
+
}
|
|
2124
2690
|
function extractStringProperty(obj, propName) {
|
|
2125
2691
|
const properties = obj.properties;
|
|
2126
|
-
if (!Array.isArray(properties))
|
|
2692
|
+
if (!Array.isArray(properties)) {
|
|
2127
2693
|
return null;
|
|
2694
|
+
}
|
|
2128
2695
|
for (const prop of properties) {
|
|
2129
|
-
if (prop.type !== "Property")
|
|
2696
|
+
if (prop.type !== "Property") {
|
|
2130
2697
|
continue;
|
|
2698
|
+
}
|
|
2131
2699
|
const key = prop.key;
|
|
2132
2700
|
const value = prop.value;
|
|
2133
2701
|
const keyMatches = key.type === "Identifier" && key.name === propName || key.type === "Literal" && key.value === propName;
|
|
2134
|
-
if (!keyMatches)
|
|
2702
|
+
if (!keyMatches) {
|
|
2135
2703
|
continue;
|
|
2704
|
+
}
|
|
2136
2705
|
if (value?.type === "Literal" && typeof value.value === "string") {
|
|
2137
2706
|
return value.value;
|
|
2138
2707
|
}
|
|
@@ -2142,33 +2711,46 @@ function extractStringProperty(obj, propName) {
|
|
|
2142
2711
|
}
|
|
2143
2712
|
|
|
2144
2713
|
// src/build/index.ts
|
|
2145
|
-
var IMPLEMENTED_TARGETS = ["bun"];
|
|
2714
|
+
var IMPLEMENTED_TARGETS = ["bun", "static"];
|
|
2146
2715
|
var BUILD_OUTPUT_DIR = ".furin/build";
|
|
2147
2716
|
function resolvePagesDirFromServer(serverEntry, rootDir) {
|
|
2148
|
-
if (!serverEntry)
|
|
2717
|
+
if (!serverEntry) {
|
|
2149
2718
|
return null;
|
|
2719
|
+
}
|
|
2150
2720
|
const detected = scanFurinInstances(serverEntry);
|
|
2151
|
-
if (detected.length === 0)
|
|
2721
|
+
if (detected.length === 0) {
|
|
2152
2722
|
return null;
|
|
2153
|
-
|
|
2723
|
+
}
|
|
2724
|
+
return resolve3(rootDir, detected[0]);
|
|
2154
2725
|
}
|
|
2155
2726
|
async function buildApp(options) {
|
|
2156
|
-
const rootDir =
|
|
2157
|
-
const buildRoot =
|
|
2727
|
+
const rootDir = resolve3(options.rootDir ?? process.cwd());
|
|
2728
|
+
const buildRoot = join8(rootDir, BUILD_OUTPUT_DIR);
|
|
2158
2729
|
const serverEntry = (() => {
|
|
2730
|
+
if (options.target === "static") {
|
|
2731
|
+
return null;
|
|
2732
|
+
}
|
|
2159
2733
|
if (options.serverEntry) {
|
|
2160
|
-
const resolved =
|
|
2161
|
-
if (
|
|
2734
|
+
const resolved = resolve3(rootDir, options.serverEntry);
|
|
2735
|
+
if (existsSync7(resolved)) {
|
|
2162
2736
|
return resolved;
|
|
2737
|
+
}
|
|
2163
2738
|
}
|
|
2164
|
-
const
|
|
2165
|
-
if (!
|
|
2739
|
+
const entry = resolve3(rootDir, "src/server.ts");
|
|
2740
|
+
if (!existsSync7(entry)) {
|
|
2166
2741
|
throw new Error("[furin] Entrypoint server.ts not found");
|
|
2167
2742
|
}
|
|
2168
|
-
return
|
|
2743
|
+
return entry;
|
|
2169
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
|
+
}
|
|
2170
2752
|
const rawPagesDir = options.pagesDir ?? resolvePagesDirFromServer(serverEntry, rootDir) ?? "src/pages";
|
|
2171
|
-
const pagesDir =
|
|
2753
|
+
const pagesDir = resolve3(rootDir, rawPagesDir);
|
|
2172
2754
|
const requestedTargets = options.target === "all" ? [...IMPLEMENTED_TARGETS] : [options.target].map((target) => {
|
|
2173
2755
|
if (!BUILD_TARGETS.includes(target)) {
|
|
2174
2756
|
throw new Error(`[furin] Unsupported build target "${target}"`);
|
|
@@ -2181,9 +2763,9 @@ async function buildApp(options) {
|
|
|
2181
2763
|
version: 1,
|
|
2182
2764
|
generatedAt: new Date().toISOString(),
|
|
2183
2765
|
rootDir: toPosixPath(rootDir),
|
|
2184
|
-
pagesDir: toPosixPath(
|
|
2185
|
-
rootPath: toPosixPath(
|
|
2186
|
-
serverEntry: serverEntry ? toPosixPath(
|
|
2766
|
+
pagesDir: toPosixPath(relative4(rootDir, pagesDir)),
|
|
2767
|
+
rootPath: toPosixPath(relative4(rootDir, root.path)),
|
|
2768
|
+
serverEntry: serverEntry ? toPosixPath(relative4(rootDir, serverEntry)) : null,
|
|
2187
2769
|
routes: routes.map((route) => toBuildRouteManifestEntry(route, rootDir)),
|
|
2188
2770
|
targets: {}
|
|
2189
2771
|
};
|
|
@@ -2192,6 +2774,9 @@ async function buildApp(options) {
|
|
|
2192
2774
|
case "bun":
|
|
2193
2775
|
manifest.targets.bun = await buildBunTarget(routes, rootDir, buildRoot, root.path, serverEntry, options);
|
|
2194
2776
|
break;
|
|
2777
|
+
case "static":
|
|
2778
|
+
manifest.targets.static = await buildStaticTarget(routes, rootDir, buildRoot, root, options);
|
|
2779
|
+
break;
|
|
2195
2780
|
case "node":
|
|
2196
2781
|
case "vercel":
|
|
2197
2782
|
case "cloudflare":
|
|
@@ -2200,7 +2785,7 @@ async function buildApp(options) {
|
|
|
2200
2785
|
throw new Error(`[furin] Unsupported build target "${target}"`);
|
|
2201
2786
|
}
|
|
2202
2787
|
}
|
|
2203
|
-
|
|
2788
|
+
writeFileSync6(join8(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
|
|
2204
2789
|
`);
|
|
2205
2790
|
return {
|
|
2206
2791
|
manifest,
|
|
@@ -2209,8 +2794,8 @@ async function buildApp(options) {
|
|
|
2209
2794
|
}
|
|
2210
2795
|
|
|
2211
2796
|
// src/cli/config.ts
|
|
2212
|
-
import { existsSync as
|
|
2213
|
-
import { resolve as
|
|
2797
|
+
import { existsSync as existsSync8 } from "fs";
|
|
2798
|
+
import { resolve as resolve4 } from "path";
|
|
2214
2799
|
import { pathToFileURL } from "url";
|
|
2215
2800
|
import { TypeCompiler } from "elysia/type-system";
|
|
2216
2801
|
var compiledConfigSchema = TypeCompiler.Compile(configSchema);
|
|
@@ -2220,13 +2805,13 @@ var DEFAULT_CONFIG_FILENAMES = [
|
|
|
2220
2805
|
"furin.config.mjs"
|
|
2221
2806
|
];
|
|
2222
2807
|
async function loadCliConfig(cwd, explicitConfigPath) {
|
|
2223
|
-
const rootDir =
|
|
2224
|
-
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));
|
|
2225
2810
|
if (!configPath) {
|
|
2226
2811
|
return {
|
|
2227
2812
|
configPath: null,
|
|
2228
2813
|
rootDir,
|
|
2229
|
-
pagesDir:
|
|
2814
|
+
pagesDir: resolve4(rootDir, "src/pages")
|
|
2230
2815
|
};
|
|
2231
2816
|
}
|
|
2232
2817
|
const imported = await import(pathToFileURL(configPath).href);
|
|
@@ -2239,13 +2824,13 @@ async function loadCliConfig(cwd, explicitConfigPath) {
|
|
|
2239
2824
|
const [firstError] = compiledConfigSchema.Errors(configToValidate);
|
|
2240
2825
|
throw new Error(`[furin] Invalid config at ${configPath}: ${firstError?.message ?? "unknown error"} (path: ${firstError?.path ?? "/"})`);
|
|
2241
2826
|
}
|
|
2242
|
-
const resolvedRootDir =
|
|
2827
|
+
const resolvedRootDir = resolve4(rootDir, configToValidate.rootDir ?? ".");
|
|
2243
2828
|
return {
|
|
2244
2829
|
...configToValidate,
|
|
2245
2830
|
plugins,
|
|
2246
2831
|
configPath,
|
|
2247
2832
|
rootDir: resolvedRootDir,
|
|
2248
|
-
pagesDir:
|
|
2833
|
+
pagesDir: resolve4(resolvedRootDir, configToValidate.pagesDir ?? "src/pages")
|
|
2249
2834
|
};
|
|
2250
2835
|
}
|
|
2251
2836
|
|
|
@@ -2296,11 +2881,15 @@ if (command === "build") {
|
|
|
2296
2881
|
bail(`Unsupported build target "${target}". Valid: ${BUILD_TARGETS.join(", ")}, all`);
|
|
2297
2882
|
}
|
|
2298
2883
|
const config = await loadCliConfig(process.cwd(), values.config);
|
|
2299
|
-
const
|
|
2300
|
-
|
|
2301
|
-
const
|
|
2302
|
-
|
|
2303
|
-
|
|
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
|
+
})();
|
|
2304
2893
|
log(`Building Furin for ${target}\u2026`);
|
|
2305
2894
|
const result = await buildApp({
|
|
2306
2895
|
target,
|
|
@@ -2308,7 +2897,8 @@ if (command === "build") {
|
|
|
2308
2897
|
rootDir: config.rootDir,
|
|
2309
2898
|
pagesDir: values.pagesDir ?? config.pagesDir,
|
|
2310
2899
|
serverEntry: resolvedServerEntry,
|
|
2311
|
-
plugins: config.plugins
|
|
2900
|
+
plugins: config.plugins,
|
|
2901
|
+
staticConfig: config.static
|
|
2312
2902
|
});
|
|
2313
2903
|
const built = Object.keys(result.targets).join(", ") || "none";
|
|
2314
2904
|
log(`Done: ${built} \u2192 .furin/build`);
|