@teyik0/furin 0.2.0-alpha.4 → 0.3.0-alpha.1

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 (263) hide show
  1. package/README.md +2 -3
  2. package/dist/adapter/bun.d.ts +17 -1
  3. package/dist/adapter/package.d.ts +26 -0
  4. package/dist/adapter/static.d.ts +1 -1
  5. package/dist/build/bun-build.d.ts +3 -0
  6. package/dist/build/client.d.ts +1 -1
  7. package/dist/build/compile-entry.d.ts +3 -3
  8. package/dist/build/compile-entry.ts +88 -83
  9. package/dist/build/entry-template.d.ts +37 -9
  10. package/dist/build/entry-template.ts +109 -56
  11. package/dist/build/hydrate.d.ts +2 -2
  12. package/dist/build/index.js +6817 -4544
  13. package/dist/build/production-instrumentation.d.ts +1 -0
  14. package/dist/build/route-types.d.ts +1 -1
  15. package/dist/build/scan-server.d.ts +10 -4
  16. package/dist/build/server-routes-entry.d.ts +3 -3
  17. package/dist/build/server-routes-entry.ts +5 -11
  18. package/dist/build/ssg-cache.d.ts +1 -1
  19. package/dist/build/types.d.ts +37 -1
  20. package/dist/cli/config.d.ts +6 -1
  21. package/dist/cli/index.js +6854 -4549
  22. package/dist/client/boundaries.d.ts +4 -4
  23. package/dist/client/internal/runtime-types.d.ts +30 -0
  24. package/dist/client/link.d.ts +2 -1
  25. package/dist/client/link.js +712 -338
  26. package/dist/client/router/boundary-tree.d.ts +1 -1
  27. package/dist/client/router/index.d.ts +1 -1
  28. package/dist/client/router/link-utils.d.ts +5 -1
  29. package/dist/client/router/sync-catch-up.d.ts +4 -4
  30. package/dist/client/router/types.d.ts +2 -2
  31. package/dist/client-only.d.ts +1 -0
  32. package/dist/client-only.js +1 -0
  33. package/dist/client.d.ts +108 -111
  34. package/dist/client.js +16 -17
  35. package/dist/config.d.ts +11 -2
  36. package/dist/config.js +7 -3
  37. package/dist/devtools/devtools-element.d.ts +1 -0
  38. package/dist/devtools/protocol.d.ts +119 -0
  39. package/dist/furin.d.ts +40 -21
  40. package/dist/furin.js +7198 -3518
  41. package/dist/isomorphic.d.ts +18 -0
  42. package/dist/plugin/binding-scope.d.ts +2 -0
  43. package/dist/plugin/dead-code-elimination.d.ts +3 -0
  44. package/dist/plugin/index.js +933 -423
  45. package/dist/plugin/transform-client.d.ts +0 -2
  46. package/dist/plugin/transform-isomorphic.d.ts +9 -0
  47. package/dist/rsc/build/environment.d.ts +2 -0
  48. package/dist/rsc/build/index.d.ts +15 -0
  49. package/dist/rsc/client-codec.d.ts +1 -0
  50. package/dist/rsc/codec.d.ts +4 -0
  51. package/dist/rsc/flight-drain.d.ts +11 -0
  52. package/dist/rsc/render-error.d.ts +17 -0
  53. package/dist/rsc/server-codec.d.ts +2 -0
  54. package/dist/rsc/server-codec.js +24 -0
  55. package/dist/rsc/shared.d.ts +30 -0
  56. package/dist/rsc/symbols.d.ts +2 -0
  57. package/dist/rsc/transport-benchmark.d.ts +13 -0
  58. package/dist/rsc/version.d.ts +7 -0
  59. package/dist/rsc-client.d.ts +4 -0
  60. package/dist/rsc-client.js +166 -0
  61. package/dist/rsc-server.d.ts +11 -0
  62. package/dist/rsc.d.ts +11 -0
  63. package/dist/rsc.js +353 -0
  64. package/dist/server/auto-invalidate/registry.d.ts +8 -1
  65. package/dist/server/cache/dev-loader.d.ts +3 -2
  66. package/dist/server/cache/index.d.ts +2 -2
  67. package/dist/server/cache/invalidation.d.ts +20 -2
  68. package/dist/server/cache/isr-ssg.d.ts +5 -1
  69. package/dist/server/cache/isr.d.ts +15 -2
  70. package/dist/server/cache/registry.d.ts +3 -3
  71. package/dist/server/cache/route-cache.d.ts +10 -8
  72. package/dist/server/cache/ssg.d.ts +6 -2
  73. package/dist/server/cache/store-view.d.ts +11 -0
  74. package/dist/server/dev-page-plugin.d.ts +4 -0
  75. package/dist/server/devtools/hub.d.ts +11 -0
  76. package/dist/server/devtools/instrumentation.d.ts +22 -0
  77. package/dist/server/devtools/instrumentation.production.d.ts +44 -0
  78. package/dist/server/devtools/plugin.d.ts +3 -0
  79. package/dist/server/devtools/request-context.d.ts +6 -0
  80. package/dist/server/instance.d.ts +86 -0
  81. package/dist/server/internal.d.ts +18 -1
  82. package/dist/server/internal.js +74 -7
  83. package/dist/server/lang-detect.d.ts +1 -0
  84. package/dist/server/render/assemble.d.ts +4 -0
  85. package/dist/server/render/element.d.ts +1 -1
  86. package/dist/server/render/index.d.ts +2 -2
  87. package/dist/server/render/index.ts +6 -2
  88. package/dist/server/render/loaders.d.ts +8 -0
  89. package/dist/server/render/not-found.d.ts +1 -1
  90. package/dist/server/render/ppr-route.d.ts +8 -0
  91. package/dist/server/render/route-frame-transport.d.ts +2 -0
  92. package/dist/server/render/shell.ts +0 -1
  93. package/dist/server/render/ssr.d.ts +2 -3
  94. package/dist/server/render/template.d.ts +3 -2
  95. package/dist/server/router/discovery.d.ts +1 -1
  96. package/dist/server/router/hmr.d.ts +1 -1
  97. package/dist/server/router/index.d.ts +2 -1
  98. package/dist/server/router/index.js +23 -23
  99. package/dist/server/router/index.ts +1 -1
  100. package/dist/server/router/patterns.d.ts +1 -1
  101. package/dist/server/router/plugin.d.ts +4 -7
  102. package/dist/server/router/schema-merge.d.ts +3 -0
  103. package/dist/server/router/schemas.d.ts +12 -7
  104. package/dist/server/router/types.d.ts +1 -1
  105. package/dist/server/runtime-env.js +2 -2
  106. package/dist/server/sync/adapter.d.ts +45 -26
  107. package/dist/server/sync/config.d.ts +9 -2
  108. package/dist/server/sync/fingerprint.d.ts +2 -1
  109. package/dist/server/sync/index.d.ts +15 -4
  110. package/dist/server/sync/index.js +2868 -0
  111. package/dist/server/sync/notifier.d.ts +18 -0
  112. package/dist/server/sync/plugin.d.ts +53 -54
  113. package/dist/server/sync/postgres/index.d.ts +19 -0
  114. package/dist/server/sync/postgres/index.js +252 -0
  115. package/dist/server/sync/postgres/migrate.d.ts +2 -0
  116. package/dist/server/sync/postgres/migrate.js +16 -0
  117. package/dist/server/sync/postgres/migration.sql +66 -0
  118. package/dist/server/sync/redis/index.d.ts +30 -0
  119. package/dist/server/sync/redis/index.js +336 -0
  120. package/dist/server/sync/redis/scripts.d.ts +4 -0
  121. package/dist/server/sync/response.d.ts +10 -1
  122. package/dist/server/sync/runtime.d.ts +6 -0
  123. package/dist/server/sync/sqlite/index.d.ts +20 -0
  124. package/dist/server/sync/sqlite/index.js +250 -0
  125. package/dist/server/sync/stream.d.ts +12 -4
  126. package/dist/server-only.d.ts +1 -0
  127. package/dist/server-only.js +1 -0
  128. package/dist/shared/parser.d.ts +2 -0
  129. package/dist/shared/prefix.d.ts +15 -0
  130. package/dist/shared/route-frame.d.ts +49 -0
  131. package/dist/shared/utils/index.d.ts +1 -1
  132. package/package.json +59 -12
  133. package/src/adapter/bun.ts +175 -55
  134. package/src/adapter/package.ts +208 -0
  135. package/src/adapter/static.ts +94 -48
  136. package/src/build/bun-build.ts +11 -0
  137. package/src/build/client.ts +31 -27
  138. package/src/build/compile-entry.ts +88 -83
  139. package/src/build/entry-template.ts +109 -56
  140. package/src/build/hydrate.ts +37 -10
  141. package/src/build/index.ts +111 -28
  142. package/src/build/production-instrumentation.ts +14 -0
  143. package/src/build/route-types.ts +7 -8
  144. package/src/build/scan-server.ts +26 -9
  145. package/src/build/server-routes-entry.ts +5 -11
  146. package/src/build/ssg-cache.ts +13 -4
  147. package/src/build/types.ts +38 -1
  148. package/src/cli/config.ts +9 -3
  149. package/src/cli/index.ts +73 -24
  150. package/src/client/boundaries.tsx +42 -18
  151. package/src/client/default-screens.tsx +4 -4
  152. package/src/client/internal/runtime-types.ts +31 -0
  153. package/src/client/link.tsx +35 -37
  154. package/src/client/router/boundary-tree.tsx +2 -2
  155. package/src/client/router/context.ts +13 -9
  156. package/src/client/router/index.ts +3 -0
  157. package/src/client/router/link-utils.ts +66 -3
  158. package/src/client/router/navigation.ts +9 -15
  159. package/src/client/router/provider.tsx +74 -52
  160. package/src/client/router/search/index.ts +5 -7
  161. package/src/client/router/search-store.ts +5 -1
  162. package/src/client/router/spa-response.ts +3 -4
  163. package/src/client/router/sync-catch-up.ts +9 -8
  164. package/src/client/router/types.ts +2 -2
  165. package/src/client/sync.ts +3 -2
  166. package/src/client-only.ts +1 -0
  167. package/src/client.ts +221 -174
  168. package/src/config.ts +14 -1
  169. package/src/devtools/devtools-element.js +884 -0
  170. package/src/devtools/protocol.ts +139 -0
  171. package/src/furin.ts +414 -171
  172. package/src/isomorphic.ts +66 -0
  173. package/src/plugin/binding-scope.ts +158 -0
  174. package/src/plugin/dead-code-elimination.ts +202 -0
  175. package/src/plugin/index.ts +14 -18
  176. package/src/plugin/transform-client.ts +237 -273
  177. package/src/plugin/transform-isomorphic.ts +464 -0
  178. package/src/rsc/build/environment.ts +30 -0
  179. package/src/rsc/build/index.ts +94 -0
  180. package/src/rsc/client-codec.ts +11 -0
  181. package/src/rsc/codec.ts +85 -0
  182. package/src/rsc/flight-drain.ts +68 -0
  183. package/src/rsc/react-server-dom-webpack.d.ts +23 -0
  184. package/src/rsc/render-error.ts +120 -0
  185. package/src/rsc/server-codec.ts +25 -0
  186. package/src/rsc/shared.tsx +113 -0
  187. package/src/rsc/symbols.ts +2 -0
  188. package/src/rsc/transport-benchmark.ts +73 -0
  189. package/src/rsc/version.ts +57 -0
  190. package/src/rsc-client.ts +12 -0
  191. package/src/rsc-server.tsx +91 -0
  192. package/src/rsc.tsx +75 -0
  193. package/src/server/auto-invalidate/registry.ts +23 -1
  194. package/src/server/auto-invalidate/runtime.ts +58 -7
  195. package/src/server/cache/dev-loader.ts +143 -44
  196. package/src/server/cache/index.ts +7 -3
  197. package/src/server/cache/invalidation.ts +100 -41
  198. package/src/server/cache/isr-ssg.ts +12 -3
  199. package/src/server/cache/isr.ts +95 -5
  200. package/src/server/cache/registry.ts +17 -20
  201. package/src/server/cache/route-cache.ts +49 -36
  202. package/src/server/cache/ssg.ts +19 -4
  203. package/src/server/cache/store-view.ts +30 -0
  204. package/src/server/context-logger.ts +7 -7
  205. package/src/server/dev-page-plugin.ts +8 -6
  206. package/src/server/devtools/hub.ts +64 -0
  207. package/src/server/devtools/instrumentation.production.ts +80 -0
  208. package/src/server/devtools/instrumentation.ts +72 -0
  209. package/src/server/devtools/plugin.ts +267 -0
  210. package/src/server/devtools/request-context.ts +76 -0
  211. package/src/server/instance.ts +252 -0
  212. package/src/server/internal.ts +102 -5
  213. package/src/server/lang-detect.ts +14 -10
  214. package/src/server/render/assemble.ts +73 -10
  215. package/src/server/render/element.tsx +11 -8
  216. package/src/server/render/index.ts +6 -2
  217. package/src/server/render/isr.ts +154 -110
  218. package/src/server/render/loaders.ts +259 -45
  219. package/src/server/render/not-found.ts +18 -17
  220. package/src/server/render/ppr-route.ts +146 -0
  221. package/src/server/render/route-frame-transport.ts +62 -0
  222. package/src/server/render/shell.ts +0 -1
  223. package/src/server/render/ssg.ts +6 -5
  224. package/src/server/render/ssr.ts +170 -70
  225. package/src/server/render/template.ts +59 -25
  226. package/src/server/router/discovery.ts +39 -22
  227. package/src/server/router/hmr.ts +15 -13
  228. package/src/server/router/index.ts +1 -1
  229. package/src/server/router/patterns.ts +16 -15
  230. package/src/server/router/plugin.ts +151 -158
  231. package/src/server/router/schema-merge.ts +52 -0
  232. package/src/server/router/schemas.ts +55 -73
  233. package/src/server/router/types.ts +1 -1
  234. package/src/server/sync/adapter.ts +44 -28
  235. package/src/server/sync/config.ts +22 -9
  236. package/src/server/sync/fingerprint.ts +8 -3
  237. package/src/server/sync/index.ts +37 -13
  238. package/src/server/sync/notifier.ts +109 -0
  239. package/src/server/sync/plugin.ts +184 -90
  240. package/src/server/sync/postgres/index.ts +301 -0
  241. package/src/server/sync/postgres/migrate.ts +15 -0
  242. package/src/server/sync/postgres/migration.sql +66 -0
  243. package/src/server/sync/redis/index.ts +342 -0
  244. package/src/server/sync/redis/scripts.ts +74 -0
  245. package/src/server/sync/response.ts +141 -16
  246. package/src/server/sync/runtime.ts +27 -0
  247. package/src/server/sync/sql.d.ts +4 -0
  248. package/src/server/sync/sqlite/index.ts +337 -0
  249. package/src/server/sync/sqlite/migration.sql +70 -0
  250. package/src/server/sync/stream.ts +136 -70
  251. package/src/server-only.ts +1 -0
  252. package/src/shared/await.tsx +4 -4
  253. package/src/shared/deferred-ndjson.ts +34 -6
  254. package/src/shared/digest.ts +2 -2
  255. package/src/shared/parser.ts +5 -0
  256. package/src/shared/prefix.ts +38 -0
  257. package/src/shared/route-frame.ts +429 -0
  258. package/src/shared/search-params.ts +7 -7
  259. package/src/shared/utils/index.ts +5 -3
  260. package/dist/server/dev-inspector.d.ts +0 -89
  261. package/dist/server/sync/memory-adapter.d.ts +0 -17
  262. package/src/server/dev-inspector.ts +0 -60
  263. package/src/server/sync/memory-adapter.ts +0 -196
@@ -0,0 +1,208 @@
1
+ import { existsSync, rmSync, writeFileSync } from "node:fs";
2
+ import { join, relative, resolve } from "node:path";
3
+ import { type BunTargetApp, createBuildFingerprint } from "../adapter/bun.ts";
4
+ import { runBunBuild } from "../build/bun-build.ts";
5
+ import { buildClient } from "../build/client.ts";
6
+ import { buildEntrySource } from "../build/entry-template.ts";
7
+ import { copyDirRecursive, ensureDir, toPosixPath } from "../build/shared.ts";
8
+ import { buildSSGCacheSnapshot } from "../build/ssg-cache.ts";
9
+ import type { BuildAppOptions, PackageTargetBuildManifest } from "../build/types.ts";
10
+ import { ssgRouteCache } from "../server/cache/ssg.ts";
11
+ import { generateProdIndexHtml } from "../server/render/shell.ts";
12
+ import { setProductionTemplateContent } from "../server/render/template.ts";
13
+
14
+ /**
15
+ * `--target package` — builds a furin app as a PUBLISHABLE Elysia plugin
16
+ * instead of a bootable server. Output (`.furin/build/package/`):
17
+ *
18
+ * - `client/` content-hashed chunks + index.html SSR template
19
+ * - `register.js` side-effect module registering the app's CompileContext;
20
+ * page modules are bundled in, but everything from
21
+ * node_modules (incl. @teyik0/furin itself) stays external so
22
+ * the host and the register module share ONE furin runtime
23
+ * - `index.js` `createFurinApp()` factory the host `.use()`es
24
+ * - `index.d.ts` minimal typings for the factory
25
+ *
26
+ * The host composes it like any Elysia plugin:
27
+ *
28
+ * ```ts
29
+ * import { createFurinApp as admin } from "@org/admin/furin";
30
+ * new Elysia().use(await furin({...})).use(await admin()).listen(3000)
31
+ * ```
32
+ *
33
+ * In a monorepo the baked relative `pagesDir` still points at real sources,
34
+ * so the same factory works under `bun --hot` (dev scans live). A published
35
+ * package without sources is production-only; its context is found by prefix.
36
+ */
37
+ export async function buildPackageTarget(
38
+ app: BunTargetApp,
39
+ rootDir: string,
40
+ buildRoot: string,
41
+ options: BuildAppOptions
42
+ ): Promise<PackageTargetBuildManifest> {
43
+ const { prefix, root, routes, pagesDir } = app;
44
+ const targetDir = join(buildRoot, "package");
45
+
46
+ rmSync(targetDir, { force: true, recursive: true });
47
+ ensureDir(targetDir);
48
+
49
+ const { entryChunk, cssChunks } = await buildClient(routes, {
50
+ outDir: targetDir,
51
+ rootLayout: root.path,
52
+ plugins: options.plugins,
53
+ publicPath: `${prefix}/_client/`,
54
+ basePath: prefix,
55
+ clientLogging: options.clientLogging ?? false,
56
+ });
57
+
58
+ // Same fingerprint as the Bun target: hashing only the client chunks would
59
+ // keep the old build ID across SSR-only changes (page/loader code that never
60
+ // reaches the client bundle), defeating stale-deploy detection. The package
61
+ // target has no server entry, hence `null`.
62
+ const buildFingerprint = await createBuildFingerprint(
63
+ `${prefix}\n${entryChunk}`,
64
+ cssChunks,
65
+ routes,
66
+ root,
67
+ null
68
+ );
69
+ const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
70
+
71
+ const clientDir = join(targetDir, "client");
72
+
73
+ // At runtime furin() derives publicDir next to the baked clientDir
74
+ // (join(dirname(clientDir), "public")), so the project's public/ assets must
75
+ // ship inside the artifact or /public/* and /favicon.ico 404 in production.
76
+ const publicDir = join(rootDir, "public");
77
+ if (existsSync(publicDir)) {
78
+ copyDirRecursive(publicDir, join(targetDir, "public"));
79
+ }
80
+
81
+ const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
82
+ writeFileSync(join(clientDir, "index.html"), indexHtml);
83
+
84
+ // SSG snapshot renders through the build-time default state bucket. The
85
+ // mount prefix is passed explicitly — no instance scope exists at build time.
86
+ setProductionTemplateContent(indexHtml);
87
+ ssgRouteCache().clear();
88
+ const ssgCache = await buildSSGCacheSnapshot(routes, root, "http://localhost", prefix);
89
+
90
+ const rootConventions =
91
+ root.errorPath || root.notFoundPath
92
+ ? {
93
+ errorPath: root.errorPath ? toPosixPath(root.errorPath) : undefined,
94
+ notFoundPath: root.notFoundPath ? toPosixPath(root.notFoundPath) : undefined,
95
+ }
96
+ : undefined;
97
+ const routeMetadata: Record<
98
+ string,
99
+ {
100
+ segmentBoundaries: Array<{
101
+ depth: number;
102
+ path: string;
103
+ errorPath?: string;
104
+ notFoundPath?: string;
105
+ }>;
106
+ }
107
+ > = {};
108
+ for (const route of routes) {
109
+ routeMetadata[toPosixPath(route.path)] = {
110
+ segmentBoundaries: route.segmentBoundaries.map((b) => ({
111
+ depth: b.depth,
112
+ path: toPosixPath(b.path),
113
+ errorPath: b.errorPath ? toPosixPath(b.errorPath) : undefined,
114
+ notFoundPath: b.notFoundPath ? toPosixPath(b.notFoundPath) : undefined,
115
+ })),
116
+ };
117
+ }
118
+
119
+ // 1. register.ts — context registration side-effect module.
120
+ const registerSource = buildEntrySource({
121
+ apps: [
122
+ {
123
+ buildId,
124
+ clientLogging: options.clientLogging ?? false,
125
+ prefix,
126
+ rootPath: root.path,
127
+ routes: routes.map((r) => ({ pattern: r.pattern, path: r.path, mode: r.mode })),
128
+ rootConventions,
129
+ routeMetadata,
130
+ ssgCache,
131
+ },
132
+ ],
133
+ headerComment: "// Auto-generated by `furin build --target package` — do not edit",
134
+ mode: "register",
135
+ });
136
+ const registerEntry = join(targetDir, "register.ts");
137
+ writeFileSync(registerEntry, registerSource);
138
+
139
+ const result = await runBunBuild({
140
+ entrypoints: [registerEntry],
141
+ outdir: targetDir,
142
+ target: "bun",
143
+ // Keep EVERY dependency external (incl. @teyik0/furin): the host must
144
+ // share one copy of the furin runtime with this register module — only
145
+ // the package's own page sources get bundled in.
146
+ packages: "external",
147
+ naming: { entry: "[name].[ext]", chunk: "[name]-[hash].[ext]" },
148
+ sourcemap: "none",
149
+ minify: false,
150
+ plugins: options.plugins,
151
+ });
152
+ if (!result.success) {
153
+ throw new AggregateError(result.logs, "[furin] package register build failed");
154
+ }
155
+ rmSync(registerEntry, { force: true });
156
+ rmSync(join(targetDir, "_hydrate.tsx"), { force: true });
157
+
158
+ // 2. index.js — the factory the host mounts. The baked relative pagesDir
159
+ // keeps monorepo dev working; in a published package the compile context is
160
+ // resolved by prefix instead.
161
+ const relativePagesDir = toPosixPath(relative(targetDir, resolve(rootDir, pagesDir)));
162
+ const factorySource = `// Auto-generated by \`furin build --target package\` — do not edit
163
+ import { fileURLToPath } from "node:url";
164
+ import { furin } from "@teyik0/furin";
165
+ import "./register.js";
166
+
167
+ const PAGES_DIR = fileURLToPath(new URL(${JSON.stringify(`./${relativePagesDir}`)}, import.meta.url));
168
+ const CLIENT_DIR = fileURLToPath(new URL("./client", import.meta.url));
169
+
170
+ /**
171
+ * Mounts this packaged furin app as an Elysia plugin.
172
+ *
173
+ * @param {object} [options] Extra furin() options (logger, sync, ...) —
174
+ * pagesDir/prefix/clientDir are baked into the package and cannot be overridden.
175
+ * @returns {Promise<import("elysia").Elysia>}
176
+ */
177
+ export function createFurinApp(options = {}) {
178
+ return furin({
179
+ ...options,
180
+ pagesDir: PAGES_DIR,
181
+ prefix: ${JSON.stringify(prefix)},
182
+ clientDir: CLIENT_DIR,
183
+ });
184
+ }
185
+
186
+ export const prefix = ${JSON.stringify(prefix)};
187
+ `;
188
+ writeFileSync(join(targetDir, "index.js"), factorySource);
189
+
190
+ const dtsSource = `import type { Elysia } from "elysia";
191
+ import type { FurinOptions } from "@teyik0/furin";
192
+
193
+ /** Extra furin() options — pagesDir/prefix/clientDir are baked into the package and cannot be overridden. */
194
+ export type CreateFurinAppOptions = Omit<FurinOptions, "pagesDir" | "prefix" | "clientDir">;
195
+ export declare function createFurinApp(options?: CreateFurinAppOptions): Promise<Elysia>;
196
+ export declare const prefix: string;
197
+ `;
198
+ writeFileSync(join(targetDir, "index.d.ts"), dtsSource);
199
+
200
+ console.log(`[furin] Package artifact: ${toPosixPath(relative(rootDir, targetDir))}`);
201
+
202
+ return {
203
+ buildId,
204
+ generatedAt: new Date().toISOString(),
205
+ prefix,
206
+ targetDir: toPosixPath(relative(rootDir, targetDir)),
207
+ };
208
+ }
@@ -1,3 +1,4 @@
1
+ // biome-ignore-all lint/performance/noAwaitInLoops: static build emits routes in sequence to keep output deterministic
1
2
  import { cpSync, existsSync, rmSync, writeFileSync } from "node:fs";
2
3
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
4
  import { buildClient } from "../build/client.ts";
@@ -5,14 +6,11 @@ import { ensureDir, toPosixPath } from "../build/shared.ts";
5
6
  import type { BuildAppOptions, StaticTargetBuildManifest } from "../build/types.ts";
6
7
  import type { StaticExportConfig } from "../config.ts";
7
8
  import { resolvePath } from "../server/render/assemble.ts";
8
- import { prerenderSSG } from "../server/render/index.ts";
9
9
  import { generateProdIndexHtml } from "../server/render/shell.ts";
10
+ import { prerenderSSG } from "../server/render/ssg.ts";
10
11
  import { setProductionTemplateContent } from "../server/render/template.ts";
11
- import {
12
- createSearchRouteMetadata,
13
- type ResolvedRoute,
14
- type RootLayout,
15
- } from "../server/router/index.ts";
12
+ import { createSearchRouteMetadata } from "../server/router/schemas.ts";
13
+ import type { ResolvedRoute, RootLayout } from "../server/router/types.ts";
16
14
  import type { SearchRouteMetadata } from "../shared/search-params.ts";
17
15
  import { mapWithConcurrency } from "../shared/utils/index.ts";
18
16
 
@@ -51,6 +49,38 @@ function pathToOutputFile(urlPath: string, outDir: string, fileName: string): st
51
49
  return resolved;
52
50
  }
53
51
 
52
+ function sortRouteList(routes: string[]): string[] {
53
+ return routes.toSorted((a, b) => (a < b ? -1 : Number(a > b)));
54
+ }
55
+
56
+ function assertNoStaticExportSkips(onSSR: "error" | "skip", skippedRoutes: string[]): void {
57
+ if (onSSR !== "error" || skippedRoutes.length === 0) {
58
+ return;
59
+ }
60
+ const failed = sortRouteList(skippedRoutes);
61
+ const list = failed.map((r) => ` • ${r}`).join("\n");
62
+ throw new Error(
63
+ `[furin] static: ${failed.length} route(s) cannot be statically exported:\n${list}\n` +
64
+ `Define \`staticParams()\` for dynamic SSG routes or set \`onSSR: "skip"\` in your static config.`
65
+ );
66
+ }
67
+
68
+ function assertNoPrerenderSkips(
69
+ onSSR: "error" | "skip",
70
+ skippedRoutes: string[],
71
+ afterQueueCount: number
72
+ ): void {
73
+ if (onSSR !== "error" || skippedRoutes.length <= afterQueueCount) {
74
+ return;
75
+ }
76
+ const failed = sortRouteList(skippedRoutes.slice(afterQueueCount));
77
+ const list = failed.map((r) => ` • ${r}`).join("\n");
78
+ throw new Error(
79
+ `[furin] static: ${failed.length} route(s) failed to pre-render:\n${list}\n` +
80
+ `Set \`onSSR: "skip"\` in your static config to suppress this error.`
81
+ );
82
+ }
83
+
54
84
  // ── Pre-render worker ─────────────────────────────────────────────────────────
55
85
 
56
86
  async function prerenderAndWrite(
@@ -165,18 +195,18 @@ async function buildTaskQueue(
165
195
  STATIC_CONCURRENCY,
166
196
  async (route) => {
167
197
  if (!DYNAMIC_SEGMENT_RE.test(route.pattern)) {
168
- return { route, paramSets: [{}] };
198
+ return { paramSets: [{}], route };
169
199
  }
170
200
  if (!route.page.staticParams) {
171
201
  console.warn(
172
202
  `[furin] static: skipping dynamic route "${route.pattern}" — no staticParams() defined.`
173
203
  );
174
204
  skippedRoutes.push(route.pattern);
175
- return { route, paramSets: null };
205
+ return { paramSets: null, route };
176
206
  }
177
207
  try {
178
208
  const paramSets = (await route.page.staticParams()) ?? [];
179
- return { route, paramSets };
209
+ return { paramSets, route };
180
210
  } catch (err) {
181
211
  return { error: err, paramSets: null, route };
182
212
  }
@@ -184,12 +214,10 @@ async function buildTaskQueue(
184
214
  );
185
215
 
186
216
  for (const result of staticParamsResults) {
217
+ const { pattern } = result.route;
187
218
  if ("error" in result) {
188
- console.error(
189
- `[furin] static: staticParams() failed for "${result.route.pattern}":`,
190
- result.error
191
- );
192
- skippedRoutes.push(result.route.pattern);
219
+ console.error(`[furin] static: staticParams() failed for "${pattern}":`, result.error);
220
+ skippedRoutes.push(pattern);
193
221
  continue;
194
222
  }
195
223
  if (result.paramSets === null) {
@@ -206,6 +234,8 @@ async function buildTaskQueue(
206
234
  continue;
207
235
  }
208
236
  for (const params of result.paramSets) {
237
+ const urlPath = resolvePath(result.route.pattern, params);
238
+ pathToOutputFile(urlPath, outDir, "index.html");
209
239
  tasks.push(() =>
210
240
  prerenderAndWrite(
211
241
  result.route,
@@ -243,6 +273,24 @@ async function runWithConcurrency(
243
273
 
244
274
  // ── Main adapter ──────────────────────────────────────────────────────────────
245
275
 
276
+ function assertNoRequestLoaders(routes: ResolvedRoute[], root: RootLayout): void {
277
+ const offenders: string[] = [];
278
+ if (root.route.requestLoader !== undefined) {
279
+ offenders.push(" • <root layout>");
280
+ }
281
+ const requestScopedRoutes = routes.filter((route) =>
282
+ route.routeChain.some((entry) => entry.requestLoader !== undefined)
283
+ );
284
+ offenders.push(...requestScopedRoutes.map((route) => ` • ${route.pattern}`));
285
+ if (offenders.length === 0) {
286
+ return;
287
+ }
288
+ throw new Error(
289
+ "[furin] requestLoader requires a Bun server and is incompatible with a pure static export.\n" +
290
+ offenders.join("\n")
291
+ );
292
+ }
293
+
246
294
  export async function buildStaticTarget(
247
295
  routes: ResolvedRoute[],
248
296
  rootDir: string,
@@ -250,6 +298,8 @@ export async function buildStaticTarget(
250
298
  root: RootLayout,
251
299
  options: BuildAppOptions
252
300
  ): Promise<StaticTargetBuildManifest> {
301
+ assertNoRequestLoaders(routes, root);
302
+
253
303
  const staticConfig: StaticExportConfig = options.staticConfig ?? {};
254
304
 
255
305
  // Normalize basePath: treat "" and "/" identically as no prefix; strip any
@@ -311,7 +361,22 @@ export async function buildStaticTarget(
311
361
  const ssgRoutes = collectSsgRoutes(routes, onSSR, skippedRoutes);
312
362
  const searchRoutes = createSearchRouteMetadata(ssgRoutes);
313
363
 
314
- // ── 2. Clean & create output directories ─────────────────────────────────
364
+ // ── 2. Resolve and validate every output path before writing artifacts ────
365
+ const tasks = await buildTaskQueue(
366
+ ssgRoutes,
367
+ root,
368
+ outDir,
369
+ renderedRoutes,
370
+ skippedRoutes,
371
+ basePath,
372
+ searchRoutes
373
+ );
374
+ assertNoStaticExportSkips(onSSR, skippedRoutes);
375
+ // Snapshot after queue-building: routes skipped due to missing staticParams() are
376
+ // already recorded; only routes added during task execution are prerender failures.
377
+ const afterQueueCount = skippedRoutes.length;
378
+
379
+ // ── 3. Clean & create output directories ─────────────────────────────────
315
380
  rmSync(outDir, { force: true, recursive: true });
316
381
  ensureDir(outDir);
317
382
 
@@ -319,71 +384,52 @@ export async function buildStaticTarget(
319
384
  rmSync(targetDir, { force: true, recursive: true });
320
385
  ensureDir(targetDir);
321
386
 
322
- // ── 3. Build client bundle ────────────────────────────────────────────────
387
+ // ── 4. Build client bundle ────────────────────────────────────────────────
323
388
  const { entryChunk, cssChunks } = await buildClient(ssgRoutes, {
389
+ basePath,
390
+ clientLogging: Boolean(options.clientLogging),
324
391
  outDir: targetDir,
325
- rootLayout: root.path,
326
392
  plugins: options.plugins,
327
393
  publicPath,
328
- basePath,
329
- clientLogging: Boolean(options.clientLogging),
394
+ rootLayout: root.path,
330
395
  });
331
396
 
332
- // ── 4. Generate HTML shell template ──────────────────────────────────────
397
+ // ── 5. Generate HTML shell template ──────────────────────────────────────
333
398
  // Emit a <link rel="icon"> only when a favicon.ico exists in the public dir.
334
399
  // This ensures the browser finds it even when the site is served from a sub-path.
335
400
  const publicFavicon = join(rootDir, "public", "favicon.ico");
336
401
  const faviconHref = existsSync(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
337
402
  const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref, true);
338
403
 
339
- // ── 5. Prime the renderer with the production shell ──────────────────────
404
+ // ── 6. Prime the renderer with the production shell ──────────────────────
340
405
  // Must be called before any prerenderSSG invocation.
341
406
  // prepareRender() checks getProductionTemplate() first (before IS_DEV), so
342
407
  // setting the content here is sufficient — no need to flip IS_DEV globally.
343
408
  setProductionTemplateContent(shellHtml);
344
409
 
345
- // ── 6. Copy public/ → outDir/ ─────────────────────────────────────────────
410
+ // ── 7. Copy public/ → outDir/ ─────────────────────────────────────────────
346
411
  const publicSrcDir = join(rootDir, "public");
347
412
  if (existsSync(publicSrcDir)) {
348
413
  cpSync(publicSrcDir, outDir, { recursive: true });
349
414
  }
350
415
 
351
- // ── 7. Copy _client/ chunks → outDir/_client/ ────────────────────────────
416
+ // ── 8. Copy _client/ chunks → outDir/_client/ ────────────────────────────
352
417
  const clientSrcDir = join(targetDir, "client");
353
418
  if (existsSync(clientSrcDir)) {
354
419
  cpSync(clientSrcDir, join(outDir, "_client"), { recursive: true });
355
420
  }
356
421
 
357
- // ── 8. Pre-render SSG routes ──────────────────────────────────────────────
358
- const tasks = await buildTaskQueue(
359
- ssgRoutes,
360
- root,
361
- outDir,
362
- renderedRoutes,
363
- skippedRoutes,
364
- basePath,
365
- searchRoutes
366
- );
367
- // Snapshot after queue-building: routes skipped due to missing staticParams() are
368
- // already recorded; only routes added during task execution are prerender failures.
369
- const afterQueueCount = skippedRoutes.length;
422
+ // ── 9. Pre-render SSG routes ──────────────────────────────────────────────
370
423
  await runWithConcurrency(tasks, STATIC_CONCURRENCY);
371
424
 
372
425
  // Fail the build when onSSR="error" and any prerender task was recorded as skipped.
373
- if (onSSR === "error" && skippedRoutes.length > afterQueueCount) {
374
- const failed = skippedRoutes.slice(afterQueueCount);
375
- const list = failed.map((r) => ` • ${r}`).join("\n");
376
- throw new Error(
377
- `[furin] static: ${failed.length} route(s) failed to pre-render:\n${list}\n` +
378
- `Set \`onSSR: "skip"\` in your static config to suppress this error.`
379
- );
380
- }
426
+ assertNoPrerenderSkips(onSSR, skippedRoutes, afterQueueCount);
381
427
 
382
- // ── 9. Write 404.html (SPA fallback for GitHub Pages) ───────────────────
428
+ // ── 10. Write 404.html (SPA fallback for GitHub Pages) ──────────────────
383
429
  writeFileSync(join(outDir, "404.html"), shellHtml);
384
430
  console.log("[furin] static: wrote 404.html (SPA shell fallback)");
385
431
 
386
- // ── 10. Clean up intermediate build artifacts ────────────────────────────
432
+ // ── 11. Clean up intermediate build artifacts ───────────────────────────
387
433
  rmSync(targetDir, { force: true, recursive: true });
388
434
 
389
435
  console.log(
@@ -395,7 +441,7 @@ export async function buildStaticTarget(
395
441
  basePath,
396
442
  generatedAt: new Date().toISOString(),
397
443
  outDir: toPosixPath(outDir),
398
- renderedRoutes,
399
- skippedRoutes,
444
+ renderedRoutes: sortRouteList(renderedRoutes),
445
+ skippedRoutes: sortRouteList(skippedRoutes),
400
446
  };
401
447
  }
@@ -0,0 +1,11 @@
1
+ type BunBuild = typeof Bun.build;
2
+
3
+ type BunBuildGlobal = typeof globalThis & {
4
+ __FURIN_BUN_BUILD_FOR_TESTS?: BunBuild;
5
+ };
6
+
7
+ export function runBunBuild(config: Bun.BuildConfig): ReturnType<BunBuild> {
8
+ return (((globalThis as BunBuildGlobal).__FURIN_BUN_BUILD_FOR_TESTS ?? Bun.build) as BunBuild)(
9
+ config
10
+ );
11
+ }
@@ -1,12 +1,15 @@
1
1
  import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
2
  import { basename, join } from "node:path";
3
3
  import { transformForClient } from "../plugin/transform-client";
4
+ import { environmentGuardPlugin } from "../rsc/build/environment.ts";
5
+ import { detectLoaderFromPath } from "../server/lang-detect.ts";
4
6
  import type { ResolvedRoute } from "../server/router/index.ts";
7
+ import { runBunBuild } from "./bun-build.ts";
5
8
  import { generateHydrateEntry } from "./hydrate";
6
9
  import { CLIENT_MODULE_PATH, LINK_MODULE_PATH, SEARCH_MODULE_PATH } from "./shared";
7
10
  import type { BuildClientOptions, BunBuildAliasConfig } from "./types";
8
11
 
9
- const TS_FILE_FILTER = /\.(tsx|ts)$/;
12
+ const SCRIPT_FILE_FILTER = /\.(tsx?|jsx?)$/;
10
13
 
11
14
  export interface BuildClientResult {
12
15
  /** Public paths of all CSS chunks, e.g. `["/_client/chunk-abc.css"]` */
@@ -33,9 +36,12 @@ export interface BuildClientResult {
33
36
  */
34
37
  export async function buildClient(
35
38
  routes: ResolvedRoute[],
36
- { outDir, rootLayout, plugins, publicPath, basePath, clientLogging }: BuildClientOptions
39
+ { outDir, rootLayout, plugins, publicPath, basePath, clientLogging, clientDirName }: BuildClientOptions
37
40
  ): Promise<BuildClientResult> {
38
- const clientDir = join(outDir, "client");
41
+ // Per-app client dir so several mounted apps build side by side
42
+ // ("client", "client-admin", …) without clobbering each other.
43
+ const dirName = clientDirName ?? "client";
44
+ const clientDir = join(outDir, dirName);
39
45
 
40
46
  if (!existsSync(outDir)) {
41
47
  mkdirSync(outDir, { recursive: true });
@@ -45,7 +51,10 @@ export async function buildClient(
45
51
  }
46
52
 
47
53
  const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging);
48
- const hydratePath = join(outDir, "_hydrate.tsx");
54
+ const hydratePath = join(
55
+ outDir,
56
+ dirName === "client" ? "_hydrate.tsx" : `_hydrate-${dirName}.tsx`
57
+ );
49
58
  writeFileSync(hydratePath, hydrateCode);
50
59
 
51
60
  console.log("[furin] Building production client bundle…");
@@ -53,34 +62,29 @@ export async function buildClient(
53
62
  const transformPlugin: Bun.BunPlugin = {
54
63
  name: "furin-transform-client",
55
64
  setup(build) {
56
- build.onLoad({ filter: TS_FILE_FILTER }, async (args) => {
65
+ build.onLoad({ filter: SCRIPT_FILE_FILTER }, async (args) => {
57
66
  const { path } = args;
58
67
  if (path.includes("node_modules")) {
59
68
  return;
60
69
  }
61
70
 
62
71
  const code = await Bun.file(path).text();
63
- try {
64
- const result = transformForClient(code, path);
65
- // transformForClient now emits TS/TSX directly (no pre-transpile),
66
- // so JSX → React handling is delegated to Bun.build's loader, which
67
- // applies the project tsconfig's automatic runtime by default.
68
- const transformed = result.code
69
- .replaceAll(`"@teyik0/furin/client"`, JSON.stringify(CLIENT_MODULE_PATH))
70
- .replaceAll(`'furin/client'`, JSON.stringify(CLIENT_MODULE_PATH))
71
- .replaceAll(`"@teyik0/furin/link"`, JSON.stringify(LINK_MODULE_PATH))
72
- .replaceAll(`'furin/link'`, JSON.stringify(LINK_MODULE_PATH))
73
- .replaceAll(`"@teyik0/furin/search"`, JSON.stringify(SEARCH_MODULE_PATH))
74
- .replaceAll(`'furin/search'`, JSON.stringify(SEARCH_MODULE_PATH));
72
+ const result = transformForClient(code, path);
73
+ // transformForClient now emits TS/TSX directly (no pre-transpile),
74
+ // so JSX → React handling is delegated to Bun.build's loader, which
75
+ // applies the project tsconfig's automatic runtime by default.
76
+ const transformed = result.code
77
+ .replaceAll(`"@teyik0/furin/client"`, JSON.stringify(CLIENT_MODULE_PATH))
78
+ .replaceAll(`'furin/client'`, JSON.stringify(CLIENT_MODULE_PATH))
79
+ .replaceAll(`"@teyik0/furin/link"`, JSON.stringify(LINK_MODULE_PATH))
80
+ .replaceAll(`'furin/link'`, JSON.stringify(LINK_MODULE_PATH))
81
+ .replaceAll(`"@teyik0/furin/search"`, JSON.stringify(SEARCH_MODULE_PATH))
82
+ .replaceAll(`'furin/search'`, JSON.stringify(SEARCH_MODULE_PATH));
75
83
 
76
- return {
77
- contents: transformed,
78
- loader: path.endsWith(".tsx") ? "tsx" : "ts",
79
- };
80
- } catch (error) {
81
- console.error(`[furin] Transform error for ${path}:`, error);
82
- return;
83
- }
84
+ return {
85
+ contents: transformed,
86
+ loader: detectLoaderFromPath(path),
87
+ };
84
88
  });
85
89
  },
86
90
  };
@@ -108,7 +112,7 @@ export async function buildClient(
108
112
  // Overridable via the `publicPath` option (e.g. "/furin/_client/" for basePath builds).
109
113
  publicPath,
110
114
  // User plugins run before the internal transform so they pre-process files first
111
- plugins: plugins ? [...plugins, transformPlugin] : [transformPlugin],
115
+ plugins: [...(plugins ?? []), environmentGuardPlugin("client"), transformPlugin],
112
116
  alias: {
113
117
  "@teyik0/furin/client": CLIENT_MODULE_PATH,
114
118
  "@teyik0/furin/link": LINK_MODULE_PATH,
@@ -119,7 +123,7 @@ export async function buildClient(
119
123
  },
120
124
  };
121
125
 
122
- const result = await Bun.build(clientBuildConfig);
126
+ const result = await runBunBuild(clientBuildConfig);
123
127
  for (const output of result.outputs) {
124
128
  console.log(`[furin] ${output.path} (${(output.size / 1024).toFixed(1)} KB)`);
125
129
  }