@teyik0/furin 0.1.0-alpha.11 → 0.1.0-alpha.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -2,18 +2,18 @@
2
2
  // @bun
3
3
 
4
4
  // src/cli/index.ts
5
- import { existsSync as existsSync9 } from "fs";
5
+ import { existsSync as existsSync10 } from "fs";
6
6
  import { resolve as resolve5 } from "path";
7
7
  import { parseArgs } from "util";
8
8
 
9
9
  // src/build/index.ts
10
- import { existsSync as existsSync7, writeFileSync as writeFileSync6 } from "fs";
11
- import { join as join8, relative as relative4, resolve as resolve3 } from "path";
10
+ import { existsSync as existsSync8, writeFileSync as writeFileSync6 } from "fs";
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 existsSync4, rmSync as rmSync2, writeFileSync as writeFileSync4 } from "fs";
15
- import { dirname as dirname2, join as join5, resolve } from "path";
16
- import { fileURLToPath } from "url";
14
+ import { existsSync as existsSync5, rmSync as rmSync2, writeFileSync as writeFileSync4 } from "fs";
15
+ import { dirname as dirname2, join as join6, resolve } from "path";
16
+ import { fileURLToPath as fileURLToPath2 } from "url";
17
17
 
18
18
  // src/build/client.ts
19
19
  import { existsSync as existsSync2, mkdirSync as mkdirSync2, writeFileSync } from "fs";
@@ -1157,7 +1157,7 @@ class MagicString {
1157
1157
  }
1158
1158
 
1159
1159
  // src/plugin/transform-client.ts
1160
- import { parseSync } from "oxc-parser";
1160
+ import { parse } from "yuku-parser";
1161
1161
  var bunTranspiler = new Bun.Transpiler({
1162
1162
  loader: "tsx",
1163
1163
  tsconfig: {
@@ -1308,9 +1308,10 @@ function removeUnusedSpecifiers(s, code, decl, refs) {
1308
1308
  }
1309
1309
  function deadCodeElimination(s) {
1310
1310
  const code = s.toString();
1311
- const { program, errors } = parseSync("dce.js", code);
1312
- if (errors.length > 0) {
1313
- console.error("[furin] DCE: failed to parse transformed output:", errors[0]?.message);
1311
+ const { program, diagnostics } = parse(code, { sourceType: "module" });
1312
+ const firstError = diagnostics.find((d) => d.severity === "error");
1313
+ if (firstError) {
1314
+ console.error("[furin] DCE: failed to parse transformed output:", firstError.message);
1314
1315
  return s;
1315
1316
  }
1316
1317
  const fresh = new MagicString(code);
@@ -1360,9 +1361,10 @@ function removeServerExports(s, source, program) {
1360
1361
  }
1361
1362
  function transformForClient(code, filename) {
1362
1363
  const plainJs = bunTranspiler.transformSync(code);
1363
- const { program, errors } = parseSync(filename, plainJs);
1364
- if (errors.length > 0) {
1365
- throw new Error(`Failed to parse ${filename}: ${errors[0]?.message}`);
1364
+ const { program, diagnostics } = parse(plainJs, { sourceType: "module" });
1365
+ const firstError = diagnostics.find((d) => d.severity === "error");
1366
+ if (firstError) {
1367
+ throw new Error(`Failed to parse ${filename}: ${firstError.message}`);
1366
1368
  }
1367
1369
  let s = new MagicString(plainJs);
1368
1370
  const removedServerCode = removeServerExports(s, plainJs, program);
@@ -1537,10 +1539,15 @@ function generateHydrateEntry(routes, rootLayout, basePath) {
1537
1539
  const conventionImportLines = [...conventionIdents.entries()].map(([filePath, ident]) => `import ${ident} from "${filePath.replace(/\\/g, "/")}";`).join(`
1538
1540
  `);
1539
1541
  const basePathLiteral = JSON.stringify(basePath);
1540
- const pathnameExpr = basePath ? `(() => { const p = window.location.pathname; const b = ${basePathLiteral}; return (p.startsWith(b) && (p.length === b.length || p[b.length] === "/")) ? p.slice(b.length) || "/" : p; })()` : "window.location.pathname";
1542
+ 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(/\\/+$/, "") || "/"`;
1541
1543
  const logEndpoint = basePath ? `${JSON.stringify(basePath)} + "/_furin/ingest"` : `"/_furin/ingest"`;
1542
- const basePathProp = basePath ? `
1543
- basePath: ${basePathLiteral},` : "";
1544
+ const routerProviderDefaults = `
1545
+ autoRefresh: true,
1546
+ basePath: ${basePathLiteral},
1547
+ defaultPreload: "intent",
1548
+ defaultPreloadDelay: 50,
1549
+ defaultPreloadStaleTime: 30000,
1550
+ prefetchCacheSize: 50,`;
1544
1551
  const conventionImportsBlock = conventionImportLines ? `
1545
1552
  ${conventionImportLines}` : "";
1546
1553
  return `import { hydrateRoot, createRoot } from "react-dom/client";
@@ -1589,7 +1596,7 @@ const rootEl = document.getElementById("root") as HTMLElement;
1589
1596
  initialMatch: match,
1590
1597
  initialData: loaderData,
1591
1598
  initialDigest: loaderData.__furinError?.digest,
1592
- initialNotFound: isNotFound ? (loaderData.__furinNotFound ?? loaderData) : undefined,${basePathProp}
1599
+ initialNotFound: isNotFound ? (loaderData.__furinNotFound ?? loaderData) : undefined,${routerProviderDefaults}
1593
1600
  } as any);
1594
1601
  } else if (loaderData.__furinStatus === 404) {
1595
1602
  // Direct load to an unknown URL. The server sent the root not-found UI
@@ -1606,7 +1613,7 @@ const rootEl = document.getElementById("root") as HTMLElement;
1606
1613
  initialMatch: null,
1607
1614
  initialData: cleanData,
1608
1615
  initialDigest: loaderData.__furinError?.digest,
1609
- initialNotFound: loaderData.__furinNotFound ?? {},${basePathProp}
1616
+ initialNotFound: loaderData.__furinNotFound ?? {},${routerProviderDefaults}
1610
1617
  } as any);
1611
1618
  } else {
1612
1619
  // No match and no 404 signal \u2014 either the client bundle is out of sync
@@ -1799,14 +1806,19 @@ ${transformed}`;
1799
1806
  }
1800
1807
 
1801
1808
  // src/build/compile-entry.ts
1802
- import { existsSync as existsSync3, writeFileSync as writeFileSync2 } from "fs";
1803
- import { join as join3, relative as relative2 } from "path";
1809
+ import { existsSync as existsSync4, writeFileSync as writeFileSync2 } from "fs";
1810
+ import { join as join4, relative as relative2 } from "path";
1804
1811
 
1805
1812
  // src/build/entry-template.ts
1806
- import { dirname } from "path";
1807
- var _pkgSrcDir = dirname(new URL(import.meta.resolve("@teyik0/furin")).pathname);
1808
- var INTERNAL_MODULE_PATH = `${_pkgSrcDir}/internal.ts`;
1809
- var RUNTIME_ENV_MODULE_PATH = `${_pkgSrcDir}/runtime-env.ts`;
1813
+ import { existsSync as existsSync3 } from "fs";
1814
+ import { dirname, join as join3 } from "path";
1815
+ import { fileURLToPath } from "url";
1816
+ var _pkgRoot = dirname(dirname(fileURLToPath(import.meta.resolve("@teyik0/furin"))));
1817
+ var _pkgSrcDirRaw = existsSync3(join3(_pkgRoot, "src", "furin.ts")) ? join3(_pkgRoot, "src") : join3(_pkgRoot, "dist");
1818
+ var _pkgSrcDir = _pkgSrcDirRaw.replace(/\\/g, "/");
1819
+ var _ext = _pkgSrcDir.endsWith("/src") ? ".ts" : ".js";
1820
+ var INTERNAL_MODULE_PATH = `${_pkgSrcDir}/internal${_ext}`;
1821
+ var RUNTIME_ENV_MODULE_PATH = `${_pkgSrcDir}/runtime-env${_ext}`;
1810
1822
  function collectConventionPaths(rootConventions, routeMetadata) {
1811
1823
  const paths = [];
1812
1824
  if (rootConventions?.errorPath) {
@@ -1903,7 +1915,7 @@ function generateCompileEntry(options) {
1903
1915
  const assetImports = [];
1904
1916
  let embeddedBlock = [];
1905
1917
  if (embed) {
1906
- if (!existsSync3(embed.clientDir)) {
1918
+ if (!existsSync4(embed.clientDir)) {
1907
1919
  throw new Error(`[furin] Client directory not found: ${embed.clientDir}. Run the client build first.`);
1908
1920
  }
1909
1921
  const clientFiles = collectFilesRecursive(embed.clientDir);
@@ -1923,9 +1935,9 @@ function generateCompileEntry(options) {
1923
1935
  }
1924
1936
  }
1925
1937
  if (templateVarName === null) {
1926
- throw new Error(`[furin] Embed mode requires a client index.html at ${join3(embed.clientDir, "index.html")}. Run the client build first.`);
1938
+ throw new Error(`[furin] Embed mode requires a client index.html at ${join4(embed.clientDir, "index.html")}. Run the client build first.`);
1927
1939
  }
1928
- if (publicDir && existsSync3(publicDir)) {
1940
+ if (publicDir && existsSync4(publicDir)) {
1929
1941
  const publicFiles = collectFilesRecursive(publicDir);
1930
1942
  for (const file of publicFiles) {
1931
1943
  const varName = `_asset${assetIndex++}`;
@@ -1956,14 +1968,14 @@ function generateCompileEntry(options) {
1956
1968
  rootConventions,
1957
1969
  routeMetadata
1958
1970
  });
1959
- const entryPath = join3(outDir, "_compile-entry.ts");
1971
+ const entryPath = join4(outDir, "_compile-entry.ts");
1960
1972
  writeFileSync2(entryPath, source);
1961
1973
  return entryPath;
1962
1974
  }
1963
1975
 
1964
1976
  // src/build/server-routes-entry.ts
1965
1977
  import { writeFileSync as writeFileSync3 } from "fs";
1966
- import { join as join4 } from "path";
1978
+ import { join as join5 } from "path";
1967
1979
  function generateServerRoutesEntry(options) {
1968
1980
  const { buildId, outDir, rootPath, routes, serverEntry, rootConventions, routeMetadata } = options;
1969
1981
  ensureDir(outDir);
@@ -1976,13 +1988,14 @@ function generateServerRoutesEntry(options) {
1976
1988
  rootConventions,
1977
1989
  routeMetadata
1978
1990
  });
1979
- const entryPath = join4(outDir, "server.ts");
1991
+ const entryPath = join5(outDir, "server.ts");
1980
1992
  writeFileSync3(entryPath, source);
1981
1993
  return entryPath;
1982
1994
  }
1983
1995
 
1984
1996
  // src/adapter/bun.ts
1985
- var _pkgSrcDir2 = dirname2(fileURLToPath(import.meta.resolve("@teyik0/furin")));
1997
+ var _pkgRoot2 = dirname2(dirname2(fileURLToPath2(import.meta.resolve("@teyik0/furin"))));
1998
+ var _pkgSrcDir2 = existsSync5(join6(_pkgRoot2, "src", "furin.ts")) ? join6(_pkgRoot2, "src") : join6(_pkgRoot2, "dist");
1986
1999
  var BUILD_ID_INPUT_PATHS = [
1987
2000
  `${_pkgSrcDir2}/build/compile-entry.ts`,
1988
2001
  `${_pkgSrcDir2}/build/entry-template.ts`,
@@ -2013,13 +2026,13 @@ async function createBuildFingerprint(entryChunk, cssChunks, routes, root, serve
2013
2026
  }
2014
2027
  }
2015
2028
  for (const path of BUILD_ID_INPUT_PATHS) {
2016
- if (!existsSync4(path)) {
2029
+ if (!existsSync5(path)) {
2017
2030
  console.warn(`[furin] Warning: build fingerprint input "${toPosixPath(path)}" is missing \u2014 ` + "the generated build ID may not reflect all framework changes.");
2018
2031
  }
2019
2032
  fingerprintPaths.add(path);
2020
2033
  }
2021
2034
  const fileParts = await Promise.all([...fingerprintPaths].sort().map(async (path) => {
2022
- const content = existsSync4(path) ? await Bun.file(path).text() : "";
2035
+ const content = existsSync5(path) ? await Bun.file(path).text() : "";
2023
2036
  return `${toPosixPath(path)}:${content}`;
2024
2037
  }));
2025
2038
  const routeParts = routes.map((route) => JSON.stringify({ mode: route.mode, path: toPosixPath(route.path), pattern: route.pattern })).sort();
@@ -2063,18 +2076,18 @@ async function buildBunTarget(routes, rootDir, buildRoot, root, serverEntry, opt
2063
2076
  const buildFingerprint = await createBuildFingerprint(entryChunk, cssChunks, routes, root, serverEntry);
2064
2077
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
2065
2078
  targetManifest.buildId = buildId;
2066
- const clientDir = join5(targetDir, "client");
2067
- writeFileSync4(join5(clientDir, "index.html"), generateProdIndexHtml(entryChunk, cssChunks, buildId));
2079
+ const clientDir = join6(targetDir, "client");
2080
+ writeFileSync4(join6(clientDir, "index.html"), generateProdIndexHtml(entryChunk, cssChunks, buildId));
2068
2081
  const routeManifest = routes.map((r) => ({ pattern: r.pattern, path: r.path, mode: r.mode }));
2069
- const publicDir = existsSync4(join5(rootDir, "public")) ? join5(rootDir, "public") : undefined;
2070
- const targetPublicDir = publicDir ? join5(targetDir, "public") : undefined;
2082
+ const publicDir = existsSync5(join6(rootDir, "public")) ? join6(rootDir, "public") : undefined;
2083
+ const targetPublicDir = publicDir ? join6(targetDir, "public") : undefined;
2071
2084
  if (publicDir && targetPublicDir && options.compile !== "embed") {
2072
2085
  copyDirRecursive(publicDir, targetPublicDir);
2073
2086
  }
2074
2087
  const { rootConventions, routeMetadata } = buildCompileMetadata(root, routes);
2075
2088
  if (options.compile && serverEntry) {
2076
- const clientDir2 = join5(targetDir, "client");
2077
- const outfile = join5(targetDir, "server");
2089
+ const clientDir2 = join6(targetDir, "client");
2090
+ const outfile = join6(targetDir, "server");
2078
2091
  const entryPath = generateCompileEntry({
2079
2092
  buildId,
2080
2093
  rootPath: root.path,
@@ -2095,7 +2108,7 @@ async function buildBunTarget(routes, rootDir, buildRoot, root, serverEntry, opt
2095
2108
  plugins: options.plugins
2096
2109
  });
2097
2110
  console.log(`[furin] Server binary: ${outfile}`);
2098
- targetManifest.serverPath = toPosixPath(join5(targetManifest.targetDir, "server"));
2111
+ targetManifest.serverPath = toPosixPath(join6(targetManifest.targetDir, "server"));
2099
2112
  if (options.compile === "embed") {
2100
2113
  rmSync2(clientDir2, { force: true, recursive: true });
2101
2114
  targetManifest.clientDir = null;
@@ -2119,8 +2132,8 @@ async function buildBunTarget(routes, rootDir, buildRoot, root, serverEntry, opt
2119
2132
  sourcemap: "linked",
2120
2133
  plugins: options.plugins
2121
2134
  });
2122
- console.log(`[furin] Server bundle: ${toPosixPath(join5(targetManifest.targetDir, "server.js"))}`);
2123
- targetManifest.serverPath = toPosixPath(join5(targetManifest.targetDir, "server.js"));
2135
+ console.log(`[furin] Server bundle: ${toPosixPath(join6(targetManifest.targetDir, "server.js"))}`);
2136
+ targetManifest.serverPath = toPosixPath(join6(targetManifest.targetDir, "server.js"));
2124
2137
  }
2125
2138
  for (const file of [
2126
2139
  "_compile-entry.ts",
@@ -2128,14 +2141,14 @@ async function buildBunTarget(routes, rootDir, buildRoot, root, serverEntry, opt
2128
2141
  "server.ts",
2129
2142
  "_hydrate.tsx"
2130
2143
  ]) {
2131
- rmSync2(join5(targetDir, file), { force: true });
2144
+ rmSync2(join6(targetDir, file), { force: true });
2132
2145
  }
2133
2146
  return targetManifest;
2134
2147
  }
2135
2148
 
2136
2149
  // src/adapter/static.ts
2137
- import { cpSync as cpSync2, existsSync as existsSync5, rmSync as rmSync3, writeFileSync as writeFileSync5 } from "fs";
2138
- import { dirname as dirname3, isAbsolute, join as join6, relative as relative3, resolve as resolve2, sep } from "path";
2150
+ import { cpSync as cpSync2, existsSync as existsSync6, rmSync as rmSync3, writeFileSync as writeFileSync5 } from "fs";
2151
+ import { dirname as dirname3, isAbsolute, join as join7, relative as relative3, resolve as resolve2, sep } from "path";
2139
2152
 
2140
2153
  // src/render/assemble.ts
2141
2154
  function resolvePath(pattern, params) {
@@ -2175,9 +2188,24 @@ function assembleHTML(template, headData, reactHtml, data) {
2175
2188
  }
2176
2189
 
2177
2190
  // src/render/index.ts
2178
- import { createElement as createElement2 } from "react";
2191
+ import { createElement as createElement3 } from "react";
2179
2192
  import { renderToReadableStream } from "react-dom/server";
2180
2193
 
2194
+ // src/not-found.ts
2195
+ var NOT_FOUND_BRAND = "FURIN_NOT_FOUND";
2196
+
2197
+ class FurinNotFoundError extends Error {
2198
+ __furinBrand = NOT_FOUND_BRAND;
2199
+ data;
2200
+ constructor(options) {
2201
+ super(options?.message ?? "");
2202
+ this.data = options?.data;
2203
+ }
2204
+ }
2205
+ function isNotFoundError(err) {
2206
+ return err instanceof FurinNotFoundError || typeof err === "object" && err !== null && err.__furinBrand === NOT_FOUND_BRAND;
2207
+ }
2208
+
2181
2209
  // ../../node_modules/.bun/evlog@2.14.1+6b630eaba8c4f70c/node_modules/evlog/dist/utils.mjs
2182
2210
  function formatDuration(ms) {
2183
2211
  if (ms < 1000)
@@ -3083,15 +3111,16 @@ function finalizeAudit(event) {
3083
3111
  return;
3084
3112
  event.audit = decorateAudit(a, String(event.timestamp));
3085
3113
  }
3086
- // src/link.tsx
3114
+ // src/router-provider.tsx
3087
3115
  import {
3088
3116
  createContext,
3089
- createElement,
3090
- useCallback,
3117
+ createElement as createElement2,
3118
+ useCallback as useCallback2,
3091
3119
  useContext,
3092
- useEffect,
3120
+ useEffect as useEffect2,
3121
+ useLayoutEffect,
3093
3122
  useMemo,
3094
- useRef,
3123
+ useRef as useRef2,
3095
3124
  useState
3096
3125
  } from "react";
3097
3126
 
@@ -3107,19 +3136,193 @@ function getPublicErrorMessage(error) {
3107
3136
  return "Something went wrong";
3108
3137
  }
3109
3138
 
3110
- // src/not-found.ts
3111
- var NOT_FOUND_BRAND = "FURIN_NOT_FOUND";
3112
-
3113
- class FurinNotFoundError extends Error {
3114
- __furinBrand = NOT_FOUND_BRAND;
3115
- data;
3116
- constructor(options) {
3117
- super(options?.message ?? "");
3118
- this.data = options?.data;
3119
- }
3139
+ // src/link.tsx
3140
+ import { createElement, useCallback, useEffect, useRef } from "react";
3141
+ function computeLinkView({
3142
+ to,
3143
+ search,
3144
+ hash,
3145
+ children,
3146
+ activeProps,
3147
+ inactiveProps
3148
+ }, router) {
3149
+ const logicalHref = buildHref(to, search, hash);
3150
+ const logicalHrefWithoutHash = buildHref(to, search, undefined);
3151
+ const isAbsolute = logicalHref.startsWith("http://") || logicalHref.startsWith("https://") || logicalHref.startsWith("//");
3152
+ const href = isAbsolute ? logicalHref : router.basePath + logicalHref;
3153
+ const isActive = !isAbsolute && router.currentHref === normalizeHref(logicalHrefWithoutHash);
3154
+ const resolvedChildren = typeof children === "function" ? children({ isActive }) : children;
3155
+ const extraProps = {
3156
+ ...inactiveProps && !isActive ? inactiveProps() : {},
3157
+ ...activeProps ? activeProps({ isActive }) : {}
3158
+ };
3159
+ return { logicalHref, href, isActive, resolvedChildren, extraProps };
3120
3160
  }
3121
- function isNotFoundError(err) {
3122
- return err instanceof FurinNotFoundError || typeof err === "object" && err !== null && err.__furinBrand === NOT_FOUND_BRAND;
3161
+ function LinkInteractive({
3162
+ to,
3163
+ search,
3164
+ hash,
3165
+ preload,
3166
+ preloadDelay,
3167
+ preloadStaleTime,
3168
+ replace,
3169
+ disabled,
3170
+ resetScroll,
3171
+ activeProps,
3172
+ inactiveProps,
3173
+ onClick,
3174
+ onMouseEnter,
3175
+ onMouseLeave,
3176
+ onFocus,
3177
+ children,
3178
+ href: _href,
3179
+ ...anchorProps
3180
+ }) {
3181
+ const router = useRouter();
3182
+ const anchorRef = useRef(null);
3183
+ const intentTimerRef = useRef(null);
3184
+ const { logicalHref, href, isActive, resolvedChildren, extraProps } = computeLinkView({ to, search, hash, children, activeProps, inactiveProps }, router);
3185
+ const effectivePreload = preload ?? router.defaultPreload;
3186
+ const effectiveDelay = preloadDelay ?? router.defaultPreloadDelay;
3187
+ const effectiveStaleTime = preloadStaleTime ?? router.defaultPreloadStaleTime;
3188
+ const triggerPrefetch = useCallback(() => {
3189
+ router.prefetch(logicalHref, { staleTime: effectiveStaleTime });
3190
+ }, [router, logicalHref, effectiveStaleTime]);
3191
+ useEffect(() => {
3192
+ if (effectivePreload === "render") {
3193
+ triggerPrefetch();
3194
+ }
3195
+ }, [effectivePreload, triggerPrefetch]);
3196
+ useEffect(() => {
3197
+ if (effectivePreload !== "viewport" || !anchorRef.current) {
3198
+ return;
3199
+ }
3200
+ const observer = new IntersectionObserver(([entry]) => {
3201
+ if (entry?.isIntersecting) {
3202
+ triggerPrefetch();
3203
+ observer.disconnect();
3204
+ }
3205
+ }, { rootMargin: "200px" });
3206
+ observer.observe(anchorRef.current);
3207
+ return () => observer.disconnect();
3208
+ }, [effectivePreload, triggerPrefetch]);
3209
+ useEffect(() => () => {
3210
+ if (intentTimerRef.current !== null) {
3211
+ clearTimeout(intentTimerRef.current);
3212
+ intentTimerRef.current = null;
3213
+ }
3214
+ }, []);
3215
+ const isInternal = (url) => {
3216
+ try {
3217
+ return new URL(url, window.location.origin).origin === window.location.origin;
3218
+ } catch {
3219
+ return false;
3220
+ }
3221
+ };
3222
+ const handleClick = (e) => {
3223
+ onClick?.(e);
3224
+ if (e.defaultPrevented) {
3225
+ return;
3226
+ }
3227
+ if (disabled) {
3228
+ e.preventDefault();
3229
+ return;
3230
+ }
3231
+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
3232
+ return;
3233
+ }
3234
+ if (anchorProps.target && anchorProps.target !== "_self") {
3235
+ return;
3236
+ }
3237
+ if (!isInternal(href)) {
3238
+ return;
3239
+ }
3240
+ e.preventDefault();
3241
+ router.navigate(logicalHref, { replace, resetScroll: resetScroll ?? true });
3242
+ };
3243
+ const handleMouseEnter = (e) => {
3244
+ onMouseEnter?.(e);
3245
+ if (!disabled && effectivePreload === "intent" && isInternal(href)) {
3246
+ intentTimerRef.current = setTimeout(triggerPrefetch, effectiveDelay);
3247
+ }
3248
+ };
3249
+ const handleMouseLeave = (e) => {
3250
+ onMouseLeave?.(e);
3251
+ if (intentTimerRef.current !== null) {
3252
+ clearTimeout(intentTimerRef.current);
3253
+ intentTimerRef.current = null;
3254
+ }
3255
+ };
3256
+ const handleFocus = (e) => {
3257
+ onFocus?.(e);
3258
+ if (!disabled && effectivePreload === "intent" && isInternal(href)) {
3259
+ triggerPrefetch();
3260
+ }
3261
+ };
3262
+ return createElement("a", {
3263
+ ref: anchorRef,
3264
+ href,
3265
+ "data-furin-link": true,
3266
+ onClick: handleClick,
3267
+ onMouseEnter: handleMouseEnter,
3268
+ onMouseLeave: handleMouseLeave,
3269
+ onFocus: handleFocus,
3270
+ ...isActive ? { "data-status": "active" } : {},
3271
+ ...anchorProps,
3272
+ ...extraProps,
3273
+ ...disabled ? { "aria-disabled": true } : {}
3274
+ }, resolvedChildren);
3275
+ }
3276
+ var SSR_FALLBACK_ROUTER = {
3277
+ basePath: "",
3278
+ currentHref: "/",
3279
+ navigate: () => Promise.resolve(),
3280
+ prefetch: () => {},
3281
+ invalidatePrefetch: () => {},
3282
+ refresh: () => Promise.resolve(),
3283
+ isNavigating: false,
3284
+ defaultPreload: "intent",
3285
+ defaultPreloadDelay: 50,
3286
+ defaultPreloadStaleTime: 30000
3287
+ };
3288
+ function renderLinkElement(props, router) {
3289
+ const { href, isActive, resolvedChildren, extraProps } = computeLinkView(props, router);
3290
+ const {
3291
+ to: _to,
3292
+ search: _search,
3293
+ hash: _hash,
3294
+ children: _children,
3295
+ activeProps: _ap,
3296
+ inactiveProps: _ip,
3297
+ disabled,
3298
+ preload: _p,
3299
+ preloadDelay: _pd,
3300
+ preloadStaleTime: _ps,
3301
+ replace: _r,
3302
+ resetScroll: _rs,
3303
+ onClick: _oc,
3304
+ onMouseEnter: _ome,
3305
+ onMouseLeave: _oml,
3306
+ onFocus: _of,
3307
+ href: _href,
3308
+ ...anchorProps
3309
+ } = props;
3310
+ return createElement("a", {
3311
+ href,
3312
+ "data-furin-link": true,
3313
+ ...isActive ? { "data-status": "active" } : {},
3314
+ ...anchorProps,
3315
+ ...extraProps,
3316
+ ...disabled ? { "aria-disabled": true } : {}
3317
+ }, resolvedChildren);
3318
+ }
3319
+ function Link(props) {
3320
+ if (typeof window === "undefined") {
3321
+ return createElement(RouterContext.Consumer, {
3322
+ children: (routerCtx) => renderLinkElement(props, routerCtx ?? SSR_FALLBACK_ROUTER)
3323
+ });
3324
+ }
3325
+ return createElement(LinkInteractive, props);
3123
3326
  }
3124
3327
 
3125
3328
  // src/render/default-screens.tsx
@@ -3507,7 +3710,7 @@ class FurinNotFoundBoundary extends Component {
3507
3710
  }
3508
3711
  }
3509
3712
 
3510
- // src/link.tsx
3713
+ // src/router-provider.tsx
3511
3714
  import { jsxDEV as jsxDEV3 } from "react/jsx-dev-runtime";
3512
3715
  function buildHref(to, search, hash) {
3513
3716
  let url = to;
@@ -3530,7 +3733,8 @@ function buildHref(to, search, hash) {
3530
3733
  }
3531
3734
  var RouterContext = createContext(null);
3532
3735
  function useRouter() {
3533
- return useContext(RouterContext) ?? {
3736
+ const ctx = useContext(RouterContext);
3737
+ return ctx ?? {
3534
3738
  basePath: "",
3535
3739
  currentHref: "/",
3536
3740
  navigate: (href) => {
@@ -3549,176 +3753,13 @@ function useRouter() {
3549
3753
  defaultPreloadStaleTime: 30000
3550
3754
  };
3551
3755
  }
3552
- function computeLinkView({
3553
- to,
3554
- search,
3555
- hash,
3556
- children,
3557
- activeProps,
3558
- inactiveProps
3559
- }, router) {
3560
- const logicalHref = buildHref(to, search, hash);
3561
- const logicalHrefWithoutHash = buildHref(to, search, undefined);
3562
- const href = router.basePath + logicalHref;
3563
- const isActive = router.currentHref === logicalHrefWithoutHash;
3564
- const resolvedChildren = typeof children === "function" ? children({ isActive }) : children;
3565
- const extraProps = {
3566
- ...inactiveProps && !isActive ? inactiveProps() : {},
3567
- ...activeProps ? activeProps({ isActive }) : {}
3568
- };
3569
- return { logicalHref, href, isActive, resolvedChildren, extraProps };
3570
- }
3571
- function LinkInteractive({
3572
- to,
3573
- search,
3574
- hash,
3575
- preload,
3576
- preloadDelay,
3577
- preloadStaleTime,
3578
- replace,
3579
- disabled,
3580
- resetScroll,
3581
- activeProps,
3582
- inactiveProps,
3583
- onClick,
3584
- onMouseEnter,
3585
- onMouseLeave,
3586
- onFocus,
3587
- children,
3588
- ...anchorProps
3589
- }) {
3590
- const router = useRouter();
3591
- const anchorRef = useRef(null);
3592
- const intentTimerRef = useRef(null);
3593
- const { logicalHref, href, isActive, resolvedChildren, extraProps } = computeLinkView({ to, search, hash, children, activeProps, inactiveProps }, router);
3594
- const effectivePreload = preload ?? router.defaultPreload;
3595
- const effectiveDelay = preloadDelay ?? router.defaultPreloadDelay;
3596
- const effectiveStaleTime = preloadStaleTime ?? router.defaultPreloadStaleTime;
3597
- const triggerPrefetch = useCallback(() => {
3598
- router.prefetch(logicalHref, { staleTime: effectiveStaleTime });
3599
- }, [router, logicalHref, effectiveStaleTime]);
3600
- useEffect(() => {
3601
- if (effectivePreload === "render") {
3602
- triggerPrefetch();
3603
- }
3604
- }, [effectivePreload, triggerPrefetch]);
3605
- useEffect(() => {
3606
- if (effectivePreload !== "viewport" || !anchorRef.current) {
3607
- return;
3608
- }
3609
- const observer = new IntersectionObserver(([entry]) => {
3610
- if (entry?.isIntersecting) {
3611
- triggerPrefetch();
3612
- observer.disconnect();
3613
- }
3614
- }, { rootMargin: "200px" });
3615
- observer.observe(anchorRef.current);
3616
- return () => observer.disconnect();
3617
- }, [effectivePreload, triggerPrefetch]);
3618
- const isInternal = (url) => {
3619
- try {
3620
- return new URL(url, window.location.origin).origin === window.location.origin;
3621
- } catch {
3622
- return false;
3623
- }
3624
- };
3625
- const handleClick = (e) => {
3626
- onClick?.(e);
3627
- if (e.defaultPrevented || disabled) {
3628
- return;
3629
- }
3630
- if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
3631
- return;
3632
- }
3633
- if (anchorProps.target && anchorProps.target !== "_self") {
3634
- return;
3635
- }
3636
- if (!isInternal(href)) {
3637
- return;
3638
- }
3639
- e.preventDefault();
3640
- router.navigate(logicalHref, { replace, resetScroll: resetScroll ?? true });
3641
- };
3642
- const handleMouseEnter = (e) => {
3643
- onMouseEnter?.(e);
3644
- if (!disabled && effectivePreload === "intent" && isInternal(href)) {
3645
- intentTimerRef.current = setTimeout(triggerPrefetch, effectiveDelay);
3646
- }
3647
- };
3648
- const handleMouseLeave = (e) => {
3649
- onMouseLeave?.(e);
3650
- if (intentTimerRef.current !== null) {
3651
- clearTimeout(intentTimerRef.current);
3652
- intentTimerRef.current = null;
3653
- }
3654
- };
3655
- const handleFocus = (e) => {
3656
- onFocus?.(e);
3657
- if (!disabled && effectivePreload === "intent" && isInternal(href)) {
3658
- triggerPrefetch();
3659
- }
3660
- };
3661
- return createElement("a", {
3662
- ref: anchorRef,
3663
- href,
3664
- onClick: handleClick,
3665
- onMouseEnter: handleMouseEnter,
3666
- onMouseLeave: handleMouseLeave,
3667
- onFocus: handleFocus,
3668
- ...isActive ? { "data-status": "active" } : {},
3669
- ...anchorProps,
3670
- ...extraProps,
3671
- ...disabled ? { "aria-disabled": true } : {}
3672
- }, resolvedChildren);
3673
- }
3674
- var SSR_FALLBACK_ROUTER = {
3675
- basePath: "",
3676
- currentHref: "/",
3677
- navigate: () => Promise.resolve(),
3678
- prefetch: () => {},
3679
- invalidatePrefetch: () => {},
3680
- refresh: () => Promise.resolve(),
3681
- isNavigating: false,
3682
- defaultPreload: "intent",
3683
- defaultPreloadDelay: 50,
3684
- defaultPreloadStaleTime: 30000
3685
- };
3686
- function renderLinkElement(props, router) {
3687
- const { href, isActive, resolvedChildren, extraProps } = computeLinkView(props, router);
3688
- const {
3689
- to: _to,
3690
- search: _search,
3691
- hash: _hash,
3692
- children: _children,
3693
- activeProps: _ap,
3694
- inactiveProps: _ip,
3695
- disabled,
3696
- preload: _p,
3697
- preloadDelay: _pd,
3698
- preloadStaleTime: _ps,
3699
- replace: _r,
3700
- resetScroll: _rs,
3701
- onClick: _oc,
3702
- onMouseEnter: _ome,
3703
- onMouseLeave: _oml,
3704
- onFocus: _of,
3705
- ...anchorProps
3706
- } = props;
3707
- return createElement("a", {
3708
- href,
3709
- ...isActive ? { "data-status": "active" } : {},
3710
- ...anchorProps,
3711
- ...extraProps,
3712
- ...disabled ? { "aria-disabled": true } : {}
3713
- }, resolvedChildren);
3714
- }
3715
- function Link(props) {
3716
- if (typeof window === "undefined") {
3717
- return createElement(RouterContext.Consumer, {
3718
- children: (routerCtx) => renderLinkElement(props, routerCtx ?? SSR_FALLBACK_ROUTER)
3719
- });
3756
+ function normalizeHref(href) {
3757
+ const url = new URL(href, "http://localhost");
3758
+ let pathname = url.pathname;
3759
+ if (pathname !== "/") {
3760
+ pathname = pathname.replace(/\/+$/g, "");
3720
3761
  }
3721
- return createElement(LinkInteractive, props);
3762
+ return pathname + url.search + url.hash;
3722
3763
  }
3723
3764
 
3724
3765
  // src/render/cache.ts
@@ -3770,33 +3811,139 @@ async function runInSyntheticRenderScope(fn, initialContext) {
3770
3811
  }
3771
3812
  }
3772
3813
 
3773
- // src/render/cache.ts
3774
- var MAX_SSG_CACHE_SIZE = 1000;
3775
- var isrCache = new Map;
3776
- var ssgCache = new Map;
3777
- function evictOldest(map, maxSize) {
3778
- if (map.size > maxSize) {
3779
- const oldest = map.keys().next().value;
3814
+ // src/render/route-cache.ts
3815
+ function defaultPathFromKey(key) {
3816
+ return key;
3817
+ }
3818
+ function matchesPath(urlPath, path, type) {
3819
+ if (type === "page") {
3820
+ return urlPath === path;
3821
+ }
3822
+ const prefix = path === "/" || path.endsWith("/") ? path : `${path}/`;
3823
+ return urlPath === path || urlPath.startsWith(prefix);
3824
+ }
3825
+ function createRouteCache(options) {
3826
+ const store = new Map;
3827
+ const pathFromKey = options.pathFromKey ?? defaultPathFromKey;
3828
+ const evictOldest = () => {
3829
+ if (options.maxSize === undefined || store.size <= options.maxSize) {
3830
+ return;
3831
+ }
3832
+ const oldest = store.keys().next().value;
3780
3833
  if (oldest !== undefined) {
3781
- map.delete(oldest);
3834
+ deleteEntry(oldest);
3782
3835
  }
3783
- }
3836
+ };
3837
+ const deleteEntry = (key) => {
3838
+ const entry = store.get(key);
3839
+ if (entry === undefined) {
3840
+ return false;
3841
+ }
3842
+ store.delete(key);
3843
+ options.onDelete?.(key, entry);
3844
+ return true;
3845
+ };
3846
+ return {
3847
+ name: options.name,
3848
+ store,
3849
+ get size() {
3850
+ return store.size;
3851
+ },
3852
+ get(key) {
3853
+ const entry = store.get(key);
3854
+ if (entry !== undefined && options.maxSize !== undefined) {
3855
+ store.delete(key);
3856
+ store.set(key, entry);
3857
+ }
3858
+ return entry;
3859
+ },
3860
+ set(key, entry) {
3861
+ const previous = store.get(key);
3862
+ if (previous !== undefined) {
3863
+ store.delete(key);
3864
+ }
3865
+ store.set(key, entry);
3866
+ options.onSet?.(key, entry, previous);
3867
+ evictOldest();
3868
+ },
3869
+ delete(key) {
3870
+ return deleteEntry(key);
3871
+ },
3872
+ clear() {
3873
+ for (const key of [...store.keys()]) {
3874
+ deleteEntry(key);
3875
+ }
3876
+ store.clear();
3877
+ },
3878
+ has(key) {
3879
+ return store.has(key);
3880
+ },
3881
+ entries() {
3882
+ return store.entries();
3883
+ },
3884
+ keys() {
3885
+ return store.keys();
3886
+ },
3887
+ invalidatePath(path, type) {
3888
+ let deleted = false;
3889
+ const purgedPaths = [];
3890
+ for (const key of [...store.keys()]) {
3891
+ const urlPath = pathFromKey(key);
3892
+ if (urlPath === null || !matchesPath(urlPath, path, type)) {
3893
+ continue;
3894
+ }
3895
+ deleteEntry(key);
3896
+ deleted = true;
3897
+ purgedPaths.push(urlPath);
3898
+ }
3899
+ return { deleted, purgedPaths: [...new Set(purgedPaths)] };
3900
+ }
3901
+ };
3784
3902
  }
3903
+
3904
+ // src/render/cache.ts
3905
+ var MAX_ISR_CACHE_SIZE = 1000;
3906
+ var MAX_SSG_CACHE_SIZE = 1000;
3907
+ var isrRouteCache = createRouteCache({
3908
+ maxSize: MAX_ISR_CACHE_SIZE,
3909
+ name: "render:isr-html"
3910
+ });
3911
+ var ssgRouteCache = createRouteCache({
3912
+ maxSize: MAX_SSG_CACHE_SIZE,
3913
+ name: "render:ssg-html"
3914
+ });
3915
+ var isrCache = isrRouteCache.store;
3916
+ var ssgCache = ssgRouteCache.store;
3785
3917
  function getSSGCache(key) {
3786
- const entry = ssgCache.get(key);
3787
- if (entry !== undefined) {
3788
- ssgCache.delete(key);
3789
- ssgCache.set(key, entry);
3790
- }
3791
- return entry;
3918
+ return ssgRouteCache.get(key);
3792
3919
  }
3793
3920
  function setSSGCache(key, entry) {
3794
- ssgCache.delete(key);
3795
- ssgCache.set(key, entry);
3796
- evictOldest(ssgCache, MAX_SSG_CACHE_SIZE);
3921
+ ssgRouteCache.set(key, entry);
3797
3922
  }
3798
3923
  var _requestInvalidationScope = new AsyncLocalStorage3;
3799
3924
  var _globalPendingInvalidations = new Set;
3925
+ var _cacheInvalidators = new Map;
3926
+ function registerCacheInvalidator(invalidator) {
3927
+ const existing = _cacheInvalidators.get(invalidator.name);
3928
+ if (existing !== undefined && existing !== invalidator) {
3929
+ throw new Error(`Cache invalidator "${invalidator.name}" is already registered with a different instance.`);
3930
+ }
3931
+ if (existing === invalidator) {
3932
+ return () => {
3933
+ if (_cacheInvalidators.get(invalidator.name) === invalidator) {
3934
+ _cacheInvalidators.delete(invalidator.name);
3935
+ }
3936
+ };
3937
+ }
3938
+ _cacheInvalidators.set(invalidator.name, invalidator);
3939
+ return () => {
3940
+ if (_cacheInvalidators.get(invalidator.name) === invalidator) {
3941
+ _cacheInvalidators.delete(invalidator.name);
3942
+ }
3943
+ };
3944
+ }
3945
+ registerCacheInvalidator(isrRouteCache);
3946
+ registerCacheInvalidator(ssgRouteCache);
3800
3947
 
3801
3948
  // src/render/element.tsx
3802
3949
  import { jsxDEV as jsxDEV4 } from "react/jsx-dev-runtime";
@@ -3981,12 +4128,13 @@ function getProductionTemplate() {
3981
4128
  return null;
3982
4129
  }
3983
4130
  }
4131
+
3984
4132
  // src/runtime-env.ts
3985
4133
  var IS_DEV = true;
3986
4134
 
3987
4135
  // src/render/index.ts
3988
4136
  function withSSRRouterContext(element, contextValue) {
3989
- return createElement2(RouterContext.Provider, { value: contextValue }, element);
4137
+ return createElement3(RouterContext.Provider, { value: contextValue }, element);
3990
4138
  }
3991
4139
  async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomputedLoaderResult) {
3992
4140
  const loaderStart = Date.now();
@@ -4029,7 +4177,7 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
4029
4177
  }
4030
4178
  const ssrContext = {
4031
4179
  basePath: basePath ?? "",
4032
- currentHref: ctx.path,
4180
+ currentHref: normalizeHref(ctx.path),
4033
4181
  navigate: () => Promise.resolve(),
4034
4182
  prefetch: () => {},
4035
4183
  invalidatePrefetch: () => {},
@@ -4114,7 +4262,7 @@ var TRAILING_SLASHES_RE = /\/+$/;
4114
4262
  function pathToOutputFile(urlPath, outDir) {
4115
4263
  const normalizedOutDir = resolve2(outDir);
4116
4264
  if (urlPath === "/" || urlPath === "") {
4117
- return join6(normalizedOutDir, "index.html");
4265
+ return join7(normalizedOutDir, "index.html");
4118
4266
  }
4119
4267
  const resolved = resolve2(normalizedOutDir, urlPath.slice(1), "index.html");
4120
4268
  if (!resolved.startsWith(`${normalizedOutDir}${sep}`)) {
@@ -4226,7 +4374,7 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
4226
4374
  const ssgRoutes = collectSsgRoutes(routes, onSSR, skippedRoutes);
4227
4375
  rmSync3(outDir, { force: true, recursive: true });
4228
4376
  ensureDir(outDir);
4229
- const targetDir = join6(buildRoot, "static");
4377
+ const targetDir = join7(buildRoot, "static");
4230
4378
  rmSync3(targetDir, { force: true, recursive: true });
4231
4379
  ensureDir(targetDir);
4232
4380
  const { entryChunk, cssChunks } = await buildClient(ssgRoutes, {
@@ -4236,17 +4384,17 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
4236
4384
  publicPath,
4237
4385
  basePath
4238
4386
  });
4239
- const publicFavicon = join6(rootDir, "public", "favicon.ico");
4240
- const faviconHref = existsSync5(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
4387
+ const publicFavicon = join7(rootDir, "public", "favicon.ico");
4388
+ const faviconHref = existsSync6(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
4241
4389
  const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref);
4242
4390
  setProductionTemplateContent(shellHtml);
4243
- const publicSrcDir = join6(rootDir, "public");
4244
- if (existsSync5(publicSrcDir)) {
4391
+ const publicSrcDir = join7(rootDir, "public");
4392
+ if (existsSync6(publicSrcDir)) {
4245
4393
  cpSync2(publicSrcDir, outDir, { recursive: true });
4246
4394
  }
4247
- const clientSrcDir = join6(targetDir, "client");
4248
- if (existsSync5(clientSrcDir)) {
4249
- cpSync2(clientSrcDir, join6(outDir, "_client"), { recursive: true });
4395
+ const clientSrcDir = join7(targetDir, "client");
4396
+ if (existsSync6(clientSrcDir)) {
4397
+ cpSync2(clientSrcDir, join7(outDir, "_client"), { recursive: true });
4250
4398
  }
4251
4399
  const tasks = await buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRoutes, basePath);
4252
4400
  const afterQueueCount = skippedRoutes.length;
@@ -4259,7 +4407,7 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
4259
4407
  ${list}
4260
4408
  ` + `Set \`onSSR: "skip"\` in your static config to suppress this error.`);
4261
4409
  }
4262
- writeFileSync5(join6(outDir, "404.html"), shellHtml);
4410
+ writeFileSync5(join7(outDir, "404.html"), shellHtml);
4263
4411
  console.log("[furin] static: wrote 404.html (SPA shell fallback)");
4264
4412
  rmSync3(targetDir, { force: true, recursive: true });
4265
4413
  console.log(`[furin] static: export complete \u2192 ${toPosixPath(outDir)}` + ` (${renderedRoutes.length} rendered, ${skippedRoutes.length} skipped)`);
@@ -4293,9 +4441,9 @@ var configSchema = t.Object({
4293
4441
  });
4294
4442
 
4295
4443
  // src/router.ts
4296
- import { existsSync as existsSync6 } from "fs";
4444
+ import { existsSync as existsSync7 } from "fs";
4297
4445
  import { readdir } from "fs/promises";
4298
- import { join as join7, parse } from "path";
4446
+ import { join as join8, parse as parse2 } from "path";
4299
4447
  import { Elysia as Elysia2, t as t2 } from "elysia";
4300
4448
 
4301
4449
  // src/internal.ts
@@ -4304,11 +4452,6 @@ function getCompileContext() {
4304
4452
  return _compileCtx;
4305
4453
  }
4306
4454
 
4307
- // src/render/dev-cache.ts
4308
- var devISRLoaderCache = new Map;
4309
- var devSSGLoaderCache = new Map;
4310
- var sourceFileToCacheKeys = new Map;
4311
-
4312
4455
  // src/utils.ts
4313
4456
  function isFurinPage(value) {
4314
4457
  return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_PAGE";
@@ -4359,7 +4502,7 @@ async function scanPages(pagesDir) {
4359
4502
  async function scanRootLayout(pagesDir) {
4360
4503
  const rootPath = `${pagesDir}/root.tsx`;
4361
4504
  const ctx = getCompileContext();
4362
- if (!(existsSync6(rootPath) || ctx?.modules[rootPath])) {
4505
+ if (!(existsSync7(rootPath) || ctx?.modules[rootPath])) {
4363
4506
  throw new Error("[furin] root.tsx: not found.");
4364
4507
  }
4365
4508
  const mod = ctx?.modules[rootPath] ?? await import(rootPath);
@@ -4392,7 +4535,7 @@ function getSourceModuleCandidates(dir, name) {
4392
4535
  async function loadConventionComponent(dir, name) {
4393
4536
  const ctx = getCompileContext();
4394
4537
  for (const filePath of getSourceModuleCandidates(dir, name)) {
4395
- if (existsSync6(filePath) || ctx?.modules[filePath]) {
4538
+ if (existsSync7(filePath) || ctx?.modules[filePath]) {
4396
4539
  const mod = ctx?.modules[filePath] ?? await import(filePath);
4397
4540
  if (mod.default) {
4398
4541
  return { component: mod.default, path: filePath };
@@ -4410,7 +4553,7 @@ async function scanPageFiles(pagesDir, root) {
4410
4553
  continue;
4411
4554
  }
4412
4555
  const relativePath = absolutePath.replace(`${pagesDir}/`, "");
4413
- const fileName = parse(relativePath).name;
4556
+ const fileName = parse2(relativePath).name;
4414
4557
  if (fileName.startsWith("_") || fileName === "root" || isConventionFileName(fileName)) {
4415
4558
  continue;
4416
4559
  }
@@ -4529,7 +4672,7 @@ async function collectPageFilePaths(dir) {
4529
4672
  const files = [];
4530
4673
  const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name));
4531
4674
  for (const entry of entries) {
4532
- const absolutePath = join7(dir, entry.name);
4675
+ const absolutePath = join8(dir, entry.name);
4533
4676
  if (entry.isDirectory()) {
4534
4677
  files.push(...await collectPageFilePaths(absolutePath));
4535
4678
  continue;
@@ -4560,7 +4703,7 @@ function filePathToPattern(path) {
4560
4703
  const parts = path.replaceAll("\\", "/").split("/");
4561
4704
  const segments = [];
4562
4705
  for (const part of parts) {
4563
- const name = parse(part).name;
4706
+ const name = parse2(part).name;
4564
4707
  if (name === "index") {
4565
4708
  continue;
4566
4709
  }
@@ -4580,11 +4723,39 @@ function filePathToPattern(path) {
4580
4723
 
4581
4724
  // src/build/scan-server.ts
4582
4725
  import { readFileSync as readFileSync2 } from "fs";
4583
- import { parseSync as parseSync2 } from "oxc-parser";
4726
+ import { parse as parse3 } from "yuku-parser";
4727
+ function detectLangFromPath(filePath) {
4728
+ if (filePath.endsWith(".d.ts")) {
4729
+ return "dts";
4730
+ }
4731
+ const ext = filePath.split(".").pop()?.toLowerCase();
4732
+ switch (ext) {
4733
+ case "ts":
4734
+ return "ts";
4735
+ case "tsx":
4736
+ return "tsx";
4737
+ case "jsx":
4738
+ return "jsx";
4739
+ default:
4740
+ return "js";
4741
+ }
4742
+ }
4584
4743
  function scanFurinInstances(serverEntryPath) {
4585
4744
  const code = readFileSync2(serverEntryPath, "utf8");
4586
- const { program, errors } = parseSync2(serverEntryPath, code);
4587
- if (errors.length > 0) {
4745
+ let lang = detectLangFromPath(serverEntryPath);
4746
+ if (lang === "dts") {
4747
+ return [];
4748
+ }
4749
+ let parseInput = code;
4750
+ if (lang === "ts" || lang === "tsx") {
4751
+ const transpiler = new Bun.Transpiler({ loader: lang });
4752
+ parseInput = transpiler.transformSync(code);
4753
+ lang = "js";
4754
+ }
4755
+ const { program, diagnostics } = parse3(parseInput, { sourceType: "module", lang });
4756
+ const firstError = diagnostics.find((d) => d.severity === "error");
4757
+ if (firstError) {
4758
+ console.error("[furin] scan-server: parse error:", firstError.message, "in", serverEntryPath);
4588
4759
  return [];
4589
4760
  }
4590
4761
  const results = [];
@@ -4672,19 +4843,19 @@ function resolvePagesDirFromServer(serverEntry, rootDir) {
4672
4843
  }
4673
4844
  async function buildApp(options) {
4674
4845
  const rootDir = resolve3(options.rootDir ?? process.cwd());
4675
- const buildRoot = join8(rootDir, BUILD_OUTPUT_DIR);
4846
+ const buildRoot = join9(rootDir, BUILD_OUTPUT_DIR);
4676
4847
  const serverEntry = (() => {
4677
4848
  if (options.target === "static") {
4678
4849
  return null;
4679
4850
  }
4680
4851
  if (options.serverEntry) {
4681
4852
  const resolved = resolve3(rootDir, options.serverEntry);
4682
- if (existsSync7(resolved)) {
4853
+ if (existsSync8(resolved)) {
4683
4854
  return resolved;
4684
4855
  }
4685
4856
  }
4686
4857
  const entry = resolve3(rootDir, "src/server.ts");
4687
- if (!existsSync7(entry)) {
4858
+ if (!existsSync8(entry)) {
4688
4859
  throw new Error("[furin] Entrypoint server.ts not found");
4689
4860
  }
4690
4861
  return entry;
@@ -4736,7 +4907,7 @@ async function buildApp(options) {
4736
4907
  throw new Error(`[furin] Unsupported build target "${target}"`);
4737
4908
  }
4738
4909
  }
4739
- writeFileSync6(join8(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
4910
+ writeFileSync6(join9(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
4740
4911
  `);
4741
4912
  return {
4742
4913
  manifest,
@@ -4745,7 +4916,7 @@ async function buildApp(options) {
4745
4916
  }
4746
4917
 
4747
4918
  // src/cli/config.ts
4748
- import { existsSync as existsSync8 } from "fs";
4919
+ import { existsSync as existsSync9 } from "fs";
4749
4920
  import { resolve as resolve4 } from "path";
4750
4921
  import { pathToFileURL } from "url";
4751
4922
  import { TypeCompiler } from "elysia/type-system";
@@ -4757,7 +4928,7 @@ var DEFAULT_CONFIG_FILENAMES = [
4757
4928
  ];
4758
4929
  async function loadCliConfig(cwd, explicitConfigPath) {
4759
4930
  const rootDir = resolve4(cwd);
4760
- const configPath = explicitConfigPath ? resolve4(rootDir, explicitConfigPath) : DEFAULT_CONFIG_FILENAMES.map((filename) => resolve4(rootDir, filename)).find((path) => existsSync8(path));
4931
+ const configPath = explicitConfigPath ? resolve4(rootDir, explicitConfigPath) : DEFAULT_CONFIG_FILENAMES.map((filename) => resolve4(rootDir, filename)).find((path) => existsSync9(path));
4761
4932
  if (!configPath) {
4762
4933
  return {
4763
4934
  configPath: null,
@@ -4835,7 +5006,7 @@ if (command === "build") {
4835
5006
  const isStaticTarget = target === "static";
4836
5007
  const resolvedServerEntry = isStaticTarget ? undefined : (() => {
4837
5008
  const entry = resolve5(config.rootDir, config.serverEntry ?? "src/server.ts");
4838
- if (!existsSync9(entry)) {
5009
+ if (!existsSync10(entry)) {
4839
5010
  const expected = config.serverEntry ?? "src/server.ts";
4840
5011
  throw new Error(`[furin] Entrypoint ${expected} not found`);
4841
5012
  }