@teyik0/furin 0.2.0-alpha.1 → 0.2.0-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +33 -33
- package/dist/adapter/static.d.ts +1 -1
- package/dist/build/compile-entry.ts +109 -109
- package/dist/build/entry-template.ts +156 -156
- package/dist/build/index.js +1724 -687
- package/dist/build/route-types.d.ts +3 -1
- package/dist/build/server-routes-entry.ts +36 -36
- package/dist/build/shared.d.ts +1 -0
- package/dist/build/ssg-cache.d.ts +1 -1
- package/dist/cli/index.js +1673 -658
- package/dist/client/link.js +883 -89
- package/dist/client/router/index.d.ts +4 -0
- package/dist/client/router/link-utils.d.ts +3 -1
- package/dist/client/router/navigation.d.ts +10 -0
- package/dist/client/router/provider.d.ts +1 -1
- package/dist/client/router/search/index.d.ts +18 -0
- package/dist/client/router/search-store.d.ts +21 -0
- package/dist/client/router/types.d.ts +14 -1
- package/dist/client/sync.d.ts +25 -0
- package/dist/client.d.ts +1 -0
- package/dist/client.js +44 -0
- package/dist/furin.d.ts +9 -1
- package/dist/furin.js +1578 -258
- package/dist/server/auto-invalidate/runtime.d.ts +1 -1
- package/dist/server/dev-page-plugin.d.ts +3 -0
- package/dist/server/render/assemble.d.ts +2 -0
- package/dist/server/render/isr.d.ts +2 -1
- package/dist/server/render/ssg.d.ts +3 -2
- package/dist/server/render/ssr.d.ts +5 -4
- package/dist/server/router/hmr.d.ts +4 -3
- package/dist/server/router/index.d.ts +1 -1
- package/dist/server/router/index.js +1 -2
- package/dist/server/router/index.ts +1 -2
- package/dist/server/router/plugin.d.ts +2 -1
- package/dist/server/router/schemas.d.ts +25 -17
- package/dist/server/sync/config.d.ts +6 -0
- package/dist/server/sync/index.d.ts +4 -0
- package/dist/server/sync/plugin.d.ts +369 -0
- package/dist/server/sync/stream.d.ts +47 -0
- package/dist/shared/search-params.d.ts +17 -0
- package/package.json +10 -5
- package/src/adapter/README.md +13 -13
- package/src/adapter/static.ts +23 -6
- package/src/build/client.ts +152 -149
- package/src/build/compile-entry.ts +109 -109
- package/src/build/entry-template.ts +156 -156
- package/src/build/hydrate.ts +340 -331
- package/src/build/index.ts +152 -152
- package/src/build/route-types.ts +145 -115
- package/src/build/scan-server.ts +95 -95
- package/src/build/server-routes-entry.ts +36 -36
- package/src/build/shared.ts +80 -78
- package/src/build/ssg-cache.ts +32 -31
- package/src/build/types.ts +89 -89
- package/src/client/link.tsx +13 -4
- package/src/client/router/context.ts +2 -0
- package/src/client/router/index.ts +9 -0
- package/src/client/router/link-utils.ts +184 -180
- package/src/client/router/navigation.ts +61 -0
- package/src/client/router/provider.tsx +804 -723
- package/src/client/router/search/index.ts +99 -0
- package/src/client/router/search-store.ts +86 -0
- package/src/client/router/types.ts +276 -263
- package/src/client/sync.ts +98 -0
- package/src/client.ts +369 -355
- package/src/furin.ts +465 -437
- package/src/server/auto-invalidate/runtime.ts +134 -133
- package/src/server/dev-page-plugin.ts +454 -449
- package/src/server/render/assemble.ts +160 -133
- package/src/server/render/isr.ts +323 -295
- package/src/server/render/not-found.ts +2 -0
- package/src/server/render/ssg.ts +15 -4
- package/src/server/render/ssr.ts +585 -545
- package/src/server/router/hmr.ts +14 -10
- package/src/server/router/index.ts +1 -2
- package/src/server/router/patterns.ts +5 -0
- package/src/server/router/plugin.ts +384 -401
- package/src/server/router/schemas.ts +172 -57
- package/src/server/sync/config.ts +29 -0
- package/src/server/sync/index.ts +14 -0
- package/src/server/sync/plugin.ts +108 -0
- package/src/server/sync/stream.ts +144 -0
- package/src/shared/search-params.ts +182 -0
package/dist/cli/index.js
CHANGED
|
@@ -11,13 +11,13 @@ import { existsSync as existsSync8, writeFileSync as writeFileSync6 } from "fs";
|
|
|
11
11
|
import { join as join9, relative as relative4, resolve as resolve3 } from "path";
|
|
12
12
|
|
|
13
13
|
// src/adapter/bun.ts
|
|
14
|
-
import { existsSync as
|
|
15
|
-
import { dirname as dirname2, join as
|
|
16
|
-
import { fileURLToPath as
|
|
14
|
+
import { existsSync as existsSync6, rmSync as rmSync2, writeFileSync as writeFileSync4 } from "fs";
|
|
15
|
+
import { dirname as dirname2, join as join7, resolve } from "path";
|
|
16
|
+
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
17
17
|
|
|
18
18
|
// src/build/client.ts
|
|
19
|
-
import { existsSync as
|
|
20
|
-
import { basename, join as
|
|
19
|
+
import { existsSync as existsSync3, mkdirSync as mkdirSync2, writeFileSync } from "fs";
|
|
20
|
+
import { basename, join as join3 } from "path";
|
|
21
21
|
|
|
22
22
|
// ../../node_modules/.bun/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
|
|
23
23
|
var comma = 44;
|
|
@@ -1599,6 +1599,79 @@ ${buildIdMeta}${modeMeta}${faviconLink}${cssLinks ? `${cssLinks}
|
|
|
1599
1599
|
`;
|
|
1600
1600
|
}
|
|
1601
1601
|
|
|
1602
|
+
// src/server/router/discovery.ts
|
|
1603
|
+
import { existsSync } from "fs";
|
|
1604
|
+
import { readdir } from "fs/promises";
|
|
1605
|
+
import { join, parse as parse3 } from "path";
|
|
1606
|
+
|
|
1607
|
+
// src/shared/utils/index.ts
|
|
1608
|
+
function isFurinPage(value) {
|
|
1609
|
+
return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_PAGE";
|
|
1610
|
+
}
|
|
1611
|
+
function isFurinRoute(value) {
|
|
1612
|
+
return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_ROUTE";
|
|
1613
|
+
}
|
|
1614
|
+
function collectRouteChainFromRoute(route) {
|
|
1615
|
+
const chain = [];
|
|
1616
|
+
let current = route;
|
|
1617
|
+
while (current) {
|
|
1618
|
+
chain.unshift(current);
|
|
1619
|
+
current = current.parent;
|
|
1620
|
+
}
|
|
1621
|
+
return chain;
|
|
1622
|
+
}
|
|
1623
|
+
function hasCycle(route) {
|
|
1624
|
+
const visited = new Set;
|
|
1625
|
+
let current = route;
|
|
1626
|
+
while (current) {
|
|
1627
|
+
if (visited.has(current)) {
|
|
1628
|
+
return true;
|
|
1629
|
+
}
|
|
1630
|
+
visited.add(current);
|
|
1631
|
+
current = current.parent;
|
|
1632
|
+
}
|
|
1633
|
+
return false;
|
|
1634
|
+
}
|
|
1635
|
+
async function mapWithConcurrency(items, concurrency, fn) {
|
|
1636
|
+
if (items.length === 0) {
|
|
1637
|
+
return [];
|
|
1638
|
+
}
|
|
1639
|
+
const results = new Array(items.length);
|
|
1640
|
+
let cursor = 0;
|
|
1641
|
+
const workerCount = Math.min(Math.max(concurrency, 1), items.length);
|
|
1642
|
+
await Promise.all(Array.from({ length: workerCount }, async () => {
|
|
1643
|
+
while (true) {
|
|
1644
|
+
const index = cursor++;
|
|
1645
|
+
if (index >= items.length) {
|
|
1646
|
+
return;
|
|
1647
|
+
}
|
|
1648
|
+
results[index] = await fn(items[index], index);
|
|
1649
|
+
}
|
|
1650
|
+
}));
|
|
1651
|
+
return results;
|
|
1652
|
+
}
|
|
1653
|
+
function validateRouteChain(chain, root, pagePath) {
|
|
1654
|
+
const hasRoot = chain.some((r) => r === root);
|
|
1655
|
+
if (!hasRoot) {
|
|
1656
|
+
const location = pagePath ? `in ${pagePath}` : "";
|
|
1657
|
+
throw new Error(`[furin] Page ${location} must inherit from root route. ` + 'Add: import { route } from "./root"; and use route.page() or set parent: route');
|
|
1658
|
+
}
|
|
1659
|
+
for (const route of chain) {
|
|
1660
|
+
if (hasCycle(route)) {
|
|
1661
|
+
throw new Error("[furin] Cycle detected in route chain. A route cannot be its own ancestor.");
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
|
|
1666
|
+
// src/server/internal.ts
|
|
1667
|
+
var _compileCtx = null;
|
|
1668
|
+
function getCompileContext() {
|
|
1669
|
+
return _compileCtx;
|
|
1670
|
+
}
|
|
1671
|
+
|
|
1672
|
+
// src/server/runtime-env.ts
|
|
1673
|
+
var IS_DEV = true;
|
|
1674
|
+
|
|
1602
1675
|
// src/server/router/patterns.ts
|
|
1603
1676
|
import { parse as parse2 } from "path";
|
|
1604
1677
|
function resolveMode(page, routeChain) {
|
|
@@ -1609,6 +1682,10 @@ function resolveMode(page, routeChain) {
|
|
|
1609
1682
|
return mode;
|
|
1610
1683
|
}
|
|
1611
1684
|
const hasLoader = routeChain.some((r) => r.loader) || !!page.loader;
|
|
1685
|
+
const hasQuery = routeChain.some((r) => r.query);
|
|
1686
|
+
if (hasQuery) {
|
|
1687
|
+
return "ssr";
|
|
1688
|
+
}
|
|
1612
1689
|
if (!hasLoader) {
|
|
1613
1690
|
return "ssg";
|
|
1614
1691
|
}
|
|
@@ -1675,134 +1752,544 @@ function buildRouteRegex(pattern) {
|
|
|
1675
1752
|
return { regex: new RegExp(`^${source}$`), paramNames };
|
|
1676
1753
|
}
|
|
1677
1754
|
|
|
1678
|
-
// src/
|
|
1679
|
-
function
|
|
1680
|
-
const
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
const existing = idents.get(filePath);
|
|
1685
|
-
if (existing) {
|
|
1686
|
-
return existing;
|
|
1755
|
+
// src/server/router/discovery.ts
|
|
1756
|
+
function collectRouteTags(routeChain, page) {
|
|
1757
|
+
const tags = new Set;
|
|
1758
|
+
for (const route of routeChain) {
|
|
1759
|
+
for (const tag of route.tags ?? []) {
|
|
1760
|
+
tags.add(tag);
|
|
1687
1761
|
}
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1762
|
+
}
|
|
1763
|
+
for (const tag of page?.tags ?? []) {
|
|
1764
|
+
tags.add(tag);
|
|
1765
|
+
}
|
|
1766
|
+
return tags.size > 0 ? [...tags] : undefined;
|
|
1767
|
+
}
|
|
1768
|
+
function toPosixPath(path) {
|
|
1769
|
+
return path.replaceAll("\\", "/");
|
|
1770
|
+
}
|
|
1771
|
+
function routeRelativePath(pagesDir, absolutePath) {
|
|
1772
|
+
const dir = toPosixPath(pagesDir).replace(/\/+$/g, "");
|
|
1773
|
+
const path = toPosixPath(absolutePath);
|
|
1774
|
+
return path.startsWith(`${dir}/`) ? path.slice(dir.length + 1) : path;
|
|
1775
|
+
}
|
|
1776
|
+
async function scanPages(pagesDir) {
|
|
1777
|
+
const dir = toPosixPath(pagesDir);
|
|
1778
|
+
const root = await scanRootLayout(dir);
|
|
1779
|
+
const routes = await scanPageFiles(dir, root);
|
|
1780
|
+
return { root, routes };
|
|
1781
|
+
}
|
|
1782
|
+
async function scanRootLayout(pagesDir) {
|
|
1783
|
+
const rootPath = `${pagesDir}/root.tsx`;
|
|
1784
|
+
const ctx = getCompileContext();
|
|
1785
|
+
if (!(existsSync(rootPath) || ctx?.modules[rootPath])) {
|
|
1786
|
+
throw new Error("[furin] root.tsx: not found.");
|
|
1787
|
+
}
|
|
1788
|
+
const mod = ctx?.modules[rootPath] ?? await import(rootPath);
|
|
1789
|
+
const rootExport = mod.route ?? mod.default;
|
|
1790
|
+
if (!(rootExport && isFurinRoute(rootExport))) {
|
|
1791
|
+
throw new Error("[furin] root.tsx: createRoute() export not found.");
|
|
1792
|
+
}
|
|
1793
|
+
if (!rootExport.layout) {
|
|
1794
|
+
throw new Error("[furin] root.tsx: createRoute() has no layout.");
|
|
1795
|
+
}
|
|
1796
|
+
const [notFoundEntry, errorEntry] = await Promise.all([
|
|
1797
|
+
loadConventionComponent(pagesDir, "not-found"),
|
|
1798
|
+
loadConventionComponent(pagesDir, "error")
|
|
1799
|
+
]);
|
|
1800
|
+
return {
|
|
1801
|
+
path: rootPath,
|
|
1802
|
+
route: rootExport,
|
|
1803
|
+
notFound: notFoundEntry?.component,
|
|
1804
|
+
notFoundPath: notFoundEntry?.path,
|
|
1805
|
+
error: errorEntry?.component,
|
|
1806
|
+
errorPath: errorEntry?.path
|
|
1691
1807
|
};
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
if (notFoundIdent) {
|
|
1709
|
-
parts.push(`notFound: ${notFoundIdent}.default`);
|
|
1808
|
+
}
|
|
1809
|
+
var CONVENTION_FILE_NAMES = ["not-found", "error"];
|
|
1810
|
+
var SOURCE_MODULE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js"];
|
|
1811
|
+
function isConventionFileName(name) {
|
|
1812
|
+
return CONVENTION_FILE_NAMES.includes(name);
|
|
1813
|
+
}
|
|
1814
|
+
function getSourceModuleCandidates(dir, name) {
|
|
1815
|
+
return SOURCE_MODULE_EXTENSIONS.map((ext) => `${dir}/${name}${ext}`);
|
|
1816
|
+
}
|
|
1817
|
+
async function loadConventionComponent(dir, name) {
|
|
1818
|
+
const ctx = getCompileContext();
|
|
1819
|
+
for (const filePath of getSourceModuleCandidates(dir, name)) {
|
|
1820
|
+
if (existsSync(filePath) || ctx?.modules[filePath]) {
|
|
1821
|
+
const mod = ctx?.modules[filePath] ?? await import(filePath);
|
|
1822
|
+
if (mod.default) {
|
|
1823
|
+
return { component: mod.default, path: filePath };
|
|
1710
1824
|
}
|
|
1711
|
-
boundaryLiterals.push(`{ ${parts.join(", ")} }`);
|
|
1712
1825
|
}
|
|
1713
|
-
const lazyImports = [
|
|
1714
|
-
`import("${resolvedPage}")`,
|
|
1715
|
-
...[...boundaryIdents.keys()].map((filePath) => `import("${filePath.replace(/\\/g, "/")}")`)
|
|
1716
|
-
];
|
|
1717
|
-
const loadBody = boundaryLiterals.length > 0 ? `Promise.all([${lazyImports.join(", ")}]).then(([__furin_page, ${[
|
|
1718
|
-
...boundaryIdents.values()
|
|
1719
|
-
].join(", ")}]) => ({ default: __furin_page.default, segmentBoundaries: [${boundaryLiterals.join(", ")}] }))` : `import("${resolvedPage}")`;
|
|
1720
|
-
routeEntries.push(` { pattern: "${route.pattern}", regex: new RegExp(${JSON.stringify(regexPattern)}), load: () => ${loadBody} }`);
|
|
1721
1826
|
}
|
|
1722
|
-
|
|
1723
|
-
const pathnameExpr = basePath ? `(() => { const p = window.location.pathname; const b = ${basePathLiteral}; const stripped = (p.startsWith(b) && (p.length === b.length || p[b.length] === "/")) ? p.slice(b.length) || "/" : p; return stripped === "/" ? "/" : stripped.replace(/\\/+$/, ""); })()` : `window.location.pathname.replace(/\\/+$/, "") || "/"`;
|
|
1724
|
-
const logEndpoint = basePath ? `${JSON.stringify(basePath)} + "/_furin/ingest"` : `"/_furin/ingest"`;
|
|
1725
|
-
const loggingImports = clientLogging ? `import { initLogger, log } from "evlog";
|
|
1726
|
-
import { createHttpLogDrain } from "evlog/http";
|
|
1727
|
-
` : "";
|
|
1728
|
-
const loggerSetup = clientLogging ? `initLogger({ drain: createHttpLogDrain({ drain: { endpoint: ${logEndpoint} } }) });` : "const log = { error() {}, info() {} };";
|
|
1729
|
-
const routerProviderDefaults = `
|
|
1730
|
-
autoRefresh: true,
|
|
1731
|
-
basePath: ${basePathLiteral},
|
|
1732
|
-
defaultPreload: "intent",
|
|
1733
|
-
defaultPreloadDelay: 50,
|
|
1734
|
-
defaultPreloadStaleTime: 30000,
|
|
1735
|
-
prefetchCacheSize: 50,`;
|
|
1736
|
-
return `import { hydrateRoot, createRoot } from "react-dom/client";
|
|
1737
|
-
import { createElement } from "react";
|
|
1738
|
-
${loggingImports}import { RouterProvider } from "@teyik0/furin/link";
|
|
1739
|
-
import { fromCrossJSON } from "@teyik0/furin/link";
|
|
1740
|
-
import type { SerovalNode } from "seroval";
|
|
1741
|
-
import { route as root } from "${rootLayout.replace(/\\/g, "/")}";
|
|
1742
|
-
|
|
1743
|
-
${loggerSetup}
|
|
1744
|
-
|
|
1745
|
-
const routes = [
|
|
1746
|
-
${routeEntries.join(`,
|
|
1747
|
-
`)}
|
|
1748
|
-
];
|
|
1749
|
-
|
|
1750
|
-
const pathname = ${pathnameExpr};
|
|
1751
|
-
const _match = routes.find((r) => r.regex.test(pathname));
|
|
1752
|
-
|
|
1753
|
-
// Parse the server-embedded loader payload up front. It carries:
|
|
1754
|
-
// - normal loader props under arbitrary keys,
|
|
1755
|
-
// - __furinError.digest when SSR caught an error,
|
|
1756
|
-
// - __furinStatus: 404 when the server rendered the catch-all not-found
|
|
1757
|
-
// (direct load to an unknown URL, emitted by renderRootNotFound) OR when
|
|
1758
|
-
// a matched loader threw notFound(). The latter still has a _match; the
|
|
1759
|
-
// former does not \u2014 so the two cases fork on _match below.
|
|
1760
|
-
const dataEl = document.getElementById("__FURIN_DATA__");
|
|
1761
|
-
const loaderData = dataEl ? JSON.parse(dataEl.textContent || "{}") : {};
|
|
1762
|
-
|
|
1763
|
-
// \u2500\u2500 Deferred data hydration \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1764
|
-
// window.__FURIN_DEFERRED__ is injected by the server when a loader returns
|
|
1765
|
-
// defer(). It carries:
|
|
1766
|
-
// - _chunks: raw CrossJSON chunks keyed by field name (from late <script> tags)
|
|
1767
|
-
// We deserialise each chunk with fromCrossJSON and create a Promise so <Await>
|
|
1768
|
-
// components receive a proper resolved Promise instead of the raw CrossJSON node.
|
|
1769
|
-
// Sync loader fields live exclusively in __FURIN_DATA__ (read above).
|
|
1770
|
-
interface FurinDeferredRegistry {
|
|
1771
|
-
_chunks: Record<string, { a: 0 | 1; v: SerovalNode }>;
|
|
1772
|
-
_deferredKeys: string[];
|
|
1773
|
-
_resolvers: Record<string, {
|
|
1774
|
-
promise: Promise<unknown>;
|
|
1775
|
-
reject: (reason: unknown) => void;
|
|
1776
|
-
resolve: (value: unknown) => void;
|
|
1777
|
-
}>;
|
|
1778
|
-
getPromise: (key: string) => Promise<unknown>;
|
|
1779
|
-
reject: (key: string, chunk: SerovalNode) => void;
|
|
1780
|
-
resolve: (key: string, chunk: SerovalNode) => void;
|
|
1827
|
+
return;
|
|
1781
1828
|
}
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
const
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
const
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1829
|
+
async function scanPageFiles(pagesDir, root) {
|
|
1830
|
+
const routes = [];
|
|
1831
|
+
const notFoundCache = new Map;
|
|
1832
|
+
const errorCache = new Map;
|
|
1833
|
+
for (const absolutePath of await collectPageFilePaths(pagesDir)) {
|
|
1834
|
+
if (!SOURCE_MODULE_EXTENSIONS.some((ext) => absolutePath.endsWith(ext))) {
|
|
1835
|
+
continue;
|
|
1836
|
+
}
|
|
1837
|
+
const relativePath = routeRelativePath(pagesDir, absolutePath);
|
|
1838
|
+
const fileName = parse3(relativePath).name;
|
|
1839
|
+
if (fileName.startsWith("_") || fileName === "root" || isConventionFileName(fileName)) {
|
|
1840
|
+
continue;
|
|
1841
|
+
}
|
|
1842
|
+
const [notFound, errorComponent, segmentBoundaries] = await Promise.all([
|
|
1843
|
+
resolveNearestConvention(absolutePath, pagesDir, "not-found", notFoundCache, root.notFound),
|
|
1844
|
+
resolveNearestConvention(absolutePath, pagesDir, "error", errorCache, root.error),
|
|
1845
|
+
collectSegmentBoundaries(absolutePath, pagesDir, notFoundCache, errorCache)
|
|
1846
|
+
]);
|
|
1847
|
+
if (IS_DEV) {
|
|
1848
|
+
const devRoute = await buildDevRoute(absolutePath, relativePath, root);
|
|
1849
|
+
devRoute.notFound = notFound;
|
|
1850
|
+
devRoute.error = errorComponent;
|
|
1851
|
+
devRoute.segmentBoundaries = segmentBoundaries;
|
|
1852
|
+
routes.push(devRoute);
|
|
1853
|
+
continue;
|
|
1854
|
+
}
|
|
1855
|
+
const ctx = getCompileContext();
|
|
1856
|
+
const pageMod = ctx?.modules[absolutePath] ?? await import(absolutePath);
|
|
1857
|
+
const page = pageMod.default;
|
|
1858
|
+
if (!isFurinPage(page)) {
|
|
1859
|
+
throw new Error(`[furin] ${relativePath}: no valid createRoute().page() export found`);
|
|
1860
|
+
}
|
|
1861
|
+
const routeChain = collectRouteChainFromRoute(page._route);
|
|
1862
|
+
validateRouteChain(routeChain, root.route, relativePath);
|
|
1863
|
+
routes.push({
|
|
1864
|
+
pattern: filePathToPattern(relativePath),
|
|
1865
|
+
page,
|
|
1866
|
+
path: absolutePath,
|
|
1867
|
+
routeChain,
|
|
1868
|
+
mode: resolveMode(page, routeChain),
|
|
1869
|
+
notFound,
|
|
1870
|
+
error: errorComponent,
|
|
1871
|
+
segmentBoundaries,
|
|
1872
|
+
tags: collectRouteTags(routeChain, page)
|
|
1873
|
+
});
|
|
1874
|
+
}
|
|
1875
|
+
return routes;
|
|
1876
|
+
}
|
|
1877
|
+
async function collectSegmentBoundaries(pageAbsolutePath, pagesDir, notFoundCache, errorCache) {
|
|
1878
|
+
const pageDir = pageAbsolutePath.slice(0, pageAbsolutePath.lastIndexOf("/"));
|
|
1879
|
+
const dirs = [pagesDir];
|
|
1880
|
+
if (pageDir.length > pagesDir.length) {
|
|
1881
|
+
const relativeTail = pageDir.slice(pagesDir.length + 1);
|
|
1882
|
+
const parts = relativeTail.split("/");
|
|
1883
|
+
let acc = pagesDir;
|
|
1884
|
+
for (const part of parts) {
|
|
1885
|
+
acc = `${acc}/${part}`;
|
|
1886
|
+
dirs.push(acc);
|
|
1887
|
+
}
|
|
1888
|
+
}
|
|
1889
|
+
const boundaries = [];
|
|
1890
|
+
for (let depth = 0;depth < dirs.length; depth++) {
|
|
1891
|
+
const dir = dirs[depth];
|
|
1892
|
+
const [errorEntry, notFoundEntry] = await Promise.all([
|
|
1893
|
+
errorCache.has(dir) ? Promise.resolve(errorCache.get(dir)) : loadConventionComponent(dir, "error").then((r) => {
|
|
1894
|
+
errorCache.set(dir, r);
|
|
1895
|
+
return r;
|
|
1896
|
+
}),
|
|
1897
|
+
notFoundCache.has(dir) ? Promise.resolve(notFoundCache.get(dir)) : loadConventionComponent(dir, "not-found").then((r) => {
|
|
1898
|
+
notFoundCache.set(dir, r);
|
|
1899
|
+
return r;
|
|
1900
|
+
})
|
|
1901
|
+
]);
|
|
1902
|
+
if (errorEntry || notFoundEntry) {
|
|
1903
|
+
boundaries.push({
|
|
1904
|
+
path: dir,
|
|
1905
|
+
depth,
|
|
1906
|
+
error: errorEntry?.component,
|
|
1907
|
+
errorPath: errorEntry?.path,
|
|
1908
|
+
notFound: notFoundEntry?.component,
|
|
1909
|
+
notFoundPath: notFoundEntry?.path
|
|
1910
|
+
});
|
|
1911
|
+
}
|
|
1912
|
+
}
|
|
1913
|
+
return boundaries;
|
|
1914
|
+
}
|
|
1915
|
+
async function resolveNearestConvention(pageAbsolutePath, pagesDir, conventionName, cache, rootFallback) {
|
|
1916
|
+
let dir = pageAbsolutePath.slice(0, pageAbsolutePath.lastIndexOf("/"));
|
|
1917
|
+
while (dir.length >= pagesDir.length) {
|
|
1918
|
+
if (!cache.has(dir)) {
|
|
1919
|
+
cache.set(dir, await loadConventionComponent(dir, conventionName));
|
|
1920
|
+
}
|
|
1921
|
+
const found = cache.get(dir);
|
|
1922
|
+
if (found) {
|
|
1923
|
+
return found.component;
|
|
1924
|
+
}
|
|
1925
|
+
if (dir === pagesDir) {
|
|
1926
|
+
break;
|
|
1927
|
+
}
|
|
1928
|
+
dir = dir.slice(0, dir.lastIndexOf("/"));
|
|
1929
|
+
}
|
|
1930
|
+
return rootFallback;
|
|
1931
|
+
}
|
|
1932
|
+
async function buildDevRoute(absolutePath, relativePath, root) {
|
|
1933
|
+
let page;
|
|
1934
|
+
let routeChain = [];
|
|
1935
|
+
try {
|
|
1936
|
+
const pageMod = await import(`${absolutePath}?furin-server&t=${Date.now()}`);
|
|
1937
|
+
if (isFurinPage(pageMod.default)) {
|
|
1938
|
+
page = pageMod.default;
|
|
1939
|
+
routeChain = collectRouteChainFromRoute(page._route);
|
|
1940
|
+
validateRouteChain(routeChain, root.route, relativePath);
|
|
1941
|
+
}
|
|
1942
|
+
} catch {}
|
|
1943
|
+
const devStubPage = {
|
|
1944
|
+
__type: "FURIN_PAGE",
|
|
1945
|
+
_route: { __type: "FURIN_ROUTE" },
|
|
1946
|
+
component: () => null
|
|
1947
|
+
};
|
|
1948
|
+
return {
|
|
1949
|
+
pattern: filePathToPattern(relativePath),
|
|
1950
|
+
path: absolutePath,
|
|
1951
|
+
mode: page ? resolveMode(page, routeChain) : "ssr",
|
|
1952
|
+
page: page ?? devStubPage,
|
|
1953
|
+
routeChain,
|
|
1954
|
+
tags: collectRouteTags(routeChain, page),
|
|
1955
|
+
segmentBoundaries: []
|
|
1956
|
+
};
|
|
1957
|
+
}
|
|
1958
|
+
var DIR_SCAN_CONCURRENCY = 8;
|
|
1959
|
+
async function collectPageFilePaths(dir) {
|
|
1960
|
+
const files = [];
|
|
1961
|
+
const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name));
|
|
1962
|
+
const resolved = await mapWithConcurrency(entries, DIR_SCAN_CONCURRENCY, async (entry) => {
|
|
1963
|
+
const absolutePath = toPosixPath(join(dir, entry.name));
|
|
1964
|
+
if (entry.isDirectory()) {
|
|
1965
|
+
return await collectPageFilePaths(absolutePath);
|
|
1966
|
+
}
|
|
1967
|
+
if (entry.isFile()) {
|
|
1968
|
+
return [absolutePath];
|
|
1969
|
+
}
|
|
1970
|
+
return [];
|
|
1971
|
+
});
|
|
1972
|
+
for (const chunk of resolved) {
|
|
1973
|
+
files.push(...chunk);
|
|
1974
|
+
}
|
|
1975
|
+
return files;
|
|
1976
|
+
}
|
|
1977
|
+
// src/server/router/schemas.ts
|
|
1978
|
+
import { t } from "elysia";
|
|
1979
|
+
import { parseQueryFromURL, parseQueryStandardSchema } from "elysia/parse-query";
|
|
1980
|
+
import { getSchemaValidator } from "elysia/schema";
|
|
1981
|
+
|
|
1982
|
+
// src/shared/search-params.ts
|
|
1983
|
+
function routeSegmentSpecificity(segment) {
|
|
1984
|
+
if (segment === "*") {
|
|
1985
|
+
return 1;
|
|
1986
|
+
}
|
|
1987
|
+
if (segment.startsWith(":")) {
|
|
1988
|
+
return 2;
|
|
1989
|
+
}
|
|
1990
|
+
return 3;
|
|
1991
|
+
}
|
|
1992
|
+
function compareSearchRouteSpecificity(a, b) {
|
|
1993
|
+
const aSegments = a.split("/").filter((segment) => segment.length > 0);
|
|
1994
|
+
const bSegments = b.split("/").filter((segment) => segment.length > 0);
|
|
1995
|
+
const length = Math.max(aSegments.length, bSegments.length);
|
|
1996
|
+
for (let i = 0;i < length; i++) {
|
|
1997
|
+
const aSegment = aSegments[i];
|
|
1998
|
+
const bSegment = bSegments[i];
|
|
1999
|
+
if (aSegment === undefined) {
|
|
2000
|
+
return -1;
|
|
2001
|
+
}
|
|
2002
|
+
if (bSegment === undefined) {
|
|
2003
|
+
return 1;
|
|
2004
|
+
}
|
|
2005
|
+
const diff = routeSegmentSpecificity(aSegment) - routeSegmentSpecificity(bSegment);
|
|
2006
|
+
if (diff !== 0) {
|
|
2007
|
+
return diff;
|
|
2008
|
+
}
|
|
2009
|
+
}
|
|
2010
|
+
return 0;
|
|
2011
|
+
}
|
|
2012
|
+
function isObject2(value) {
|
|
2013
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
2014
|
+
}
|
|
2015
|
+
function arraysDeepEqual(a, b) {
|
|
2016
|
+
if (a.length !== b.length) {
|
|
2017
|
+
return false;
|
|
2018
|
+
}
|
|
2019
|
+
for (let i = 0;i < a.length; i++) {
|
|
2020
|
+
if (!deepEqual(a[i], b[i])) {
|
|
2021
|
+
return false;
|
|
2022
|
+
}
|
|
2023
|
+
}
|
|
2024
|
+
return true;
|
|
2025
|
+
}
|
|
2026
|
+
function objectsDeepEqual(a, b) {
|
|
2027
|
+
const aKeys = Object.keys(a);
|
|
2028
|
+
if (aKeys.length !== Object.keys(b).length) {
|
|
2029
|
+
return false;
|
|
2030
|
+
}
|
|
2031
|
+
for (const key of aKeys) {
|
|
2032
|
+
if (!(Object.hasOwn(b, key) && deepEqual(a[key], b[key]))) {
|
|
2033
|
+
return false;
|
|
2034
|
+
}
|
|
2035
|
+
}
|
|
2036
|
+
return true;
|
|
2037
|
+
}
|
|
2038
|
+
function deepEqual(a, b) {
|
|
2039
|
+
if (Object.is(a, b)) {
|
|
2040
|
+
return true;
|
|
2041
|
+
}
|
|
2042
|
+
if (Array.isArray(a) && Array.isArray(b)) {
|
|
2043
|
+
return arraysDeepEqual(a, b);
|
|
2044
|
+
}
|
|
2045
|
+
if (isObject2(a) && isObject2(b)) {
|
|
2046
|
+
return objectsDeepEqual(a, b);
|
|
2047
|
+
}
|
|
2048
|
+
return false;
|
|
2049
|
+
}
|
|
2050
|
+
function stripSearchDefaults(search, defaults) {
|
|
2051
|
+
if (!defaults) {
|
|
2052
|
+
return search;
|
|
2053
|
+
}
|
|
2054
|
+
const stripped = {};
|
|
2055
|
+
for (const [key, value] of Object.entries(search)) {
|
|
2056
|
+
if (Object.hasOwn(defaults, key) && deepEqual(value, defaults[key])) {
|
|
2057
|
+
continue;
|
|
2058
|
+
}
|
|
2059
|
+
stripped[key] = value;
|
|
2060
|
+
}
|
|
2061
|
+
return stripped;
|
|
2062
|
+
}
|
|
2063
|
+
function appendSearchParamValue(params, key, value) {
|
|
2064
|
+
if (value == null) {
|
|
2065
|
+
return;
|
|
2066
|
+
}
|
|
2067
|
+
if (Array.isArray(value)) {
|
|
2068
|
+
for (const item of value) {
|
|
2069
|
+
if (item != null) {
|
|
2070
|
+
params.append(key, typeof item === "object" ? JSON.stringify(item) : String(item));
|
|
2071
|
+
}
|
|
2072
|
+
}
|
|
2073
|
+
return;
|
|
2074
|
+
}
|
|
2075
|
+
params.set(key, typeof value === "object" ? JSON.stringify(value) : String(value));
|
|
2076
|
+
}
|
|
2077
|
+
function buildSearchParams(search, defaults) {
|
|
2078
|
+
const params = new URLSearchParams;
|
|
2079
|
+
for (const [key, value] of Object.entries(stripSearchDefaults(search, defaults))) {
|
|
2080
|
+
appendSearchParamValue(params, key, value);
|
|
2081
|
+
}
|
|
2082
|
+
return params;
|
|
2083
|
+
}
|
|
2084
|
+
function collectSearchDefaults(schema) {
|
|
2085
|
+
if (!(isObject2(schema) && isObject2(schema.properties))) {
|
|
2086
|
+
return;
|
|
2087
|
+
}
|
|
2088
|
+
const defaults = {};
|
|
2089
|
+
for (const [key, value] of Object.entries(schema.properties)) {
|
|
2090
|
+
if (isObject2(value) && Object.hasOwn(value, "default") && value.default != null) {
|
|
2091
|
+
defaults[key] = value.default;
|
|
2092
|
+
}
|
|
2093
|
+
}
|
|
2094
|
+
return Object.keys(defaults).length > 0 ? defaults : undefined;
|
|
2095
|
+
}
|
|
2096
|
+
function findSearchDefaults(pathname, routes) {
|
|
2097
|
+
let match;
|
|
2098
|
+
for (const route of routes) {
|
|
2099
|
+
if (!route.regex.test(pathname)) {
|
|
2100
|
+
continue;
|
|
2101
|
+
}
|
|
2102
|
+
if (!match || compareSearchRouteSpecificity(route.pattern, match.pattern) > 0) {
|
|
2103
|
+
match = route;
|
|
2104
|
+
}
|
|
2105
|
+
}
|
|
2106
|
+
return match?.searchDefaults;
|
|
2107
|
+
}
|
|
2108
|
+
function findSearchDefaultsForRouteTarget(to, routes) {
|
|
2109
|
+
if (to.startsWith("http://") || to.startsWith("https://") || to.startsWith("//")) {
|
|
2110
|
+
return;
|
|
2111
|
+
}
|
|
2112
|
+
try {
|
|
2113
|
+
const pathname = new URL(to, "http://furin.local").pathname;
|
|
2114
|
+
return findSearchDefaults(pathname, routes);
|
|
2115
|
+
} catch {
|
|
2116
|
+
return;
|
|
2117
|
+
}
|
|
2118
|
+
}
|
|
2119
|
+
|
|
2120
|
+
// src/server/router/schemas.ts
|
|
2121
|
+
function isObjectSchema(schema) {
|
|
2122
|
+
return !!schema && typeof schema === "object";
|
|
2123
|
+
}
|
|
2124
|
+
var TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
|
|
2125
|
+
var TYPEBOX_KIND = Symbol.for("TypeBox.Kind");
|
|
2126
|
+
function isTypeBoxObjectSchema(schema) {
|
|
2127
|
+
return isObjectSchema(schema) && schema[TYPEBOX_KIND] === "Object";
|
|
2128
|
+
}
|
|
2129
|
+
function mergeRouteSchemas(routeChain, key) {
|
|
2130
|
+
const schemas = routeChain.flatMap((r) => r[key] ? [r[key]] : []);
|
|
2131
|
+
if (schemas.length === 0) {
|
|
2132
|
+
return;
|
|
2133
|
+
}
|
|
2134
|
+
if (schemas.length === 1) {
|
|
2135
|
+
return schemas[0];
|
|
2136
|
+
}
|
|
2137
|
+
if (schemas.some((s) => !isTypeBoxObjectSchema(s))) {
|
|
2138
|
+
throw new Error(`[furin] Merging ${key} schemas across the route chain requires TypeBox in V1. Use TypeBox for parent/child ${key}, or define ${key} only on leaf routes.`);
|
|
2139
|
+
}
|
|
2140
|
+
const mergedProperties = Object.assign({}, ...schemas.map((s) => s.properties ?? {}));
|
|
2141
|
+
const mergedOptions = Object.assign({}, ...schemas.map((s) => Object.fromEntries(Object.entries(s).filter(([k]) => !TOBJECT_STRUCTURAL_KEYS.has(k)))));
|
|
2142
|
+
return t.Object(mergedProperties, mergedOptions);
|
|
2143
|
+
}
|
|
2144
|
+
function createSearchRouteMetadata(routes) {
|
|
2145
|
+
const metadata = [];
|
|
2146
|
+
for (const route of routes) {
|
|
2147
|
+
const searchDefaults = collectSearchDefaults(mergeRouteSchemas(route.routeChain, "query"));
|
|
2148
|
+
if (!searchDefaults) {
|
|
2149
|
+
continue;
|
|
2150
|
+
}
|
|
2151
|
+
metadata.push({
|
|
2152
|
+
pattern: route.pattern,
|
|
2153
|
+
regex: buildRouteRegex(route.pattern).regex,
|
|
2154
|
+
searchDefaults
|
|
2155
|
+
});
|
|
2156
|
+
}
|
|
2157
|
+
return metadata;
|
|
2158
|
+
}
|
|
2159
|
+
// src/build/hydrate.ts
|
|
2160
|
+
function generateHydrateEntry(routes, rootLayout, basePath, clientLogging) {
|
|
2161
|
+
const getBoundaryIdent = (idents, filePath) => {
|
|
2162
|
+
if (!filePath) {
|
|
2163
|
+
return;
|
|
2164
|
+
}
|
|
2165
|
+
const existing = idents.get(filePath);
|
|
2166
|
+
if (existing) {
|
|
2167
|
+
return existing;
|
|
2168
|
+
}
|
|
2169
|
+
const ident = `__furin_bnd_${idents.size}`;
|
|
2170
|
+
idents.set(filePath, ident);
|
|
2171
|
+
return ident;
|
|
2172
|
+
};
|
|
2173
|
+
const routeEntries = [];
|
|
2174
|
+
for (const route of routes) {
|
|
2175
|
+
const resolvedPage = route.path.replace(/\\/g, "/");
|
|
2176
|
+
const regexPattern = buildRouteRegex(route.pattern).regex.source;
|
|
2177
|
+
const searchDefaults = collectSearchDefaults(mergeRouteSchemas(route.routeChain ?? [], "query"));
|
|
2178
|
+
const boundaryIdents = new Map;
|
|
2179
|
+
const boundaryLiterals = [];
|
|
2180
|
+
for (const seg of route.segmentBoundaries ?? []) {
|
|
2181
|
+
const errorIdent = getBoundaryIdent(boundaryIdents, seg.errorPath);
|
|
2182
|
+
const notFoundIdent = getBoundaryIdent(boundaryIdents, seg.notFoundPath);
|
|
2183
|
+
if (!(errorIdent || notFoundIdent)) {
|
|
2184
|
+
continue;
|
|
2185
|
+
}
|
|
2186
|
+
const parts = [`depth: ${seg.depth}`];
|
|
2187
|
+
if (errorIdent) {
|
|
2188
|
+
parts.push(`error: ${errorIdent}.default`);
|
|
2189
|
+
}
|
|
2190
|
+
if (notFoundIdent) {
|
|
2191
|
+
parts.push(`notFound: ${notFoundIdent}.default`);
|
|
2192
|
+
}
|
|
2193
|
+
boundaryLiterals.push(`{ ${parts.join(", ")} }`);
|
|
2194
|
+
}
|
|
2195
|
+
const lazyImports = [
|
|
2196
|
+
`import("${resolvedPage}")`,
|
|
2197
|
+
...[...boundaryIdents.keys()].map((filePath) => `import("${filePath.replace(/\\/g, "/")}")`)
|
|
2198
|
+
];
|
|
2199
|
+
const loadBody = boundaryLiterals.length > 0 ? `Promise.all([${lazyImports.join(", ")}]).then(([__furin_page, ${[
|
|
2200
|
+
...boundaryIdents.values()
|
|
2201
|
+
].join(", ")}]) => ({ default: __furin_page.default, segmentBoundaries: [${boundaryLiterals.join(", ")}] }))` : `import("${resolvedPage}")`;
|
|
2202
|
+
const searchDefaultsEntry = searchDefaults ? `, searchDefaults: ${JSON.stringify(searchDefaults)}` : "";
|
|
2203
|
+
routeEntries.push(` { pattern: "${route.pattern}", regex: new RegExp(${JSON.stringify(regexPattern)}), load: () => ${loadBody}${searchDefaultsEntry} }`);
|
|
2204
|
+
}
|
|
2205
|
+
const basePathLiteral = JSON.stringify(basePath);
|
|
2206
|
+
const pathnameExpr = basePath ? `(() => { const p = window.location.pathname; const b = ${basePathLiteral}; const stripped = (p.startsWith(b) && (p.length === b.length || p[b.length] === "/")) ? p.slice(b.length) || "/" : p; return stripped === "/" ? "/" : stripped.replace(/\\/+$/, ""); })()` : `window.location.pathname.replace(/\\/+$/, "") || "/"`;
|
|
2207
|
+
const logEndpoint = basePath ? `${JSON.stringify(basePath)} + "/_furin/ingest"` : `"/_furin/ingest"`;
|
|
2208
|
+
const loggingImports = clientLogging ? `import { initLogger, log } from "evlog";
|
|
2209
|
+
import { createHttpLogDrain } from "evlog/http";
|
|
2210
|
+
` : "";
|
|
2211
|
+
const loggerSetup = clientLogging ? `initLogger({ drain: createHttpLogDrain({ drain: { endpoint: ${logEndpoint} } }) });` : "const log = { error() {}, info() {} };";
|
|
2212
|
+
const routerProviderDefaults = `
|
|
2213
|
+
autoRefresh: true,
|
|
2214
|
+
basePath: ${basePathLiteral},
|
|
2215
|
+
defaultPreload: "intent",
|
|
2216
|
+
defaultPreloadDelay: 50,
|
|
2217
|
+
defaultPreloadStaleTime: 30000,
|
|
2218
|
+
prefetchCacheSize: 50,
|
|
2219
|
+
syncStream,`;
|
|
2220
|
+
return `import { hydrateRoot, createRoot } from "react-dom/client";
|
|
2221
|
+
import { createElement } from "react";
|
|
2222
|
+
${loggingImports}import { RouterProvider } from "@teyik0/furin/link";
|
|
2223
|
+
import { fromCrossJSON } from "@teyik0/furin/link";
|
|
2224
|
+
import type { SerovalNode } from "seroval";
|
|
2225
|
+
import { route as root } from "${rootLayout.replace(/\\/g, "/")}";
|
|
2226
|
+
|
|
2227
|
+
${loggerSetup}
|
|
2228
|
+
|
|
2229
|
+
const routes = [
|
|
2230
|
+
${routeEntries.join(`,
|
|
2231
|
+
`)}
|
|
2232
|
+
];
|
|
2233
|
+
|
|
2234
|
+
const pathname = ${pathnameExpr};
|
|
2235
|
+
const _match = routes.find((r) => r.regex.test(pathname));
|
|
2236
|
+
|
|
2237
|
+
// Parse the server-embedded loader payload up front. It carries:
|
|
2238
|
+
// - normal loader props under arbitrary keys,
|
|
2239
|
+
// - __furinError.digest when SSR caught an error,
|
|
2240
|
+
// - __furinStatus: 404 when the server rendered the catch-all not-found
|
|
2241
|
+
// (direct load to an unknown URL, emitted by renderRootNotFound) OR when
|
|
2242
|
+
// a matched loader threw notFound(). The latter still has a _match; the
|
|
2243
|
+
// former does not \u2014 so the two cases fork on _match below.
|
|
2244
|
+
const dataEl = document.getElementById("__FURIN_DATA__");
|
|
2245
|
+
const loaderData = dataEl ? JSON.parse(dataEl.textContent || "{}") : {};
|
|
2246
|
+
const syncEl = document.getElementById("__FURIN_SYNC__");
|
|
2247
|
+
const syncConfig = syncEl ? JSON.parse(syncEl.textContent || "{}") : {};
|
|
2248
|
+
const syncStream = typeof syncConfig.stream === "string" ? syncConfig.stream : undefined;
|
|
2249
|
+
|
|
2250
|
+
// \u2500\u2500 Deferred data hydration \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2251
|
+
// window.__FURIN_DEFERRED__ is injected by the server when a loader returns
|
|
2252
|
+
// defer(). It carries:
|
|
2253
|
+
// - _chunks: raw CrossJSON chunks keyed by field name (from late <script> tags)
|
|
2254
|
+
// We deserialise each chunk with fromCrossJSON and create a Promise so <Await>
|
|
2255
|
+
// components receive a proper resolved Promise instead of the raw CrossJSON node.
|
|
2256
|
+
// Sync loader fields live exclusively in __FURIN_DATA__ (read above).
|
|
2257
|
+
interface FurinDeferredRegistry {
|
|
2258
|
+
_chunks: Record<string, { a: 0 | 1; v: SerovalNode }>;
|
|
2259
|
+
_deferredKeys: string[];
|
|
2260
|
+
_resolvers: Record<string, {
|
|
2261
|
+
promise: Promise<unknown>;
|
|
2262
|
+
reject: (reason: unknown) => void;
|
|
2263
|
+
resolve: (value: unknown) => void;
|
|
2264
|
+
}>;
|
|
2265
|
+
getPromise: (key: string) => Promise<unknown>;
|
|
2266
|
+
reject: (key: string, chunk: SerovalNode) => void;
|
|
2267
|
+
resolve: (key: string, chunk: SerovalNode) => void;
|
|
2268
|
+
}
|
|
2269
|
+
const __deferred = (window as unknown as { __FURIN_DEFERRED__?: FurinDeferredRegistry })
|
|
2270
|
+
.__FURIN_DEFERRED__;
|
|
2271
|
+
const deferredData: Record<string, Promise<unknown>> = {};
|
|
2272
|
+
if (__deferred && __deferred._chunks) {
|
|
2273
|
+
// Patch resolve/reject so any chunks that arrive AFTER this entry has run
|
|
2274
|
+
// settle immediately. The previous version stored late chunks in _chunks
|
|
2275
|
+
// when no resolver was registered yet, but the drain loop below only runs
|
|
2276
|
+
// ONCE at hydrate time \u2014 so any chunk landing after the drain would stay
|
|
2277
|
+
// orphaned and the corresponding Await would hang forever. Eagerly creating
|
|
2278
|
+
// the resolver via getPromise() fixes the race.
|
|
2279
|
+
__deferred.resolve = (key: string, chunk: SerovalNode) => {
|
|
2280
|
+
__deferred.getPromise(key);
|
|
2281
|
+
__deferred._resolvers[key].resolve(fromCrossJSON(chunk, {}));
|
|
2282
|
+
};
|
|
2283
|
+
__deferred.reject = (key: string, chunk: SerovalNode) => {
|
|
2284
|
+
__deferred.getPromise(key);
|
|
2285
|
+
__deferred._resolvers[key].reject(fromCrossJSON(chunk, {}));
|
|
2286
|
+
};
|
|
2287
|
+
for (const key of Object.keys(__deferred._chunks)) {
|
|
2288
|
+
const entry = __deferred._chunks[key] as { a: 0 | 1; v: SerovalNode };
|
|
2289
|
+
const p = __deferred.getPromise(key) as Promise<unknown>;
|
|
2290
|
+
const resolver = __deferred._resolvers[key];
|
|
2291
|
+
const value = fromCrossJSON(entry.v, {});
|
|
2292
|
+
if (entry.a === 0) {
|
|
1806
2293
|
resolver.resolve(value);
|
|
1807
2294
|
} else {
|
|
1808
2295
|
resolver.reject(value);
|
|
@@ -1917,23 +2404,25 @@ const rootEl = document.getElementById("root") as HTMLElement;
|
|
|
1917
2404
|
}
|
|
1918
2405
|
|
|
1919
2406
|
// src/build/shared.ts
|
|
1920
|
-
import { cpSync, existsSync, mkdirSync, readdirSync, rmSync } from "fs";
|
|
1921
|
-
import { join, relative } from "path";
|
|
1922
|
-
|
|
1923
|
-
var
|
|
2407
|
+
import { cpSync, existsSync as existsSync2, mkdirSync, readdirSync, rmSync } from "fs";
|
|
2408
|
+
import { join as join2, relative } from "path";
|
|
2409
|
+
import { fileURLToPath } from "url";
|
|
2410
|
+
var CLIENT_MODULE_PATH = fileURLToPath(import.meta.resolve("@teyik0/furin/client"));
|
|
2411
|
+
var LINK_MODULE_PATH = fileURLToPath(import.meta.resolve("@teyik0/furin/link"));
|
|
2412
|
+
var SEARCH_MODULE_PATH = fileURLToPath(import.meta.resolve("@teyik0/furin/search"));
|
|
1924
2413
|
function ensureDir(path) {
|
|
1925
|
-
if (!
|
|
2414
|
+
if (!existsSync2(path)) {
|
|
1926
2415
|
mkdirSync(path, { recursive: true });
|
|
1927
2416
|
}
|
|
1928
2417
|
}
|
|
1929
|
-
function
|
|
2418
|
+
function toPosixPath2(path) {
|
|
1930
2419
|
return path.replace(/\\/g, "/");
|
|
1931
2420
|
}
|
|
1932
2421
|
function collectFilesRecursive(dir) {
|
|
1933
2422
|
const files = [];
|
|
1934
2423
|
const entries = readdirSync(dir, { withFileTypes: true });
|
|
1935
2424
|
for (const entry of entries) {
|
|
1936
|
-
const absolutePath =
|
|
2425
|
+
const absolutePath = join2(dir, entry.name);
|
|
1937
2426
|
if (entry.isDirectory()) {
|
|
1938
2427
|
files.push(...collectFilesRecursive(absolutePath));
|
|
1939
2428
|
continue;
|
|
@@ -1952,37 +2441,37 @@ function toBuildRouteManifestEntry(route, rootDir) {
|
|
|
1952
2441
|
return {
|
|
1953
2442
|
pattern: route.pattern,
|
|
1954
2443
|
mode: route.mode,
|
|
1955
|
-
pagePath:
|
|
2444
|
+
pagePath: toPosixPath2(relative(rootDir, route.path)),
|
|
1956
2445
|
hasLayout: route.routeChain.some((entry) => !!entry.layout),
|
|
1957
2446
|
hasStaticParams: !!route.page?.staticParams,
|
|
1958
2447
|
revalidate: route.page?._route.revalidate ?? null
|
|
1959
2448
|
};
|
|
1960
2449
|
}
|
|
1961
2450
|
function buildTargetManifest(rootDir, buildRoot, target, serverEntry) {
|
|
1962
|
-
const targetDir =
|
|
2451
|
+
const targetDir = join2(buildRoot, target);
|
|
1963
2452
|
return {
|
|
1964
2453
|
buildId: "",
|
|
1965
2454
|
generatedAt: new Date().toISOString(),
|
|
1966
|
-
targetDir:
|
|
1967
|
-
clientDir:
|
|
1968
|
-
templatePath:
|
|
2455
|
+
targetDir: toPosixPath2(relative(rootDir, targetDir)),
|
|
2456
|
+
clientDir: toPosixPath2(relative(rootDir, join2(targetDir, "client"))),
|
|
2457
|
+
templatePath: toPosixPath2(relative(rootDir, join2(targetDir, "client", "index.html"))),
|
|
1969
2458
|
serverPath: null,
|
|
1970
|
-
serverEntry: serverEntry ?
|
|
2459
|
+
serverEntry: serverEntry ? toPosixPath2(relative(rootDir, serverEntry)) : null
|
|
1971
2460
|
};
|
|
1972
2461
|
}
|
|
1973
2462
|
|
|
1974
2463
|
// src/build/client.ts
|
|
1975
2464
|
var TS_FILE_FILTER = /\.(tsx|ts)$/;
|
|
1976
2465
|
async function buildClient(routes, { outDir, rootLayout, plugins, publicPath, basePath, clientLogging }) {
|
|
1977
|
-
const clientDir =
|
|
1978
|
-
if (!
|
|
2466
|
+
const clientDir = join3(outDir, "client");
|
|
2467
|
+
if (!existsSync3(outDir)) {
|
|
1979
2468
|
mkdirSync2(outDir, { recursive: true });
|
|
1980
2469
|
}
|
|
1981
|
-
if (!
|
|
2470
|
+
if (!existsSync3(clientDir)) {
|
|
1982
2471
|
mkdirSync2(clientDir, { recursive: true });
|
|
1983
2472
|
}
|
|
1984
2473
|
const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging);
|
|
1985
|
-
const hydratePath =
|
|
2474
|
+
const hydratePath = join3(outDir, "_hydrate.tsx");
|
|
1986
2475
|
writeFileSync(hydratePath, hydrateCode);
|
|
1987
2476
|
console.log("[furin] Building production client bundle\u2026");
|
|
1988
2477
|
const transformPlugin = {
|
|
@@ -1996,7 +2485,7 @@ async function buildClient(routes, { outDir, rootLayout, plugins, publicPath, ba
|
|
|
1996
2485
|
const code = await Bun.file(path).text();
|
|
1997
2486
|
try {
|
|
1998
2487
|
const result2 = transformForClient(code, path);
|
|
1999
|
-
const transformed = result2.code.replaceAll(`"@teyik0/furin/client"`, JSON.stringify(CLIENT_MODULE_PATH)).replaceAll(`'furin/client'`, JSON.stringify(CLIENT_MODULE_PATH)).replaceAll(`"@teyik0/furin/link"`, JSON.stringify(LINK_MODULE_PATH)).replaceAll(`'furin/link'`, JSON.stringify(LINK_MODULE_PATH));
|
|
2488
|
+
const transformed = result2.code.replaceAll(`"@teyik0/furin/client"`, JSON.stringify(CLIENT_MODULE_PATH)).replaceAll(`'furin/client'`, JSON.stringify(CLIENT_MODULE_PATH)).replaceAll(`"@teyik0/furin/link"`, JSON.stringify(LINK_MODULE_PATH)).replaceAll(`'furin/link'`, JSON.stringify(LINK_MODULE_PATH)).replaceAll(`"@teyik0/furin/search"`, JSON.stringify(SEARCH_MODULE_PATH)).replaceAll(`'furin/search'`, JSON.stringify(SEARCH_MODULE_PATH));
|
|
2000
2489
|
return {
|
|
2001
2490
|
contents: transformed,
|
|
2002
2491
|
loader: path.endsWith(".tsx") ? "tsx" : "ts"
|
|
@@ -2024,7 +2513,8 @@ async function buildClient(routes, { outDir, rootLayout, plugins, publicPath, ba
|
|
|
2024
2513
|
plugins: plugins ? [...plugins, transformPlugin] : [transformPlugin],
|
|
2025
2514
|
alias: {
|
|
2026
2515
|
"@teyik0/furin/client": CLIENT_MODULE_PATH,
|
|
2027
|
-
"@teyik0/furin/link": LINK_MODULE_PATH
|
|
2516
|
+
"@teyik0/furin/link": LINK_MODULE_PATH,
|
|
2517
|
+
"@teyik0/furin/search": SEARCH_MODULE_PATH
|
|
2028
2518
|
},
|
|
2029
2519
|
define: {
|
|
2030
2520
|
"process.env.NODE_ENV": JSON.stringify("production")
|
|
@@ -2052,15 +2542,15 @@ async function buildClient(routes, { outDir, rootLayout, plugins, publicPath, ba
|
|
|
2052
2542
|
}
|
|
2053
2543
|
|
|
2054
2544
|
// src/build/compile-entry.ts
|
|
2055
|
-
import { existsSync as
|
|
2056
|
-
import { join as
|
|
2545
|
+
import { existsSync as existsSync5, writeFileSync as writeFileSync2 } from "fs";
|
|
2546
|
+
import { join as join5, relative as relative2 } from "path";
|
|
2057
2547
|
|
|
2058
2548
|
// src/build/entry-template.ts
|
|
2059
|
-
import { existsSync as
|
|
2060
|
-
import { dirname, join as
|
|
2061
|
-
import { fileURLToPath } from "url";
|
|
2062
|
-
var _pkgRoot = dirname(dirname(
|
|
2063
|
-
var _pkgSrcDirRaw =
|
|
2549
|
+
import { existsSync as existsSync4 } from "fs";
|
|
2550
|
+
import { dirname, join as join4 } from "path";
|
|
2551
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
2552
|
+
var _pkgRoot = dirname(dirname(fileURLToPath2(import.meta.resolve("@teyik0/furin"))));
|
|
2553
|
+
var _pkgSrcDirRaw = existsSync4(join4(_pkgRoot, "src", "furin.ts")) ? join4(_pkgRoot, "src") : join4(_pkgRoot, "dist");
|
|
2064
2554
|
var _pkgSrcDir = _pkgSrcDirRaw.replace(/\\/g, "/");
|
|
2065
2555
|
var _ext = _pkgSrcDir.endsWith("/src") ? ".ts" : ".js";
|
|
2066
2556
|
var INTERNAL_MODULE_PATH = `${_pkgSrcDir}/server/internal${_ext}`;
|
|
@@ -2173,7 +2663,7 @@ function generateCompileEntry(options) {
|
|
|
2173
2663
|
const assetImports = [];
|
|
2174
2664
|
let embeddedBlock = [];
|
|
2175
2665
|
if (embed) {
|
|
2176
|
-
if (!
|
|
2666
|
+
if (!existsSync5(embed.clientDir)) {
|
|
2177
2667
|
throw new Error(`[furin] Client directory not found: ${embed.clientDir}. Run the client build first.`);
|
|
2178
2668
|
}
|
|
2179
2669
|
const clientFiles = collectFilesRecursive(embed.clientDir).filter((file) => !file.endsWith(".map"));
|
|
@@ -2182,10 +2672,10 @@ function generateCompileEntry(options) {
|
|
|
2182
2672
|
let assetIndex = 0;
|
|
2183
2673
|
for (const file of clientFiles) {
|
|
2184
2674
|
const varName = `_asset${assetIndex++}`;
|
|
2185
|
-
const relPath =
|
|
2675
|
+
const relPath = toPosixPath2(relative2(outDir, file));
|
|
2186
2676
|
const importPath = relPath.startsWith(".") ? relPath : `./${relPath}`;
|
|
2187
2677
|
assetImports.push(`import ${varName} from ${JSON.stringify(importPath)} with { type: "file" };`);
|
|
2188
|
-
const clientRelativePath =
|
|
2678
|
+
const clientRelativePath = toPosixPath2(relative2(embed.clientDir, file));
|
|
2189
2679
|
if (clientRelativePath === "index.html") {
|
|
2190
2680
|
templateVarName = varName;
|
|
2191
2681
|
} else {
|
|
@@ -2193,16 +2683,16 @@ function generateCompileEntry(options) {
|
|
|
2193
2683
|
}
|
|
2194
2684
|
}
|
|
2195
2685
|
if (templateVarName === null) {
|
|
2196
|
-
throw new Error(`[furin] Embed mode requires a client index.html at ${
|
|
2686
|
+
throw new Error(`[furin] Embed mode requires a client index.html at ${join5(embed.clientDir, "index.html")}. Run the client build first.`);
|
|
2197
2687
|
}
|
|
2198
|
-
if (publicDir &&
|
|
2688
|
+
if (publicDir && existsSync5(publicDir)) {
|
|
2199
2689
|
const publicFiles = collectFilesRecursive(publicDir);
|
|
2200
2690
|
for (const file of publicFiles) {
|
|
2201
2691
|
const varName = `_asset${assetIndex++}`;
|
|
2202
|
-
const relPath =
|
|
2692
|
+
const relPath = toPosixPath2(relative2(outDir, file));
|
|
2203
2693
|
const importPath = relPath.startsWith(".") ? relPath : `./${relPath}`;
|
|
2204
2694
|
assetImports.push(`import ${varName} from ${JSON.stringify(importPath)} with { type: "file" };`);
|
|
2205
|
-
const publicRelativePath =
|
|
2695
|
+
const publicRelativePath = toPosixPath2(relative2(publicDir, file));
|
|
2206
2696
|
assetEntries.push(` ${JSON.stringify(`/public/${publicRelativePath}`)}: ${varName},`);
|
|
2207
2697
|
}
|
|
2208
2698
|
}
|
|
@@ -2215,102 +2705,43 @@ function generateCompileEntry(options) {
|
|
|
2215
2705
|
" },"
|
|
2216
2706
|
];
|
|
2217
2707
|
}
|
|
2218
|
-
const source = buildEntrySource({
|
|
2219
|
-
buildId,
|
|
2220
|
-
headerComment: "// Auto-generated by furin compile \u2014 do not edit",
|
|
2221
|
-
rootPath,
|
|
2222
|
-
routes,
|
|
2223
|
-
serverEntry,
|
|
2224
|
-
extraImports: assetImports,
|
|
2225
|
-
extraContext: embeddedBlock,
|
|
2226
|
-
rootConventions,
|
|
2227
|
-
routeMetadata,
|
|
2228
|
-
ssgCache
|
|
2229
|
-
});
|
|
2230
|
-
const entryPath =
|
|
2231
|
-
writeFileSync2(entryPath, source);
|
|
2232
|
-
return entryPath;
|
|
2233
|
-
}
|
|
2234
|
-
|
|
2235
|
-
// src/build/server-routes-entry.ts
|
|
2236
|
-
import { writeFileSync as writeFileSync3 } from "fs";
|
|
2237
|
-
import { join as join5 } from "path";
|
|
2238
|
-
function generateServerRoutesEntry(options) {
|
|
2239
|
-
const { buildId, outDir, rootPath, routes, serverEntry, rootConventions, routeMetadata, ssgCache } = options;
|
|
2240
|
-
ensureDir(outDir);
|
|
2241
|
-
const source = buildEntrySource({
|
|
2242
|
-
buildId,
|
|
2243
|
-
headerComment: "// Auto-generated by furin build \u2014 do not edit",
|
|
2244
|
-
rootPath,
|
|
2245
|
-
routes,
|
|
2246
|
-
serverEntry,
|
|
2247
|
-
rootConventions,
|
|
2248
|
-
routeMetadata,
|
|
2249
|
-
ssgCache
|
|
2250
|
-
});
|
|
2251
|
-
const entryPath = join5(outDir, "server.ts");
|
|
2252
|
-
writeFileSync3(entryPath, source);
|
|
2253
|
-
return entryPath;
|
|
2254
|
-
}
|
|
2255
|
-
// src/shared/utils/index.ts
|
|
2256
|
-
function isFurinPage(value) {
|
|
2257
|
-
return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_PAGE";
|
|
2258
|
-
}
|
|
2259
|
-
function isFurinRoute(value) {
|
|
2260
|
-
return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_ROUTE";
|
|
2261
|
-
}
|
|
2262
|
-
function collectRouteChainFromRoute(route) {
|
|
2263
|
-
const chain = [];
|
|
2264
|
-
let current = route;
|
|
2265
|
-
while (current) {
|
|
2266
|
-
chain.unshift(current);
|
|
2267
|
-
current = current.parent;
|
|
2268
|
-
}
|
|
2269
|
-
return chain;
|
|
2270
|
-
}
|
|
2271
|
-
function hasCycle(route) {
|
|
2272
|
-
const visited = new Set;
|
|
2273
|
-
let current = route;
|
|
2274
|
-
while (current) {
|
|
2275
|
-
if (visited.has(current)) {
|
|
2276
|
-
return true;
|
|
2277
|
-
}
|
|
2278
|
-
visited.add(current);
|
|
2279
|
-
current = current.parent;
|
|
2280
|
-
}
|
|
2281
|
-
return false;
|
|
2282
|
-
}
|
|
2283
|
-
async function mapWithConcurrency(items, concurrency, fn) {
|
|
2284
|
-
if (items.length === 0) {
|
|
2285
|
-
return [];
|
|
2286
|
-
}
|
|
2287
|
-
const results = new Array(items.length);
|
|
2288
|
-
let cursor = 0;
|
|
2289
|
-
const workerCount = Math.min(Math.max(concurrency, 1), items.length);
|
|
2290
|
-
await Promise.all(Array.from({ length: workerCount }, async () => {
|
|
2291
|
-
while (true) {
|
|
2292
|
-
const index = cursor++;
|
|
2293
|
-
if (index >= items.length) {
|
|
2294
|
-
return;
|
|
2295
|
-
}
|
|
2296
|
-
results[index] = await fn(items[index], index);
|
|
2297
|
-
}
|
|
2298
|
-
}));
|
|
2299
|
-
return results;
|
|
2300
|
-
}
|
|
2301
|
-
function validateRouteChain(chain, root, pagePath) {
|
|
2302
|
-
const hasRoot = chain.some((r) => r === root);
|
|
2303
|
-
if (!hasRoot) {
|
|
2304
|
-
const location = pagePath ? `in ${pagePath}` : "";
|
|
2305
|
-
throw new Error(`[furin] Page ${location} must inherit from root route. ` + 'Add: import { route } from "./root"; and use route.page() or set parent: route');
|
|
2306
|
-
}
|
|
2307
|
-
for (const route of chain) {
|
|
2308
|
-
if (hasCycle(route)) {
|
|
2309
|
-
throw new Error("[furin] Cycle detected in route chain. A route cannot be its own ancestor.");
|
|
2310
|
-
}
|
|
2311
|
-
}
|
|
2708
|
+
const source = buildEntrySource({
|
|
2709
|
+
buildId,
|
|
2710
|
+
headerComment: "// Auto-generated by furin compile \u2014 do not edit",
|
|
2711
|
+
rootPath,
|
|
2712
|
+
routes,
|
|
2713
|
+
serverEntry,
|
|
2714
|
+
extraImports: assetImports,
|
|
2715
|
+
extraContext: embeddedBlock,
|
|
2716
|
+
rootConventions,
|
|
2717
|
+
routeMetadata,
|
|
2718
|
+
ssgCache
|
|
2719
|
+
});
|
|
2720
|
+
const entryPath = join5(outDir, "_compile-entry.ts");
|
|
2721
|
+
writeFileSync2(entryPath, source);
|
|
2722
|
+
return entryPath;
|
|
2312
2723
|
}
|
|
2313
2724
|
|
|
2725
|
+
// src/build/server-routes-entry.ts
|
|
2726
|
+
import { writeFileSync as writeFileSync3 } from "fs";
|
|
2727
|
+
import { join as join6 } from "path";
|
|
2728
|
+
function generateServerRoutesEntry(options) {
|
|
2729
|
+
const { buildId, outDir, rootPath, routes, serverEntry, rootConventions, routeMetadata, ssgCache } = options;
|
|
2730
|
+
ensureDir(outDir);
|
|
2731
|
+
const source = buildEntrySource({
|
|
2732
|
+
buildId,
|
|
2733
|
+
headerComment: "// Auto-generated by furin build \u2014 do not edit",
|
|
2734
|
+
rootPath,
|
|
2735
|
+
routes,
|
|
2736
|
+
serverEntry,
|
|
2737
|
+
rootConventions,
|
|
2738
|
+
routeMetadata,
|
|
2739
|
+
ssgCache
|
|
2740
|
+
});
|
|
2741
|
+
const entryPath = join6(outDir, "server.ts");
|
|
2742
|
+
writeFileSync3(entryPath, source);
|
|
2743
|
+
return entryPath;
|
|
2744
|
+
}
|
|
2314
2745
|
// src/server/auto-invalidate/registry.ts
|
|
2315
2746
|
class AutoInvalidateRegistry {
|
|
2316
2747
|
pathToTags = new Map;
|
|
@@ -2480,13 +2911,15 @@ function setSSGCache(key, entry) {
|
|
|
2480
2911
|
|
|
2481
2912
|
// src/server/context-logger.ts
|
|
2482
2913
|
import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
|
|
2483
|
-
|
|
2484
|
-
// ../../node_modules/.bun/evlog@2.18.1+21e9b0bb4450b609/node_modules/evlog/dist/utils.mjs
|
|
2914
|
+
// ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/utils.mjs
|
|
2485
2915
|
function formatDuration(ms) {
|
|
2486
2916
|
if (ms < 1000)
|
|
2487
2917
|
return `${Math.round(ms)}ms`;
|
|
2488
2918
|
return `${(ms / 1000).toFixed(2)}s`;
|
|
2489
2919
|
}
|
|
2920
|
+
function isServer() {
|
|
2921
|
+
return typeof window === "undefined";
|
|
2922
|
+
}
|
|
2490
2923
|
function isBrowser() {
|
|
2491
2924
|
if (typeof window === "undefined")
|
|
2492
2925
|
return false;
|
|
@@ -2577,25 +3010,468 @@ var SENSITIVE_HEADERS = [
|
|
|
2577
3010
|
"x-auth-token",
|
|
2578
3011
|
"proxy-authorization"
|
|
2579
3012
|
];
|
|
3013
|
+
var SENSITIVE_HEADER_SET = new Set(SENSITIVE_HEADERS);
|
|
2580
3014
|
function filterSafeHeaders(headers) {
|
|
2581
3015
|
const safeHeaders = {};
|
|
2582
3016
|
for (const [key, value] of Object.entries(headers))
|
|
2583
|
-
if (value !== undefined && !
|
|
3017
|
+
if (value !== undefined && !SENSITIVE_HEADER_SET.has(key.toLowerCase()))
|
|
2584
3018
|
safeHeaders[key] = value;
|
|
2585
3019
|
return safeHeaders;
|
|
2586
3020
|
}
|
|
2587
3021
|
var patternCache = /* @__PURE__ */ new Map;
|
|
2588
|
-
function
|
|
2589
|
-
|
|
3022
|
+
function globToRegExp(pattern, separator = "/") {
|
|
3023
|
+
const cacheKey = `${separator}:${pattern}`;
|
|
3024
|
+
let regex = patternCache.get(cacheKey);
|
|
2590
3025
|
if (!regex) {
|
|
2591
|
-
const
|
|
3026
|
+
const segment = separator === "/" ? "[^/]*" : "[^.]*";
|
|
3027
|
+
const char = separator === "/" ? "[^/]" : "[^.]";
|
|
3028
|
+
const regexPattern = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "{{GLOBSTAR}}").replace(/\*/g, segment).replace(/{{GLOBSTAR}}/g, ".*").replace(/\?/g, char);
|
|
2592
3029
|
regex = new RegExp(`^${regexPattern}$`);
|
|
2593
|
-
patternCache.set(
|
|
3030
|
+
patternCache.set(cacheKey, regex);
|
|
3031
|
+
}
|
|
3032
|
+
return regex;
|
|
3033
|
+
}
|
|
3034
|
+
function matchesPattern(path, pattern) {
|
|
3035
|
+
return globToRegExp(pattern, "/").test(path);
|
|
3036
|
+
}
|
|
3037
|
+
|
|
3038
|
+
// ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/pretty-error-THg0U0w9.mjs
|
|
3039
|
+
var snippetReader = null;
|
|
3040
|
+
var PRETTY_ERROR_TREE_SPACER = "__EVLOG_TREE_SPACER__";
|
|
3041
|
+
function pushTreeSpacer(children) {
|
|
3042
|
+
children.push(PRETTY_ERROR_TREE_SPACER);
|
|
3043
|
+
}
|
|
3044
|
+
var SKIP_PATH_RE = /(?:^|[/\\])(?:node_modules|\.nuxt|\.next|\.output)(?:[/\\]|$)/;
|
|
3045
|
+
var SKIP_FRAME_PATH_RE = /(?:^|[/\\])(?:packages[/\\]evlog|evlog[/\\](?:dist|src))(?:[/\\]|$)/;
|
|
3046
|
+
var SKIP_FRAME_FN_RE = /^(?:createError|EvlogError|new EvlogError)$/;
|
|
3047
|
+
function isPlainObject(val) {
|
|
3048
|
+
return val !== null && typeof val === "object" && !Array.isArray(val);
|
|
3049
|
+
}
|
|
3050
|
+
function pickString(obj, key) {
|
|
3051
|
+
const val = obj[key];
|
|
3052
|
+
return typeof val === "string" && val.length > 0 ? val : undefined;
|
|
3053
|
+
}
|
|
3054
|
+
function pickNumber(obj, key) {
|
|
3055
|
+
const val = obj[key];
|
|
3056
|
+
return typeof val === "number" ? val : undefined;
|
|
3057
|
+
}
|
|
3058
|
+
function extractGuidance(data) {
|
|
3059
|
+
return {
|
|
3060
|
+
code: pickString(data, "code"),
|
|
3061
|
+
why: pickString(data, "why"),
|
|
3062
|
+
fix: pickString(data, "fix"),
|
|
3063
|
+
link: pickString(data, "link")
|
|
3064
|
+
};
|
|
3065
|
+
}
|
|
3066
|
+
function normalizeErrorContext(error) {
|
|
3067
|
+
if (error === null || error === undefined)
|
|
3068
|
+
return null;
|
|
3069
|
+
if (typeof error === "string")
|
|
3070
|
+
return { message: error };
|
|
3071
|
+
if (!isPlainObject(error))
|
|
3072
|
+
return { message: String(error) };
|
|
3073
|
+
const result = {
|
|
3074
|
+
message: pickString(error, "message") ?? pickString(error, "statusText") ?? pickString(error, "statusMessage") ?? "Unknown error",
|
|
3075
|
+
name: pickString(error, "name"),
|
|
3076
|
+
code: pickString(error, "code"),
|
|
3077
|
+
why: pickString(error, "why"),
|
|
3078
|
+
fix: pickString(error, "fix"),
|
|
3079
|
+
link: pickString(error, "link"),
|
|
3080
|
+
status: pickNumber(error, "status") ?? pickNumber(error, "statusCode"),
|
|
3081
|
+
stack: pickString(error, "stack")
|
|
3082
|
+
};
|
|
3083
|
+
const { data, cause } = error;
|
|
3084
|
+
if (isPlainObject(data)) {
|
|
3085
|
+
const guidance = extractGuidance(data);
|
|
3086
|
+
if (!result.code)
|
|
3087
|
+
result.code = guidance.code;
|
|
3088
|
+
if (!result.why)
|
|
3089
|
+
result.why = guidance.why;
|
|
3090
|
+
if (!result.fix)
|
|
3091
|
+
result.fix = guidance.fix;
|
|
3092
|
+
if (!result.link)
|
|
3093
|
+
result.link = guidance.link;
|
|
3094
|
+
}
|
|
3095
|
+
if (cause instanceof Error)
|
|
3096
|
+
result.cause = cause.message;
|
|
3097
|
+
else if (isPlainObject(cause) && pickString(cause, "message"))
|
|
3098
|
+
result.cause = pickString(cause, "message");
|
|
3099
|
+
return result;
|
|
3100
|
+
}
|
|
3101
|
+
function decodeFileUrl(file) {
|
|
3102
|
+
if (file.startsWith("file://"))
|
|
3103
|
+
try {
|
|
3104
|
+
return decodeURIComponent(new URL(file).pathname);
|
|
3105
|
+
} catch {
|
|
3106
|
+
return file.slice(7);
|
|
3107
|
+
}
|
|
3108
|
+
return file;
|
|
3109
|
+
}
|
|
3110
|
+
function isAppPath(file) {
|
|
3111
|
+
const normalized = decodeFileUrl(file).replace(/\\/g, "/");
|
|
3112
|
+
if (normalized.startsWith("node:"))
|
|
3113
|
+
return false;
|
|
3114
|
+
if (SKIP_PATH_RE.test(normalized))
|
|
3115
|
+
return false;
|
|
3116
|
+
if (normalized.includes("/node_modules/"))
|
|
3117
|
+
return false;
|
|
3118
|
+
if (isFrameworkRuntimePath(normalized))
|
|
3119
|
+
return false;
|
|
3120
|
+
return true;
|
|
3121
|
+
}
|
|
3122
|
+
function formatDisplayPath(file, cwd) {
|
|
3123
|
+
const decoded = decodeFileUrl(file).replace(/\\/g, "/");
|
|
3124
|
+
const cwdNorm = cwd.replace(/\\/g, "/").replace(/\/$/, "");
|
|
3125
|
+
if (cwdNorm && decoded.startsWith(`${cwdNorm}/`)) {
|
|
3126
|
+
const rel = decoded.slice(cwdNorm.length + 1);
|
|
3127
|
+
return rel.startsWith("./") ? rel.slice(2) : rel;
|
|
3128
|
+
}
|
|
3129
|
+
const serverIdx = decoded.indexOf("/server/");
|
|
3130
|
+
if (serverIdx >= 0)
|
|
3131
|
+
return decoded.slice(serverIdx + 1);
|
|
3132
|
+
const srcIdx = decoded.indexOf("/src/");
|
|
3133
|
+
if (srcIdx >= 0)
|
|
3134
|
+
return decoded.slice(srcIdx + 1);
|
|
3135
|
+
return decoded;
|
|
3136
|
+
}
|
|
3137
|
+
function compactStackForStorage(stack, maxFrames = 5) {
|
|
3138
|
+
if (!stack)
|
|
3139
|
+
return;
|
|
3140
|
+
const head = stack.split(`
|
|
3141
|
+
`)[0] ?? "";
|
|
3142
|
+
const useful = parseStackFrames(stack).filter((f) => f.file && f.line && f.isApp && !isInternalErrorFrame(f)).slice(0, maxFrames);
|
|
3143
|
+
if (useful.length === 0)
|
|
3144
|
+
return stack;
|
|
3145
|
+
return [head, ...useful.map((f) => f.raw)].join(`
|
|
3146
|
+
`);
|
|
3147
|
+
}
|
|
3148
|
+
function parseStackFrames(stack) {
|
|
3149
|
+
if (!stack)
|
|
3150
|
+
return [];
|
|
3151
|
+
const lines = stack.split(`
|
|
3152
|
+
`);
|
|
3153
|
+
const frames = [];
|
|
3154
|
+
for (const line of lines) {
|
|
3155
|
+
const trimmed = line.trim();
|
|
3156
|
+
if (!trimmed.startsWith("at "))
|
|
3157
|
+
continue;
|
|
3158
|
+
const withFn = trimmed.match(/^at (.+?) \((.+):(\d+):(\d+)\)$/);
|
|
3159
|
+
if (withFn) {
|
|
3160
|
+
const [, fn, file, lineStr, colStr] = withFn;
|
|
3161
|
+
frames.push({
|
|
3162
|
+
raw: trimmed,
|
|
3163
|
+
fn,
|
|
3164
|
+
file,
|
|
3165
|
+
line: Number(lineStr),
|
|
3166
|
+
column: Number(colStr),
|
|
3167
|
+
isApp: isAppPath(file)
|
|
3168
|
+
});
|
|
3169
|
+
continue;
|
|
3170
|
+
}
|
|
3171
|
+
const withoutFn = trimmed.match(/^at (.+):(\d+):(\d+)$/);
|
|
3172
|
+
if (withoutFn) {
|
|
3173
|
+
const [, file, lineStr, colStr] = withoutFn;
|
|
3174
|
+
frames.push({
|
|
3175
|
+
raw: trimmed,
|
|
3176
|
+
file,
|
|
3177
|
+
line: Number(lineStr),
|
|
3178
|
+
column: Number(colStr),
|
|
3179
|
+
isApp: isAppPath(file)
|
|
3180
|
+
});
|
|
3181
|
+
continue;
|
|
3182
|
+
}
|
|
3183
|
+
const asyncFn = trimmed.match(/^at async (.+?) \((.+):(\d+):(\d+)\)$/);
|
|
3184
|
+
if (asyncFn) {
|
|
3185
|
+
const [, fn, file, lineStr, colStr] = asyncFn;
|
|
3186
|
+
frames.push({
|
|
3187
|
+
raw: trimmed,
|
|
3188
|
+
fn: `async ${fn}`,
|
|
3189
|
+
file,
|
|
3190
|
+
line: Number(lineStr),
|
|
3191
|
+
column: Number(colStr),
|
|
3192
|
+
isApp: isAppPath(file)
|
|
3193
|
+
});
|
|
3194
|
+
}
|
|
3195
|
+
}
|
|
3196
|
+
return frames;
|
|
3197
|
+
}
|
|
3198
|
+
function isFrameworkRuntimePath(path) {
|
|
3199
|
+
const normalized = path.replace(/\\/g, "/");
|
|
3200
|
+
return normalized.includes("route-modules/") || normalized.includes("webpack://next/") || normalized.includes("/next/dist/") || normalized.includes("/compiled/next-server/");
|
|
3201
|
+
}
|
|
3202
|
+
function isFrameworkRuntimeFrame(frame) {
|
|
3203
|
+
if (!frame.file)
|
|
3204
|
+
return false;
|
|
3205
|
+
return isFrameworkRuntimePath(decodeFileUrl(frame.file));
|
|
3206
|
+
}
|
|
3207
|
+
function isInternalErrorFrame(frame) {
|
|
3208
|
+
if (isFrameworkRuntimeFrame(frame))
|
|
3209
|
+
return true;
|
|
3210
|
+
if (frame.fn) {
|
|
3211
|
+
const fn = frame.fn.replace(/^async /, "");
|
|
3212
|
+
if (SKIP_FRAME_FN_RE.test(fn))
|
|
3213
|
+
return true;
|
|
3214
|
+
}
|
|
3215
|
+
if (!frame.file)
|
|
3216
|
+
return true;
|
|
3217
|
+
const path = decodeFileUrl(frame.file).replace(/\\/g, "/");
|
|
3218
|
+
if (SKIP_FRAME_PATH_RE.test(path))
|
|
3219
|
+
return true;
|
|
3220
|
+
if (path.includes(".nuxt/"))
|
|
3221
|
+
return true;
|
|
3222
|
+
if (path.includes(".next/"))
|
|
3223
|
+
return true;
|
|
3224
|
+
return false;
|
|
3225
|
+
}
|
|
3226
|
+
function pickPrimaryFrame(frames) {
|
|
3227
|
+
for (const frame of frames)
|
|
3228
|
+
if (frame.isApp && frame.file && frame.line && !isInternalErrorFrame(frame))
|
|
3229
|
+
return frame;
|
|
3230
|
+
}
|
|
3231
|
+
function readCodeSnippet(file, line, contextLines = 2) {
|
|
3232
|
+
if (!isDev() || isBrowser() || !snippetReader)
|
|
3233
|
+
return null;
|
|
3234
|
+
const path = decodeFileUrl(file).replace(/\\/g, "/");
|
|
3235
|
+
if (path.includes(".next/") || path.includes(".nuxt/") || path.includes(".output/"))
|
|
3236
|
+
return null;
|
|
3237
|
+
return snippetReader(file, line, contextLines);
|
|
3238
|
+
}
|
|
3239
|
+
function formatSnippetLines(snippet) {
|
|
3240
|
+
const width = String(snippet[snippet.length - 1]?.line ?? 0).length;
|
|
3241
|
+
return snippet.map(({ line, content, isErrorLine }) => {
|
|
3242
|
+
const marker = isErrorLine ? `${colors.red}\u276F${colors.reset}` : `${colors.dim} ${colors.reset}`;
|
|
3243
|
+
const numColor = isErrorLine ? colors.red : colors.gray;
|
|
3244
|
+
const trimmed = content.length > 120 ? `${content.slice(0, 117)}\u2026` : content;
|
|
3245
|
+
return `${marker} ${numColor}${String(line).padStart(width, " ")}${colors.reset} ${colors.dim}\u2503${colors.reset} ${colors.dim}${trimmed}${colors.reset}`;
|
|
3246
|
+
});
|
|
3247
|
+
}
|
|
3248
|
+
function formatFrameLocation(frame, cwd) {
|
|
3249
|
+
const file = frame.file ? formatDisplayPath(frame.file, cwd) : "unknown";
|
|
3250
|
+
const loc = frame.line ? `${file}:${frame.line}` : file;
|
|
3251
|
+
const fn = frame.fn && frame.fn !== "<unknown>" ? frame.fn : undefined;
|
|
3252
|
+
return fn ? `at ${fn} (${loc})` : `at ${loc}`;
|
|
3253
|
+
}
|
|
3254
|
+
function formatCollapsedFrame(frame, cwd) {
|
|
3255
|
+
const file = frame.file ? formatDisplayPath(frame.file, cwd) : "unknown";
|
|
3256
|
+
const loc = frame.line ? `${file}:${frame.line}` : file;
|
|
3257
|
+
const prefix = frame.fn?.startsWith("async") ? "at async " : "at ";
|
|
3258
|
+
const fn = frame.fn?.replace(/^async /, "");
|
|
3259
|
+
if (fn && fn !== "<unknown>" && fn !== loc)
|
|
3260
|
+
return `${prefix}${fn} (${loc})`;
|
|
3261
|
+
return `${prefix}${loc}`;
|
|
3262
|
+
}
|
|
3263
|
+
var GUIDANCE_WRAP_WIDTH = 76;
|
|
3264
|
+
var GUIDANCE_CONTINUATION = " ";
|
|
3265
|
+
function formatGuidanceLine(label, text, labelColor) {
|
|
3266
|
+
const prefix = `${labelColor}${label}:${colors.reset} `;
|
|
3267
|
+
const lines = [];
|
|
3268
|
+
let remaining = text.trim();
|
|
3269
|
+
let first = true;
|
|
3270
|
+
while (remaining.length > 0) {
|
|
3271
|
+
const budget = first ? Math.max(24, GUIDANCE_WRAP_WIDTH - prefix.length) : Math.max(24, GUIDANCE_WRAP_WIDTH - 5);
|
|
3272
|
+
if (remaining.length <= budget) {
|
|
3273
|
+
lines.push(first ? `${prefix}${remaining}` : `${GUIDANCE_CONTINUATION}${remaining}`);
|
|
3274
|
+
break;
|
|
3275
|
+
}
|
|
3276
|
+
let split = remaining.lastIndexOf(" ", budget);
|
|
3277
|
+
if (split <= 0)
|
|
3278
|
+
split = budget;
|
|
3279
|
+
const chunk = remaining.slice(0, split).trimEnd();
|
|
3280
|
+
lines.push(first ? `${prefix}${chunk}` : `${GUIDANCE_CONTINUATION}${chunk}`);
|
|
3281
|
+
remaining = remaining.slice(split).trimStart();
|
|
3282
|
+
first = false;
|
|
2594
3283
|
}
|
|
2595
|
-
return
|
|
3284
|
+
return lines;
|
|
2596
3285
|
}
|
|
3286
|
+
function buildErrorEntries(error, options = {}) {
|
|
3287
|
+
const normalized = normalizeErrorContext(error);
|
|
3288
|
+
if (!normalized)
|
|
3289
|
+
return [];
|
|
3290
|
+
const cwd = options.cwd ?? (typeof process !== "undefined" && typeof process.cwd === "function" ? process.cwd() : ".");
|
|
3291
|
+
const compact = options.compact ?? isDev();
|
|
3292
|
+
const guidanceOnly = (options.detail ?? "full") === "guidance";
|
|
3293
|
+
const showFrames = !guidanceOnly && !isBrowser() && (options.snippet ?? isDev());
|
|
3294
|
+
const stackDepth = guidanceOnly ? 0 : options.stackDepth ?? (compact ? 2 : 3);
|
|
3295
|
+
const snippetContextLines = compact ? 1 : 2;
|
|
3296
|
+
const children = [];
|
|
3297
|
+
const frames = guidanceOnly ? [] : parseStackFrames(normalized.stack);
|
|
3298
|
+
const primary = guidanceOnly ? undefined : pickPrimaryFrame(frames);
|
|
3299
|
+
if (!guidanceOnly && primary?.file && primary.line) {
|
|
3300
|
+
pushTreeSpacer(children);
|
|
3301
|
+
if (showFrames) {
|
|
3302
|
+
const snippet = readCodeSnippet(primary.file, primary.line, snippetContextLines);
|
|
3303
|
+
children.push(`${colors.dim} ${formatFrameLocation(primary, cwd)}${colors.reset}`);
|
|
3304
|
+
if (snippet)
|
|
3305
|
+
children.push(...formatSnippetLines(snippet));
|
|
3306
|
+
} else
|
|
3307
|
+
children.push(`${colors.dim} ${formatFrameLocation(primary, cwd)}${colors.reset}`);
|
|
3308
|
+
}
|
|
3309
|
+
if (normalized.code)
|
|
3310
|
+
children.push(`${colors.dim}Code:${colors.reset} ${normalized.code}`);
|
|
3311
|
+
if (Boolean(normalized.why || normalized.fix || normalized.link))
|
|
3312
|
+
pushTreeSpacer(children);
|
|
3313
|
+
if (normalized.why)
|
|
3314
|
+
children.push(...formatGuidanceLine("Why", normalized.why, colors.yellow));
|
|
3315
|
+
if (normalized.fix)
|
|
3316
|
+
children.push(...formatGuidanceLine("Fix", normalized.fix, colors.cyan));
|
|
3317
|
+
if (normalized.link)
|
|
3318
|
+
children.push(`${colors.dim}More:${colors.reset} ${normalized.link}`);
|
|
3319
|
+
if (normalized.cause && normalized.cause !== normalized.message)
|
|
3320
|
+
children.push(`${colors.dim}Caused by:${colors.reset} ${normalized.cause}`);
|
|
3321
|
+
const hiddenCount = guidanceOnly ? 0 : frames.filter((f) => !f.isApp || isInternalErrorFrame(f)).length;
|
|
3322
|
+
const tailFrames = stackDepth > 0 ? frames.filter((f) => f !== primary && !isInternalErrorFrame(f)).slice(0, stackDepth) : [];
|
|
3323
|
+
if (!guidanceOnly && (hiddenCount > 0 || tailFrames.length > 0)) {
|
|
3324
|
+
pushTreeSpacer(children);
|
|
3325
|
+
if (hiddenCount > 0)
|
|
3326
|
+
children.push(`${colors.gray}stack (${hiddenCount} frame${hiddenCount === 1 ? "" : "s"} hidden in node_modules)${colors.reset}`);
|
|
3327
|
+
else
|
|
3328
|
+
children.push(`${colors.gray}stack${colors.reset}`);
|
|
3329
|
+
for (const frame of tailFrames)
|
|
3330
|
+
children.push(`${colors.gray} ${formatCollapsedFrame(frame, cwd)}${colors.reset}`);
|
|
3331
|
+
}
|
|
3332
|
+
return [{
|
|
3333
|
+
key: "error",
|
|
3334
|
+
value: `${colors.red}${colors.bold}${normalized.message}${colors.reset}`,
|
|
3335
|
+
children: children.length > 0 ? children : undefined
|
|
3336
|
+
}];
|
|
3337
|
+
}
|
|
3338
|
+
|
|
3339
|
+
// ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/dev-terminal-D4UaEm17.mjs
|
|
3340
|
+
var DEV_PRESETS = {
|
|
3341
|
+
evlog: {
|
|
3342
|
+
frameworkOverlay: false,
|
|
3343
|
+
detail: "full"
|
|
3344
|
+
},
|
|
3345
|
+
nitro: {
|
|
3346
|
+
frameworkOverlay: true,
|
|
3347
|
+
detail: "guidance"
|
|
3348
|
+
},
|
|
3349
|
+
both: {
|
|
3350
|
+
frameworkOverlay: true,
|
|
3351
|
+
detail: "full"
|
|
3352
|
+
}
|
|
3353
|
+
};
|
|
3354
|
+
function finalizePrettyError(partial, frameworkOverlay, pretty, inDev) {
|
|
3355
|
+
const compact = partial.compact ?? (inDev && pretty);
|
|
3356
|
+
const detail = partial.detail ?? (frameworkOverlay ? "guidance" : "full");
|
|
3357
|
+
const stackDepth = detail === "guidance" ? 0 : partial.stackDepth ?? (compact ? 2 : 3);
|
|
3358
|
+
return {
|
|
3359
|
+
snippet: partial.snippet ?? (detail === "full" && pretty && inDev),
|
|
3360
|
+
stackDepth,
|
|
3361
|
+
compact,
|
|
3362
|
+
detail
|
|
3363
|
+
};
|
|
3364
|
+
}
|
|
3365
|
+
function resolveDevTerminal(input = {}) {
|
|
3366
|
+
const pretty = input.pretty ?? isDev();
|
|
3367
|
+
const inDev = isDev();
|
|
3368
|
+
let frameworkOverlay;
|
|
3369
|
+
let prettyError = {};
|
|
3370
|
+
if (typeof input.dev === "string" && input.dev in DEV_PRESETS) {
|
|
3371
|
+
const { frameworkOverlay: presetOverlay, detail } = DEV_PRESETS[input.dev];
|
|
3372
|
+
frameworkOverlay = presetOverlay;
|
|
3373
|
+
prettyError = { detail };
|
|
3374
|
+
} else if (input.dev && typeof input.dev === "object") {
|
|
3375
|
+
const { frameworkOverlay: devOverlay, prettyError: devPrettyError } = input.dev;
|
|
3376
|
+
frameworkOverlay = devOverlay;
|
|
3377
|
+
if (devPrettyError)
|
|
3378
|
+
prettyError = devPrettyError;
|
|
3379
|
+
}
|
|
3380
|
+
if (frameworkOverlay === undefined)
|
|
3381
|
+
frameworkOverlay = !(pretty && inDev);
|
|
3382
|
+
return {
|
|
3383
|
+
frameworkOverlay,
|
|
3384
|
+
prettyError: finalizePrettyError(prettyError, frameworkOverlay, pretty, inDev)
|
|
3385
|
+
};
|
|
3386
|
+
}
|
|
3387
|
+
|
|
3388
|
+
// ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/error.mjs
|
|
3389
|
+
var evlogErrorInternalKey = Symbol.for("evlog.error.internal");
|
|
3390
|
+
var EvlogError = class EvlogError2 extends Error {
|
|
3391
|
+
code;
|
|
3392
|
+
status;
|
|
3393
|
+
why;
|
|
3394
|
+
fix;
|
|
3395
|
+
link;
|
|
3396
|
+
get internal() {
|
|
3397
|
+
return this[evlogErrorInternalKey];
|
|
3398
|
+
}
|
|
3399
|
+
constructor(options) {
|
|
3400
|
+
const opts = typeof options === "string" ? { message: options } : options;
|
|
3401
|
+
super(opts.message, { cause: opts.cause });
|
|
3402
|
+
this.name = "EvlogError";
|
|
3403
|
+
this.code = opts.code;
|
|
3404
|
+
this.status = opts.status ?? 500;
|
|
3405
|
+
this.why = opts.why;
|
|
3406
|
+
this.fix = opts.fix;
|
|
3407
|
+
this.link = opts.link;
|
|
3408
|
+
if (opts.internal !== undefined)
|
|
3409
|
+
Object.defineProperty(this, evlogErrorInternalKey, {
|
|
3410
|
+
value: opts.internal,
|
|
3411
|
+
enumerable: false,
|
|
3412
|
+
writable: false,
|
|
3413
|
+
configurable: true
|
|
3414
|
+
});
|
|
3415
|
+
if (Error.captureStackTrace)
|
|
3416
|
+
Error.captureStackTrace(this, EvlogError2);
|
|
3417
|
+
}
|
|
3418
|
+
get statusText() {
|
|
3419
|
+
return this.message;
|
|
3420
|
+
}
|
|
3421
|
+
get statusCode() {
|
|
3422
|
+
return this.status;
|
|
3423
|
+
}
|
|
3424
|
+
get statusMessage() {
|
|
3425
|
+
return this.message;
|
|
3426
|
+
}
|
|
3427
|
+
get data() {
|
|
3428
|
+
if (this.code || this.why || this.fix || this.link)
|
|
3429
|
+
return {
|
|
3430
|
+
code: this.code,
|
|
3431
|
+
why: this.why,
|
|
3432
|
+
fix: this.fix,
|
|
3433
|
+
link: this.link
|
|
3434
|
+
};
|
|
3435
|
+
}
|
|
3436
|
+
toString() {
|
|
3437
|
+
const useColors = isServer();
|
|
3438
|
+
const red = useColors ? colors.red : "";
|
|
3439
|
+
const yellow = useColors ? colors.yellow : "";
|
|
3440
|
+
const cyan = useColors ? colors.cyan : "";
|
|
3441
|
+
const dim = useColors ? colors.dim : "";
|
|
3442
|
+
const reset = useColors ? colors.reset : "";
|
|
3443
|
+
const bold = useColors ? colors.bold : "";
|
|
3444
|
+
const lines = [];
|
|
3445
|
+
lines.push(`${red}${bold}Error:${reset} ${this.message}`);
|
|
3446
|
+
if (this.code)
|
|
3447
|
+
lines.push(`${dim}Code:${reset} ${this.code}`);
|
|
3448
|
+
if (this.why)
|
|
3449
|
+
lines.push(`${yellow}Why:${reset} ${this.why}`);
|
|
3450
|
+
if (this.fix)
|
|
3451
|
+
lines.push(`${cyan}Fix:${reset} ${this.fix}`);
|
|
3452
|
+
if (this.link)
|
|
3453
|
+
lines.push(`${dim}More info:${reset} ${this.link}`);
|
|
3454
|
+
if (this.cause)
|
|
3455
|
+
lines.push(`${dim}Caused by:${reset} ${this.cause.message}`);
|
|
3456
|
+
return lines.join(`
|
|
3457
|
+
`);
|
|
3458
|
+
}
|
|
3459
|
+
toJSON() {
|
|
3460
|
+
const { data } = this;
|
|
3461
|
+
return {
|
|
3462
|
+
name: this.name,
|
|
3463
|
+
message: this.message,
|
|
3464
|
+
status: this.status,
|
|
3465
|
+
...data && { data },
|
|
3466
|
+
...this.cause instanceof Error && { cause: {
|
|
3467
|
+
name: this.cause.name,
|
|
3468
|
+
message: this.cause.message
|
|
3469
|
+
} }
|
|
3470
|
+
};
|
|
3471
|
+
}
|
|
3472
|
+
};
|
|
2597
3473
|
|
|
2598
|
-
// ../../node_modules/.bun/evlog@2.
|
|
3474
|
+
// ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/headers-VtmnWcfn.mjs
|
|
2599
3475
|
function extractSafeHeaders(headers) {
|
|
2600
3476
|
const raw = {};
|
|
2601
3477
|
headers.forEach((value, key) => {
|
|
@@ -2613,8 +3489,89 @@ function extractSafeNodeHeaders(headers) {
|
|
|
2613
3489
|
return filterSafeHeaders(raw);
|
|
2614
3490
|
}
|
|
2615
3491
|
|
|
2616
|
-
// ../../node_modules/.bun/evlog@2.
|
|
3492
|
+
// ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/audit-CL0q7GJU.mjs
|
|
2617
3493
|
var DEFAULT_REPLACEMENT = "[REDACTED]";
|
|
3494
|
+
function normalizeRedactPathPattern(pattern) {
|
|
3495
|
+
if (!pattern.includes("*") && !pattern.includes("."))
|
|
3496
|
+
return `**.${pattern}`;
|
|
3497
|
+
return pattern;
|
|
3498
|
+
}
|
|
3499
|
+
function compileRedactPathMatchers(patterns) {
|
|
3500
|
+
if (!patterns?.length)
|
|
3501
|
+
return;
|
|
3502
|
+
const exactPaths = /* @__PURE__ */ new Set;
|
|
3503
|
+
const pathGlobs = [];
|
|
3504
|
+
const keyGlobs = [];
|
|
3505
|
+
const caseInsensitiveLeaves = /* @__PURE__ */ new Set;
|
|
3506
|
+
for (const raw of patterns) {
|
|
3507
|
+
if (!raw.includes("*")) {
|
|
3508
|
+
if (raw.includes("."))
|
|
3509
|
+
exactPaths.add(raw);
|
|
3510
|
+
else
|
|
3511
|
+
addPathGlobPattern(normalizeRedactPathPattern(raw), exactPaths, pathGlobs, caseInsensitiveLeaves);
|
|
3512
|
+
continue;
|
|
3513
|
+
}
|
|
3514
|
+
if (!raw.includes("."))
|
|
3515
|
+
keyGlobs.push(globToRegExp(raw, "."));
|
|
3516
|
+
else
|
|
3517
|
+
addPathGlobPattern(raw, exactPaths, pathGlobs, caseInsensitiveLeaves);
|
|
3518
|
+
}
|
|
3519
|
+
if (exactPaths.size === 0 && pathGlobs.length === 0 && keyGlobs.length === 0 && caseInsensitiveLeaves.size === 0)
|
|
3520
|
+
return;
|
|
3521
|
+
return {
|
|
3522
|
+
exactPaths,
|
|
3523
|
+
pathGlobs,
|
|
3524
|
+
keyGlobs,
|
|
3525
|
+
caseInsensitiveLeaves
|
|
3526
|
+
};
|
|
3527
|
+
}
|
|
3528
|
+
function addPathGlobPattern(pattern, exactPaths, pathGlobs, caseInsensitiveLeaves) {
|
|
3529
|
+
pathGlobs.push(globToRegExp(pattern, "."));
|
|
3530
|
+
const leaf = pattern.match(/^\*\*\.([^.?*]+)$/);
|
|
3531
|
+
if (leaf) {
|
|
3532
|
+
exactPaths.add(leaf[1]);
|
|
3533
|
+
caseInsensitiveLeaves.add(leaf[1].toLowerCase());
|
|
3534
|
+
}
|
|
3535
|
+
}
|
|
3536
|
+
function matchesRedactPath(fullPath, leafKey, matchers) {
|
|
3537
|
+
if (matchers.exactPaths.has(fullPath))
|
|
3538
|
+
return true;
|
|
3539
|
+
if (matchers.caseInsensitiveLeaves.has(leafKey.toLowerCase()))
|
|
3540
|
+
return true;
|
|
3541
|
+
for (const glob of matchers.pathGlobs) {
|
|
3542
|
+
glob.lastIndex = 0;
|
|
3543
|
+
if (glob.test(fullPath))
|
|
3544
|
+
return true;
|
|
3545
|
+
}
|
|
3546
|
+
for (const glob of matchers.keyGlobs) {
|
|
3547
|
+
glob.lastIndex = 0;
|
|
3548
|
+
if (glob.test(leafKey))
|
|
3549
|
+
return true;
|
|
3550
|
+
}
|
|
3551
|
+
return false;
|
|
3552
|
+
}
|
|
3553
|
+
function redactPathsInTree(obj, matchers, replacement, prefix = "") {
|
|
3554
|
+
if (obj === null || obj === undefined)
|
|
3555
|
+
return;
|
|
3556
|
+
if (Array.isArray(obj)) {
|
|
3557
|
+
for (let i = 0;i < obj.length; i++) {
|
|
3558
|
+
const segment = String(i);
|
|
3559
|
+
const fullPath = prefix ? `${prefix}.${segment}` : segment;
|
|
3560
|
+
redactPathsInTree(obj[i], matchers, replacement, fullPath);
|
|
3561
|
+
}
|
|
3562
|
+
return;
|
|
3563
|
+
}
|
|
3564
|
+
if (typeof obj === "object") {
|
|
3565
|
+
const record = obj;
|
|
3566
|
+
for (const key in record) {
|
|
3567
|
+
const fullPath = prefix ? `${prefix}.${key}` : key;
|
|
3568
|
+
if (matchesRedactPath(fullPath, key, matchers))
|
|
3569
|
+
record[key] = replacement;
|
|
3570
|
+
else
|
|
3571
|
+
redactPathsInTree(record[key], matchers, replacement, fullPath);
|
|
3572
|
+
}
|
|
3573
|
+
}
|
|
3574
|
+
}
|
|
2618
3575
|
var builtinPatterns = {
|
|
2619
3576
|
creditCard: {
|
|
2620
3577
|
pattern: /\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,
|
|
@@ -2668,11 +3625,15 @@ function resolveRedactConfig(input) {
|
|
|
2668
3625
|
if (input === true)
|
|
2669
3626
|
return { _maskers: allBuiltinMaskers() };
|
|
2670
3627
|
if (input.builtins === false)
|
|
2671
|
-
return
|
|
3628
|
+
return {
|
|
3629
|
+
...input,
|
|
3630
|
+
_pathMatchers: compileRedactPathMatchers(input.paths)
|
|
3631
|
+
};
|
|
2672
3632
|
const maskers = Array.isArray(input.builtins) ? input.builtins.map((name) => builtinPatterns[name]).filter(Boolean).map((b) => [cloneRegex(b.pattern), b.mask]) : allBuiltinMaskers();
|
|
2673
3633
|
return {
|
|
2674
3634
|
...input,
|
|
2675
|
-
_maskers: maskers
|
|
3635
|
+
_maskers: maskers,
|
|
3636
|
+
_pathMatchers: compileRedactPathMatchers(input.paths)
|
|
2676
3637
|
};
|
|
2677
3638
|
}
|
|
2678
3639
|
function allBuiltinMaskers() {
|
|
@@ -2681,28 +3642,40 @@ function allBuiltinMaskers() {
|
|
|
2681
3642
|
function cloneRegex(re) {
|
|
2682
3643
|
return new RegExp(re.source, re.flags);
|
|
2683
3644
|
}
|
|
3645
|
+
var globallyRedacted = Symbol.for("evlog.globallyRedacted");
|
|
3646
|
+
function markGloballyRedacted(event) {
|
|
3647
|
+
Object.defineProperty(event, globallyRedacted, {
|
|
3648
|
+
value: true,
|
|
3649
|
+
enumerable: false,
|
|
3650
|
+
configurable: true
|
|
3651
|
+
});
|
|
3652
|
+
}
|
|
3653
|
+
function isGloballyRedacted(event) {
|
|
3654
|
+
return Reflect.has(event, globallyRedacted);
|
|
3655
|
+
}
|
|
3656
|
+
function cloneForRedaction(event) {
|
|
3657
|
+
try {
|
|
3658
|
+
return structuredClone(event);
|
|
3659
|
+
} catch {
|
|
3660
|
+
try {
|
|
3661
|
+
return JSON.parse(JSON.stringify(event));
|
|
3662
|
+
} catch {
|
|
3663
|
+
console.warn("[cloneForRedaction] Shallow clone used \u2014 nested objects may be mutated by redactPath, redactPatterns, and applyMaskersToTree");
|
|
3664
|
+
return { ...event };
|
|
3665
|
+
}
|
|
3666
|
+
}
|
|
3667
|
+
}
|
|
2684
3668
|
function redactEvent(event, config) {
|
|
3669
|
+
const clone = cloneForRedaction(event);
|
|
2685
3670
|
const replacement = config.replacement ?? DEFAULT_REPLACEMENT;
|
|
2686
|
-
|
|
2687
|
-
|
|
2688
|
-
|
|
3671
|
+
const pathMatchers = config._pathMatchers ?? compileRedactPathMatchers(config.paths);
|
|
3672
|
+
if (pathMatchers)
|
|
3673
|
+
redactPathsInTree(clone, pathMatchers, replacement);
|
|
2689
3674
|
if (config._maskers?.length)
|
|
2690
|
-
applyMaskersToTree(
|
|
3675
|
+
applyMaskersToTree(clone, config._maskers);
|
|
2691
3676
|
if (config.patterns?.length)
|
|
2692
|
-
redactPatterns(
|
|
2693
|
-
|
|
2694
|
-
function redactPath(obj, segments, replacement) {
|
|
2695
|
-
let current = obj;
|
|
2696
|
-
for (let i = 0;i < segments.length - 1; i++) {
|
|
2697
|
-
if (current === null || current === undefined || typeof current !== "object")
|
|
2698
|
-
return;
|
|
2699
|
-
current = current[segments[i]];
|
|
2700
|
-
}
|
|
2701
|
-
if (current === null || current === undefined || typeof current !== "object")
|
|
2702
|
-
return;
|
|
2703
|
-
const leaf = segments[segments.length - 1];
|
|
2704
|
-
if (leaf in current)
|
|
2705
|
-
current[leaf] = replacement;
|
|
3677
|
+
redactPatterns(clone, config.patterns, replacement);
|
|
3678
|
+
return clone;
|
|
2706
3679
|
}
|
|
2707
3680
|
function redactPatterns(obj, patterns, replacement) {
|
|
2708
3681
|
if (obj === null || obj === undefined)
|
|
@@ -2728,10 +3701,8 @@ function redactPatterns(obj, patterns, replacement) {
|
|
|
2728
3701
|
}
|
|
2729
3702
|
function applyPatterns(value, patterns, replacement) {
|
|
2730
3703
|
let result = value;
|
|
2731
|
-
for (const pattern of patterns)
|
|
2732
|
-
pattern.lastIndex = 0;
|
|
3704
|
+
for (const pattern of patterns)
|
|
2733
3705
|
result = result.replace(pattern, replacement);
|
|
2734
|
-
}
|
|
2735
3706
|
return result;
|
|
2736
3707
|
}
|
|
2737
3708
|
function applyMaskersToTree(obj, maskers) {
|
|
@@ -2758,10 +3729,8 @@ function applyMaskersToTree(obj, maskers) {
|
|
|
2758
3729
|
}
|
|
2759
3730
|
function applyMaskers(value, maskers) {
|
|
2760
3731
|
let result = value;
|
|
2761
|
-
for (const [pattern, mask] of maskers)
|
|
2762
|
-
pattern.lastIndex = 0;
|
|
3732
|
+
for (const [pattern, mask] of maskers)
|
|
2763
3733
|
result = result.replace(pattern, mask);
|
|
2764
|
-
}
|
|
2765
3734
|
return result;
|
|
2766
3735
|
}
|
|
2767
3736
|
function logPluginError(name, hook, err) {
|
|
@@ -2875,6 +3844,10 @@ var emptyRunner = createPluginRunner([]);
|
|
|
2875
3844
|
function getEmptyPluginRunner() {
|
|
2876
3845
|
return emptyRunner;
|
|
2877
3846
|
}
|
|
3847
|
+
var nativeStdoutWrite = typeof process !== "undefined" && typeof process.stdout?.write === "function" ? process.stdout.write.bind(process.stdout) : undefined;
|
|
3848
|
+
function writePrettyStdout(text) {
|
|
3849
|
+
(globalThis.__evlogNativeStdoutWrite ?? nativeStdoutWrite)?.(text);
|
|
3850
|
+
}
|
|
2878
3851
|
function isPlainObject$1(val) {
|
|
2879
3852
|
return val !== null && typeof val === "object" && !Array.isArray(val);
|
|
2880
3853
|
}
|
|
@@ -2901,11 +3874,29 @@ function mergeInto(target, source) {
|
|
|
2901
3874
|
target[key] = sourceVal;
|
|
2902
3875
|
}
|
|
2903
3876
|
}
|
|
3877
|
+
var pendingDrainState = /* @__PURE__ */ new WeakMap;
|
|
3878
|
+
function isAiOnlyFieldUpdate(data) {
|
|
3879
|
+
const keys = Object.keys(data);
|
|
3880
|
+
return keys.length === 1 && keys[0] === "ai";
|
|
3881
|
+
}
|
|
3882
|
+
function markWideEventDrainStarted(event) {
|
|
3883
|
+
if (!event)
|
|
3884
|
+
return;
|
|
3885
|
+
const state = pendingDrainState.get(event);
|
|
3886
|
+
if (state)
|
|
3887
|
+
state.drainStarted = true;
|
|
3888
|
+
}
|
|
2904
3889
|
var globalEnv = {
|
|
2905
3890
|
service: "app",
|
|
2906
3891
|
environment: "development"
|
|
2907
3892
|
};
|
|
2908
3893
|
var globalPretty = isDev();
|
|
3894
|
+
var globalPrettyError = {
|
|
3895
|
+
snippet: isDev(),
|
|
3896
|
+
stackDepth: 2,
|
|
3897
|
+
compact: isDev(),
|
|
3898
|
+
detail: "full"
|
|
3899
|
+
};
|
|
2909
3900
|
var globalSampling = {};
|
|
2910
3901
|
var globalStringify = true;
|
|
2911
3902
|
var globalDrain;
|
|
@@ -2925,6 +3916,7 @@ function initLogger(config = {}) {
|
|
|
2925
3916
|
region: config.env?.region ?? detected.region
|
|
2926
3917
|
};
|
|
2927
3918
|
globalPretty = config.pretty ?? isDev();
|
|
3919
|
+
globalPrettyError = resolveDevTerminal(config).prettyError;
|
|
2928
3920
|
globalSampling = config.sampling ?? {};
|
|
2929
3921
|
globalStringify = config.stringify ?? true;
|
|
2930
3922
|
globalDrain = config.drain;
|
|
@@ -3005,8 +3997,10 @@ function emitWideEvent(level, event, options = {}) {
|
|
|
3005
3997
|
...event
|
|
3006
3998
|
};
|
|
3007
3999
|
finalizeAudit(formatted);
|
|
3008
|
-
if (globalRedact)
|
|
3009
|
-
redactEvent(formatted, globalRedact);
|
|
4000
|
+
if (globalRedact) {
|
|
4001
|
+
formatted = redactEvent(formatted, globalRedact);
|
|
4002
|
+
markGloballyRedacted(formatted);
|
|
4003
|
+
}
|
|
3010
4004
|
if (!globalSilent)
|
|
3011
4005
|
if (globalPretty)
|
|
3012
4006
|
prettyPrintWideEvent(formatted);
|
|
@@ -3196,11 +4190,11 @@ function buildAIEntries(ai) {
|
|
|
3196
4190
|
const toolCallEntries = toolCalls ? asToolCallArray(toolCalls) : undefined;
|
|
3197
4191
|
const hasInputs = toolCallEntries !== undefined && toolCallEntries.length > 0;
|
|
3198
4192
|
if (tools?.length) {
|
|
3199
|
-
const children = tools.map((
|
|
3200
|
-
const mark =
|
|
3201
|
-
let line = `${
|
|
3202
|
-
if (
|
|
3203
|
-
line += ` ${
|
|
4193
|
+
const children = tools.map((t2, idx) => {
|
|
4194
|
+
const mark = t2.success ? "\u2713" : "\u2717";
|
|
4195
|
+
let line = `${t2.name} ${formatDuration(t2.durationMs)} ${mark}`;
|
|
4196
|
+
if (t2.error)
|
|
4197
|
+
line += ` ${t2.error}`;
|
|
3204
4198
|
if (hasInputs && toolCallEntries && idx < toolCallEntries.length) {
|
|
3205
4199
|
const tc = toolCallEntries[idx];
|
|
3206
4200
|
const inputStr = serializeToolInput(tc.input);
|
|
@@ -3287,11 +4281,34 @@ function buildAIEntries(ai) {
|
|
|
3287
4281
|
});
|
|
3288
4282
|
return entries;
|
|
3289
4283
|
}
|
|
4284
|
+
function flushPrettyLines(lines) {
|
|
4285
|
+
if (lines.length === 0)
|
|
4286
|
+
return;
|
|
4287
|
+
const text = `${lines.join(`
|
|
4288
|
+
`)}
|
|
4289
|
+
`;
|
|
4290
|
+
if (nativeStdoutWrite && !isBrowser() && process.env.VITEST !== "true") {
|
|
4291
|
+
writePrettyStdout(text);
|
|
4292
|
+
return;
|
|
4293
|
+
}
|
|
4294
|
+
console.log(lines.join(`
|
|
4295
|
+
`));
|
|
4296
|
+
}
|
|
3290
4297
|
function prettyPrintWideEvent(event) {
|
|
3291
4298
|
const { timestamp, level, service, environment, version, ...rest } = event;
|
|
3292
4299
|
const ts = typeof timestamp === "string" ? timestamp.slice(11, 23) : "";
|
|
3293
4300
|
const levelLabel = typeof level === "string" ? level : "info";
|
|
3294
4301
|
const browser = isBrowser();
|
|
4302
|
+
const lines = [];
|
|
4303
|
+
const writeLine = (...args) => {
|
|
4304
|
+
if (browser) {
|
|
4305
|
+
console.log(...args);
|
|
4306
|
+
return;
|
|
4307
|
+
}
|
|
4308
|
+
const [line] = args;
|
|
4309
|
+
if (typeof line === "string")
|
|
4310
|
+
lines.push(line);
|
|
4311
|
+
};
|
|
3295
4312
|
const parts = [];
|
|
3296
4313
|
const styles = [];
|
|
3297
4314
|
if (browser) {
|
|
@@ -3300,7 +4317,10 @@ function prettyPrintWideEvent(event) {
|
|
|
3300
4317
|
styles.push(cssColors.dim, cssColors.reset, lc, cssColors.reset, cssColors.cyan, cssColors.reset);
|
|
3301
4318
|
} else {
|
|
3302
4319
|
const lc = getLevelColor(levelLabel);
|
|
3303
|
-
|
|
4320
|
+
if (isDev())
|
|
4321
|
+
parts.push(`${lc}${levelLabel.toUpperCase()}${colors.reset} ${colors.cyan}[${service}]${colors.reset}`);
|
|
4322
|
+
else
|
|
4323
|
+
parts.push(`${colors.dim}${ts}${colors.reset} ${lc}${levelLabel.toUpperCase()}${colors.reset} ${colors.cyan}[${service}]${colors.reset}`);
|
|
3304
4324
|
}
|
|
3305
4325
|
if (rest.method && rest.path) {
|
|
3306
4326
|
parts.push(browser ? ` ${escapeFormatString(String(rest.method))} ${escapeFormatString(String(rest.path))}` : ` ${rest.method} ${rest.path}`);
|
|
@@ -3325,16 +4345,21 @@ function prettyPrintWideEvent(event) {
|
|
|
3325
4345
|
parts.push(` ${colors.dim}in ${rest.duration}${colors.reset}`);
|
|
3326
4346
|
delete rest.duration;
|
|
3327
4347
|
}
|
|
3328
|
-
|
|
4348
|
+
writeLine(parts.join(""), ...styles);
|
|
3329
4349
|
const aiData = isPlainObject$1(rest.ai) ? rest.ai : undefined;
|
|
3330
4350
|
if (aiData)
|
|
3331
4351
|
delete rest.ai;
|
|
4352
|
+
const errorData = rest.error;
|
|
4353
|
+
if (errorData !== undefined)
|
|
4354
|
+
delete rest.error;
|
|
3332
4355
|
const restEntries = Object.entries(rest).filter(([_, v]) => v !== undefined);
|
|
3333
4356
|
const aiEntries = aiData ? buildAIEntries(aiData) : [];
|
|
3334
|
-
const
|
|
4357
|
+
const errorEntries = errorData !== undefined ? buildErrorEntries(errorData, globalPrettyError) : [];
|
|
4358
|
+
const contextEntries = [...restEntries.map(([key, value]) => ({
|
|
3335
4359
|
key,
|
|
3336
4360
|
value: formatValue(value)
|
|
3337
4361
|
})), ...aiEntries];
|
|
4362
|
+
const allEntries = errorEntries.length > 0 ? [...errorEntries, ...contextEntries] : contextEntries;
|
|
3338
4363
|
for (let i = 0;i < allEntries.length; i++) {
|
|
3339
4364
|
const entry = allEntries[i];
|
|
3340
4365
|
if (!entry)
|
|
@@ -3344,10 +4369,10 @@ function prettyPrintWideEvent(event) {
|
|
|
3344
4369
|
const prefix = i === allEntries.length - 1 && !hasChildren ? "\u2514\u2500" : "\u251C\u2500";
|
|
3345
4370
|
if (browser) {
|
|
3346
4371
|
const val = entry.value ? ` ${escapeFormatString(entry.value)}` : "";
|
|
3347
|
-
|
|
4372
|
+
writeLine(` %c${prefix}%c %c${escapeFormatString(entry.key)}:%c${val}`, cssColors.dim, cssColors.reset, cssColors.cyan, cssColors.reset);
|
|
3348
4373
|
} else {
|
|
3349
4374
|
const val = entry.value ? ` ${entry.value}` : "";
|
|
3350
|
-
|
|
4375
|
+
writeLine(` ${colors.dim}${prefix}${colors.reset} ${colors.cyan}${entry.key}:${colors.reset}${val}`);
|
|
3351
4376
|
}
|
|
3352
4377
|
if (hasChildren && children) {
|
|
3353
4378
|
const connector = i === allEntries.length - 1 ? " " : "\u2502";
|
|
@@ -3355,14 +4380,26 @@ function prettyPrintWideEvent(event) {
|
|
|
3355
4380
|
const child = children[j];
|
|
3356
4381
|
if (child === undefined)
|
|
3357
4382
|
continue;
|
|
4383
|
+
if (child === "__EVLOG_TREE_SPACER__") {
|
|
4384
|
+
writeLine(` ${colors.dim}${connector}${colors.reset}`);
|
|
4385
|
+
continue;
|
|
4386
|
+
}
|
|
3358
4387
|
const childPrefix = j === children.length - 1 ? "\u2514\u2500" : "\u251C\u2500";
|
|
4388
|
+
if (child === "") {
|
|
4389
|
+
writeLine("");
|
|
4390
|
+
continue;
|
|
4391
|
+
}
|
|
3359
4392
|
if (browser)
|
|
3360
|
-
|
|
4393
|
+
writeLine(` %c${connector} ${childPrefix}%c ${escapeFormatString(child)}`, cssColors.dim, cssColors.reset);
|
|
4394
|
+
else if (child.startsWith(" ") || child.startsWith("\x1B"))
|
|
4395
|
+
writeLine(` ${colors.dim}${connector}${colors.reset}${child}`);
|
|
3361
4396
|
else
|
|
3362
|
-
|
|
4397
|
+
writeLine(` ${colors.dim}${connector} ${childPrefix}${colors.reset} ${child}`);
|
|
3363
4398
|
}
|
|
3364
4399
|
}
|
|
3365
4400
|
}
|
|
4401
|
+
if (!browser && lines.length > 0)
|
|
4402
|
+
flushPrettyLines(lines);
|
|
3366
4403
|
}
|
|
3367
4404
|
function createLogMethod(level) {
|
|
3368
4405
|
return function logMethod(tagOrEvent, message) {
|
|
@@ -3405,6 +4442,7 @@ function createLogger(initialContext = {}, internalOptions) {
|
|
|
3405
4442
|
let hasWarn = false;
|
|
3406
4443
|
let manualLevel;
|
|
3407
4444
|
let emitted = false;
|
|
4445
|
+
let pendingWideEvent = null;
|
|
3408
4446
|
function addLog(level, message) {
|
|
3409
4447
|
if (!Array.isArray(context.requestLogs))
|
|
3410
4448
|
context.requestLogs = [];
|
|
@@ -3437,7 +4475,13 @@ function createLogger(initialContext = {}, internalOptions) {
|
|
|
3437
4475
|
audit: auditMethod,
|
|
3438
4476
|
set(data) {
|
|
3439
4477
|
if (emitted) {
|
|
3440
|
-
const
|
|
4478
|
+
const record = data;
|
|
4479
|
+
const pendingState = pendingWideEvent ? pendingDrainState.get(pendingWideEvent) : undefined;
|
|
4480
|
+
if (pendingWideEvent && pendingState && !pendingState.drainStarted && isAiOnlyFieldUpdate(record)) {
|
|
4481
|
+
mergeInto(pendingWideEvent, record);
|
|
4482
|
+
return;
|
|
4483
|
+
}
|
|
4484
|
+
const keys = Object.keys(record);
|
|
3441
4485
|
warnPostEmit("log.set()", `Keys dropped: ${keys.length ? keys.join(", ") : "(empty)"}.`);
|
|
3442
4486
|
return;
|
|
3443
4487
|
}
|
|
@@ -3462,7 +4506,7 @@ function createLogger(initialContext = {}, internalOptions) {
|
|
|
3462
4506
|
const errorObj = {
|
|
3463
4507
|
name: err.name,
|
|
3464
4508
|
message: err.message,
|
|
3465
|
-
stack: err.stack
|
|
4509
|
+
stack: isDev() ? compactStackForStorage(err.stack) : err.stack
|
|
3466
4510
|
};
|
|
3467
4511
|
const errRecord = err;
|
|
3468
4512
|
for (const k of [
|
|
@@ -3477,6 +4521,18 @@ function createLogger(initialContext = {}, internalOptions) {
|
|
|
3477
4521
|
])
|
|
3478
4522
|
if (k in err)
|
|
3479
4523
|
errorObj[k] = errRecord[k];
|
|
4524
|
+
if (err instanceof EvlogError) {
|
|
4525
|
+
if (err.code)
|
|
4526
|
+
errorObj.code = err.code;
|
|
4527
|
+
if (err.why)
|
|
4528
|
+
errorObj.why = err.why;
|
|
4529
|
+
if (err.fix)
|
|
4530
|
+
errorObj.fix = err.fix;
|
|
4531
|
+
if (err.link)
|
|
4532
|
+
errorObj.link = err.link;
|
|
4533
|
+
if (err.status)
|
|
4534
|
+
errorObj.status = err.status;
|
|
4535
|
+
}
|
|
3480
4536
|
if (isPlainObject$1(context.error))
|
|
3481
4537
|
mergeInto(context.error, errorObj);
|
|
3482
4538
|
else
|
|
@@ -3527,6 +4583,7 @@ function createLogger(initialContext = {}, internalOptions) {
|
|
|
3527
4583
|
});
|
|
3528
4584
|
if (!forceKeep && !shouldSample(level)) {
|
|
3529
4585
|
emitted = true;
|
|
4586
|
+
pendingWideEvent = null;
|
|
3530
4587
|
return null;
|
|
3531
4588
|
}
|
|
3532
4589
|
if (overrides) {
|
|
@@ -3542,6 +4599,9 @@ function createLogger(initialContext = {}, internalOptions) {
|
|
|
3542
4599
|
waitUntil
|
|
3543
4600
|
});
|
|
3544
4601
|
emitted = true;
|
|
4602
|
+
pendingWideEvent = wide;
|
|
4603
|
+
if (wide)
|
|
4604
|
+
pendingDrainState.set(wide, { drainStarted: !deferDrain });
|
|
3545
4605
|
return wide;
|
|
3546
4606
|
},
|
|
3547
4607
|
getContext() {
|
|
@@ -3565,21 +4625,24 @@ function createRequestLogger(options = {}, internalOptions) {
|
|
|
3565
4625
|
}
|
|
3566
4626
|
if (typeof __EVLOG_CONFIG__ !== "undefined")
|
|
3567
4627
|
initLogger(__EVLOG_CONFIG__);
|
|
3568
|
-
function
|
|
4628
|
+
function isPlainObject2(value) {
|
|
3569
4629
|
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
3570
4630
|
return false;
|
|
3571
4631
|
if (Object.prototype.toString.call(value) !== "[object Object]")
|
|
3572
4632
|
return false;
|
|
3573
4633
|
return Object.getPrototypeOf(value) === Object.prototype || value.constructor === Object;
|
|
3574
4634
|
}
|
|
3575
|
-
function stableStringify(value) {
|
|
4635
|
+
function stableStringify(value, ancestors = /* @__PURE__ */ new WeakSet) {
|
|
3576
4636
|
if (value === null || typeof value !== "object")
|
|
3577
4637
|
return JSON.stringify(value);
|
|
3578
|
-
if (
|
|
3579
|
-
return
|
|
3580
|
-
if (!
|
|
4638
|
+
if (ancestors.has(value))
|
|
4639
|
+
return '"[Circular]"';
|
|
4640
|
+
if (!Array.isArray(value) && !isPlainObject2(value))
|
|
3581
4641
|
return JSON.stringify(value);
|
|
3582
|
-
|
|
4642
|
+
ancestors.add(value);
|
|
4643
|
+
const out = Array.isArray(value) ? `[${value.map((v) => stableStringify(v, ancestors)).join(",")}]` : `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${stableStringify(value[k], ancestors)}`).join(",")}}`;
|
|
4644
|
+
ancestors.delete(value);
|
|
4645
|
+
return out;
|
|
3583
4646
|
}
|
|
3584
4647
|
function fnv1a32(input, seed) {
|
|
3585
4648
|
let h = seed >>> 0;
|
|
@@ -3623,6 +4686,7 @@ function buildAuditFields(input) {
|
|
|
3623
4686
|
version: input.version ?? 1
|
|
3624
4687
|
};
|
|
3625
4688
|
}
|
|
4689
|
+
var _testCollector = null;
|
|
3626
4690
|
function decorateAudit(audit, timestamp) {
|
|
3627
4691
|
if (audit.idempotencyKey)
|
|
3628
4692
|
return audit;
|
|
@@ -3644,10 +4708,11 @@ function finalizeAudit(event) {
|
|
|
3644
4708
|
const a = event.audit;
|
|
3645
4709
|
if (!a)
|
|
3646
4710
|
return;
|
|
3647
|
-
|
|
4711
|
+
const decorated = decorateAudit(a, String(event.timestamp));
|
|
4712
|
+
event.audit = decorated;
|
|
4713
|
+
_testCollector?.(decorated, event);
|
|
3648
4714
|
}
|
|
3649
|
-
|
|
3650
|
-
// ../../node_modules/.bun/evlog@2.18.1+21e9b0bb4450b609/node_modules/evlog/dist/errors-BQgyQ9xe.mjs
|
|
4715
|
+
// ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/errors-DA0cyr8q.mjs
|
|
3651
4716
|
function extractErrorStatus(error) {
|
|
3652
4717
|
if (error === null || typeof error !== "object")
|
|
3653
4718
|
return 500;
|
|
@@ -3656,7 +4721,7 @@ function extractErrorStatus(error) {
|
|
|
3656
4721
|
return Number.isFinite(status) ? status : 500;
|
|
3657
4722
|
}
|
|
3658
4723
|
|
|
3659
|
-
// ../../node_modules/.bun/evlog@2.
|
|
4724
|
+
// ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/routes-4rMzRyTk.mjs
|
|
3660
4725
|
function shouldLog(path, include, exclude) {
|
|
3661
4726
|
if (exclude && exclude.length > 0) {
|
|
3662
4727
|
if (exclude.some((pattern) => matchesPattern(path, pattern)))
|
|
@@ -3674,7 +4739,86 @@ function getServiceForPath(path, routes) {
|
|
|
3674
4739
|
return config.service;
|
|
3675
4740
|
}
|
|
3676
4741
|
|
|
3677
|
-
// ../../node_modules/.bun/evlog@2.
|
|
4742
|
+
// ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/streamResponse-CmQ3qUbF.mjs
|
|
4743
|
+
function shouldDeferEmitForResponse(response) {
|
|
4744
|
+
if (!response.body)
|
|
4745
|
+
return false;
|
|
4746
|
+
const contentType = (response.headers.get("content-type") ?? "").toLowerCase();
|
|
4747
|
+
if (contentType.includes("text/event-stream"))
|
|
4748
|
+
return true;
|
|
4749
|
+
if (contentType.includes("application/x-ndjson"))
|
|
4750
|
+
return true;
|
|
4751
|
+
if (response.headers.has("x-vercel-ai-ui-message-stream"))
|
|
4752
|
+
return true;
|
|
4753
|
+
if (response.headers.get("transfer-encoding")?.toLowerCase().includes("chunked"))
|
|
4754
|
+
return true;
|
|
4755
|
+
return false;
|
|
4756
|
+
}
|
|
4757
|
+
function toError(value) {
|
|
4758
|
+
return value instanceof Error ? value : new Error(String(value));
|
|
4759
|
+
}
|
|
4760
|
+
function createObservedBody(body, onDone, onError) {
|
|
4761
|
+
if (body.locked) {
|
|
4762
|
+
Promise.resolve(onError(/* @__PURE__ */ new TypeError("stream is already locked"))).catch((err) => {
|
|
4763
|
+
console.error("[evlog] stream error handling failed:", err);
|
|
4764
|
+
});
|
|
4765
|
+
return null;
|
|
4766
|
+
}
|
|
4767
|
+
const reader = body.getReader();
|
|
4768
|
+
let settled = false;
|
|
4769
|
+
const settle = (fn) => {
|
|
4770
|
+
if (settled)
|
|
4771
|
+
return;
|
|
4772
|
+
settled = true;
|
|
4773
|
+
Promise.resolve(fn()).catch((err) => {
|
|
4774
|
+
console.error("[evlog] stream completion handling failed:", err);
|
|
4775
|
+
});
|
|
4776
|
+
};
|
|
4777
|
+
return new ReadableStream({
|
|
4778
|
+
async pull(controller) {
|
|
4779
|
+
try {
|
|
4780
|
+
const { done, value } = await reader.read();
|
|
4781
|
+
if (done) {
|
|
4782
|
+
settle(onDone);
|
|
4783
|
+
controller.close();
|
|
4784
|
+
return;
|
|
4785
|
+
}
|
|
4786
|
+
controller.enqueue(value);
|
|
4787
|
+
} catch (err) {
|
|
4788
|
+
settle(() => onError(err));
|
|
4789
|
+
controller.error(err);
|
|
4790
|
+
}
|
|
4791
|
+
},
|
|
4792
|
+
async cancel(reason) {
|
|
4793
|
+
try {
|
|
4794
|
+
await reader.cancel(reason);
|
|
4795
|
+
} finally {
|
|
4796
|
+
settle(onDone);
|
|
4797
|
+
}
|
|
4798
|
+
}
|
|
4799
|
+
});
|
|
4800
|
+
}
|
|
4801
|
+
function bindStreamingResponseLifecycle(response, onComplete) {
|
|
4802
|
+
if (!response.body) {
|
|
4803
|
+
Promise.resolve(onComplete({ status: response.status })).catch((err) => {
|
|
4804
|
+
console.error("[evlog] stream completion handling failed:", err);
|
|
4805
|
+
});
|
|
4806
|
+
return response;
|
|
4807
|
+
}
|
|
4808
|
+
const body = createObservedBody(response.body, () => onComplete({ status: response.status }), (err) => onComplete({
|
|
4809
|
+
status: response.status,
|
|
4810
|
+
error: toError(err)
|
|
4811
|
+
}));
|
|
4812
|
+
if (!body)
|
|
4813
|
+
return response;
|
|
4814
|
+
return new Response(body, {
|
|
4815
|
+
status: response.status,
|
|
4816
|
+
statusText: response.statusText,
|
|
4817
|
+
headers: response.headers
|
|
4818
|
+
});
|
|
4819
|
+
}
|
|
4820
|
+
|
|
4821
|
+
// ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/fork-Di44utlp.mjs
|
|
3678
4822
|
var noopResult = {
|
|
3679
4823
|
logger: {
|
|
3680
4824
|
set() {},
|
|
@@ -3690,6 +4834,7 @@ var noopResult = {
|
|
|
3690
4834
|
}
|
|
3691
4835
|
},
|
|
3692
4836
|
finish: () => Promise.resolve(null),
|
|
4837
|
+
finishResponse: (response) => Promise.resolve(response),
|
|
3693
4838
|
skipped: true
|
|
3694
4839
|
};
|
|
3695
4840
|
var runnerCache = /* @__PURE__ */ new WeakMap;
|
|
@@ -3715,11 +4860,17 @@ function resolveMiddlewarePluginRunner(options) {
|
|
|
3715
4860
|
});
|
|
3716
4861
|
return runner;
|
|
3717
4862
|
}
|
|
4863
|
+
function assignRedactedEvent(target, redacted) {
|
|
4864
|
+
for (const key of Object.keys(target))
|
|
4865
|
+
if (!(key in redacted))
|
|
4866
|
+
delete target[key];
|
|
4867
|
+
Object.assign(target, redacted);
|
|
4868
|
+
}
|
|
3718
4869
|
async function runEnrichAndDrain(emittedEvent, options, requestInfo, responseStatus, plugins) {
|
|
3719
4870
|
const runner = plugins ?? resolveMiddlewarePluginRunner(options);
|
|
3720
4871
|
const resolvedRedact = resolveRedactConfig(options.redact);
|
|
3721
|
-
if (resolvedRedact)
|
|
3722
|
-
redactEvent(emittedEvent, resolvedRedact);
|
|
4872
|
+
if (resolvedRedact && !isGloballyRedacted(emittedEvent))
|
|
4873
|
+
assignRedactedEvent(emittedEvent, redactEvent(emittedEvent, resolvedRedact));
|
|
3723
4874
|
if (options.enrich || runner.hasEnrich) {
|
|
3724
4875
|
const enrichCtx = {
|
|
3725
4876
|
event: emittedEvent,
|
|
@@ -3736,6 +4887,7 @@ async function runEnrichAndDrain(emittedEvent, options, requestInfo, responseSta
|
|
|
3736
4887
|
if (runner.hasEnrich)
|
|
3737
4888
|
await runner.runEnrich(enrichCtx);
|
|
3738
4889
|
}
|
|
4890
|
+
markWideEventDrainStarted(emittedEvent);
|
|
3739
4891
|
const drain = options.drain ?? getGlobalDrain();
|
|
3740
4892
|
const hasUserDrain = !!drain;
|
|
3741
4893
|
const hasPluginDrain = runner.hasDrain;
|
|
@@ -3789,22 +4941,38 @@ function createMiddlewareLogger(options) {
|
|
|
3789
4941
|
request: requestInfo,
|
|
3790
4942
|
headers: options.headers
|
|
3791
4943
|
});
|
|
3792
|
-
const finish =
|
|
4944
|
+
const finish = (opts) => {
|
|
4945
|
+
return performFinish(logger, opts);
|
|
4946
|
+
};
|
|
4947
|
+
const finishResponse = async (response, opts) => {
|
|
4948
|
+
const status = opts?.status ?? response.status;
|
|
4949
|
+
if (!shouldDeferEmitForResponse(response)) {
|
|
4950
|
+
await performFinish(logger, { status });
|
|
4951
|
+
return response;
|
|
4952
|
+
}
|
|
4953
|
+
return bindStreamingResponseLifecycle(response, async (meta) => {
|
|
4954
|
+
await performFinish(logger, {
|
|
4955
|
+
status: meta.status ?? status,
|
|
4956
|
+
error: meta.error
|
|
4957
|
+
});
|
|
4958
|
+
});
|
|
4959
|
+
};
|
|
4960
|
+
async function performFinish(requestLogger, opts) {
|
|
3793
4961
|
const { status, error } = opts ?? {};
|
|
3794
4962
|
if (error) {
|
|
3795
|
-
|
|
4963
|
+
requestLogger.error(error);
|
|
3796
4964
|
const errorStatus = extractErrorStatus(error);
|
|
3797
|
-
|
|
4965
|
+
requestLogger.set({ status: errorStatus });
|
|
3798
4966
|
} else if (status !== undefined)
|
|
3799
|
-
|
|
4967
|
+
requestLogger.set({ status });
|
|
3800
4968
|
const durationMs = Date.now() - startTime;
|
|
3801
|
-
const resolvedStatus = error ? extractErrorStatus(error) : status ??
|
|
4969
|
+
const resolvedStatus = error ? extractErrorStatus(error) : status ?? requestLogger.getContext().status;
|
|
3802
4970
|
const tailCtx = {
|
|
3803
4971
|
status: resolvedStatus,
|
|
3804
4972
|
duration: durationMs,
|
|
3805
4973
|
path,
|
|
3806
4974
|
method,
|
|
3807
|
-
context:
|
|
4975
|
+
context: requestLogger.getContext(),
|
|
3808
4976
|
shouldKeep: false
|
|
3809
4977
|
};
|
|
3810
4978
|
if (keep)
|
|
@@ -3812,12 +4980,12 @@ function createMiddlewareLogger(options) {
|
|
|
3812
4980
|
if (pluginRunner.hasKeep)
|
|
3813
4981
|
await pluginRunner.runKeep(tailCtx);
|
|
3814
4982
|
const forceKeep = tailCtx.shouldKeep || shouldKeep(tailCtx);
|
|
3815
|
-
const emittedEvent =
|
|
4983
|
+
const emittedEvent = requestLogger.emit({ _forceKeep: forceKeep });
|
|
3816
4984
|
if (emittedEvent && (options.enrich || options.drain || pluginRunner.hasEnrich || pluginRunner.hasDrain || getGlobalDrain()))
|
|
3817
4985
|
await runEnrichAndDrain(emittedEvent, options, requestInfo, resolvedStatus, pluginRunner);
|
|
3818
4986
|
if (pluginRunner.hasRequestLifecycle)
|
|
3819
4987
|
pluginRunner.runOnRequestFinish({
|
|
3820
|
-
logger,
|
|
4988
|
+
logger: requestLogger,
|
|
3821
4989
|
request: requestInfo,
|
|
3822
4990
|
headers: options.headers,
|
|
3823
4991
|
event: emittedEvent,
|
|
@@ -3826,10 +4994,11 @@ function createMiddlewareLogger(options) {
|
|
|
3826
4994
|
error
|
|
3827
4995
|
});
|
|
3828
4996
|
return emittedEvent;
|
|
3829
|
-
}
|
|
4997
|
+
}
|
|
3830
4998
|
return {
|
|
3831
4999
|
logger,
|
|
3832
5000
|
finish,
|
|
5001
|
+
finishResponse,
|
|
3833
5002
|
skipped: false
|
|
3834
5003
|
};
|
|
3835
5004
|
}
|
|
@@ -3890,7 +5059,7 @@ function forkBackgroundLogger(options) {
|
|
|
3890
5059
|
});
|
|
3891
5060
|
}
|
|
3892
5061
|
|
|
3893
|
-
// ../../node_modules/.bun/evlog@2.
|
|
5062
|
+
// ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/integration-2PpI-bCm.mjs
|
|
3894
5063
|
function normalizeHeaders(headers) {
|
|
3895
5064
|
if (!headers)
|
|
3896
5065
|
return;
|
|
@@ -3929,12 +5098,12 @@ function defineFrameworkIntegration(spec) {
|
|
|
3929
5098
|
} };
|
|
3930
5099
|
}
|
|
3931
5100
|
|
|
3932
|
-
// ../../node_modules/.bun/evlog@2.
|
|
5101
|
+
// ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/elysia/index.mjs
|
|
3933
5102
|
import { AsyncLocalStorage } from "async_hooks";
|
|
3934
5103
|
import { Elysia } from "elysia";
|
|
3935
5104
|
var storage = new AsyncLocalStorage;
|
|
3936
5105
|
var activeLoggers = /* @__PURE__ */ new WeakSet;
|
|
3937
|
-
function
|
|
5106
|
+
function useLogger2() {
|
|
3938
5107
|
const logger = storage.getStore();
|
|
3939
5108
|
if (!logger || !activeLoggers.has(logger))
|
|
3940
5109
|
throw new Error("[evlog] useLogger() was called outside of an evlog plugin context. Make sure app.use(evlog()) is registered before your routes.");
|
|
@@ -3977,9 +5146,9 @@ var noopLogger2 = {
|
|
|
3977
5146
|
fork: (_label, fn) => fn()
|
|
3978
5147
|
};
|
|
3979
5148
|
var syntheticRenderStorage = new AsyncLocalStorage2;
|
|
3980
|
-
function
|
|
5149
|
+
function useLogger3() {
|
|
3981
5150
|
try {
|
|
3982
|
-
return
|
|
5151
|
+
return useLogger2();
|
|
3983
5152
|
} catch {
|
|
3984
5153
|
return syntheticRenderStorage.getStore() ?? noopLogger2;
|
|
3985
5154
|
}
|
|
@@ -3997,6 +5166,13 @@ async function runInSyntheticRenderScope(fn, initialContext) {
|
|
|
3997
5166
|
}
|
|
3998
5167
|
}
|
|
3999
5168
|
|
|
5169
|
+
// src/server/sync/config.ts
|
|
5170
|
+
import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
|
|
5171
|
+
var requestSyncStreamPath = new AsyncLocalStorage3;
|
|
5172
|
+
function getSyncStreamPath() {
|
|
5173
|
+
return requestSyncStreamPath.getStore();
|
|
5174
|
+
}
|
|
5175
|
+
|
|
4000
5176
|
// src/server/render/assemble.ts
|
|
4001
5177
|
function resolvePath(pattern, params) {
|
|
4002
5178
|
let path = pattern;
|
|
@@ -4027,11 +5203,20 @@ function splitTemplate(template) {
|
|
|
4027
5203
|
function assembleHTML(template, headData, reactHtml, data) {
|
|
4028
5204
|
const { headPre, bodyPre, bodyPost } = splitTemplate(template);
|
|
4029
5205
|
const dataScript = data ? `<script id="__FURIN_DATA__" type="application/json">${safeJson(data)}</script>` : "";
|
|
5206
|
+
const syncScript = buildSyncRuntimeScript();
|
|
5207
|
+
const runtimeScripts = `${syncScript}${dataScript}`;
|
|
4030
5208
|
let injectedBodyPost = bodyPost;
|
|
4031
|
-
if (
|
|
4032
|
-
injectedBodyPost = bodyPost.includes("</body>") ? bodyPost.replace("</body>", `${
|
|
5209
|
+
if (runtimeScripts) {
|
|
5210
|
+
injectedBodyPost = bodyPost.includes("</body>") ? bodyPost.replace("</body>", `${runtimeScripts}</body>`) : bodyPost + runtimeScripts;
|
|
5211
|
+
}
|
|
5212
|
+
return headPre + headData + bodyPre + reactHtml + injectedBodyPost;
|
|
5213
|
+
}
|
|
5214
|
+
function buildSyncRuntimeScript() {
|
|
5215
|
+
const syncStreamPath = getSyncStreamPath();
|
|
5216
|
+
if (!syncStreamPath) {
|
|
5217
|
+
return "";
|
|
4033
5218
|
}
|
|
4034
|
-
return
|
|
5219
|
+
return `<script id="__FURIN_SYNC__" type="application/json">${safeJson({ stream: syncStreamPath })}</script>`;
|
|
4035
5220
|
}
|
|
4036
5221
|
|
|
4037
5222
|
// src/server/render/ssr.ts
|
|
@@ -4088,9 +5273,9 @@ var ERROR_CONSTRUCTOR_STRING = {
|
|
|
4088
5273
|
[5]: "TypeError",
|
|
4089
5274
|
[6]: "URIError"
|
|
4090
5275
|
};
|
|
4091
|
-
function createSerovalNode(
|
|
5276
|
+
function createSerovalNode(t2, i, s, c, m, p, e, a, f, b, o, l) {
|
|
4092
5277
|
return {
|
|
4093
|
-
t,
|
|
5278
|
+
t: t2,
|
|
4094
5279
|
i,
|
|
4095
5280
|
s,
|
|
4096
5281
|
c,
|
|
@@ -4825,7 +6010,7 @@ async function parseBigIntTypedArray(ctx, depth, id, current) {
|
|
|
4825
6010
|
async function parseDataView(ctx, depth, id, current) {
|
|
4826
6011
|
return createDataViewNode(id, current, await parseAsync(ctx, depth, current.buffer));
|
|
4827
6012
|
}
|
|
4828
|
-
async function
|
|
6013
|
+
async function parseError2(ctx, depth, id, current) {
|
|
4829
6014
|
const options = getErrorOptions(current, ctx.base.features);
|
|
4830
6015
|
return createErrorNode(id, current, options ? await parseProperties(ctx, depth, options) : NIL);
|
|
4831
6016
|
}
|
|
@@ -4945,7 +6130,7 @@ async function parseObjectAsync(ctx, depth, id, current) {
|
|
|
4945
6130
|
case SyntaxError:
|
|
4946
6131
|
case TypeError:
|
|
4947
6132
|
case URIError:
|
|
4948
|
-
return
|
|
6133
|
+
return parseError2(ctx, depth, id, current);
|
|
4949
6134
|
case Number:
|
|
4950
6135
|
case Boolean:
|
|
4951
6136
|
case String:
|
|
@@ -4992,7 +6177,7 @@ async function parseObjectAsync(ctx, depth, id, current) {
|
|
|
4992
6177
|
return parseAggregateError(ctx, depth, id, current);
|
|
4993
6178
|
}
|
|
4994
6179
|
if (current instanceof Error) {
|
|
4995
|
-
return
|
|
6180
|
+
return parseError2(ctx, depth, id, current);
|
|
4996
6181
|
}
|
|
4997
6182
|
if (SYM_ITERATOR in current || SYM_ASYNC_ITERATOR in current) {
|
|
4998
6183
|
return parsePlainObject(ctx, depth, id, current, !!currentClass);
|
|
@@ -5082,6 +6267,8 @@ var RouterContext = createContext(null);
|
|
|
5082
6267
|
var CLIENT_FALLBACK_ROUTER = {
|
|
5083
6268
|
basePath: "",
|
|
5084
6269
|
currentHref: "/",
|
|
6270
|
+
search: {},
|
|
6271
|
+
searchRoutes: [],
|
|
5085
6272
|
navigate: (href, _opts) => {
|
|
5086
6273
|
window.location.href = href;
|
|
5087
6274
|
return Promise.resolve();
|
|
@@ -5102,15 +6289,10 @@ function useRouter() {
|
|
|
5102
6289
|
return ctx ?? CLIENT_FALLBACK_ROUTER;
|
|
5103
6290
|
}
|
|
5104
6291
|
// src/client/router/link-utils.ts
|
|
5105
|
-
function buildHref(to, search, hash) {
|
|
6292
|
+
function buildHref(to, search, hash, searchDefaults) {
|
|
5106
6293
|
let url = to;
|
|
5107
6294
|
if (search && Object.keys(search).length > 0) {
|
|
5108
|
-
const params =
|
|
5109
|
-
for (const [k, v] of Object.entries(search)) {
|
|
5110
|
-
if (v != null) {
|
|
5111
|
-
params.set(k, String(v));
|
|
5112
|
-
}
|
|
5113
|
-
}
|
|
6295
|
+
const params = buildSearchParams(search, searchDefaults);
|
|
5114
6296
|
const qs = params.toString();
|
|
5115
6297
|
if (qs) {
|
|
5116
6298
|
url += `?${qs}`;
|
|
@@ -5129,6 +6311,63 @@ function normalizeHref(href) {
|
|
|
5129
6311
|
}
|
|
5130
6312
|
return pathname + url.search + url.hash;
|
|
5131
6313
|
}
|
|
6314
|
+
// src/client/router/search-store.ts
|
|
6315
|
+
import { createContext as createContext2 } from "react";
|
|
6316
|
+
function searchSnapshotChanged(a, b) {
|
|
6317
|
+
return a.currentHref !== b.currentHref || a.navigate !== b.navigate || a.search !== b.search || a.searchRoutes !== b.searchRoutes;
|
|
6318
|
+
}
|
|
6319
|
+
function createSearchStore(initialSnapshot) {
|
|
6320
|
+
let snapshot = initialSnapshot;
|
|
6321
|
+
let version = 0;
|
|
6322
|
+
let flushedVersion = 0;
|
|
6323
|
+
const listeners = new Set;
|
|
6324
|
+
return {
|
|
6325
|
+
flush: () => {
|
|
6326
|
+
if (flushedVersion === version) {
|
|
6327
|
+
return;
|
|
6328
|
+
}
|
|
6329
|
+
flushedVersion = version;
|
|
6330
|
+
for (const listener of [...listeners]) {
|
|
6331
|
+
listener();
|
|
6332
|
+
}
|
|
6333
|
+
},
|
|
6334
|
+
getServerSnapshot: () => snapshot,
|
|
6335
|
+
getSnapshot: () => snapshot,
|
|
6336
|
+
setSnapshot: (next) => {
|
|
6337
|
+
if (!searchSnapshotChanged(snapshot, next)) {
|
|
6338
|
+
return;
|
|
6339
|
+
}
|
|
6340
|
+
snapshot = next;
|
|
6341
|
+
version++;
|
|
6342
|
+
},
|
|
6343
|
+
subscribe: (listener) => {
|
|
6344
|
+
listeners.add(listener);
|
|
6345
|
+
return () => {
|
|
6346
|
+
listeners.delete(listener);
|
|
6347
|
+
};
|
|
6348
|
+
}
|
|
6349
|
+
};
|
|
6350
|
+
}
|
|
6351
|
+
function searchSnapshotFromRouterContext(context) {
|
|
6352
|
+
return {
|
|
6353
|
+
currentHref: context.currentHref,
|
|
6354
|
+
navigate: context.navigate,
|
|
6355
|
+
search: context.search,
|
|
6356
|
+
searchRoutes: context.searchRoutes
|
|
6357
|
+
};
|
|
6358
|
+
}
|
|
6359
|
+
var FALLBACK_SEARCH_STORE = createSearchStore({
|
|
6360
|
+
currentHref: "/",
|
|
6361
|
+
navigate: (href, _opts) => {
|
|
6362
|
+
if (typeof window !== "undefined") {
|
|
6363
|
+
window.location.href = href;
|
|
6364
|
+
}
|
|
6365
|
+
return Promise.resolve();
|
|
6366
|
+
},
|
|
6367
|
+
search: {},
|
|
6368
|
+
searchRoutes: []
|
|
6369
|
+
});
|
|
6370
|
+
var SearchStoreContext = createContext2(null);
|
|
5132
6371
|
// src/shared/digest.ts
|
|
5133
6372
|
function computeErrorDigest(err) {
|
|
5134
6373
|
let message = "";
|
|
@@ -5164,9 +6403,6 @@ function cyrb53(input) {
|
|
|
5164
6403
|
return 4294967296 * (2097151 & h2) + (4294967295 & h1);
|
|
5165
6404
|
}
|
|
5166
6405
|
|
|
5167
|
-
// src/server/runtime-env.ts
|
|
5168
|
-
var IS_DEV = true;
|
|
5169
|
-
|
|
5170
6406
|
// src/client/boundaries.tsx
|
|
5171
6407
|
import { Component, Fragment } from "react";
|
|
5172
6408
|
|
|
@@ -5204,8 +6440,9 @@ function computeLinkView({
|
|
|
5204
6440
|
activeProps,
|
|
5205
6441
|
inactiveProps
|
|
5206
6442
|
}, router2) {
|
|
5207
|
-
const
|
|
5208
|
-
const
|
|
6443
|
+
const searchDefaults = findSearchDefaultsForRouteTarget(to, router2.searchRoutes);
|
|
6444
|
+
const logicalHref = buildHref(to, search, hash, searchDefaults);
|
|
6445
|
+
const logicalHrefWithoutHash = buildHref(to, search, undefined, searchDefaults);
|
|
5209
6446
|
const isAbsolute = logicalHref.startsWith("http://") || logicalHref.startsWith("https://") || logicalHref.startsWith("//");
|
|
5210
6447
|
const href = isAbsolute ? logicalHref : router2.basePath + logicalHref;
|
|
5211
6448
|
const isActive = !isAbsolute && router2.currentHref === normalizeHref(logicalHrefWithoutHash);
|
|
@@ -5339,6 +6576,8 @@ function LinkInteractive({
|
|
|
5339
6576
|
var SSR_FALLBACK_ROUTER = {
|
|
5340
6577
|
basePath: "",
|
|
5341
6578
|
currentHref: "/",
|
|
6579
|
+
search: {},
|
|
6580
|
+
searchRoutes: [],
|
|
5342
6581
|
navigate: (_href, _opts) => Promise.resolve(),
|
|
5343
6582
|
prefetch: (_href, _opts) => {},
|
|
5344
6583
|
invalidatePrefetch: (_path, _type) => {},
|
|
@@ -5921,7 +7160,7 @@ function mergeLoaderResults(results) {
|
|
|
5921
7160
|
}
|
|
5922
7161
|
async function runLoaders(route, ctx) {
|
|
5923
7162
|
try {
|
|
5924
|
-
const ctxRecord = { ...ctx, log:
|
|
7163
|
+
const ctxRecord = { ...ctx, log: useLogger3() };
|
|
5925
7164
|
const loaderMap = new Map;
|
|
5926
7165
|
let accumulatedParentPromise = Promise.resolve({});
|
|
5927
7166
|
for (const r of route.routeChain) {
|
|
@@ -6015,13 +7254,18 @@ function getProductionTemplate() {
|
|
|
6015
7254
|
|
|
6016
7255
|
// src/server/render/ssr.ts
|
|
6017
7256
|
function withSSRRouterContext(element, contextValue) {
|
|
6018
|
-
return createElement2(RouterContext.Provider, { value: contextValue }, element);
|
|
7257
|
+
return createElement2(SearchStoreContext.Provider, { value: createSearchStore(searchSnapshotFromRouterContext(contextValue)) }, createElement2(RouterContext.Provider, { value: contextValue }, element));
|
|
6019
7258
|
}
|
|
6020
7259
|
function assertDeferredModeAllowed(route, deferredPromises) {
|
|
6021
7260
|
if (deferredPromises !== undefined && route.mode !== "ssr") {
|
|
6022
7261
|
throw new Error(`[furin] page "${route.pattern}" returned defer() but the route is rendered in "${route.mode}" mode. ` + "defer() streams data progressively and is only supported in SSR. " + "Return the data directly (await it inside the loader) or switch the route to SSR mode.");
|
|
6023
7262
|
}
|
|
6024
7263
|
}
|
|
7264
|
+
function currentHrefFromContext(ctx) {
|
|
7265
|
+
const pathUrl = new URL(ctx.path, "http://furin.local");
|
|
7266
|
+
const requestUrl = new URL(ctx.request.url);
|
|
7267
|
+
return normalizeHref(pathUrl.pathname) + (pathUrl.search || requestUrl.search);
|
|
7268
|
+
}
|
|
6025
7269
|
function buildSuccessRender(route, root, componentProps, throwOnFailure) {
|
|
6026
7270
|
try {
|
|
6027
7271
|
const headData = buildHeadInjection(route.page?.head?.(componentProps));
|
|
@@ -6036,7 +7280,7 @@ function buildSuccessRender(route, root, componentProps, throwOnFailure) {
|
|
|
6036
7280
|
return { element, headData: "", errorDigest, status: 500 };
|
|
6037
7281
|
}
|
|
6038
7282
|
}
|
|
6039
|
-
async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomputedLoaderResult) {
|
|
7283
|
+
async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomputedLoaderResult, searchRoutes) {
|
|
6040
7284
|
const loaderStart = Date.now();
|
|
6041
7285
|
const loaderResult = precomputedLoaderResult ?? await runLoaders(route, ctx);
|
|
6042
7286
|
const loader_ms = Date.now() - loaderStart;
|
|
@@ -6084,7 +7328,9 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
|
|
|
6084
7328
|
}
|
|
6085
7329
|
const ssrContext = {
|
|
6086
7330
|
basePath: basePath ?? "",
|
|
6087
|
-
currentHref:
|
|
7331
|
+
currentHref: currentHrefFromContext(ctx),
|
|
7332
|
+
search: ctx.query ?? {},
|
|
7333
|
+
searchRoutes: searchRoutes ?? [],
|
|
6088
7334
|
navigate: (_href, _opts) => Promise.resolve(),
|
|
6089
7335
|
prefetch: (_href, _opts) => {},
|
|
6090
7336
|
invalidatePrefetch: (_path, _type) => {},
|
|
@@ -6110,7 +7356,7 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
|
|
|
6110
7356
|
template
|
|
6111
7357
|
};
|
|
6112
7358
|
}
|
|
6113
|
-
function renderForPath(route, params, root, origin, mode, basePath) {
|
|
7359
|
+
function renderForPath(route, params, root, origin, mode, basePath, searchRoutes) {
|
|
6114
7360
|
return runInSyntheticRenderScope(async () => {
|
|
6115
7361
|
const resolvedPath = resolvePath(route.pattern, params);
|
|
6116
7362
|
const ctx = {
|
|
@@ -6123,11 +7369,11 @@ function renderForPath(route, params, root, origin, mode, basePath) {
|
|
|
6123
7369
|
set: { headers: {} },
|
|
6124
7370
|
path: resolvedPath
|
|
6125
7371
|
};
|
|
6126
|
-
const prepared = await prepareRender(route, ctx, root, basePath, true, undefined);
|
|
7372
|
+
const prepared = await prepareRender(route, ctx, root, basePath, true, undefined, searchRoutes);
|
|
6127
7373
|
if (prepared instanceof Response) {
|
|
6128
7374
|
return prepared;
|
|
6129
7375
|
}
|
|
6130
|
-
|
|
7376
|
+
useLogger3().set({
|
|
6131
7377
|
furin: {
|
|
6132
7378
|
render: mode,
|
|
6133
7379
|
route: route.pattern,
|
|
@@ -6159,7 +7405,7 @@ async function serializeLoaderDataNdjson(syncData, deferredPromises) {
|
|
|
6159
7405
|
}
|
|
6160
7406
|
|
|
6161
7407
|
// src/server/render/ssg.ts
|
|
6162
|
-
async function prerenderSSG(route, params, root, origin, basePath) {
|
|
7408
|
+
async function prerenderSSG(route, params, root, origin, basePath, searchRoutes) {
|
|
6163
7409
|
const resolvedPath = resolvePath(route.pattern, params);
|
|
6164
7410
|
const cached = getSSGCache(resolvedPath);
|
|
6165
7411
|
if (cached) {
|
|
@@ -6170,7 +7416,7 @@ async function prerenderSSG(route, params, root, origin, basePath) {
|
|
|
6170
7416
|
setSSGCache(resolvedPath, taggedEntry);
|
|
6171
7417
|
return taggedEntry;
|
|
6172
7418
|
}
|
|
6173
|
-
const renderResult = await renderForPath(route, params, root, origin, "ssg", basePath);
|
|
7419
|
+
const renderResult = await renderForPath(route, params, root, origin, "ssg", basePath, searchRoutes);
|
|
6174
7420
|
if (renderResult instanceof Response) {
|
|
6175
7421
|
return renderResult;
|
|
6176
7422
|
}
|
|
@@ -6188,13 +7434,14 @@ async function prerenderSSG(route, params, root, origin, basePath) {
|
|
|
6188
7434
|
// src/build/ssg-cache.ts
|
|
6189
7435
|
async function buildSSGCacheSnapshot(routes, root, origin) {
|
|
6190
7436
|
const snapshot = {};
|
|
7437
|
+
const searchRoutes = createSearchRouteMetadata(routes);
|
|
6191
7438
|
for (const route of routes) {
|
|
6192
7439
|
if (route.mode !== "ssg" || !route.page.staticParams) {
|
|
6193
7440
|
continue;
|
|
6194
7441
|
}
|
|
6195
7442
|
const paramSets = await route.page.staticParams();
|
|
6196
7443
|
for (const params of paramSets) {
|
|
6197
|
-
const entry = await prerenderSSG(route, params, root, origin, undefined);
|
|
7444
|
+
const entry = await prerenderSSG(route, params, root, origin, undefined, searchRoutes);
|
|
6198
7445
|
if (entry instanceof Response) {
|
|
6199
7446
|
continue;
|
|
6200
7447
|
}
|
|
@@ -6205,8 +7452,8 @@ async function buildSSGCacheSnapshot(routes, root, origin) {
|
|
|
6205
7452
|
}
|
|
6206
7453
|
|
|
6207
7454
|
// src/adapter/bun.ts
|
|
6208
|
-
var _pkgRoot2 = dirname2(dirname2(
|
|
6209
|
-
var _pkgSrcDir2 =
|
|
7455
|
+
var _pkgRoot2 = dirname2(dirname2(fileURLToPath3(import.meta.resolve("@teyik0/furin"))));
|
|
7456
|
+
var _pkgSrcDir2 = existsSync6(join7(_pkgRoot2, "src", "furin.ts")) ? join7(_pkgRoot2, "src") : join7(_pkgRoot2, "dist");
|
|
6210
7457
|
var _ext2 = ".ts";
|
|
6211
7458
|
var BUILD_ID_INPUT_PATHS = [
|
|
6212
7459
|
`${_pkgSrcDir2}/build/compile-entry${_ext2}`,
|
|
@@ -6238,32 +7485,32 @@ async function createBuildFingerprint(entryChunk, cssChunks, routes, root, serve
|
|
|
6238
7485
|
}
|
|
6239
7486
|
}
|
|
6240
7487
|
for (const path of BUILD_ID_INPUT_PATHS) {
|
|
6241
|
-
if (!
|
|
6242
|
-
console.warn(`[furin] Warning: build fingerprint input "${
|
|
7488
|
+
if (!existsSync6(path)) {
|
|
7489
|
+
console.warn(`[furin] Warning: build fingerprint input "${toPosixPath2(path)}" is missing \u2014 ` + "the generated build ID may not reflect all framework changes.");
|
|
6243
7490
|
}
|
|
6244
7491
|
fingerprintPaths.add(path);
|
|
6245
7492
|
}
|
|
6246
7493
|
const fileParts = await Promise.all([...fingerprintPaths].toSorted().map(async (path) => {
|
|
6247
|
-
const content =
|
|
6248
|
-
return `${
|
|
7494
|
+
const content = existsSync6(path) ? await Bun.file(path).text() : "";
|
|
7495
|
+
return `${toPosixPath2(path)}:${content}`;
|
|
6249
7496
|
}));
|
|
6250
|
-
const routeParts = routes.map((route) => JSON.stringify({ mode: route.mode, path:
|
|
7497
|
+
const routeParts = routes.map((route) => JSON.stringify({ mode: route.mode, path: toPosixPath2(route.path), pattern: route.pattern })).sort();
|
|
6251
7498
|
return [entryChunk, ...[...cssChunks].toSorted(), ...routeParts, ...fileParts].join(`
|
|
6252
7499
|
`);
|
|
6253
7500
|
}
|
|
6254
7501
|
function buildCompileMetadata(root, routes) {
|
|
6255
7502
|
const rootConventions = root.errorPath || root.notFoundPath ? {
|
|
6256
|
-
errorPath: root.errorPath ?
|
|
6257
|
-
notFoundPath: root.notFoundPath ?
|
|
7503
|
+
errorPath: root.errorPath ? toPosixPath2(root.errorPath) : undefined,
|
|
7504
|
+
notFoundPath: root.notFoundPath ? toPosixPath2(root.notFoundPath) : undefined
|
|
6258
7505
|
} : undefined;
|
|
6259
7506
|
const routeMetadata = {};
|
|
6260
7507
|
for (const route of routes) {
|
|
6261
|
-
routeMetadata[
|
|
7508
|
+
routeMetadata[toPosixPath2(route.path)] = {
|
|
6262
7509
|
segmentBoundaries: route.segmentBoundaries.map((b) => ({
|
|
6263
7510
|
depth: b.depth,
|
|
6264
|
-
path:
|
|
6265
|
-
errorPath: b.errorPath ?
|
|
6266
|
-
notFoundPath: b.notFoundPath ?
|
|
7511
|
+
path: toPosixPath2(b.path),
|
|
7512
|
+
errorPath: b.errorPath ? toPosixPath2(b.errorPath) : undefined,
|
|
7513
|
+
notFoundPath: b.notFoundPath ? toPosixPath2(b.notFoundPath) : undefined
|
|
6267
7514
|
}))
|
|
6268
7515
|
};
|
|
6269
7516
|
}
|
|
@@ -6289,21 +7536,21 @@ async function buildBunTarget(routes, rootDir, buildRoot, root, serverEntry, opt
|
|
|
6289
7536
|
const buildFingerprint = await createBuildFingerprint(entryChunk, cssChunks, routes, root, serverEntry);
|
|
6290
7537
|
const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
|
|
6291
7538
|
targetManifest.buildId = buildId;
|
|
6292
|
-
const clientDir =
|
|
7539
|
+
const clientDir = join7(targetDir, "client");
|
|
6293
7540
|
const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
|
|
6294
|
-
writeFileSync4(
|
|
7541
|
+
writeFileSync4(join7(clientDir, "index.html"), indexHtml);
|
|
6295
7542
|
setProductionTemplateContent(indexHtml);
|
|
6296
7543
|
const routeManifest = routes.map((r) => ({ pattern: r.pattern, path: r.path, mode: r.mode }));
|
|
6297
7544
|
const ssgCache2 = serverEntry ? await buildSSGCacheSnapshot(routes, root, "http://localhost") : undefined;
|
|
6298
|
-
const publicDir =
|
|
6299
|
-
const targetPublicDir = publicDir ?
|
|
7545
|
+
const publicDir = existsSync6(join7(rootDir, "public")) ? join7(rootDir, "public") : undefined;
|
|
7546
|
+
const targetPublicDir = publicDir ? join7(targetDir, "public") : undefined;
|
|
6300
7547
|
if (publicDir && targetPublicDir && options.compile !== "embed") {
|
|
6301
7548
|
copyDirRecursive(publicDir, targetPublicDir);
|
|
6302
7549
|
}
|
|
6303
7550
|
const { rootConventions, routeMetadata } = buildCompileMetadata(root, routes);
|
|
6304
7551
|
if (options.compile && serverEntry) {
|
|
6305
|
-
const clientDir2 =
|
|
6306
|
-
const outfile =
|
|
7552
|
+
const clientDir2 = join7(targetDir, "client");
|
|
7553
|
+
const outfile = join7(targetDir, "server");
|
|
6307
7554
|
const entryPath = generateCompileEntry({
|
|
6308
7555
|
buildId,
|
|
6309
7556
|
rootPath: root.path,
|
|
@@ -6325,7 +7572,7 @@ async function buildBunTarget(routes, rootDir, buildRoot, root, serverEntry, opt
|
|
|
6325
7572
|
plugins: options.plugins
|
|
6326
7573
|
});
|
|
6327
7574
|
console.log(`[furin] Server binary: ${outfile}`);
|
|
6328
|
-
targetManifest.serverPath =
|
|
7575
|
+
targetManifest.serverPath = toPosixPath2(join7(targetManifest.targetDir, "server"));
|
|
6329
7576
|
if (options.compile === "embed") {
|
|
6330
7577
|
rmSync2(clientDir2, { force: true, recursive: true });
|
|
6331
7578
|
targetManifest.clientDir = null;
|
|
@@ -6350,8 +7597,8 @@ async function buildBunTarget(routes, rootDir, buildRoot, root, serverEntry, opt
|
|
|
6350
7597
|
sourcemap: "none",
|
|
6351
7598
|
plugins: options.plugins
|
|
6352
7599
|
});
|
|
6353
|
-
console.log(`[furin] Server bundle: ${
|
|
6354
|
-
targetManifest.serverPath =
|
|
7600
|
+
console.log(`[furin] Server bundle: ${toPosixPath2(join7(targetManifest.targetDir, "server.js"))}`);
|
|
7601
|
+
targetManifest.serverPath = toPosixPath2(join7(targetManifest.targetDir, "server.js"));
|
|
6355
7602
|
}
|
|
6356
7603
|
for (const file of [
|
|
6357
7604
|
"_compile-entry.ts",
|
|
@@ -6359,21 +7606,21 @@ async function buildBunTarget(routes, rootDir, buildRoot, root, serverEntry, opt
|
|
|
6359
7606
|
"server.ts",
|
|
6360
7607
|
"_hydrate.tsx"
|
|
6361
7608
|
]) {
|
|
6362
|
-
rmSync2(
|
|
7609
|
+
rmSync2(join7(targetDir, file), { force: true });
|
|
6363
7610
|
}
|
|
6364
7611
|
return targetManifest;
|
|
6365
7612
|
}
|
|
6366
7613
|
|
|
6367
7614
|
// src/adapter/static.ts
|
|
6368
|
-
import { cpSync as cpSync2, existsSync as
|
|
6369
|
-
import { dirname as dirname3, isAbsolute, join as
|
|
7615
|
+
import { cpSync as cpSync2, existsSync as existsSync7, rmSync as rmSync3, writeFileSync as writeFileSync5 } from "fs";
|
|
7616
|
+
import { dirname as dirname3, isAbsolute, join as join8, relative as relative3, resolve as resolve2, sep } from "path";
|
|
6370
7617
|
var STATIC_CONCURRENCY = 4;
|
|
6371
7618
|
var DYNAMIC_SEGMENT_RE = /\/:[^/]+|\/\*/;
|
|
6372
7619
|
var TRAILING_SLASHES_RE2 = /\/+$/;
|
|
6373
7620
|
function pathToOutputFile(urlPath, outDir, fileName) {
|
|
6374
7621
|
const normalizedOutDir = resolve2(outDir);
|
|
6375
7622
|
if (urlPath === "/" || urlPath === "") {
|
|
6376
|
-
return
|
|
7623
|
+
return join8(normalizedOutDir, fileName);
|
|
6377
7624
|
}
|
|
6378
7625
|
const resolved = resolve2(normalizedOutDir, urlPath.slice(1), fileName);
|
|
6379
7626
|
if (!resolved.startsWith(`${normalizedOutDir}${sep}`)) {
|
|
@@ -6381,12 +7628,12 @@ function pathToOutputFile(urlPath, outDir, fileName) {
|
|
|
6381
7628
|
}
|
|
6382
7629
|
return resolved;
|
|
6383
7630
|
}
|
|
6384
|
-
async function prerenderAndWrite(route, params, root, outDir, renderedRoutes, skippedRoutes, basePath) {
|
|
7631
|
+
async function prerenderAndWrite(route, params, root, outDir, renderedRoutes, skippedRoutes, basePath, searchRoutes) {
|
|
6385
7632
|
const urlPath = resolvePath(route.pattern, params);
|
|
6386
7633
|
const htmlOutputFile = pathToOutputFile(urlPath, outDir, "index.html");
|
|
6387
7634
|
const dataOutputFile = pathToOutputFile(urlPath, outDir, "__furin_data.ndjson");
|
|
6388
7635
|
try {
|
|
6389
|
-
const entry = await prerenderSSG(route, params, root, "http://localhost", basePath);
|
|
7636
|
+
const entry = await prerenderSSG(route, params, root, "http://localhost", basePath, searchRoutes);
|
|
6390
7637
|
if (entry instanceof Response) {
|
|
6391
7638
|
console.warn(`[furin] static: route "${route.pattern}" loader returned a redirect \u2014 skipping.`);
|
|
6392
7639
|
return;
|
|
@@ -6395,7 +7642,7 @@ async function prerenderAndWrite(route, params, root, outDir, renderedRoutes, sk
|
|
|
6395
7642
|
writeFileSync5(htmlOutputFile, entry.html);
|
|
6396
7643
|
writeFileSync5(dataOutputFile, entry.ndjson);
|
|
6397
7644
|
renderedRoutes.push(urlPath);
|
|
6398
|
-
console.log(`[furin] static: ${urlPath} \u2192 ${
|
|
7645
|
+
console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath2(htmlOutputFile)}`);
|
|
6399
7646
|
} catch (err) {
|
|
6400
7647
|
console.error(`[furin] static: prerender failed for "${route.pattern}" (params: ${JSON.stringify(params)}):`, err);
|
|
6401
7648
|
skippedRoutes.push(urlPath);
|
|
@@ -6420,7 +7667,7 @@ function collectSsgRoutes(routes, onSSR, skippedRoutes) {
|
|
|
6420
7667
|
}
|
|
6421
7668
|
return routes.filter((r) => r.mode === "ssg");
|
|
6422
7669
|
}
|
|
6423
|
-
async function buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRoutes, basePath) {
|
|
7670
|
+
async function buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRoutes, basePath, searchRoutes) {
|
|
6424
7671
|
const tasks = [];
|
|
6425
7672
|
const staticParamsResults = await mapWithConcurrency(ssgRoutes, STATIC_CONCURRENCY, async (route) => {
|
|
6426
7673
|
if (!DYNAMIC_SEGMENT_RE.test(route.pattern)) {
|
|
@@ -6453,7 +7700,7 @@ async function buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRo
|
|
|
6453
7700
|
continue;
|
|
6454
7701
|
}
|
|
6455
7702
|
for (const params of result.paramSets) {
|
|
6456
|
-
tasks.push(() => prerenderAndWrite(result.route, params, root, outDir, renderedRoutes, skippedRoutes, basePath));
|
|
7703
|
+
tasks.push(() => prerenderAndWrite(result.route, params, root, outDir, renderedRoutes, skippedRoutes, basePath, searchRoutes));
|
|
6457
7704
|
}
|
|
6458
7705
|
}
|
|
6459
7706
|
return tasks;
|
|
@@ -6499,9 +7746,10 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
|
|
|
6499
7746
|
const renderedRoutes = [];
|
|
6500
7747
|
const skippedRoutes = [];
|
|
6501
7748
|
const ssgRoutes = collectSsgRoutes(routes, onSSR, skippedRoutes);
|
|
7749
|
+
const searchRoutes = createSearchRouteMetadata(ssgRoutes);
|
|
6502
7750
|
rmSync3(outDir, { force: true, recursive: true });
|
|
6503
7751
|
ensureDir(outDir);
|
|
6504
|
-
const targetDir =
|
|
7752
|
+
const targetDir = join8(buildRoot, "static");
|
|
6505
7753
|
rmSync3(targetDir, { force: true, recursive: true });
|
|
6506
7754
|
ensureDir(targetDir);
|
|
6507
7755
|
const { entryChunk, cssChunks } = await buildClient(ssgRoutes, {
|
|
@@ -6512,19 +7760,19 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
|
|
|
6512
7760
|
basePath,
|
|
6513
7761
|
clientLogging: Boolean(options.clientLogging)
|
|
6514
7762
|
});
|
|
6515
|
-
const publicFavicon =
|
|
6516
|
-
const faviconHref =
|
|
7763
|
+
const publicFavicon = join8(rootDir, "public", "favicon.ico");
|
|
7764
|
+
const faviconHref = existsSync7(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
|
|
6517
7765
|
const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref, true);
|
|
6518
7766
|
setProductionTemplateContent(shellHtml);
|
|
6519
|
-
const publicSrcDir =
|
|
6520
|
-
if (
|
|
7767
|
+
const publicSrcDir = join8(rootDir, "public");
|
|
7768
|
+
if (existsSync7(publicSrcDir)) {
|
|
6521
7769
|
cpSync2(publicSrcDir, outDir, { recursive: true });
|
|
6522
7770
|
}
|
|
6523
|
-
const clientSrcDir =
|
|
6524
|
-
if (
|
|
6525
|
-
cpSync2(clientSrcDir,
|
|
7771
|
+
const clientSrcDir = join8(targetDir, "client");
|
|
7772
|
+
if (existsSync7(clientSrcDir)) {
|
|
7773
|
+
cpSync2(clientSrcDir, join8(outDir, "_client"), { recursive: true });
|
|
6526
7774
|
}
|
|
6527
|
-
const tasks = await buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRoutes, basePath);
|
|
7775
|
+
const tasks = await buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRoutes, basePath, searchRoutes);
|
|
6528
7776
|
const afterQueueCount = skippedRoutes.length;
|
|
6529
7777
|
await runWithConcurrency(tasks, STATIC_CONCURRENCY);
|
|
6530
7778
|
if (onSSR === "error" && skippedRoutes.length > afterQueueCount) {
|
|
@@ -6535,273 +7783,40 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
|
|
|
6535
7783
|
${list}
|
|
6536
7784
|
` + `Set \`onSSR: "skip"\` in your static config to suppress this error.`);
|
|
6537
7785
|
}
|
|
6538
|
-
writeFileSync5(
|
|
7786
|
+
writeFileSync5(join8(outDir, "404.html"), shellHtml);
|
|
6539
7787
|
console.log("[furin] static: wrote 404.html (SPA shell fallback)");
|
|
6540
7788
|
rmSync3(targetDir, { force: true, recursive: true });
|
|
6541
|
-
console.log(`[furin] static: export complete \u2192 ${
|
|
7789
|
+
console.log(`[furin] static: export complete \u2192 ${toPosixPath2(outDir)}` + ` (${renderedRoutes.length} rendered, ${skippedRoutes.length} skipped)`);
|
|
6542
7790
|
return {
|
|
6543
7791
|
basePath,
|
|
6544
7792
|
generatedAt: new Date().toISOString(),
|
|
6545
|
-
outDir:
|
|
7793
|
+
outDir: toPosixPath2(outDir),
|
|
6546
7794
|
renderedRoutes,
|
|
6547
7795
|
skippedRoutes
|
|
6548
7796
|
};
|
|
6549
7797
|
}
|
|
6550
7798
|
|
|
6551
7799
|
// src/config.ts
|
|
6552
|
-
import { t } from "elysia";
|
|
7800
|
+
import { t as t2 } from "elysia";
|
|
6553
7801
|
var BUILD_TARGETS = ["bun", "node", "vercel", "cloudflare", "static"];
|
|
6554
|
-
var buildTargetSchema =
|
|
6555
|
-
var compileTargetSchema =
|
|
6556
|
-
var configSchema =
|
|
6557
|
-
rootDir:
|
|
6558
|
-
pagesDir:
|
|
6559
|
-
serverEntry:
|
|
6560
|
-
clientLogging:
|
|
6561
|
-
targets:
|
|
6562
|
-
bun:
|
|
6563
|
-
compile:
|
|
7802
|
+
var buildTargetSchema = t2.Union(BUILD_TARGETS.map((v) => t2.Literal(v)));
|
|
7803
|
+
var compileTargetSchema = t2.Union([t2.Literal("server"), t2.Literal("embed")]);
|
|
7804
|
+
var configSchema = t2.Object({
|
|
7805
|
+
rootDir: t2.Optional(t2.String()),
|
|
7806
|
+
pagesDir: t2.Optional(t2.String()),
|
|
7807
|
+
serverEntry: t2.Optional(t2.String()),
|
|
7808
|
+
clientLogging: t2.Optional(t2.Boolean()),
|
|
7809
|
+
targets: t2.Optional(t2.Array(buildTargetSchema)),
|
|
7810
|
+
bun: t2.Optional(t2.Object({
|
|
7811
|
+
compile: t2.Optional(compileTargetSchema)
|
|
6564
7812
|
})),
|
|
6565
|
-
static:
|
|
6566
|
-
basePath:
|
|
6567
|
-
outDir:
|
|
6568
|
-
onSSR:
|
|
7813
|
+
static: t2.Optional(t2.Object({
|
|
7814
|
+
basePath: t2.Optional(t2.String()),
|
|
7815
|
+
outDir: t2.Optional(t2.String()),
|
|
7816
|
+
onSSR: t2.Optional(t2.Union([t2.Literal("error"), t2.Literal("skip")]))
|
|
6569
7817
|
}))
|
|
6570
7818
|
});
|
|
6571
7819
|
|
|
6572
|
-
// src/server/router/discovery.ts
|
|
6573
|
-
import { existsSync as existsSync7 } from "fs";
|
|
6574
|
-
import { readdir } from "fs/promises";
|
|
6575
|
-
import { join as join8, parse as parse3 } from "path";
|
|
6576
|
-
|
|
6577
|
-
// src/server/internal.ts
|
|
6578
|
-
var _compileCtx = null;
|
|
6579
|
-
function getCompileContext() {
|
|
6580
|
-
return _compileCtx;
|
|
6581
|
-
}
|
|
6582
|
-
|
|
6583
|
-
// src/server/router/discovery.ts
|
|
6584
|
-
function collectRouteTags(routeChain, page) {
|
|
6585
|
-
const tags = new Set;
|
|
6586
|
-
for (const route of routeChain) {
|
|
6587
|
-
for (const tag of route.tags ?? []) {
|
|
6588
|
-
tags.add(tag);
|
|
6589
|
-
}
|
|
6590
|
-
}
|
|
6591
|
-
for (const tag of page?.tags ?? []) {
|
|
6592
|
-
tags.add(tag);
|
|
6593
|
-
}
|
|
6594
|
-
return tags.size > 0 ? [...tags] : undefined;
|
|
6595
|
-
}
|
|
6596
|
-
function toPosixPath2(path) {
|
|
6597
|
-
return path.replaceAll("\\", "/");
|
|
6598
|
-
}
|
|
6599
|
-
function routeRelativePath(pagesDir, absolutePath) {
|
|
6600
|
-
const dir = toPosixPath2(pagesDir).replace(/\/+$/g, "");
|
|
6601
|
-
const path = toPosixPath2(absolutePath);
|
|
6602
|
-
return path.startsWith(`${dir}/`) ? path.slice(dir.length + 1) : path;
|
|
6603
|
-
}
|
|
6604
|
-
async function scanPages(pagesDir) {
|
|
6605
|
-
const dir = toPosixPath2(pagesDir);
|
|
6606
|
-
const root = await scanRootLayout(dir);
|
|
6607
|
-
const routes = await scanPageFiles(dir, root);
|
|
6608
|
-
return { root, routes };
|
|
6609
|
-
}
|
|
6610
|
-
async function scanRootLayout(pagesDir) {
|
|
6611
|
-
const rootPath = `${pagesDir}/root.tsx`;
|
|
6612
|
-
const ctx = getCompileContext();
|
|
6613
|
-
if (!(existsSync7(rootPath) || ctx?.modules[rootPath])) {
|
|
6614
|
-
throw new Error("[furin] root.tsx: not found.");
|
|
6615
|
-
}
|
|
6616
|
-
const mod = ctx?.modules[rootPath] ?? await import(rootPath);
|
|
6617
|
-
const rootExport = mod.route ?? mod.default;
|
|
6618
|
-
if (!(rootExport && isFurinRoute(rootExport))) {
|
|
6619
|
-
throw new Error("[furin] root.tsx: createRoute() export not found.");
|
|
6620
|
-
}
|
|
6621
|
-
if (!rootExport.layout) {
|
|
6622
|
-
throw new Error("[furin] root.tsx: createRoute() has no layout.");
|
|
6623
|
-
}
|
|
6624
|
-
const [notFoundEntry, errorEntry] = await Promise.all([
|
|
6625
|
-
loadConventionComponent(pagesDir, "not-found"),
|
|
6626
|
-
loadConventionComponent(pagesDir, "error")
|
|
6627
|
-
]);
|
|
6628
|
-
return {
|
|
6629
|
-
path: rootPath,
|
|
6630
|
-
route: rootExport,
|
|
6631
|
-
notFound: notFoundEntry?.component,
|
|
6632
|
-
notFoundPath: notFoundEntry?.path,
|
|
6633
|
-
error: errorEntry?.component,
|
|
6634
|
-
errorPath: errorEntry?.path
|
|
6635
|
-
};
|
|
6636
|
-
}
|
|
6637
|
-
var CONVENTION_FILE_NAMES = ["not-found", "error"];
|
|
6638
|
-
var SOURCE_MODULE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js"];
|
|
6639
|
-
function isConventionFileName(name) {
|
|
6640
|
-
return CONVENTION_FILE_NAMES.includes(name);
|
|
6641
|
-
}
|
|
6642
|
-
function getSourceModuleCandidates(dir, name) {
|
|
6643
|
-
return SOURCE_MODULE_EXTENSIONS.map((ext) => `${dir}/${name}${ext}`);
|
|
6644
|
-
}
|
|
6645
|
-
async function loadConventionComponent(dir, name) {
|
|
6646
|
-
const ctx = getCompileContext();
|
|
6647
|
-
for (const filePath of getSourceModuleCandidates(dir, name)) {
|
|
6648
|
-
if (existsSync7(filePath) || ctx?.modules[filePath]) {
|
|
6649
|
-
const mod = ctx?.modules[filePath] ?? await import(filePath);
|
|
6650
|
-
if (mod.default) {
|
|
6651
|
-
return { component: mod.default, path: filePath };
|
|
6652
|
-
}
|
|
6653
|
-
}
|
|
6654
|
-
}
|
|
6655
|
-
return;
|
|
6656
|
-
}
|
|
6657
|
-
async function scanPageFiles(pagesDir, root) {
|
|
6658
|
-
const routes = [];
|
|
6659
|
-
const notFoundCache = new Map;
|
|
6660
|
-
const errorCache = new Map;
|
|
6661
|
-
for (const absolutePath of await collectPageFilePaths(pagesDir)) {
|
|
6662
|
-
if (!SOURCE_MODULE_EXTENSIONS.some((ext) => absolutePath.endsWith(ext))) {
|
|
6663
|
-
continue;
|
|
6664
|
-
}
|
|
6665
|
-
const relativePath = routeRelativePath(pagesDir, absolutePath);
|
|
6666
|
-
const fileName = parse3(relativePath).name;
|
|
6667
|
-
if (fileName.startsWith("_") || fileName === "root" || isConventionFileName(fileName)) {
|
|
6668
|
-
continue;
|
|
6669
|
-
}
|
|
6670
|
-
const [notFound, errorComponent, segmentBoundaries] = await Promise.all([
|
|
6671
|
-
resolveNearestConvention(absolutePath, pagesDir, "not-found", notFoundCache, root.notFound),
|
|
6672
|
-
resolveNearestConvention(absolutePath, pagesDir, "error", errorCache, root.error),
|
|
6673
|
-
collectSegmentBoundaries(absolutePath, pagesDir, notFoundCache, errorCache)
|
|
6674
|
-
]);
|
|
6675
|
-
if (IS_DEV) {
|
|
6676
|
-
const devRoute = await buildDevRoute(absolutePath, relativePath, root);
|
|
6677
|
-
devRoute.notFound = notFound;
|
|
6678
|
-
devRoute.error = errorComponent;
|
|
6679
|
-
devRoute.segmentBoundaries = segmentBoundaries;
|
|
6680
|
-
routes.push(devRoute);
|
|
6681
|
-
continue;
|
|
6682
|
-
}
|
|
6683
|
-
const ctx = getCompileContext();
|
|
6684
|
-
const pageMod = ctx?.modules[absolutePath] ?? await import(absolutePath);
|
|
6685
|
-
const page = pageMod.default;
|
|
6686
|
-
if (!isFurinPage(page)) {
|
|
6687
|
-
throw new Error(`[furin] ${relativePath}: no valid createRoute().page() export found`);
|
|
6688
|
-
}
|
|
6689
|
-
const routeChain = collectRouteChainFromRoute(page._route);
|
|
6690
|
-
validateRouteChain(routeChain, root.route, relativePath);
|
|
6691
|
-
routes.push({
|
|
6692
|
-
pattern: filePathToPattern(relativePath),
|
|
6693
|
-
page,
|
|
6694
|
-
path: absolutePath,
|
|
6695
|
-
routeChain,
|
|
6696
|
-
mode: resolveMode(page, routeChain),
|
|
6697
|
-
notFound,
|
|
6698
|
-
error: errorComponent,
|
|
6699
|
-
segmentBoundaries,
|
|
6700
|
-
tags: collectRouteTags(routeChain, page)
|
|
6701
|
-
});
|
|
6702
|
-
}
|
|
6703
|
-
return routes;
|
|
6704
|
-
}
|
|
6705
|
-
async function collectSegmentBoundaries(pageAbsolutePath, pagesDir, notFoundCache, errorCache) {
|
|
6706
|
-
const pageDir = pageAbsolutePath.slice(0, pageAbsolutePath.lastIndexOf("/"));
|
|
6707
|
-
const dirs = [pagesDir];
|
|
6708
|
-
if (pageDir.length > pagesDir.length) {
|
|
6709
|
-
const relativeTail = pageDir.slice(pagesDir.length + 1);
|
|
6710
|
-
const parts = relativeTail.split("/");
|
|
6711
|
-
let acc = pagesDir;
|
|
6712
|
-
for (const part of parts) {
|
|
6713
|
-
acc = `${acc}/${part}`;
|
|
6714
|
-
dirs.push(acc);
|
|
6715
|
-
}
|
|
6716
|
-
}
|
|
6717
|
-
const boundaries = [];
|
|
6718
|
-
for (let depth = 0;depth < dirs.length; depth++) {
|
|
6719
|
-
const dir = dirs[depth];
|
|
6720
|
-
const [errorEntry, notFoundEntry] = await Promise.all([
|
|
6721
|
-
errorCache.has(dir) ? Promise.resolve(errorCache.get(dir)) : loadConventionComponent(dir, "error").then((r) => {
|
|
6722
|
-
errorCache.set(dir, r);
|
|
6723
|
-
return r;
|
|
6724
|
-
}),
|
|
6725
|
-
notFoundCache.has(dir) ? Promise.resolve(notFoundCache.get(dir)) : loadConventionComponent(dir, "not-found").then((r) => {
|
|
6726
|
-
notFoundCache.set(dir, r);
|
|
6727
|
-
return r;
|
|
6728
|
-
})
|
|
6729
|
-
]);
|
|
6730
|
-
if (errorEntry || notFoundEntry) {
|
|
6731
|
-
boundaries.push({
|
|
6732
|
-
path: dir,
|
|
6733
|
-
depth,
|
|
6734
|
-
error: errorEntry?.component,
|
|
6735
|
-
errorPath: errorEntry?.path,
|
|
6736
|
-
notFound: notFoundEntry?.component,
|
|
6737
|
-
notFoundPath: notFoundEntry?.path
|
|
6738
|
-
});
|
|
6739
|
-
}
|
|
6740
|
-
}
|
|
6741
|
-
return boundaries;
|
|
6742
|
-
}
|
|
6743
|
-
async function resolveNearestConvention(pageAbsolutePath, pagesDir, conventionName, cache, rootFallback) {
|
|
6744
|
-
let dir = pageAbsolutePath.slice(0, pageAbsolutePath.lastIndexOf("/"));
|
|
6745
|
-
while (dir.length >= pagesDir.length) {
|
|
6746
|
-
if (!cache.has(dir)) {
|
|
6747
|
-
cache.set(dir, await loadConventionComponent(dir, conventionName));
|
|
6748
|
-
}
|
|
6749
|
-
const found = cache.get(dir);
|
|
6750
|
-
if (found) {
|
|
6751
|
-
return found.component;
|
|
6752
|
-
}
|
|
6753
|
-
if (dir === pagesDir) {
|
|
6754
|
-
break;
|
|
6755
|
-
}
|
|
6756
|
-
dir = dir.slice(0, dir.lastIndexOf("/"));
|
|
6757
|
-
}
|
|
6758
|
-
return rootFallback;
|
|
6759
|
-
}
|
|
6760
|
-
async function buildDevRoute(absolutePath, relativePath, root) {
|
|
6761
|
-
let page;
|
|
6762
|
-
let routeChain = [];
|
|
6763
|
-
try {
|
|
6764
|
-
const pageMod = await import(`${absolutePath}?furin-server&t=${Date.now()}`);
|
|
6765
|
-
if (isFurinPage(pageMod.default)) {
|
|
6766
|
-
page = pageMod.default;
|
|
6767
|
-
routeChain = collectRouteChainFromRoute(page._route);
|
|
6768
|
-
validateRouteChain(routeChain, root.route, relativePath);
|
|
6769
|
-
}
|
|
6770
|
-
} catch {}
|
|
6771
|
-
const devStubPage = {
|
|
6772
|
-
__type: "FURIN_PAGE",
|
|
6773
|
-
_route: { __type: "FURIN_ROUTE" },
|
|
6774
|
-
component: () => null
|
|
6775
|
-
};
|
|
6776
|
-
return {
|
|
6777
|
-
pattern: filePathToPattern(relativePath),
|
|
6778
|
-
path: absolutePath,
|
|
6779
|
-
mode: page ? resolveMode(page, routeChain) : "ssr",
|
|
6780
|
-
page: page ?? devStubPage,
|
|
6781
|
-
routeChain,
|
|
6782
|
-
tags: collectRouteTags(routeChain, page),
|
|
6783
|
-
segmentBoundaries: []
|
|
6784
|
-
};
|
|
6785
|
-
}
|
|
6786
|
-
var DIR_SCAN_CONCURRENCY = 8;
|
|
6787
|
-
async function collectPageFilePaths(dir) {
|
|
6788
|
-
const files = [];
|
|
6789
|
-
const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name));
|
|
6790
|
-
const resolved = await mapWithConcurrency(entries, DIR_SCAN_CONCURRENCY, async (entry) => {
|
|
6791
|
-
const absolutePath = toPosixPath2(join8(dir, entry.name));
|
|
6792
|
-
if (entry.isDirectory()) {
|
|
6793
|
-
return await collectPageFilePaths(absolutePath);
|
|
6794
|
-
}
|
|
6795
|
-
if (entry.isFile()) {
|
|
6796
|
-
return [absolutePath];
|
|
6797
|
-
}
|
|
6798
|
-
return [];
|
|
6799
|
-
});
|
|
6800
|
-
for (const chunk of resolved) {
|
|
6801
|
-
files.push(...chunk);
|
|
6802
|
-
}
|
|
6803
|
-
return files;
|
|
6804
|
-
}
|
|
6805
7820
|
// src/build/scan-server.ts
|
|
6806
7821
|
import { readFileSync as readFileSync2 } from "fs";
|
|
6807
7822
|
import { parse as parse4 } from "yuku-parser";
|
|
@@ -6925,10 +7940,10 @@ async function buildApp(options) {
|
|
|
6925
7940
|
const manifest = {
|
|
6926
7941
|
version: 1,
|
|
6927
7942
|
generatedAt: new Date().toISOString(),
|
|
6928
|
-
rootDir:
|
|
6929
|
-
pagesDir:
|
|
6930
|
-
rootPath:
|
|
6931
|
-
serverEntry: serverEntry ?
|
|
7943
|
+
rootDir: toPosixPath2(rootDir),
|
|
7944
|
+
pagesDir: toPosixPath2(relative4(rootDir, pagesDir)),
|
|
7945
|
+
rootPath: toPosixPath2(relative4(rootDir, root.path)),
|
|
7946
|
+
serverEntry: serverEntry ? toPosixPath2(relative4(rootDir, serverEntry)) : null,
|
|
6932
7947
|
routes: routes.map((route) => toBuildRouteManifestEntry(route, rootDir)),
|
|
6933
7948
|
targets: {}
|
|
6934
7949
|
};
|