@teyik0/furin 0.4.0-alpha.1 → 0.4.0-alpha.2

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.
Files changed (193) hide show
  1. package/dist/adapter/bun.d.ts +2 -18
  2. package/dist/adapter/package.d.ts +2 -2
  3. package/dist/adapter/runtime-build.d.ts +33 -0
  4. package/dist/adapter/vercel.d.ts +3 -0
  5. package/dist/build/client.d.ts +1 -1
  6. package/dist/build/compile-entry.d.ts +4 -3
  7. package/dist/build/compile-entry.ts +24 -69
  8. package/dist/build/entry-template.d.ts +4 -2
  9. package/dist/build/entry-template.ts +31 -8
  10. package/dist/build/index.d.ts +1 -1
  11. package/dist/build/index.js +8596 -6375
  12. package/dist/build/ssg-cache.d.ts +13 -0
  13. package/dist/build/types.d.ts +25 -2
  14. package/dist/build/virtual-entry.d.ts +8 -0
  15. package/dist/cache.d.ts +5 -0
  16. package/dist/cache.js +97 -0
  17. package/dist/cli/index.js +9099 -6771
  18. package/dist/cli/preview.d.ts +7 -0
  19. package/dist/client/boundaries.d.ts +1 -0
  20. package/dist/client/browser-events-runtime.d.ts +2 -0
  21. package/dist/client/browser-events.d.ts +2 -0
  22. package/dist/client/define-route.d.ts +9 -8
  23. package/dist/client/dev-error-overlay.d.ts +1 -0
  24. package/dist/client/dev-error-overlay.ts +201 -0
  25. package/dist/client/document.d.ts +1 -0
  26. package/dist/client/hmr.d.ts +4 -2
  27. package/dist/client/link.js +251 -82
  28. package/dist/client/router/provider.d.ts +1 -1
  29. package/dist/client/router/sync-catch-up.d.ts +1 -1
  30. package/dist/client/router/types.d.ts +8 -10
  31. package/dist/client.js +37 -23
  32. package/dist/config.d.ts +17 -0
  33. package/dist/config.js +9 -1
  34. package/dist/define-route.d.ts +11 -8
  35. package/dist/devtools/protocol.d.ts +2 -2
  36. package/dist/furin.d.ts +1 -1
  37. package/dist/furin.js +12991 -9491
  38. package/dist/plugin/index.js +476 -7
  39. package/dist/plugin/routes.d.ts +4 -3
  40. package/dist/rsc/build/index.d.ts +5 -1
  41. package/dist/server/browser-events/plugin.d.ts +11 -0
  42. package/dist/server/browser-events/types.d.ts +9 -0
  43. package/dist/server/cache/invalidation.d.ts +1 -2
  44. package/dist/server/cache/isr.d.ts +1 -0
  45. package/dist/server/cache/purger.d.ts +7 -0
  46. package/dist/server/cache/runtime-cache.d.ts +21 -0
  47. package/dist/server/dev/browser-events.d.ts +4 -0
  48. package/dist/server/dev/diagnostics.d.ts +39 -0
  49. package/dist/server/dev/error.d.ts +17 -0
  50. package/dist/server/dev/graph.d.ts +86 -0
  51. package/dist/server/dev/plugin.d.ts +9 -0
  52. package/dist/server/dev/request-security.d.ts +1 -0
  53. package/dist/server/dev/rewrite-module-specifiers.d.ts +7 -0
  54. package/dist/server/dev/runtime.production.d.ts +5 -0
  55. package/dist/server/dev/symbolicate.d.ts +11 -0
  56. package/dist/server/dev/transform-failure.d.ts +4 -0
  57. package/dist/server/dev-page-plugin.production.d.ts +1 -0
  58. package/dist/server/devtools/hub.d.ts +3 -2
  59. package/dist/server/devtools/instrumentation.d.ts +1 -1
  60. package/dist/server/devtools/instrumentation.production.d.ts +1 -1
  61. package/dist/server/devtools/plugin.d.ts +1 -1
  62. package/dist/server/external-prerender.d.ts +2 -0
  63. package/dist/server/instance.d.ts +2 -2
  64. package/dist/server/internal.d.ts +14 -2
  65. package/dist/server/internal.js +436 -1
  66. package/dist/server/render/element.d.ts +1 -0
  67. package/dist/server/render/index.d.ts +1 -1
  68. package/dist/server/render/index.ts +1 -1
  69. package/dist/server/render/ppr-document.d.ts +21 -0
  70. package/dist/server/render/ppr-request.d.ts +26 -0
  71. package/dist/server/render/ppr-route.d.ts +3 -1
  72. package/dist/server/render/shell.ts +0 -12
  73. package/dist/server/render/ssg.d.ts +2 -0
  74. package/dist/server/render/ssr.d.ts +17 -6
  75. package/dist/server/router/hmr.production.d.ts +2 -0
  76. package/dist/server/router/patterns.d.ts +1 -0
  77. package/dist/server/router/plugin.d.ts +3 -1
  78. package/dist/server/sync/adapter.d.ts +13 -0
  79. package/dist/server/sync/config.d.ts +5 -5
  80. package/dist/server/sync/index.d.ts +6 -6
  81. package/dist/server/sync/index.js +491 -516
  82. package/dist/server/sync/notifier.d.ts +1 -0
  83. package/dist/server/sync/postgres/index.d.ts +12 -1
  84. package/dist/server/sync/postgres/index.js +101 -6
  85. package/dist/server/sync/stream.d.ts +4 -13
  86. package/dist/shared/await.d.ts +3 -3
  87. package/dist/shared/browser-events.d.ts +22 -0
  88. package/dist/shared/compact-json.d.ts +8 -0
  89. package/dist/shared/deferred-ndjson.d.ts +6 -5
  90. package/dist/shared/dev-diagnostics.d.ts +36 -0
  91. package/dist/shared/prefix.d.ts +2 -0
  92. package/package.json +16 -7
  93. package/src/adapter/README.md +45 -0
  94. package/src/adapter/bun.ts +45 -268
  95. package/src/adapter/package.ts +15 -9
  96. package/src/adapter/runtime-build.ts +375 -0
  97. package/src/adapter/static.ts +79 -2
  98. package/src/adapter/vercel.ts +857 -0
  99. package/src/build/client.ts +38 -13
  100. package/src/build/compile-entry.ts +24 -69
  101. package/src/build/entry-template.ts +31 -8
  102. package/src/build/hydrate.ts +60 -20
  103. package/src/build/index.ts +19 -5
  104. package/src/build/production-instrumentation.ts +56 -4
  105. package/src/build/shared.ts +2 -1
  106. package/src/build/ssg-cache.ts +97 -11
  107. package/src/build/types.ts +31 -2
  108. package/src/build/virtual-entry.ts +27 -0
  109. package/src/cache.ts +14 -0
  110. package/src/cli/index.ts +55 -3
  111. package/src/cli/preview.ts +90 -0
  112. package/src/client/boundaries.tsx +10 -1
  113. package/src/client/browser-events-runtime.ts +204 -0
  114. package/src/client/browser-events.ts +22 -0
  115. package/src/client/define-route.ts +7 -17
  116. package/src/client/dev-error-overlay.ts +201 -0
  117. package/src/client/document.tsx +4 -7
  118. package/src/client/hmr.ts +26 -3
  119. package/src/client/router/boundary-tree.tsx +4 -4
  120. package/src/client/router/provider.tsx +165 -63
  121. package/src/client/router/sync-catch-up.ts +3 -4
  122. package/src/client/router/types.ts +6 -6
  123. package/src/config.ts +25 -0
  124. package/src/define-route.ts +20 -7
  125. package/src/devtools/devtools-element.js +56 -77
  126. package/src/devtools/protocol.ts +2 -2
  127. package/src/furin.ts +157 -77
  128. package/src/plugin/routes.ts +206 -36
  129. package/src/plugin/transform-client.ts +685 -3
  130. package/src/react-dom-edge.d.ts +6 -0
  131. package/src/rsc/build/index.ts +15 -3
  132. package/src/server/auto-invalidate/runtime.ts +5 -2
  133. package/src/server/browser-events/plugin.ts +168 -0
  134. package/src/server/browser-events/types.ts +11 -0
  135. package/src/server/cache/dev-loader.ts +30 -29
  136. package/src/server/cache/invalidation.ts +13 -22
  137. package/src/server/cache/isr.ts +9 -0
  138. package/src/server/cache/purger.ts +41 -0
  139. package/src/server/cache/runtime-cache.ts +137 -0
  140. package/src/server/dev/browser-events.ts +54 -0
  141. package/src/server/dev/diagnostics.ts +297 -0
  142. package/src/server/dev/error.ts +148 -0
  143. package/src/server/dev/graph.ts +438 -0
  144. package/src/server/dev/plugin.ts +130 -0
  145. package/src/server/dev/request-security.ts +38 -0
  146. package/src/server/dev/rewrite-module-specifiers.ts +81 -0
  147. package/src/server/dev/runtime.production.ts +24 -0
  148. package/src/server/dev/symbolicate.ts +135 -0
  149. package/src/server/dev/transform-failure.ts +8 -0
  150. package/src/server/dev-page-plugin.production.ts +3 -0
  151. package/src/server/dev-page-plugin.ts +92 -53
  152. package/src/server/devtools/hub.ts +6 -5
  153. package/src/server/devtools/instrumentation.production.ts +1 -1
  154. package/src/server/devtools/instrumentation.ts +12 -6
  155. package/src/server/devtools/plugin.ts +7 -150
  156. package/src/server/external-prerender.ts +10 -0
  157. package/src/server/instance.ts +3 -3
  158. package/src/server/internal.ts +39 -2
  159. package/src/server/render/assemble.ts +4 -4
  160. package/src/server/render/document.tsx +13 -4
  161. package/src/server/render/element.tsx +18 -14
  162. package/src/server/render/index.ts +1 -1
  163. package/src/server/render/isr.ts +44 -19
  164. package/src/server/render/loaders.ts +13 -3
  165. package/src/server/render/not-found.ts +28 -4
  166. package/src/server/render/ppr-document.ts +239 -0
  167. package/src/server/render/ppr-request.ts +104 -0
  168. package/src/server/render/ppr-route.ts +152 -31
  169. package/src/server/render/shell.ts +0 -12
  170. package/src/server/render/ssg.ts +38 -20
  171. package/src/server/render/ssr.ts +211 -83
  172. package/src/server/render/template.ts +47 -11
  173. package/src/server/router/defined-route.ts +7 -39
  174. package/src/server/router/hmr.production.ts +7 -0
  175. package/src/server/router/hmr.ts +106 -67
  176. package/src/server/router/patterns.ts +5 -1
  177. package/src/server/router/plugin.ts +124 -35
  178. package/src/server/router/source-version.ts +3 -10
  179. package/src/server/sync/adapter.ts +13 -0
  180. package/src/server/sync/config.ts +12 -12
  181. package/src/server/sync/index.ts +8 -8
  182. package/src/server/sync/notifier.ts +1 -0
  183. package/src/server/sync/plugin.ts +4 -1
  184. package/src/server/sync/postgres/index.ts +111 -5
  185. package/src/server/sync/runtime.ts +12 -0
  186. package/src/server/sync/stream.ts +78 -113
  187. package/src/shared/await.tsx +3 -3
  188. package/src/shared/browser-events.ts +28 -0
  189. package/src/shared/compact-json.ts +77 -0
  190. package/src/shared/deferred-ndjson.ts +20 -6
  191. package/src/shared/dev-diagnostics.ts +44 -0
  192. package/src/shared/prefix.ts +8 -0
  193. package/src/shared/route-map.ts +10 -1
@@ -0,0 +1,375 @@
1
+ import { existsSync, writeFileSync } from "node:fs";
2
+ import { basename, dirname, join, relative, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { buildClient } from "../build/client.ts";
5
+ import type { BuildEntryOptions, EntryAppContext } from "../build/entry-template.ts";
6
+ import { toPosixPath } from "../build/shared.ts";
7
+ import {
8
+ buildRoutePrerenders,
9
+ buildSSGCacheSnapshot,
10
+ type RoutePrerender,
11
+ type SSGCacheSnapshot,
12
+ } from "../build/ssg-cache.ts";
13
+ import type { BuildAppOptions } from "../build/types.ts";
14
+ import { routeModuleSpecifier, routeSourcePaths } from "../plugin/routes.ts";
15
+ import { buildRscGraph } from "../rsc/build/index.ts";
16
+ import { ssgRouteCache } from "../server/cache/ssg.ts";
17
+ import { hasRequestLoader } from "../server/render/loaders.ts";
18
+ import { generateProdIndexHtml } from "../server/render/shell.ts";
19
+ import { setProductionTemplateContent } from "../server/render/template.ts";
20
+ import type { ResolvedRoute, RootLayout } from "../server/router/types.ts";
21
+ import { clientDirNameForPrefix } from "../shared/prefix.ts";
22
+
23
+ // import.meta.resolve() runs at runtime (not inlined at bundle time), resolves
24
+ // through package exports, and is the Web-standard API. The main entry is
25
+ // `src/furin.ts` (or `dist/furin.js`), so we strip two path segments to reach
26
+ // the package root.
27
+ const _pkgRoot = dirname(dirname(fileURLToPath(import.meta.resolve("@teyik0/furin"))));
28
+ const _pkgSrcDir = existsSync(join(_pkgRoot, "src", "furin.ts"))
29
+ ? join(_pkgRoot, "src")
30
+ : join(_pkgRoot, "dist");
31
+ // The published package always ships `src/` (see package.json "files"), and the
32
+ // "bun" export condition resolves to the TypeScript sources, so the fingerprint
33
+ // inputs are always the `.ts` files. Some of these inputs (e.g. entry-template)
34
+ // are never emitted to `dist/` as `.js`, so detecting the extension off the dist
35
+ // copy would point at files that don't exist and silently weaken the build ID.
36
+ const _ext = ".ts";
37
+ const PPR_ROUTE_IMPORT_RE = /ppr-route(?:\.ts)?$/;
38
+ const ANY_MODULE_RE = /.*/;
39
+ const REACT_SERVER_IMPORT_RE = /^react-dom\/server(?:\.edge)?$/;
40
+ const REACT_STATIC_IMPORT_RE = /^react-dom\/static\.edge$/;
41
+ const BUILD_ID_INPUT_PATHS = [
42
+ `${_pkgSrcDir}/build/compile-entry${_ext}`,
43
+ `${_pkgSrcDir}/build/entry-template${_ext}`,
44
+ `${_pkgSrcDir}/plugin/routes${_ext}`,
45
+ `${_pkgSrcDir}/server/render/document.tsx`,
46
+ `${_pkgSrcDir}/server/render/element.tsx`,
47
+ `${_pkgSrcDir}/server/render/index${_ext}`,
48
+ `${_pkgSrcDir}/server/render/isr${_ext}`,
49
+ `${_pkgSrcDir}/server/render/loaders${_ext}`,
50
+ `${_pkgSrcDir}/server/render/not-found${_ext}`,
51
+ `${_pkgSrcDir}/server/render/ppr-route${_ext}`,
52
+ `${_pkgSrcDir}/server/render/ppr-document${_ext}`,
53
+ `${_pkgSrcDir}/server/render/route-frame-transport${_ext}`,
54
+ `${_pkgSrcDir}/server/render/shell${_ext}`,
55
+ `${_pkgSrcDir}/server/render/ssr${_ext}`,
56
+ `${_pkgSrcDir}/shared/compact-json${_ext}`,
57
+ `${_pkgSrcDir}/shared/deferred-ndjson${_ext}`,
58
+ `${_pkgSrcDir}/shared/route-frame${_ext}`,
59
+ ];
60
+
61
+ function compareCodeUnits(a: string, b: string): number {
62
+ if (a < b) {
63
+ return -1;
64
+ }
65
+ if (a > b) {
66
+ return 1;
67
+ }
68
+ return 0;
69
+ }
70
+
71
+ /**
72
+ * Deterministic build-ID input covering everything that can change rendered
73
+ * output: client chunks, route shape, route/root/error/not-found source
74
+ * contents and the framework's own render pipeline sources.
75
+ */
76
+ export async function createBuildFingerprint(
77
+ entryChunk: string,
78
+ cssChunks: string[],
79
+ routes: ResolvedRoute[],
80
+ root: RootLayout,
81
+ serverEntry: string | null,
82
+ routeSources: string[],
83
+ projectRoot: string
84
+ ): Promise<string> {
85
+ const fingerprintPaths = new Set<string>([
86
+ root.path,
87
+ ...routes.map((route) => route.path),
88
+ ...routeSources,
89
+ ]);
90
+ if (serverEntry) {
91
+ fingerprintPaths.add(serverEntry);
92
+ }
93
+ if (root.errorPath) {
94
+ fingerprintPaths.add(root.errorPath);
95
+ }
96
+ if (root.notFoundPath) {
97
+ fingerprintPaths.add(root.notFoundPath);
98
+ }
99
+ for (const route of routes) {
100
+ for (const segment of route.segmentBoundaries) {
101
+ if (segment.errorPath) {
102
+ fingerprintPaths.add(segment.errorPath);
103
+ }
104
+ if (segment.notFoundPath) {
105
+ fingerprintPaths.add(segment.notFoundPath);
106
+ }
107
+ }
108
+ }
109
+ for (const path of BUILD_ID_INPUT_PATHS) {
110
+ if (!existsSync(path)) {
111
+ console.warn(
112
+ `[furin] Warning: build fingerprint input "${toPosixPath(path)}" is missing — ` +
113
+ "the generated build ID may not reflect all framework changes."
114
+ );
115
+ }
116
+ fingerprintPaths.add(path);
117
+ }
118
+
119
+ const fileParts = await Promise.all(
120
+ [...fingerprintPaths].toSorted().map(async (path) => {
121
+ const content = existsSync(path) ? await Bun.file(path).text() : "";
122
+ return `${stableFingerprintPath(path, projectRoot)}:${content}`;
123
+ })
124
+ );
125
+
126
+ const routeParts = routes
127
+ .map((route) =>
128
+ JSON.stringify({
129
+ mode: route.mode,
130
+ path: stableFingerprintPath(route.path, projectRoot),
131
+ pattern: route.pattern,
132
+ })
133
+ )
134
+ .sort(compareCodeUnits);
135
+
136
+ return [entryChunk, ...[...cssChunks].toSorted(), ...routeParts, ...fileParts].join("\n");
137
+ }
138
+
139
+ function stableFingerprintPath(path: string, projectRoot: string): string {
140
+ const projectPath = relative(projectRoot, path);
141
+ if (projectPath !== ".." && !projectPath.startsWith("../") && !projectPath.startsWith("..\\")) {
142
+ return `app/${toPosixPath(projectPath)}`;
143
+ }
144
+ const frameworkPath = relative(_pkgRoot, path);
145
+ if (
146
+ frameworkPath !== ".." &&
147
+ !frameworkPath.startsWith("../") &&
148
+ !frameworkPath.startsWith("..\\")
149
+ ) {
150
+ return `furin/${toPosixPath(frameworkPath)}`;
151
+ }
152
+ return `external/${basename(path)}`;
153
+ }
154
+
155
+ function buildCompileMetadata(root: RootLayout, routes: ResolvedRoute[]) {
156
+ const rootConventions =
157
+ root.errorPath || root.notFoundPath
158
+ ? {
159
+ errorPath: root.errorPath ? toPosixPath(root.errorPath) : undefined,
160
+ notFoundPath: root.notFoundPath ? toPosixPath(root.notFoundPath) : undefined,
161
+ }
162
+ : undefined;
163
+
164
+ const routeMetadata: NonNullable<EntryAppContext["routeMetadata"]> = {};
165
+ for (const route of routes) {
166
+ routeMetadata[toPosixPath(route.path)] = {
167
+ segmentBoundaries: route.segmentBoundaries.map((boundary) => ({
168
+ depth: boundary.depth,
169
+ errorPath: boundary.errorPath ? toPosixPath(boundary.errorPath) : undefined,
170
+ notFoundPath: boundary.notFoundPath ? toPosixPath(boundary.notFoundPath) : undefined,
171
+ path: toPosixPath(boundary.path),
172
+ })),
173
+ };
174
+ }
175
+
176
+ return { rootConventions, routeMetadata };
177
+ }
178
+
179
+ /** One mounted app's build input (root + routes scanned from its pagesDir). */
180
+ export interface RuntimeTargetApp {
181
+ pagesDir: string;
182
+ prefix: string;
183
+ root: RootLayout;
184
+ routes: ResolvedRoute[];
185
+ }
186
+
187
+ /** Avoid loading React's resumable renderer in applications without PPR routes. */
188
+ export function pprRuntimePlugin(apps: RuntimeTargetApp[]): Bun.BunPlugin {
189
+ const enabled = apps.some((app) =>
190
+ app.routes.some(
191
+ (route) =>
192
+ route.mode !== "ssr" &&
193
+ (app.root.route.requestLoader !== undefined || hasRequestLoader(route))
194
+ )
195
+ );
196
+ const pprPath = resolve(_pkgSrcDir, "server/render/ppr-route.ts");
197
+ const reactServerPath = fileURLToPath(
198
+ import.meta.resolve(enabled ? "react-dom/server.edge" : "react-dom/server")
199
+ );
200
+ const reactStaticPath = fileURLToPath(import.meta.resolve("react-dom/static.edge"));
201
+ return {
202
+ name: "furin-ppr-runtime",
203
+ setup(build) {
204
+ // Resolve before user plugins: linked-project plugins commonly resolve
205
+ // peer dependencies from their own root and can otherwise recurse.
206
+ build.onResolve({ filter: REACT_SERVER_IMPORT_RE }, ({ importer }) =>
207
+ isFrameworkRuntimeImporter(importer) ? { path: reactServerPath } : undefined
208
+ );
209
+ build.onResolve({ filter: REACT_STATIC_IMPORT_RE }, ({ importer }) =>
210
+ isFrameworkRuntimeImporter(importer) ? { path: reactStaticPath } : undefined
211
+ );
212
+ if (enabled) {
213
+ return;
214
+ }
215
+ build.onResolve({ filter: PPR_ROUTE_IMPORT_RE }, ({ path, importer }) => {
216
+ const absolute = resolve(dirname(importer.split("?")[0] as string), path);
217
+ if (absolute !== pprPath && `${absolute}.ts` !== pprPath) {
218
+ return;
219
+ }
220
+ return { namespace: "furin-no-ppr", path: "ppr" };
221
+ });
222
+ build.onLoad({ filter: ANY_MODULE_RE, namespace: "furin-no-ppr" }, () => ({
223
+ contents: `export function clearPprRouteCache() {}
224
+ export function invalidatePprRoute() { return false; }
225
+ export function renderPprRoute() { throw new Error("[furin] PPR route missing from the build manifest."); }
226
+ export const runPprPublicLoaders = renderPprRoute;`,
227
+ loader: "js",
228
+ }));
229
+ },
230
+ };
231
+ }
232
+
233
+ function isFrameworkRuntimeImporter(importer: string): boolean {
234
+ if (importer === "") {
235
+ return false;
236
+ }
237
+ const fromRuntimeRoot = relative(_pkgSrcDir, importer.split("?")[0] as string);
238
+ return (
239
+ fromRuntimeRoot !== ".." &&
240
+ !fromRuntimeRoot.startsWith("../") &&
241
+ !fromRuntimeRoot.startsWith("..\\")
242
+ );
243
+ }
244
+
245
+ export interface RuntimeAppBuild {
246
+ buildId: string;
247
+ clientDir: string;
248
+ entryApp: BuildEntryOptions["apps"][number];
249
+ indexHtml: string;
250
+ prerenders: RoutePrerender[];
251
+ }
252
+
253
+ /** Builds one app's client bundle and compile-context payload. */
254
+ export async function buildRuntimeApp(
255
+ app: RuntimeTargetApp,
256
+ projectRoot: string,
257
+ targetDir: string,
258
+ serverEntry: string | null,
259
+ options: BuildAppOptions,
260
+ targetName: "bun" | "vercel"
261
+ ): Promise<RuntimeAppBuild> {
262
+ const { prefix, root, routes } = app;
263
+ const modulePaths = routeSourcePaths(app);
264
+ const clientDirName = clientDirNameForPrefix(prefix);
265
+ const label = prefix === "" ? "root app" : `app "${prefix}"`;
266
+
267
+ const { entryChunk, cssChunks } = await buildClient(routes, {
268
+ basePath: prefix,
269
+ clientDirName,
270
+ clientLogging: options.clientLogging ?? false,
271
+ metafilePath: options.analyze
272
+ ? join(dirname(targetDir), "analysis", `${targetName}-${clientDirName}.json`)
273
+ : undefined,
274
+ optimizeImports: options.optimizeImports,
275
+ outDir: targetDir,
276
+ pagesDir: app.pagesDir,
277
+ plugins: options.plugins,
278
+ publicPath: `${prefix}/_client/`,
279
+ reactCompiler: options.reactCompiler,
280
+ rootLayout: root.path,
281
+ });
282
+
283
+ const buildFingerprint = await createBuildFingerprint(
284
+ `${prefix}\n${entryChunk}`,
285
+ cssChunks,
286
+ routes,
287
+ root,
288
+ serverEntry,
289
+ modulePaths,
290
+ projectRoot
291
+ );
292
+ const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
293
+
294
+ const clientDir = join(targetDir, clientDirName);
295
+ const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
296
+ writeFileSync(join(clientDir, "index.html"), indexHtml);
297
+
298
+ setProductionTemplateContent(indexHtml);
299
+ ssgRouteCache().clear();
300
+ let ssgCache: SSGCacheSnapshot | undefined;
301
+ let prerenders: RoutePrerender[] = [];
302
+ if (serverEntry) {
303
+ if (targetName === "vercel") {
304
+ prerenders = await buildRoutePrerenders(routes, root, "http://localhost", prefix);
305
+ } else {
306
+ ssgCache = await buildSSGCacheSnapshot(routes, root, "http://localhost", prefix);
307
+ }
308
+ }
309
+
310
+ const { rootConventions, routeMetadata } = buildCompileMetadata(root, routes);
311
+ console.log(`[furin] Built ${label} (buildId ${buildId})`);
312
+
313
+ return {
314
+ buildId,
315
+ clientDir,
316
+ entryApp: {
317
+ buildId,
318
+ clientLogging: options.clientLogging ?? false,
319
+ embed: options.compile === "embed" ? { clientDir } : undefined,
320
+ modulePaths,
321
+ nativeRoutes: routeModuleSpecifier(app),
322
+ prefix,
323
+ rootConventions,
324
+ rootPath: root.path,
325
+ routeMetadata,
326
+ routes: routes.map((route) => ({
327
+ mode: route.mode,
328
+ path: route.path,
329
+ pattern: route.pattern,
330
+ })),
331
+ ssgCache,
332
+ },
333
+ indexHtml,
334
+ prerenders,
335
+ };
336
+ }
337
+
338
+ export async function buildRuntimeAppsSequentially(
339
+ apps: RuntimeTargetApp[],
340
+ projectRoot: string,
341
+ targetDir: string,
342
+ serverEntry: string | null,
343
+ options: BuildAppOptions,
344
+ targetName: "bun" | "vercel"
345
+ ): Promise<{
346
+ builds: RuntimeAppBuild[];
347
+ entryApps: BuildEntryOptions["apps"];
348
+ headlineBuildId: string;
349
+ }> {
350
+ const builds: RuntimeAppBuild[] = [];
351
+ const entryApps: BuildEntryOptions["apps"] = [];
352
+ let headlineBuildId = "";
353
+
354
+ for (const app of apps) {
355
+ // biome-ignore lint/performance/noAwaitInLoops: each app installs a build-time template before SSG snapshotting, so this must remain ordered.
356
+ const built = await buildRuntimeApp(
357
+ app,
358
+ projectRoot,
359
+ targetDir,
360
+ serverEntry,
361
+ options,
362
+ targetName
363
+ );
364
+ builds.push(built);
365
+ entryApps.push(built.entryApp);
366
+ if (app.prefix === "" || headlineBuildId === "") {
367
+ headlineBuildId = built.buildId;
368
+ }
369
+ }
370
+ if (serverEntry) {
371
+ await buildRscGraph(apps, targetDir, headlineBuildId, options.plugins);
372
+ }
373
+
374
+ return { builds, entryApps, headlineBuildId };
375
+ }
@@ -1,9 +1,11 @@
1
1
  // biome-ignore-all lint/performance/noAwaitInLoops: static build emits routes in sequence to keep output deterministic
2
2
  import { cpSync, existsSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { toCrossJSONAsync } from "seroval";
4
5
  import { buildClient } from "../build/client.ts";
5
6
  import { ensureDir, toPosixPath } from "../build/shared.ts";
6
7
  import type { BuildAppOptions, StaticTargetBuildManifest } from "../build/types.ts";
8
+ import { toLogical } from "../client/router/link-utils.ts";
7
9
  import type { StaticExportConfig } from "../config.ts";
8
10
  import { resolvePath } from "../server/render/assemble.ts";
9
11
  import { generateProdIndexHtml } from "../server/render/shell.ts";
@@ -23,6 +25,13 @@ const DYNAMIC_SEGMENT_RE = /\/:[^/]+|\/\*/;
23
25
  /** Strips all trailing slashes from a string. */
24
26
  const TRAILING_SLASHES_RE = /\/+$/;
25
27
 
28
+ const STATIC_RENDER_ORIGIN = "http://localhost";
29
+
30
+ interface StaticRedirectLocation {
31
+ html: string;
32
+ spa: string | null;
33
+ }
34
+
26
35
  // ── Path helpers ──────────────────────────────────────────────────────────────
27
36
 
28
37
  /**
@@ -53,6 +62,55 @@ function sortRouteList(routes: string[]): string[] {
53
62
  return routes.toSorted((a, b) => (a < b ? -1 : Number(a > b)));
54
63
  }
55
64
 
65
+ function escapeHtmlAttribute(value: string): string {
66
+ return value
67
+ .replaceAll("&", "&amp;")
68
+ .replaceAll('"', "&quot;")
69
+ .replaceAll("<", "&lt;")
70
+ .replaceAll(">", "&gt;");
71
+ }
72
+
73
+ function resolveStaticRedirectLocation(
74
+ location: string,
75
+ basePath: string,
76
+ sourcePath: string
77
+ ): StaticRedirectLocation {
78
+ const sourceUrl = new URL(sourcePath, STATIC_RENDER_ORIGIN);
79
+ const targetUrl = new URL(location, sourceUrl);
80
+ if (targetUrl.protocol !== "http:" && targetUrl.protocol !== "https:") {
81
+ throw new Error(
82
+ `[furin] static: redirect from "${sourcePath}" uses unsupported protocol "${targetUrl.protocol}".`
83
+ );
84
+ }
85
+ if (targetUrl.origin !== sourceUrl.origin) {
86
+ return { html: targetUrl.href, spa: null };
87
+ }
88
+
89
+ const suffix = `${targetUrl.search}${targetUrl.hash}`;
90
+ const spa = `${toLogical(targetUrl.pathname, basePath)}${suffix}`;
91
+ if (
92
+ basePath === "" ||
93
+ targetUrl.pathname === basePath ||
94
+ targetUrl.pathname.startsWith(`${basePath}/`)
95
+ ) {
96
+ return { html: `${targetUrl.pathname}${suffix}`, spa };
97
+ }
98
+ const pathname = targetUrl.pathname === "/" ? `${basePath}/` : `${basePath}${targetUrl.pathname}`;
99
+ return { html: `${pathname}${suffix}`, spa };
100
+ }
101
+
102
+ function createStaticRedirectHtml(location: string): string {
103
+ const escapedLocation = escapeHtmlAttribute(location);
104
+ return (
105
+ "<!doctype html>\n" +
106
+ '<meta charset="utf-8">\n' +
107
+ `<meta http-equiv="refresh" content="0;url=${escapedLocation}">\n` +
108
+ `<link rel="canonical" href="${escapedLocation}">\n` +
109
+ "<title>Redirecting…</title>\n" +
110
+ `<a href="${escapedLocation}">Redirecting…</a>\n`
111
+ );
112
+ }
113
+
56
114
  function assertNoStaticExportSkips(onSSR: "error" | "skip", skippedRoutes: string[]): void {
57
115
  if (onSSR !== "error" || skippedRoutes.length === 0) {
58
116
  return;
@@ -108,8 +166,24 @@ async function prerenderAndWrite(
108
166
  );
109
167
 
110
168
  if (entry instanceof Response) {
111
- console.warn(
112
- `[furin] static: route "${route.pattern}" loader returned a redirect — skipping.`
169
+ const location = entry.headers.get("location");
170
+ if (entry.status < 300 || entry.status >= 400 || location === null) {
171
+ throw new Error(
172
+ `[furin] static: route "${route.pattern}" returned a response that cannot be exported.`
173
+ );
174
+ }
175
+ const staticLocation = resolveStaticRedirectLocation(location, basePath, urlPath);
176
+ ensureDir(dirname(htmlOutputFile));
177
+ writeFileSync(htmlOutputFile, createStaticRedirectHtml(staticLocation.html));
178
+ if (staticLocation.spa !== null) {
179
+ const serializedRedirect = await toCrossJSONAsync({
180
+ __furinRedirect: staticLocation.spa,
181
+ });
182
+ writeFileSync(dataOutputFile, `${JSON.stringify(serializedRedirect)}\n`);
183
+ }
184
+ renderedRoutes.push(urlPath);
185
+ console.log(
186
+ `[furin] static: ${urlPath} → ${toPosixPath(htmlOutputFile)} (redirects to ${staticLocation.html})`
113
187
  );
114
188
  return;
115
189
  }
@@ -388,10 +462,13 @@ export async function buildStaticTarget(
388
462
  const { entryChunk, cssChunks } = await buildClient(ssgRoutes, {
389
463
  basePath,
390
464
  clientLogging: Boolean(options.clientLogging),
465
+ metafilePath: options.analyze ? join(buildRoot, "analysis", "static-client.json") : undefined,
466
+ optimizeImports: options.optimizeImports,
391
467
  outDir: targetDir,
392
468
  pagesDir: dirname(root.path),
393
469
  plugins: options.plugins,
394
470
  publicPath,
471
+ reactCompiler: options.reactCompiler,
395
472
  rootLayout: root.path,
396
473
  });
397
474