@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
@@ -1,106 +1,111 @@
1
1
  import { existsSync, writeFileSync } from "node:fs";
2
2
  import { join, relative } from "node:path";
3
- import { buildEntrySource, type BuildEntryOptions } from "./entry-template";
3
+ import { buildEntrySource, type BuildEntryOptions, type EntryAppContext } from "./entry-template";
4
4
  import { collectFilesRecursive, ensureDir, toPosixPath } from "./shared";
5
5
 
6
6
  /**
7
- * Generates a single `_compile-entry.ts` that:
8
- * 1. Statically imports every page module so Bun bundles them into the binary
9
- * 2. Optionally embeds client assets via `with { type: "file" }` (embed mode)
10
- * 3. Sets production mode and registers everything in a single CompileContext
11
- * 4. Dynamically imports server.ts to boot the app
7
+ * Builds one app's embedded-asset import lines + `embedded:` context block.
8
+ * Asset keys stay UNPREFIXED (`/_client/...`) — the instance's Elysia prefix
9
+ * strips the mount path before lookup at runtime.
12
10
  */
13
- export function generateCompileEntry(options: BuildEntryOptions): string {
14
- const {
15
- buildId,
16
- outDir,
17
- rootPath,
18
- routes,
19
- serverEntry,
20
- embed,
21
- publicDir,
22
- rootConventions,
23
- routeMetadata,
24
- ssgCache,
25
- } = options;
26
- ensureDir(outDir);
27
-
28
- // Build embedded asset imports if embed mode
11
+ function buildEmbeddedAssets(
12
+ outDir: string,
13
+ clientDir: string,
14
+ publicDir: string | undefined,
15
+ varPrefix: string
16
+ ): { extraContext: string[]; extraImports: string[] } {
17
+ if (!existsSync(clientDir)) {
18
+ throw new Error(
19
+ `[furin] Client directory not found: ${clientDir}. Run the client build first.`
20
+ );
21
+ }
22
+ const clientFiles = collectFilesRecursive(clientDir).filter((file) => !file.endsWith(".map"));
29
23
  const assetImports: string[] = [];
30
- let embeddedBlock: string[] = [];
31
- if (embed) {
32
- if (!existsSync(embed.clientDir)) {
33
- throw new Error(
34
- `[furin] Client directory not found: ${embed.clientDir}. Run the client build first.`
35
- );
36
- }
37
- const clientFiles = collectFilesRecursive(embed.clientDir).filter(
38
- (file) => !file.endsWith(".map")
24
+ const assetEntries: string[] = [];
25
+ let templateVarName: string | null = null;
26
+
27
+ let assetIndex = 0;
28
+ const importAsset = (file: string): string => {
29
+ const varName = `${varPrefix}asset${assetIndex++}`;
30
+ const relPath = toPosixPath(relative(outDir, file));
31
+ const importPath = relPath.startsWith(".") ? relPath : `./${relPath}`;
32
+ assetImports.push(
33
+ `import ${varName} from ${JSON.stringify(importPath)} with { type: "file" };`
39
34
  );
40
- const assetEntries: string[] = [];
41
- let templateVarName: string | null = null;
35
+ return varName;
36
+ };
42
37
 
43
- let assetIndex = 0;
44
- for (const file of clientFiles) {
45
- const varName = `_asset${assetIndex++}`;
46
- const relPath = toPosixPath(relative(outDir, file));
47
- const importPath = relPath.startsWith(".") ? relPath : `./${relPath}`;
38
+ for (const file of clientFiles) {
39
+ const varName = importAsset(file);
40
+ const clientRelativePath = toPosixPath(relative(clientDir, file));
41
+ if (clientRelativePath === "index.html") {
42
+ templateVarName = varName;
43
+ } else {
44
+ assetEntries.push(` ${JSON.stringify(`/_client/${clientRelativePath}`)}: ${varName},`);
45
+ }
46
+ }
48
47
 
49
- assetImports.push(
50
- `import ${varName} from ${JSON.stringify(importPath)} with { type: "file" };`
51
- );
48
+ if (templateVarName === null) {
49
+ throw new Error(
50
+ `[furin] Embed mode requires a client index.html at ${join(clientDir, "index.html")}. Run the client build first.`
51
+ );
52
+ }
52
53
 
53
- const clientRelativePath = toPosixPath(relative(embed.clientDir, file));
54
- if (clientRelativePath === "index.html") {
55
- templateVarName = varName;
56
- } else {
57
- assetEntries.push(` ${JSON.stringify(`/_client/${clientRelativePath}`)}: ${varName},`);
58
- }
54
+ if (publicDir && existsSync(publicDir)) {
55
+ const publicFiles = collectFilesRecursive(publicDir);
56
+ for (const file of publicFiles) {
57
+ const varName = importAsset(file);
58
+ const publicRelativePath = toPosixPath(relative(publicDir, file));
59
+ assetEntries.push(` ${JSON.stringify(`/public/${publicRelativePath}`)}: ${varName},`);
59
60
  }
61
+ }
60
62
 
61
- if (templateVarName === null) {
62
- throw new Error(
63
- `[furin] Embed mode requires a client index.html at ${join(embed.clientDir, "index.html")}. Run the client build first.`
64
- );
65
- }
63
+ const extraContext = [
64
+ " embedded: {",
65
+ ` template: ${templateVarName},`,
66
+ " assets: {",
67
+ ...assetEntries,
68
+ " },",
69
+ " },",
70
+ ];
66
71
 
67
- if (publicDir && existsSync(publicDir)) {
68
- const publicFiles = collectFilesRecursive(publicDir);
69
- for (const file of publicFiles) {
70
- const varName = `_asset${assetIndex++}`;
71
- const relPath = toPosixPath(relative(outDir, file));
72
- const importPath = relPath.startsWith(".") ? relPath : `./${relPath}`;
72
+ return { extraContext, extraImports: assetImports };
73
+ }
73
74
 
74
- assetImports.push(
75
- `import ${varName} from ${JSON.stringify(importPath)} with { type: "file" };`
76
- );
75
+ /**
76
+ * Generates a single `_compile-entry.ts` that:
77
+ * 1. Statically imports every page module of every app so Bun bundles them
78
+ * 2. Optionally embeds client assets via `with { type: "file" }` (embed mode)
79
+ * 3. Sets production mode and registers one CompileContext PER APP
80
+ * 4. Dynamically imports server.ts to boot the composed app
81
+ */
82
+ export function generateCompileEntry(options: BuildEntryOptions): string {
83
+ const { apps, outDir, serverEntry, publicDir } = options;
84
+ ensureDir(outDir);
77
85
 
78
- const publicRelativePath = toPosixPath(relative(publicDir, file));
79
- assetEntries.push(` ${JSON.stringify(`/public/${publicRelativePath}`)}: ${varName},`);
80
- }
86
+ const preparedApps: EntryAppContext[] = apps.map((app, appIndex) => {
87
+ const { embed, ...context } = app;
88
+ if (!embed) {
89
+ return context;
81
90
  }
82
-
83
- embeddedBlock = [
84
- " embedded: {",
85
- ` template: ${templateVarName},`,
86
- " assets: {",
87
- ...assetEntries,
88
- " },",
89
- " },",
90
- ];
91
- }
91
+ const varPrefix = apps.length === 1 ? "_" : `_a${appIndex}_`;
92
+ // Every app gets the project-level public/ dir: each instance serves only
93
+ // from its own `embedded.assets`, so `/public/*` (and `/favicon.ico`) would
94
+ // 404 on non-first apps otherwise. This only duplicates the string keys —
95
+ // each app imports the same file via the same relative path, and Bun
96
+ // dedupes identical `with { type: "file" }` modules into one embedded blob.
97
+ const embedded = buildEmbeddedAssets(outDir, embed.clientDir, publicDir, varPrefix);
98
+ return {
99
+ ...context,
100
+ extraContext: [...(context.extraContext ?? []), ...embedded.extraContext],
101
+ extraImports: [...(context.extraImports ?? []), ...embedded.extraImports],
102
+ };
103
+ });
92
104
 
93
105
  const source = buildEntrySource({
94
- buildId,
95
- headerComment: "// Auto-generated by furin compile — do not edit",
96
- rootPath,
97
- routes,
106
+ apps: preparedApps,
107
+ headerComment: options.headerComment ?? "// Auto-generated by furin compile — do not edit",
98
108
  serverEntry,
99
- extraImports: assetImports,
100
- extraContext: embeddedBlock,
101
- rootConventions,
102
- routeMetadata,
103
- ssgCache,
104
109
  });
105
110
 
106
111
  const entryPath = join(outDir, "_compile-entry.ts");
@@ -17,11 +17,17 @@ const _ext = _pkgSrcDir.endsWith("/src") ? ".ts" : ".js";
17
17
  const INTERNAL_MODULE_PATH = `${_pkgSrcDir}/server/internal${_ext}`;
18
18
  const RUNTIME_ENV_MODULE_PATH = `${_pkgSrcDir}/server/runtime-env${_ext}`;
19
19
 
20
- export interface EntryTemplateOptions {
20
+ /** One app's compile context payload — the generated entry can carry several. */
21
+ export interface EntryAppContext {
21
22
  buildId?: string;
23
+ /** Whether the emitted hydration client sends browser log batches. */
24
+ clientLogging?: boolean;
25
+ /** Extra lines injected inside this app's `__setCompileContext({...})` call. */
22
26
  extraContext?: string[];
27
+ /** Extra import lines this app needs (embedded asset imports). */
23
28
  extraImports?: string[];
24
- headerComment: string;
29
+ /** Mount prefix baked into the context for runtime lookup (`""` = root). */
30
+ prefix?: string;
25
31
  rootConventions?: { errorPath?: string; notFoundPath?: string };
26
32
  rootPath: string;
27
33
  routeMetadata?: Record<
@@ -36,22 +42,47 @@ export interface EntryTemplateOptions {
36
42
  }
37
43
  >;
38
44
  routes: Array<{ mode: "ssr" | "ssg" | "isr"; path: string; pattern: string }>;
39
- serverEntry: string;
40
45
  ssgCache?: Record<string, SsgCacheEntry>;
41
46
  }
42
47
 
48
+ export interface EntryTemplateOptions {
49
+ apps: EntryAppContext[];
50
+ headerComment: string;
51
+ /**
52
+ * - "boot" (default): forces production mode and dynamically imports the
53
+ * server entry after registering contexts — the whole app's entrypoint.
54
+ * - "register": ONLY registers contexts. Emitted by `--target package` as a
55
+ * side-effect module the HOST app imports; it must not touch dev mode or
56
+ * NODE_ENV (the host decides), and it imports furin internals via the
57
+ * package specifier so the host and the register module share ONE copy of
58
+ * the context registry (`packages: "external"` keeps it unbundled).
59
+ */
60
+ mode?: "boot" | "register";
61
+ /**
62
+ * Server entry to boot after context registration. Omitted in package
63
+ * (register-module) mode where the entry only registers contexts.
64
+ */
65
+ serverEntry?: string;
66
+ }
67
+
43
68
  /** Unified options for generating a build entry (compile or disk-based). */
44
- export interface BuildEntryOptions extends Omit<EntryTemplateOptions, "headerComment"> {
45
- outDir: string;
69
+ export interface BuildEntryOptions {
70
+ apps: Array<
71
+ EntryAppContext & {
72
+ /** Embed mode: bundles this app's client assets via `with { type: "file" }`. */
73
+ embed?: { clientDir: string };
74
+ }
75
+ >;
46
76
  headerComment?: string;
47
- /** Embed mode: bundles client assets into the binary via `with { type: "file" }`. */
48
- embed?: { clientDir: string };
77
+ outDir: string;
78
+ /** Project-level public/ dir — embedded into EVERY app's assets (keys only; Bun dedupes the file payloads). */
49
79
  publicDir?: string;
80
+ serverEntry?: string;
50
81
  }
51
82
 
52
83
  function collectConventionPaths(
53
- rootConventions: EntryTemplateOptions["rootConventions"],
54
- routeMetadata: EntryTemplateOptions["routeMetadata"]
84
+ rootConventions: EntryAppContext["rootConventions"],
85
+ routeMetadata: EntryAppContext["routeMetadata"]
55
86
  ): string[] {
56
87
  const paths: string[] = [];
57
88
  if (rootConventions?.errorPath) {
@@ -75,67 +106,45 @@ function collectConventionPaths(
75
106
  return [...new Set(paths)];
76
107
  }
77
108
 
78
- export function buildEntrySource(options: EntryTemplateOptions): string {
79
- const {
80
- buildId,
81
- headerComment,
82
- rootPath,
83
- routes,
84
- serverEntry,
85
- rootConventions,
86
- routeMetadata,
87
- ssgCache,
88
- } = options;
89
- let { extraImports, extraContext } = options;
90
- if (extraImports === undefined) {
91
- extraImports = [];
92
- }
93
- if (extraContext === undefined) {
94
- extraContext = [];
95
- }
96
-
109
+ /** Emits one app's module imports + `__setCompileContext({...})` call. */
110
+ function buildAppContextBlock(
111
+ app: EntryAppContext,
112
+ varPrefix: string
113
+ ): { contextLines: string[]; importLines: string[] } {
97
114
  const allModulePaths = [
98
- rootPath,
99
- ...routes.map((r) => r.path),
100
- ...collectConventionPaths(rootConventions, routeMetadata),
115
+ app.rootPath,
116
+ ...app.routes.map((r) => r.path),
117
+ ...collectConventionPaths(app.rootConventions, app.routeMetadata),
101
118
  ];
102
- const moduleImports: string[] = [];
119
+ const importLines: string[] = [];
103
120
  const moduleEntries: string[] = [];
104
121
 
105
122
  for (let i = 0; i < allModulePaths.length; i++) {
106
123
  const absPath = (allModulePaths[i] as string).replace(/\\/g, "/");
107
- const varName = `_mod${i}`;
108
- moduleImports.push(`import * as ${varName} from ${JSON.stringify(absPath)};`);
124
+ const varName = `${varPrefix}mod${i}`;
125
+ importLines.push(`import * as ${varName} from ${JSON.stringify(absPath)};`);
109
126
  moduleEntries.push(` ${JSON.stringify(absPath)}: ${varName},`);
110
127
  }
111
128
 
112
- const routeEntries = routes.map(
129
+ const routeEntries = app.routes.map(
113
130
  (r) =>
114
131
  ` { pattern: ${JSON.stringify(r.pattern)}, path: ${JSON.stringify(r.path.replace(/\\/g, "/"))}, mode: ${JSON.stringify(r.mode)} },`
115
132
  );
116
133
 
117
- const rootConventionsLine = rootConventions
118
- ? ` rootConventions: ${JSON.stringify(rootConventions)},`
134
+ const rootConventionsLine = app.rootConventions
135
+ ? ` rootConventions: ${JSON.stringify(app.rootConventions)},`
119
136
  : "";
120
- const routeMetadataLine = routeMetadata
121
- ? ` routeMetadata: ${JSON.stringify(routeMetadata)},`
137
+ const routeMetadataLine = app.routeMetadata
138
+ ? ` routeMetadata: ${JSON.stringify(app.routeMetadata)},`
122
139
  : "";
123
- const ssgCacheLine = ssgCache ? ` ssgCache: ${JSON.stringify(ssgCache)},` : "";
140
+ const ssgCacheLine = app.ssgCache ? ` ssgCache: ${JSON.stringify(app.ssgCache)},` : "";
124
141
 
125
- const lines = [
126
- headerComment,
127
- `import { __setCompileContext } from ${JSON.stringify(INTERNAL_MODULE_PATH)};`,
128
- `import { __setDevMode } from ${JSON.stringify(RUNTIME_ENV_MODULE_PATH)};`,
129
- ...moduleImports,
130
- ...(extraImports.length > 0 ? ["", ...extraImports] : []),
131
- "",
132
- "// Force production mode — Bun may inline process.env.NODE_ENV at bundle time.",
133
- "__setDevMode(false);",
134
- 'process.env.NODE_ENV = "production";',
135
- "",
142
+ const contextLines = [
136
143
  "__setCompileContext({",
137
- ` buildId: ${JSON.stringify(buildId ?? "")},`,
138
- ` rootPath: ${JSON.stringify(rootPath.replace(/\\/g, "/"))},`,
144
+ ` buildId: ${JSON.stringify(app.buildId ?? "")},`,
145
+ ` clientLogging: ${JSON.stringify(app.clientLogging ?? false)},`,
146
+ ` prefix: ${JSON.stringify(app.prefix ?? "")},`,
147
+ ` rootPath: ${JSON.stringify(app.rootPath.replace(/\\/g, "/"))},`,
139
148
  rootConventionsLine,
140
149
  " modules: {",
141
150
  ...moduleEntries,
@@ -145,11 +154,55 @@ export function buildEntrySource(options: EntryTemplateOptions): string {
145
154
  " ],",
146
155
  routeMetadataLine,
147
156
  ssgCacheLine,
148
- ...extraContext,
157
+ ...(app.extraContext ?? []),
149
158
  "});",
159
+ ];
160
+
161
+ return { contextLines, importLines };
162
+ }
163
+
164
+ export function buildEntrySource(options: EntryTemplateOptions): string {
165
+ const { apps, headerComment, serverEntry } = options;
166
+ const mode = options.mode ?? "boot";
167
+ const internalSpecifier =
168
+ mode === "register" ? "@teyik0/furin/internal" : INTERNAL_MODULE_PATH;
169
+
170
+ const importLines: string[] = [];
171
+ const contextBlocks: string[] = [];
172
+
173
+ for (let appIndex = 0; appIndex < apps.length; appIndex++) {
174
+ const app = apps[appIndex] as EntryAppContext;
175
+ // Per-app variable namespace so several apps' module/asset imports never
176
+ // collide inside the single generated entry.
177
+ const varPrefix = apps.length === 1 ? "_" : `_a${appIndex}_`;
178
+ const block = buildAppContextBlock(app, varPrefix);
179
+ importLines.push(...block.importLines);
180
+ if (app.extraImports && app.extraImports.length > 0) {
181
+ importLines.push("", ...app.extraImports);
182
+ }
183
+ contextBlocks.push("", ...block.contextLines);
184
+ }
185
+
186
+ const lines = [
187
+ headerComment,
188
+ `import { __setCompileContext } from ${JSON.stringify(internalSpecifier)};`,
189
+ ...(mode === "boot"
190
+ ? [`import { __setDevMode } from ${JSON.stringify(RUNTIME_ENV_MODULE_PATH)};`]
191
+ : []),
192
+ ...importLines,
193
+ ...(mode === "boot"
194
+ ? [
195
+ "",
196
+ "// Force production mode — Bun may inline process.env.NODE_ENV at bundle time.",
197
+ "__setDevMode(false);",
198
+ 'process.env.NODE_ENV = "production";',
199
+ ]
200
+ : []),
201
+ ...contextBlocks,
150
202
  "",
151
- `await import(${JSON.stringify(serverEntry.replace(/\\/g, "/"))});`,
152
- "",
203
+ ...(serverEntry
204
+ ? [`await import(${JSON.stringify(serverEntry.replace(/\\/g, "/"))});`, ""]
205
+ : []),
153
206
  ];
154
207
 
155
208
  return lines.join("\n");
@@ -1,9 +1,12 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { generateIndexHtml } from "../server/render/shell.ts";
4
- import { mergeRouteSchemas } from "../server/router/index.ts";
5
- import { buildRouteRegex } from "../server/router/patterns.ts";
6
- import type { ResolvedRoute } from "../server/router/index.ts";
4
+ import {
5
+ buildRouteRegex,
6
+ compareRouteSpecificity,
7
+ } from "../server/router/patterns.ts";
8
+ import { mergeRouteSchemas } from "../server/router/schema-merge.ts";
9
+ import type { ResolvedRoute } from "../server/router/types.ts";
7
10
  import { collectSearchDefaults } from "../shared/search-params.ts";
8
11
  import { writeRouteTypes } from "./route-types";
9
12
  import type { BuildClientOptions } from "./types";
@@ -43,10 +46,16 @@ export function generateHydrateEntry(
43
46
 
44
47
  const routeEntries: string[] = [];
45
48
 
46
- for (const route of routes) {
49
+ const clientRoutes = [...routes].sort((a, b) =>
50
+ compareRouteSpecificity(b.pattern, a.pattern),
51
+ );
52
+
53
+ for (const route of clientRoutes) {
47
54
  const resolvedPage = route.path.replace(/\\/g, "/");
48
55
  const regexPattern = buildRouteRegex(route.pattern).regex.source;
49
- const searchDefaults = collectSearchDefaults(mergeRouteSchemas(route.routeChain ?? [], "query"));
56
+ const searchDefaults = collectSearchDefaults(
57
+ mergeRouteSchemas(route.routeChain ?? [], "query")
58
+ );
50
59
  const boundaryIdents = new Map<string, string>();
51
60
 
52
61
  // Emit one boundary literal per segment that actually carries a convention
@@ -77,7 +86,9 @@ export function generateHydrateEntry(
77
86
  boundaryLiterals.length > 0
78
87
  ? `Promise.all([${lazyImports.join(", ")}]).then(([__furin_page, ${[
79
88
  ...boundaryIdents.values(),
80
- ].join(", ")}]) => ({ default: __furin_page.default, segmentBoundaries: [${boundaryLiterals.join(", ")}] }))`
89
+ ].join(
90
+ ", "
91
+ )}]) => ({ default: __furin_page.default, segmentBoundaries: [${boundaryLiterals.join(", ")}] }))`
81
92
  : `import("${resolvedPage}")`;
82
93
 
83
94
  const searchDefaultsEntry = searchDefaults
@@ -121,7 +132,7 @@ export function generateHydrateEntry(
121
132
  return `import { hydrateRoot, createRoot } from "react-dom/client";
122
133
  import { createElement } from "react";
123
134
  ${loggingImports}import { RouterProvider } from "@teyik0/furin/link";
124
- import { fromCrossJSON } from "@teyik0/furin/link";
135
+ import { fromCrossJSON, parseDeferredNdjson } from "@teyik0/furin/link";
125
136
  import type { SerovalNode } from "seroval";
126
137
  import { route as root } from "${rootLayout.replace(/\\/g, "/")}";
127
138
 
@@ -142,7 +153,7 @@ const _match = routes.find((r) => r.regex.test(pathname));
142
153
  // a matched loader threw notFound(). The latter still has a _match; the
143
154
  // former does not — so the two cases fork on _match below.
144
155
  const dataEl = document.getElementById("__FURIN_DATA__");
145
- const loaderData = dataEl ? JSON.parse(dataEl.textContent || "{}") : {};
156
+ let loaderData = dataEl ? JSON.parse(dataEl.textContent || "{}") : {};
146
157
  const syncEl = document.getElementById("__FURIN_SYNC__");
147
158
  const syncConfig = syncEl ? JSON.parse(syncEl.textContent || "{}") : {};
148
159
  const syncStream = typeof syncConfig.stream === "string" ? syncConfig.stream : undefined;
@@ -166,6 +177,9 @@ interface FurinDeferredRegistry {
166
177
  reject: (key: string, chunk: SerovalNode) => void;
167
178
  resolve: (key: string, chunk: SerovalNode) => void;
168
179
  }
180
+ interface FurinRouteFrameStream {
181
+ stream: (initial: string) => ReadableStream<Uint8Array>;
182
+ }
169
183
  const __deferred = (window as unknown as { __FURIN_DEFERRED__?: FurinDeferredRegistry })
170
184
  .__FURIN_DEFERRED__;
171
185
  const deferredData: Record<string, Promise<unknown>> = {};
@@ -217,6 +231,17 @@ const rootEl = document.getElementById("root") as HTMLElement;
217
231
  // Wrapped in an async IIFE to avoid top-level await, which causes Bun's HTML
218
232
  // bundler to misidentify which chunk to reference as the entry in index.html.
219
233
  (async () => {
234
+ const frameTemplate = document.getElementById("__FURIN_ROUTE_FRAMES__") as HTMLTemplateElement | null;
235
+ if (frameTemplate) {
236
+ const payload = frameTemplate.content.textContent || "";
237
+ const routeFrameStream = (window as unknown as { __FURIN_ROUTE_FRAME_STREAM__?: FurinRouteFrameStream })
238
+ .__FURIN_ROUTE_FRAME_STREAM__;
239
+ const parsed = await parseDeferredNdjson(
240
+ routeFrameStream ? routeFrameStream.stream(payload) : new Blob([payload]).stream(),
241
+ undefined
242
+ );
243
+ loaderData = { ...parsed.syncData, ...parsed.deferredPromises };
244
+ }
220
245
  let app;
221
246
  if (_match) {
222
247
  const _mod = await _match.load();
@@ -311,7 +336,7 @@ const rootEl = document.getElementById("root") as HTMLElement;
311
336
  */
312
337
  export function writeDevFiles(
313
338
  routes: ResolvedRoute[],
314
- { outDir, rootLayout, basePath, clientLogging }: BuildClientOptions,
339
+ { outDir, rootLayout, basePath, clientLogging, skipRouteTypes }: BuildClientOptions,
315
340
  projectRoot: string
316
341
  ): void {
317
342
  if (!existsSync(outDir)) {
@@ -332,7 +357,9 @@ export function writeDevFiles(
332
357
  writeFileSync(indexPath, indexHtml);
333
358
  }
334
359
 
335
- writeRouteTypes(routes, projectRoot);
360
+ if (!skipRouteTypes) {
361
+ writeRouteTypes(routes, projectRoot);
362
+ }
336
363
 
337
364
  console.log(
338
365
  "[furin] Dev files written (.furin/_hydrate.tsx + .furin/index.html + furin-env.d.ts)"