@akanjs/devkit 3.3.0-rc.7 → 3.3.0-rc.71

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 (360) hide show
  1. package/DEV_RUNTIME_KNOBS.md +1 -1
  2. package/README.ko.md +10 -3
  3. package/README.md +10 -4
  4. package/akanApp/akanApp.host.test.ts +4 -2
  5. package/akanApp/akanApp.host.ts +26 -2
  6. package/akanApp/akanApp.host.wiring.test.ts +111 -0
  7. package/akanApp/devHostPolicy.ts +5 -0
  8. package/akanApp/devMetadataRestart.ts +93 -0
  9. package/akanApp/devRecycler.test.ts +2 -0
  10. package/akanApp/devRecycler.ts +9 -0
  11. package/akanConfig/akanBin.ts +4 -0
  12. package/akanConfig/akanConfig.test.ts +358 -21
  13. package/akanConfig/akanConfig.ts +113 -272
  14. package/akanConfig/akanPreview.test.ts +28 -0
  15. package/akanConfig/akanPreview.ts +24 -0
  16. package/akanConfig/akanWorkers.test.ts +73 -0
  17. package/akanConfig/akanWorkers.ts +61 -0
  18. package/akanConfig/desktopServerConfig.ts +96 -0
  19. package/akanConfig/dockerImage.ts +250 -0
  20. package/akanConfig/index.ts +3 -0
  21. package/akanConfig/nativeFileSettings.ts +33 -0
  22. package/akanConfig/nativeKeys.ts +52 -0
  23. package/akanConfig/types.ts +4 -0
  24. package/app/appBin.test.ts +63 -0
  25. package/app/appBin.ts +50 -0
  26. package/app/applicationBuildReporter.test.ts +51 -1
  27. package/app/applicationBuildReporter.ts +6 -1
  28. package/app/applicationBuildRunner.test.ts +427 -5
  29. package/app/applicationBuildRunner.ts +232 -37
  30. package/app/clientServerBoundary.test.ts +115 -0
  31. package/app/clientServerBoundary.ts +89 -0
  32. package/app/dictionarySizes.test.ts +40 -0
  33. package/app/dictionarySizes.ts +95 -0
  34. package/app/routeFilesReport.test.ts +59 -0
  35. package/app/routeFilesReport.ts +46 -0
  36. package/app/routeJsBudget.ts +18 -4
  37. package/artifact/implicitRootLayout.test.ts +19 -0
  38. package/artifact/implicitRootLayout.ts +16 -2
  39. package/artifact/implicitRootLayoutRender.test.tsx +4 -1
  40. package/artifact/storeBootstrap.test.ts +28 -0
  41. package/artifact/storeBootstrap.ts +64 -8
  42. package/biome.base.json +7 -5
  43. package/codeAgent/index.ts +1 -34
  44. package/codeAgent/skills/akan-agent/SKILL.md +8 -1
  45. package/codeAgent/skills/akan-code/SKILL.md +38 -3
  46. package/codeAgent/skills/akan-debug/SKILL.md +8 -3
  47. package/codeAgent/skills/akan-deps/SKILL.md +10 -3
  48. package/codeAgent/skills/akan-err/SKILL.md +13 -8
  49. package/codeAgent/skills/akan-mcp/SKILL.md +1 -1
  50. package/codeAgent/skills/akan-module/SKILL.md +2 -2
  51. package/codeAgent/skills/akan-page/SKILL.md +65 -30
  52. package/codeAgent/skills/akan-query/SKILL.md +13 -20
  53. package/codeAgent/skills/akan-runtime/SKILL.md +21 -1
  54. package/codeAgent/skills/akan-service/SKILL.md +21 -20
  55. package/codeAgent/skills/akan-transport/SKILL.md +5 -14
  56. package/codeAgent/skills/akan-ui/SKILL.md +16 -21
  57. package/codeAgent/skills/akan-validate/SKILL.md +8 -2
  58. package/commandDecorators/command.ts +28 -12
  59. package/commandDecorators/commandBuilder.ts +8 -1
  60. package/commandDecorators/commandDecorators.test.ts +70 -3
  61. package/commandDecorators/helpFormatter.ts +14 -12
  62. package/context/akanContext.ts +2 -0
  63. package/csrE2e/devHmrLatency.e2e.test.ts +1 -1
  64. package/csrE2e/ssrRegistry.e2e.test.ts +108 -22
  65. package/docs/apiReference.test.ts +25 -0
  66. package/docs/apiReference.ts +38 -5
  67. package/docs/declarationReader.ts +30 -0
  68. package/executors/appExecutor.ts +26 -12
  69. package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
  70. package/executors/clientRuntimeKeys.fixture.json +393 -0
  71. package/executors/clientRuntimeKeys.test.ts +1690 -0
  72. package/executors/executor.ts +14 -6
  73. package/executors/executors.test.ts +155 -1
  74. package/executors/pkgExecutor.ts +2 -1
  75. package/executors/sysExecutor.ts +112 -8
  76. package/executors/workspaceExecutor.ts +7 -4
  77. package/frontendBuild/allRoutesBuilder.ts +99 -7
  78. package/frontendBuild/autoImportSync.ts +3 -2
  79. package/frontendBuild/buildRouteClient.test.ts +686 -13
  80. package/frontendBuild/clientBuildTypes.ts +26 -0
  81. package/frontendBuild/clientEntriesBundler.ts +49 -1
  82. package/frontendBuild/clientEntryDiscovery.test.ts +308 -1
  83. package/frontendBuild/clientEntryDiscovery.ts +136 -14
  84. package/frontendBuild/clientEntryGroups.test.ts +77 -0
  85. package/frontendBuild/clientEntryGroups.ts +61 -0
  86. package/frontendBuild/csrDevArtifactWriter.ts +2 -2
  87. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  88. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  89. package/frontendBuild/csrDevPatcher.test.ts +4 -5
  90. package/frontendBuild/csrDevPatcher.ts +37 -11
  91. package/frontendBuild/csrDevTypes.ts +9 -0
  92. package/frontendBuild/devBarrelImports.test.ts +154 -0
  93. package/frontendBuild/devBarrelImports.ts +83 -23
  94. package/frontendBuild/devChangePlanner.ts +0 -1
  95. package/frontendBuild/devRegistryBundler.ts +4 -2
  96. package/frontendBuild/devRouteRuntime.test.ts +492 -0
  97. package/frontendBuild/devRouteRuntime.ts +167 -0
  98. package/frontendBuild/dictionaryAssetBuilder.test.ts +408 -0
  99. package/frontendBuild/dictionaryAssetBuilder.ts +185 -17
  100. package/frontendBuild/dictionaryConstants.ts +136 -0
  101. package/frontendBuild/dictionaryOwnParts.ts +88 -0
  102. package/frontendBuild/dictionaryPackState.ts +131 -0
  103. package/frontendBuild/dictionaryPacking.test.ts +207 -0
  104. package/frontendBuild/dictionaryPacking.ts +160 -0
  105. package/frontendBuild/dictionaryRoutes.test.ts +251 -0
  106. package/frontendBuild/dictionaryRoutes.ts +227 -0
  107. package/frontendBuild/frontendBuild.test.ts +5 -3
  108. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  109. package/frontendBuild/pagesBundleBuilder.ts +78 -2
  110. package/frontendBuild/precompressArtifacts.test.ts +22 -0
  111. package/frontendBuild/precompressArtifacts.ts +34 -8
  112. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  113. package/frontendBuild/renderedEntries.ts +144 -0
  114. package/frontendBuild/routeClientBuilder.ts +407 -43
  115. package/frontendBuild/routeHandoffs.test.ts +155 -0
  116. package/frontendBuild/routeHandoffs.ts +117 -0
  117. package/frontendBuild/routeModulePreloads.test.ts +32 -0
  118. package/frontendBuild/routeModulePreloads.ts +20 -11
  119. package/frontendBuild/routeRuntimeCheck.test.ts +280 -0
  120. package/frontendBuild/routeRuntimeCheck.ts +248 -0
  121. package/frontendBuild/routeRuntimePays.test.ts +143 -0
  122. package/frontendBuild/routeRuntimePays.ts +117 -0
  123. package/frontendBuild/ssrBaseArtifactBuilder.ts +30 -35
  124. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  125. package/frontendBuild/ssrDevBundler.ts +66 -11
  126. package/frontendBuild/vendorFileImports.test.ts +254 -0
  127. package/frontendBuild/vendorFileImports.ts +163 -0
  128. package/frontendBuild/vendorNarrowing.test.ts +47 -3
  129. package/frontendBuild/vendorNarrowing.ts +38 -2
  130. package/frontendBuild/vendorSpecifiers.ts +2 -0
  131. package/guideline/agentAssets.ts +1 -1
  132. package/incrementalBuilder/buildBatch.proc.ts +35 -9
  133. package/incrementalBuilder/buildBatchProtocol.ts +2 -1
  134. package/incrementalBuilder/builderBoot.ts +5 -5
  135. package/incrementalBuilder/builderGraphPayloads.ts +4 -4
  136. package/incrementalBuilder/builderLanes.ts +2 -2
  137. package/incrementalBuilder/builderWatch.ts +19 -9
  138. package/incrementalBuilder/csrRegistry.ts +4 -4
  139. package/incrementalBuilder/incrementalBuilder.proc.test.ts +159 -0
  140. package/incrementalBuilder/incrementalBuilder.proc.ts +38 -10
  141. package/incrementalBuilder/pendingMetadata.test.ts +27 -0
  142. package/incrementalBuilder/pendingMetadata.ts +19 -0
  143. package/incrementalBuilder/ssrRegistry.ts +6 -6
  144. package/index.ts +1 -1
  145. package/integration/devResourceProbe.ts +14 -0
  146. package/integration/devStability.integration.test.ts +46 -21
  147. package/integration/renderAdmissionSoak.test.ts +99 -0
  148. package/integration/renderAdmissionSoak.ts +615 -0
  149. package/integration/ssrMemoryProbe.ts +5 -0
  150. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  151. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  152. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  153. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  154. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  155. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  156. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  157. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  158. package/lint/biomeBase.test.ts +50 -3
  159. package/lint/biomeBase.ts +1 -1
  160. package/lint/biomeCheck.test.ts +162 -0
  161. package/lint/biomeCheck.ts +131 -0
  162. package/lint/linter.test.ts +16 -11
  163. package/lint/no-arbitrary-color.grit +5 -0
  164. package/lint/no-conditional-st-hook.grit +5 -1
  165. package/lint/no-daisyui-legacy-class.grit +8 -0
  166. package/lint/no-document-cookie.grit +3 -0
  167. package/lint/no-inline-color.grit +10 -2
  168. package/lint/no-oversized-list-limit.grit +2 -0
  169. package/lint/no-raw-palette-class.grit +7 -0
  170. package/lint/no-unpublished-form-setter.grit +2 -0
  171. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  172. package/lint/no-web-storage.grit +3 -0
  173. package/lint/withheldEnvFile.ts +17 -0
  174. package/mobile/desktopBin.ts +2 -2
  175. package/mobile/desktopServerStage.test.ts +18 -3
  176. package/mobile/desktopServerStage.ts +7 -2
  177. package/mobile/nativeApp.test.ts +13 -5
  178. package/mobile/nativeApp.ts +9 -4
  179. package/mobile/nativeConfig.test.ts +96 -1
  180. package/mobile/nativeConfig.ts +46 -12
  181. package/mobile/nativePublicEnv.ts +1 -1
  182. package/mobile/serverBundleSecrets.ts +43 -0
  183. package/package.json +22 -178
  184. package/packageExports.test.ts +39 -24
  185. package/preview/PreviewView.ts +25 -3
  186. package/quality/dictionaryKeys.test.ts +356 -0
  187. package/quality/dictionaryKeys.ts +488 -0
  188. package/quality/objectImportReport.test.ts +36 -0
  189. package/quality/objectImportReport.ts +105 -0
  190. package/quality/qualityScanner.ts +1 -1
  191. package/quality/routeRuntimeReport.test.ts +91 -0
  192. package/quality/routeRuntimeReport.ts +121 -0
  193. package/quality/runtimeConstantFacts.ts +71 -0
  194. package/quality/runtimeConstantGraph.ts +123 -0
  195. package/quality/runtimeConstantReads.ts +116 -0
  196. package/quality/runtimeImports.test.ts +190 -0
  197. package/quality/runtimeImports.ts +233 -0
  198. package/quality/runtimeKeyNames.ts +46 -0
  199. package/quality/runtimeLexicalScope.ts +132 -0
  200. package/quality/runtimeMarkerReach.test.ts +84 -0
  201. package/quality/runtimeMarkerReach.ts +255 -0
  202. package/quality/runtimeModuleFacts.ts +290 -0
  203. package/quality/runtimeNameTable.test.ts +172 -0
  204. package/quality/runtimeNameTable.ts +477 -0
  205. package/quality/runtimeScopeReport.test.ts +123 -0
  206. package/quality/runtimeScopeReport.ts +167 -0
  207. package/quality/runtimeSliceKey.ts +269 -0
  208. package/quality/runtimeSyntax.ts +133 -0
  209. package/quality/runtimeTable.fixture.ts +189 -0
  210. package/quality/runtimeUse.test.ts +737 -0
  211. package/quality/runtimeUse.ts +696 -0
  212. package/quality/runtimeUseReadable.test.ts +393 -0
  213. package/quality/ssrScanner.test.ts +13 -0
  214. package/quality/ssrScanner.ts +1 -1
  215. package/quality/translatorBindings.ts +187 -0
  216. package/test/fakeTerminal.ts +45 -0
  217. package/test/secretEnvFixture.ts +134 -0
  218. package/test/testHelpers.ts +11 -0
  219. package/transforms/barrelAnalyzer.ts +26 -4
  220. package/transforms/barrelImportsPlugin.ts +121 -32
  221. package/transforms/exportReach.test.ts +162 -0
  222. package/transforms/exportReach.ts +308 -0
  223. package/transforms/frameworkObjects.fixture.tsx +58 -0
  224. package/transforms/frameworkObjects.test.ts +54 -0
  225. package/transforms/modelReference.test.ts +196 -0
  226. package/transforms/modelReference.ts +39 -0
  227. package/transforms/moduleParts.test.ts +225 -0
  228. package/transforms/moduleParts.ts +418 -0
  229. package/transforms/objectImportEdits.ts +150 -0
  230. package/transforms/objectMemberImports.test.ts +633 -0
  231. package/transforms/objectMemberImports.ts +571 -0
  232. package/transforms/objectMemberLookup.ts +150 -0
  233. package/transforms/objectModule.test.ts +307 -0
  234. package/transforms/objectModule.ts +482 -0
  235. package/transforms/objectModuleAnalyzer.ts +104 -0
  236. package/transforms/partImports.test.ts +76 -0
  237. package/transforms/partImports.ts +110 -0
  238. package/transforms/partModules.test.ts +187 -0
  239. package/transforms/partModules.ts +90 -0
  240. package/transforms/partPurity.ts +124 -0
  241. package/transforms/reactIconImports.test.ts +231 -0
  242. package/transforms/reactIconImports.ts +325 -0
  243. package/transforms/routeConstants.ts +122 -0
  244. package/transforms/routeRuntime.test.ts +835 -0
  245. package/transforms/routeRuntime.ts +703 -0
  246. package/transforms/routeRuntimeEdits.ts +92 -0
  247. package/transforms/routeRuntimeGraph.ts +66 -0
  248. package/transforms/routeRuntimePlan.ts +244 -0
  249. package/transforms/secretEnvDeclaration.test.ts +211 -0
  250. package/transforms/secretEnvDeclaration.ts +219 -0
  251. package/transforms/secretEnvFile.test.ts +117 -0
  252. package/transforms/secretEnvFile.ts +113 -0
  253. package/transforms/secretEnvName.test.ts +54 -0
  254. package/transforms/secretEnvName.ts +29 -0
  255. package/transforms/secretEnvSource.test.ts +152 -0
  256. package/transforms/secretEnvSource.ts +197 -0
  257. package/transforms/serverEnvEvaluationError.ts +11 -0
  258. package/transforms/serverEnvPlugin.test.ts +118 -1
  259. package/transforms/serverEnvPlugin.ts +95 -2
  260. package/transforms/serverEnvProfile.test.ts +129 -2
  261. package/transforms/serverEnvProfile.ts +133 -43
  262. package/transforms/serverEnvSecrets.test.ts +268 -0
  263. package/transforms/signalDescriptors.test.ts +280 -0
  264. package/transforms/signalDescriptors.ts +227 -0
  265. package/transforms/thisFreeExports.ts +87 -0
  266. package/transforms/transforms.test.ts +180 -3
  267. package/transforms/tsconfigPackageResolver.test.ts +1 -0
  268. package/tunnel/createTunnel.test.ts +29 -8
  269. package/tunnel/createTunnel.ts +22 -11
  270. package/tunnel/ssh2Module.test.ts +37 -0
  271. package/tunnel/ssh2Module.ts +28 -0
  272. package/tunnel/sshTunnel.ts +4 -2
  273. package/typecheck/projectTypecheck.test.ts +32 -1
  274. package/typecheck/projectTypecheck.ts +3 -3
  275. package/typecheck/typeChecker.test.ts +49 -0
  276. package/typecheck/typeChecker.ts +9 -7
  277. package/typecheck/withheldDiagnostics.ts +41 -0
  278. package/util/devInstallCommand.ts +7 -0
  279. package/util/fileEditor.ts +1 -0
  280. package/util/jsonFormatter.test.ts +13 -9
  281. package/util/selectModel.ts +1 -0
  282. package/workflow/executor.ts +6 -2
  283. package/workflow/index.ts +1 -0
  284. package/workflow/plan.ts +36 -7
  285. package/workflow/types.ts +1 -1
  286. package/workflow/uiTarget.ts +50 -0
  287. package/workspace/envSeed.test.ts +30 -1
  288. package/workspace/envSeed.ts +30 -1
  289. package/workspace/getRelatedCnsts.ts +7 -0
  290. package/workspace/mainCheckout.test.ts +55 -0
  291. package/workspace/mainCheckout.ts +38 -0
  292. package/workspace/scanInfo.test.ts +39 -0
  293. package/workspace/scanInfo.ts +55 -6
  294. package/workspace/slicePlanner.ts +2 -1
  295. package/workspace/workspaceLayout.test.ts +22 -1
  296. package/workspace/workspaceLayout.ts +3 -3
  297. package/CHANGELOG.md +0 -2718
  298. package/codeAgent/agent/AkanCodeCompaction.ts +0 -49
  299. package/codeAgent/agent/AkanCodeServices.ts +0 -122
  300. package/codeAgent/agent/AkanContextFiles.ts +0 -94
  301. package/codeAgent/agent/CodeAgent.ts +0 -606
  302. package/codeAgent/agent/CodeAgentAsks.ts +0 -66
  303. package/codeAgent/agent/CodeAgentEventMapper.ts +0 -225
  304. package/codeAgent/agent/CodeAgentGate.ts +0 -239
  305. package/codeAgent/agent/CodeAgentProxy.ts +0 -83
  306. package/codeAgent/agent/CodeAgentRpcHost.ts +0 -109
  307. package/codeAgent/agent/CodeAgentRpcListener.ts +0 -195
  308. package/codeAgent/agent/CodeAgentStreamPrinter.ts +0 -86
  309. package/codeAgent/agent/CodeAgentSuspended.ts +0 -85
  310. package/codeAgent/agent/CodeAgentUi.ts +0 -47
  311. package/codeAgent/agent/CodeMailbox.ts +0 -148
  312. package/codeAgent/agent/CodeSessionFork.ts +0 -56
  313. package/codeAgent/agent/CodeSessionIndex.ts +0 -78
  314. package/codeAgent/agent/SubagentPool.ts +0 -219
  315. package/codeAgent/agent/WorkspaceTrust.ts +0 -200
  316. package/codeAgent/agent/akanCodeCompaction.test.ts +0 -36
  317. package/codeAgent/agent/akanCodeModel.ts +0 -47
  318. package/codeAgent/agent/akanCodeServices.test.ts +0 -54
  319. package/codeAgent/agent/akanContextFiles.test.ts +0 -116
  320. package/codeAgent/agent/akanSystemPrompt.ts +0 -50
  321. package/codeAgent/agent/codeAgent.test.ts +0 -275
  322. package/codeAgent/agent/codeAgentContract.test.ts +0 -643
  323. package/codeAgent/agent/codeAgentHosts.ts +0 -30
  324. package/codeAgent/agent/codeAgentProxy.test.ts +0 -126
  325. package/codeAgent/agent/codeAgentRpcListener.test.ts +0 -215
  326. package/codeAgent/agent/codeAgentSuspended.test.ts +0 -47
  327. package/codeAgent/agent/codeMailbox.test.ts +0 -76
  328. package/codeAgent/agent/codeSessionFork.test.ts +0 -58
  329. package/codeAgent/agent/codeSessionIndex.test.ts +0 -77
  330. package/codeAgent/agent/consoleToStderr.ts +0 -8
  331. package/codeAgent/agent/jsonLines.ts +0 -29
  332. package/codeAgent/agent/stringArg.ts +0 -5
  333. package/codeAgent/feedback/DevLogFeedback.ts +0 -82
  334. package/codeAgent/feedback/PreviewFeedback.ts +0 -46
  335. package/codeAgent/feedback/TurnFeedback.ts +0 -98
  336. package/codeAgent/feedback/VerifyFeedback.ts +0 -39
  337. package/codeAgent/tools/AkanCli.ts +0 -51
  338. package/codeAgent/tools/AkanCodePlugins.ts +0 -142
  339. package/codeAgent/tools/AkanEditScope.ts +0 -53
  340. package/codeAgent/tools/AkanEnvKeys.ts +0 -50
  341. package/codeAgent/tools/AkanToolPack.ts +0 -86
  342. package/codeAgent/tools/AkanVerifier.ts +0 -30
  343. package/codeAgent/tools/AskToolPack.ts +0 -99
  344. package/codeAgent/tools/DeepSeekWeb.ts +0 -127
  345. package/codeAgent/tools/MailToolPack.ts +0 -76
  346. package/codeAgent/tools/McpClient.ts +0 -209
  347. package/codeAgent/tools/McpOAuth.ts +0 -233
  348. package/codeAgent/tools/McpOAuthLoopback.ts +0 -64
  349. package/codeAgent/tools/McpServerConfig.ts +0 -131
  350. package/codeAgent/tools/McpSignIn.ts +0 -158
  351. package/codeAgent/tools/McpTokenStore.ts +0 -128
  352. package/codeAgent/tools/McpToolPack.ts +0 -206
  353. package/codeAgent/tools/SessionToolPack.ts +0 -91
  354. package/codeAgent/tools/WebToolPack.ts +0 -315
  355. package/codeAgent/tools/akanCodePlugins.test.ts +0 -954
  356. package/codeAgent/tools/askToolPack.test.ts +0 -116
  357. package/codeAgent/tools/deepSeekWeb.test.ts +0 -113
  358. package/codeAgent/tools/mcpOAuth.test.ts +0 -648
  359. package/codeAgent/tools/mcpServerConfig.test.ts +0 -341
  360. package/piDependencyPins.test.ts +0 -45
@@ -1,17 +1,27 @@
1
- import { mkdir } from "node:fs/promises";
1
+ import { mkdir, rm } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import type { BaseBuildArtifact, ClientManifest, ClientManifestEntry, SsrManifest } from "akanjs/server";
4
4
  import { SSR_DEV_CHUNK, SSR_DEV_ID_PREFIX } from "akanjs/server/hmr/csrDevManifest";
5
- import { StoreBootstrap } from "../artifact/storeBootstrap";
5
+ import { type ClientRuntimeScope, StoreBootstrap } from "../artifact/storeBootstrap";
6
6
  import type { App } from "../commandDecorators";
7
+ import { type RouteRuntimeBuildReport, RouteRuntimeReport } from "../quality/routeRuntimeReport";
7
8
  import { createBarrelImportsPlugin } from "../transforms/barrelImportsPlugin";
9
+ import { ModuleParts } from "../transforms/moduleParts";
8
10
  import { loaderFor } from "../transforms/moduleSyntax";
11
+ import { PartModules } from "../transforms/partModules";
12
+ import { ReactIconImports } from "../transforms/reactIconImports";
13
+ import { RouteRuntime } from "../transforms/routeRuntime";
14
+ import type { RouteRuntimeBundle } from "../transforms/routeRuntimeGraph";
9
15
  import { scanUseClientExports, toClientReferencePath } from "../transforms/rscUseClientTransform";
10
- import type { ClientBundleTarget, ClientEntryDiscovery } from "./clientBuildTypes";
16
+ import { SignalDescriptors } from "../transforms/signalDescriptors";
17
+ import type { AskedExports, ClientBundleTarget, ClientEntryDiscovery, ClientModuleImport } from "./clientBuildTypes";
11
18
  import { ClientEntriesBundler } from "./clientEntriesBundler";
12
19
  import { GraphClientEntryDiscovery } from "./clientEntryDiscovery";
20
+ import { ClientEntryGroups, type ClientEntryPart, type GroupedExport } from "./clientEntryGroups";
13
21
  import { CsrDevPaths } from "./csrDevPaths";
14
- import { VENDOR_SPECIFIERS } from "./vendorSpecifiers";
22
+ import { RouteRuntimeCheck } from "./routeRuntimeCheck";
23
+ import { type RoutePaysVerdict, RouteRuntimePays } from "./routeRuntimePays";
24
+ import { VendorFileImports } from "./vendorFileImports";
15
25
 
16
26
  const SSR_CLIENT_ALIAS_EXTERNALS = [
17
27
  "react",
@@ -36,6 +46,12 @@ export interface BuildRouteClientOptions {
36
46
  entries?: string[];
37
47
  /** Defaults to `registry` under `start`: the browser loads each entry from the SSR dev registry, so only `client-ssr` builds. */
38
48
  browser?: "chunks" | "registry";
49
+ /** The entries each route loads: an entry only whole-runtime routes hold keeps the whole runtime too. */
50
+ entriesByRoute?: ReadonlyMap<string, readonly string[]>;
51
+ /** The entries each route loads first, which its size is measured over. Defaults to `entriesByRoute`. */
52
+ sizedEntriesByRoute?: ReadonlyMap<string, readonly string[]>;
53
+ /** The exports each route asks of an entry it loads first; an entry left out, or null, is asked for all of them. */
54
+ askedByRoute?: ReadonlyMap<string, AskedExports>;
39
55
  }
40
56
 
41
57
  export interface BuildRouteClientResult {
@@ -49,13 +65,40 @@ export interface BuildRouteClientResult {
49
65
  registryEntries?: string[];
50
66
  /** Chunks mode: the importmap specifiers each browser chunk imports statically. */
51
67
  externalsByChunkUrl?: Record<string, string[]>;
68
+ /** The imports of every module the browser loads, or in registry mode of the SSR bundle standing in for it. */
69
+ clientGraph?: ReadonlyMap<string, readonly ClientModuleImport[]>;
70
+ /** Chunks mode, where the build narrowed any route: what `RouteRuntimeReport.file` now holds. */
71
+ runtimeReport?: RouteRuntimeBuildReport;
52
72
  }
53
73
 
54
74
  interface BootstrapEntries {
55
75
  buildEntries: string[];
56
76
  originalByBuildEntry: Map<string, string>;
77
+ //? Only for an entry built as several: the export names each of its build entries holds.
78
+ namesByBuildEntry?: Map<string, readonly string[]>;
79
+ //? Only for a build entry holding several entries: each name it exports, with the entry and the name behind it.
80
+ membersByBuildEntry?: Map<string, ReadonlyMap<string, GroupedExport>>;
57
81
  }
58
82
 
83
+ interface WrappedPart extends ClientEntryPart {
84
+ file: string;
85
+ split: boolean;
86
+ }
87
+
88
+ interface NarrowedBuild {
89
+ entries: BootstrapEntries;
90
+ kept: ReadonlySet<string>;
91
+ bundle: Awaited<ReturnType<ClientEntriesBundler["bundle"]>>;
92
+ runtime: RouteRuntime;
93
+ report?: RouteRuntimeBuildReport;
94
+ }
95
+
96
+ type BundleOf = (runtime: RouteRuntime, kept: ReadonlySet<string>, outputSubdir?: string) => Promise<NarrowedBuild>;
97
+
98
+ const referenceSubdir = "client-whole";
99
+ //? Each trial bundles the whole app again, and the entries left to try shrink slowly where pages share most of them.
100
+ const measuredTrials = 6;
101
+
59
102
  export class RouteClientBuilder {
60
103
  #app: App;
61
104
  #seeds: string[];
@@ -65,6 +108,10 @@ export class RouteClientBuilder {
65
108
  #discovery?: ClientEntryDiscovery;
66
109
  #entries?: string[];
67
110
  #browser: "chunks" | "registry";
111
+ #entriesByRoute?: ReadonlyMap<string, readonly string[]>;
112
+ #sizedEntriesByRoute?: ReadonlyMap<string, readonly string[]>;
113
+ #askedByRoute?: ReadonlyMap<string, AskedExports>;
114
+ readonly #parts = new Map<string, ModuleParts | null>();
68
115
 
69
116
  constructor(options: BuildRouteClientOptions) {
70
117
  this.#app = options.app;
@@ -75,6 +122,9 @@ export class RouteClientBuilder {
75
122
  this.#discovery = options.discovery;
76
123
  this.#entries = options.entries;
77
124
  this.#browser = options.browser ?? (this.#command === "start" ? "registry" : "chunks");
125
+ this.#entriesByRoute = options.entriesByRoute;
126
+ this.#sizedEntriesByRoute = options.sizedEntriesByRoute;
127
+ this.#askedByRoute = options.askedByRoute;
78
128
  }
79
129
 
80
130
  async build(): Promise<BuildRouteClientResult> {
@@ -84,12 +134,34 @@ export class RouteClientBuilder {
84
134
  ? [...new Set([...discovered, ...(await (await this.#getDiscovery()).discover(this.#graphSeeds))])].sort()
85
135
  : discovered.filter((e) => !this.#knownEntries.has(e));
86
136
 
87
- const bootstrapEntries = await this.#createBootstrapEntries(entries);
88
137
  //? Registry mode builds no browser bundle: the SSR bundle has the same entries, exports and imports to read.
89
138
  const registry = this.#browser === "registry" ? new CsrDevPaths(this.#app.workspace.workspaceRoot) : null;
90
- const browserBundle = registry ? null : await this.#buildBrowserBundle(bootstrapEntries);
91
- const ssrBundle = await this.#buildSsrBundle(bootstrapEntries);
139
+ const routeRuntime = registry ? null : await this.#readRouteRuntime();
140
+ if (!registry && !routeRuntime) await rm(path.join(this.#app.cwdPath, RouteRuntimeReport.file), { force: true });
141
+ const ssrEntries = await this.#createBootstrapEntries(entries, "whole");
142
+ //? First: its entries all load the whole runtime, so its graph says which of them a per-route build may narrow.
143
+ const ssrBundle = await this.#buildSsrBundle(ssrEntries);
144
+ const narrowed = routeRuntime
145
+ ? await this.#buildNarrowed(entries, ssrEntries, routeRuntime, {
146
+ importsByModule: ssrBundle.graph.importsByModule,
147
+ entries: entries.map((entry) => path.resolve(entry)),
148
+ entriesByRoute: this.#entriesByRoute,
149
+ })
150
+ : null;
151
+ const trusted = narrowed && this.#check(narrowed) ? narrowed : null;
152
+ const browserEntries = registry ? null : (trusted?.entries ?? ssrEntries);
153
+ const browserBundle =
154
+ trusted?.bundle ?? (browserEntries ? await this.#buildBrowserBundle(browserEntries, null) : null);
155
+ if (trusted?.report) await this.#say(trusted.report);
156
+ if (narrowed && !trusted && browserBundle) {
157
+ await rm(path.join(this.#app.cwdPath, RouteRuntimeReport.file), { force: true });
158
+ await RouteClientBuilder.#removeChunks(narrowed.bundle, browserBundle);
159
+ }
92
160
  const referenceBundle = browserBundle ?? ssrBundle;
161
+ const bootstrapEntries = browserEntries ?? ssrEntries;
162
+ const ssrEntryByOriginal = new Map(
163
+ [...ssrEntries.originalByBuildEntry].map(([buildEntry, originalEntry]) => [originalEntry, buildEntry]),
164
+ );
93
165
 
94
166
  const acceptedEntries = new Set(entries);
95
167
  const routeEntries = new Set(discovered);
@@ -103,6 +175,7 @@ export class RouteClientBuilder {
103
175
  bootstrapEntries.originalByBuildEntry,
104
176
  referenceBundle.clientReferenceIdByAbsPath,
105
177
  this.#app.workspace.workspaceRoot,
178
+ bootstrapEntries.membersByBuildEntry,
106
179
  );
107
180
  if (!manifestEntry) continue;
108
181
  if (!acceptedEntries.has(manifestEntry.originalEntry)) continue;
@@ -111,21 +184,29 @@ export class RouteClientBuilder {
111
184
  : bundleRow;
112
185
  manifestDelta[manifestEntry.key] = row;
113
186
 
114
- const ssrOutput = ssrBundle.entryOutputAbsByAbsPath.get(manifestEntry.buildEntry);
187
+ const ssrOutput = ssrBundle.entryOutputAbsByAbsPath.get(
188
+ ssrEntryByOriginal.get(manifestEntry.originalEntry) ?? manifestEntry.buildEntry,
189
+ );
115
190
  if (!ssrOutput) continue;
116
191
 
117
192
  ssrModuleMap[row.id] ??= {};
118
- ssrModuleMap[row.id][row.name] = { id: ssrOutput, chunks: [ssrOutput, ssrOutput], name: row.name, async: true };
193
+ const { name } = manifestEntry;
194
+ ssrModuleMap[row.id][row.name] = { id: ssrOutput, chunks: [ssrOutput, ssrOutput], name, async: true };
119
195
  }
120
196
  for (const entry of bootstrapEntries.buildEntries) {
121
197
  const buildEntry = path.resolve(entry);
122
- const originalEntry = path.resolve(bootstrapEntries.originalByBuildEntry.get(buildEntry) ?? buildEntry);
123
- if (!acceptedEntries.has(originalEntry)) continue;
124
- const deps = new Set<string>([originalEntry]);
125
- for (const dep of referenceBundle.entryDepsByAbsPath.get(buildEntry) ?? []) deps.add(path.resolve(dep));
126
- const sortedDeps = [...deps].sort();
127
- clientDepsByEntry[originalEntry] = sortedDeps;
128
- if (routeEntries.has(originalEntry)) for (const dep of sortedDeps) clientDeps.add(dep);
198
+ const grouped = bootstrapEntries.membersByBuildEntry?.get(buildEntry);
199
+ const originalEntries = grouped
200
+ ? new Set([...grouped.values()].map((member) => member.entry))
201
+ : [path.resolve(bootstrapEntries.originalByBuildEntry.get(buildEntry) ?? buildEntry)];
202
+ for (const originalEntry of originalEntries) {
203
+ if (!acceptedEntries.has(originalEntry)) continue;
204
+ const deps = new Set<string>(clientDepsByEntry[originalEntry] ?? [originalEntry]);
205
+ for (const dep of referenceBundle.entryDepsByAbsPath.get(buildEntry) ?? []) deps.add(path.resolve(dep));
206
+ const sortedDeps = [...deps].sort();
207
+ clientDepsByEntry[originalEntry] = sortedDeps;
208
+ if (routeEntries.has(originalEntry)) for (const dep of sortedDeps) clientDeps.add(dep);
209
+ }
129
210
  }
130
211
 
131
212
  return {
@@ -137,6 +218,8 @@ export class RouteClientBuilder {
137
218
  clientDepsByEntry,
138
219
  ...(registry ? { registryEntries: [...acceptedEntries].sort() } : {}),
139
220
  ...(browserBundle ? { externalsByChunkUrl: Object.fromEntries(browserBundle.externalsByChunkUrl) } : {}),
221
+ clientGraph: referenceBundle.graph.importsByModule,
222
+ ...(trusted?.report ? { runtimeReport: trusted.report } : {}),
140
223
  };
141
224
  }
142
225
 
@@ -165,23 +248,243 @@ export class RouteClientBuilder {
165
248
  };
166
249
  }
167
250
 
168
- async #buildBrowserBundle(bootstrapEntries: BootstrapEntries) {
251
+ async #readRouteRuntime(): Promise<RouteRuntime | null> {
252
+ const { name } = this.#app;
253
+ const whole = (why: string, first = "Run") => {
254
+ this.#app.logger.warn(
255
+ `[client-runtime] ${why}, so every page of this build loads the whole client runtime, not only what it uses. ${first} \`akan sync ${name}\` and build again.`,
256
+ );
257
+ return null;
258
+ };
259
+ const missing = `the per-module runtime files of ${name} or a lib it mounts are missing`;
260
+ if ((await StoreBootstrap.scopeOf(this.#app)) !== "page") return whole(missing);
261
+ try {
262
+ return (await RouteRuntime.read(this.#app.workspace.workspaceRoot, `apps/${name}`)) ?? whole(missing);
263
+ } catch (error) {
264
+ const reason = error instanceof Error ? error.message : String(error);
265
+ return whole(`the modules of ${name} or a lib it mounts could not be read (${reason})`, "Fix that, then run");
266
+ }
267
+ }
268
+
269
+ async #buildNarrowed(
270
+ entries: string[],
271
+ whole: BootstrapEntries,
272
+ runtime: RouteRuntime,
273
+ planned: RouteRuntimeBundle,
274
+ ): Promise<NarrowedBuild> {
275
+ const bundleOf: BundleOf = async (routeRuntime, kept, outputSubdir) => {
276
+ const started = Date.now();
277
+ const browserEntries = await this.#createBootstrapEntries(entries, "page", { kept, whole });
278
+ const bundle = await this.#buildBrowserBundle(browserEntries, routeRuntime, outputSubdir);
279
+ this.#app.verbose(`[client-runtime] bundled ${outputSubdir ?? "client"} (${Date.now() - started}ms)`);
280
+ return { entries: browserEntries, kept, bundle, runtime: routeRuntime };
281
+ };
282
+ const first = await bundleOf(runtime, runtime.plan(planned));
283
+ const routes = this.#entriesByRoute;
284
+ if (!routes || !runtime.decided) return first;
285
+ const perModuleIn = ({ kept }: NarrowedBuild) =>
286
+ [...routes].filter(([, held]) => !held.some((entry) => kept.has(entry))).map(([route]) => route);
287
+ const analysed = perModuleIn(first);
288
+ const { built, refused } =
289
+ analysed.length > 0
290
+ ? await this.#keptWhereNotSmaller(first, routes, planned, bundleOf)
291
+ : { built: first, refused: [] };
292
+ const perModule = perModuleIn(built);
293
+ return {
294
+ ...built,
295
+ report: {
296
+ app: this.#app.name,
297
+ routes: routes.size,
298
+ perModule,
299
+ notSmaller: analysed.filter((route) => !perModule.includes(route)),
300
+ refused,
301
+ causes: built.runtime.decided?.causes() ?? [],
302
+ },
303
+ };
304
+ }
305
+
306
+ async #say(report: RouteRuntimeBuildReport) {
307
+ await RouteRuntimeReport.write(this.#app.cwdPath, report);
308
+ for (const route of report.notSmaller) this.#app.verbose(`[client-runtime] not smaller per module: ${route}`);
309
+ for (const route of report.refused ?? [])
310
+ this.#app.verbose(`[client-runtime] larger with the whole runtime here: ${route}`);
311
+ for (const route of report.perModule) this.#app.verbose(`[client-runtime] per module: ${route}`);
312
+ }
313
+
314
+ static async #removeChunks(replaced: NarrowedBuild["bundle"], served: NarrowedBuild["bundle"]) {
315
+ for (const chunk of replaced.graph.importsByChunk.keys())
316
+ if (!served.graph.importsByChunk.has(chunk)) await rm(chunk, { force: true });
317
+ }
318
+
319
+ //? A pass either keeps entries or refuses some for good, and neither set ever loses one, so the passes end.
320
+ async #keptWhereNotSmaller(
321
+ first: NarrowedBuild,
322
+ routes: ReadonlyMap<string, readonly string[]>,
323
+ planned: RouteRuntimeBundle,
324
+ bundleOf: BundleOf,
325
+ ): Promise<{ built: NarrowedBuild; refused: string[] }> {
326
+ const pays = new RouteRuntimePays();
327
+ const sizesOf = (build: NarrowedBuild) => pays.sizesOf(build.bundle, this.#sizedBuildEntries(build.entries));
328
+ //? A keep is never taken back, so a build that did not pay is replaced from a runtime read again.
329
+ const bundleWith = async (verdicts: readonly RoutePaysVerdict[], last: NarrowedBuild | null, subdir?: string) => {
330
+ const runtime = await this.#readRouteRuntime();
331
+ if (!runtime) return null;
332
+ let kept = runtime.plan(planned);
333
+ for (const { entry, ...measured } of verdicts) kept = runtime.keep([entry], { rule: "not-smaller", ...measured });
334
+ const build = await bundleOf(runtime, subdir ? runtime.keepAll() : kept, subdir);
335
+ if (last) await RouteClientBuilder.#removeChunks(last.bundle, build.bundle);
336
+ return build;
337
+ };
338
+ const reference = await bundleWith([], null, referenceSubdir);
339
+ if (!reference) return { built: first, refused: [] };
340
+ const wholeSizes = await sizesOf(reference);
341
+ await rm(path.join(this.#artifactDir, referenceSubdir), { recursive: true, force: true });
342
+ let current = { build: first, sizes: await sizesOf(first), verdicts: [] as RoutePaysVerdict[] };
343
+ let onDisk = first;
344
+ const refused = new Set<string>();
345
+ const refusedRoutes = new Set<string>();
346
+ for (let trial = 0; trial < measuredTrials; trial++) {
347
+ const verdicts = RouteRuntimePays.decide({
348
+ entriesByRoute: routes,
349
+ isKept: (entry) => current.build.kept.has(entry),
350
+ isRefused: (entry) => refused.has(entry),
351
+ whole: wholeSizes,
352
+ measured: current.sizes,
353
+ });
354
+ if (verdicts.length === 0) break;
355
+ const tried = await bundleWith([...current.verdicts, ...verdicts], onDisk);
356
+ if (!tried) break;
357
+ onDisk = tried;
358
+ const sizes = await sizesOf(tried);
359
+ const larger = RouteRuntimePays.larger({
360
+ entriesByRoute: routes,
361
+ wasKept: (entry) => current.build.kept.has(entry),
362
+ isKept: (entry) => tried.kept.has(entry),
363
+ before: current.sizes,
364
+ after: sizes,
365
+ });
366
+ if (larger.length === 0) {
367
+ current = { build: tried, sizes, verdicts: [...current.verdicts, ...verdicts] };
368
+ continue;
369
+ }
370
+ for (const route of larger) {
371
+ refusedRoutes.add(route);
372
+ for (const entry of routes.get(route) ?? []) refused.add(entry);
373
+ }
374
+ if (!verdicts.some(({ entry }) => refused.has(entry))) for (const { entry } of verdicts) refused.add(entry);
375
+ }
376
+ const built = onDisk === current.build ? onDisk : ((await bundleWith(current.verdicts, onDisk)) ?? onDisk);
377
+ return { built, refused: [...refusedRoutes] };
378
+ }
379
+
380
+ get #artifactDir() {
381
+ return path.join(this.#command === "build" ? this.#app.dist.cwdPath : this.#app.cwdPath, ".akan/artifact");
382
+ }
383
+
384
+ #sizedBuildEntries(entries: BootstrapEntries): Map<string, string[]> {
385
+ const buildEntriesOf = RouteClientBuilder.#buildEntriesOf(entries);
386
+ return new Map(
387
+ [...(this.#sizedEntriesByRoute ?? this.#entriesByRoute ?? [])].map(([route, held]) => {
388
+ const asked = this.#askedByRoute?.get(route);
389
+ return [route, held.flatMap((entry) => buildEntriesOf(entry, asked?.get(path.resolve(entry))))];
390
+ }),
391
+ );
392
+ }
393
+
394
+ //? An entry built as several answers with the ones holding a name asked, and with all of them asked for none.
395
+ static #buildEntriesOf({ originalByBuildEntry, namesByBuildEntry, membersByBuildEntry }: BootstrapEntries) {
396
+ const built = new Map<string, { buildEntry: string; names?: readonly string[] }[]>();
397
+ for (const [buildEntry, original] of originalByBuildEntry)
398
+ built.getOrInsert(original, []).push({ buildEntry, names: namesByBuildEntry?.get(buildEntry) });
399
+ for (const [buildEntry, exports] of membersByBuildEntry ?? [])
400
+ for (const [original, held] of Map.groupBy(exports.values(), (member) => member.entry))
401
+ built.getOrInsert(original, []).push({ buildEntry, names: held.map((member) => member.name) });
402
+ return (entry: string, asked?: readonly string[] | null): string[] => {
403
+ const held = built.get(path.resolve(entry));
404
+ if (!held) return [path.resolve(entry)];
405
+ return held
406
+ .filter(({ names }) => !asked || !names || names.some((name) => asked.includes(name)))
407
+ .map(({ buildEntry }) => buildEntry);
408
+ };
409
+ }
410
+
411
+ #check({ entries, kept, bundle, runtime: routeRuntime }: NarrowedBuild): boolean {
412
+ const { workspaceRoot } = this.#app.workspace;
413
+ const buildEntriesOf = RouteClientBuilder.#buildEntriesOf(entries);
414
+ const grouped = [...(entries.membersByBuildEntry ?? [])].flatMap(([buildEntry, exports]) => {
415
+ const [first] = exports.values();
416
+ return first ? [[buildEntry, first.entry] as const] : [];
417
+ });
418
+ const check = new RouteRuntimeCheck(workspaceRoot, bundle.graph, {
419
+ entries: new Map([...[...entries.originalByBuildEntry].filter(([, entry]) => !kept.has(entry)), ...grouped]),
420
+ wholeReaders: routeRuntime.wholeReaders,
421
+ wholeConstantReaders: routeRuntime.wholeConstantReaders,
422
+ routes: new Map(
423
+ [...(this.#entriesByRoute ?? [])].map(([route, held]) => [
424
+ route,
425
+ held.flatMap((entry) => buildEntriesOf(entry)),
426
+ ]),
427
+ ),
428
+ });
429
+ const { refusal, repeated } = check;
430
+ if (refusal) {
431
+ this.#app.logger.warn(refusal);
432
+ return false;
433
+ }
434
+ if (repeated.length === 0) return true;
435
+ const more = repeated.length - RouteRuntimeCheck.shown;
436
+ this.#app.logger.warn(
437
+ [
438
+ `[client-runtime] a page keeping the whole runtime loads a piece of what that runtime already holds:`,
439
+ ...repeated.slice(0, RouteRuntimeCheck.shown).map((line) => ` - ${line}`),
440
+ ...(more > 0 ? [` - and ${more} more`] : []),
441
+ ].join("\n"),
442
+ );
443
+ return true;
444
+ }
445
+
446
+ async #buildBrowserBundle(
447
+ bootstrapEntries: BootstrapEntries,
448
+ routeRuntime: RouteRuntime | null,
449
+ outputSubdir?: string,
450
+ ) {
169
451
  const reactFastRefresh = process.env.AKAN_REACT_FAST_REFRESH !== "0";
452
+ const icons = ReactIconImports.forApp(this.#app);
453
+ const vendorFiles = await VendorFileImports.of(this.#app.workspace.workspaceRoot);
170
454
  return new ClientEntriesBundler({
171
455
  app: this.#app,
172
456
  entries: bootstrapEntries.buildEntries,
173
457
  plugins: [
458
+ icons.plugin,
459
+ ...(routeRuntime ? [this.#signalDescriptors(routeRuntime)] : []),
460
+ vendorFiles.plugin(),
174
461
  await createBarrelImportsPlugin(this.#app, {
175
- pipeAfter: reactFastRefresh ? RouteClientBuilder.normalizeNamedDefaultFunctionForFastRefresh : undefined,
176
- external: VENDOR_SPECIFIERS,
462
+ pipeAfter: icons.pipe(
463
+ reactFastRefresh ? RouteClientBuilder.normalizeNamedDefaultFunctionForFastRefresh : undefined,
464
+ ),
465
+ external: vendorFiles.specifiers,
466
+ routeRuntime,
467
+ ...(this.#command === "build" ? { parts: this.#parts } : {}),
177
468
  }),
178
469
  ],
179
- external: VENDOR_SPECIFIERS,
470
+ external: vendorFiles.specifiers,
180
471
  command: this.#command,
181
472
  reactFastRefresh,
473
+ ...(outputSubdir ? { outputSubdir } : {}),
182
474
  }).bundle();
183
475
  }
184
476
 
477
+ #signalDescriptors(routeRuntime: RouteRuntime) {
478
+ const scopes = routeRuntime.table.layers.map(({ scope }) => scope);
479
+ return new SignalDescriptors(this.#app.workspace.workspaceRoot, scopes, {
480
+ onUnread: (reason) =>
481
+ this.#app.logger.warn(
482
+ `[client-runtime] ${reason}, so each of their pieces reads its signal again: a slower build of the same pages. Run \`akan sync ${this.#app.name}\` if their generated files are from an earlier release.`,
483
+ ),
484
+ takenFromPieces: (absPath) => routeRuntime.takenFromPieces(absPath),
485
+ }).plugin;
486
+ }
487
+
185
488
  async #buildSsrBundle(bootstrapEntries: BootstrapEntries) {
186
489
  return new ClientEntriesBundler({
187
490
  app: this.#app,
@@ -193,40 +496,95 @@ export class RouteClientBuilder {
193
496
  }).bundle();
194
497
  }
195
498
 
196
- async #createBootstrapEntries(entries: string[]): Promise<BootstrapEntries> {
499
+ //? `narrowed.kept`: an entry keeping the whole runtime is the same file a build of every page on it bundles.
500
+ async #createBootstrapEntries(
501
+ entries: string[],
502
+ scope: ClientRuntimeScope,
503
+ narrowed?: { kept: ReadonlySet<string>; whole: BootstrapEntries },
504
+ ): Promise<BootstrapEntries> {
197
505
  if (!(await Bun.file(path.join(this.#app.cwdPath, "lib", "st.ts")).exists())) {
198
506
  return { buildEntries: entries, originalByBuildEntry: new Map() };
199
507
  }
508
+ const wholeByOriginal = new Map(
509
+ [...(narrowed?.whole.originalByBuildEntry ?? [])].map(([buildEntry, original]) => [original, buildEntry]),
510
+ );
200
511
 
201
- const outdir = path.join(this.#app.cwdPath, ".akan", "generated", "client-entry-bootstrap");
512
+ const dirName = scope === "page" ? "client-entry-bootstrap-route" : "client-entry-bootstrap";
513
+ const outdir = path.join(this.#app.cwdPath, ".akan", "generated", dirName);
202
514
  await mkdir(outdir, { recursive: true });
203
515
 
204
516
  const originalByBuildEntry = new Map<string, string>();
205
- const buildEntries = await Promise.all(
206
- entries.map(async (entry) => {
517
+ const namesByBuildEntry = new Map<string, readonly string[]>();
518
+ const membersByBuildEntry = new Map<string, ReadonlyMap<string, GroupedExport>>();
519
+ const { workspaceRoot } = this.#app.workspace;
520
+ const byExport = scope === "page" && this.#command === "build";
521
+ const read = await Promise.all(
522
+ entries.map(async (entry): Promise<{ whole?: string; parts: WrappedPart[] }> => {
207
523
  const absEntry = path.resolve(entry);
524
+ const whole = narrowed?.kept.has(absEntry) ? wholeByOriginal.get(absEntry) : undefined;
525
+ if (whole) {
526
+ originalByBuildEntry.set(whole, absEntry);
527
+ return { whole, parts: [] };
528
+ }
208
529
  const hash = Bun.hash(`${this.#app.name}\n${absEntry}`).toString(36);
209
530
  const base = path.basename(absEntry).replace(/[^A-Za-z0-9._-]/g, "_");
210
- const wrapperEntry = path.join(outdir, `${base}-${hash}.tsx`);
211
- const exportNames = await this.#scanExportNames(absEntry);
212
- await Bun.write(
213
- wrapperEntry,
214
- RouteClientBuilder.createStoreBootstrapEntrySource({
215
- appName: this.#app.name,
216
- originalEntry: absEntry,
217
- exportNames,
218
- }),
219
- );
220
- originalByBuildEntry.set(path.resolve(wrapperEntry), absEntry);
221
- return wrapperEntry;
531
+ const source = await Bun.file(absEntry).text();
532
+ const exportNames = scanUseClientExports(source, absEntry, workspaceRoot);
533
+ const groups =
534
+ byExport && PartModules.splits(workspaceRoot, absEntry)
535
+ ? RouteClientBuilder.#exportGroups(source, absEntry, exportNames)
536
+ : [exportNames];
537
+ const parts = groups.map((names, index) => ({
538
+ entry: absEntry,
539
+ names,
540
+ file: path.join(outdir, `${base}-${hash}${groups.length > 1 ? `-${index}` : ""}.tsx`),
541
+ split: groups.length > 1,
542
+ }));
543
+ return { parts };
222
544
  }),
223
545
  );
224
-
225
- return { buildEntries, originalByBuildEntry };
546
+ const parts = read.flatMap((entry) => entry.parts);
547
+ const routes = byExport ? (this.#sizedEntriesByRoute ?? this.#entriesByRoute) : undefined;
548
+ const planned = routes
549
+ ? ClientEntryGroups.plan(parts, ClientEntryGroups.loadedBy(routes, this.#askedByRoute))
550
+ : parts.map((part) => [part]);
551
+ const wrappers = await Promise.all(
552
+ planned.map(async (group) => {
553
+ const [only] = group;
554
+ if (group.length === 1 && only) {
555
+ await Bun.write(
556
+ only.file,
557
+ RouteClientBuilder.createStoreBootstrapEntrySource({
558
+ appName: this.#app.name,
559
+ originalEntry: only.entry,
560
+ exportNames: [...only.names],
561
+ scope,
562
+ }),
563
+ );
564
+ originalByBuildEntry.set(path.resolve(only.file), only.entry);
565
+ if (only.split) namesByBuildEntry.set(path.resolve(only.file), only.names);
566
+ return only.file;
567
+ }
568
+ const exports = ClientEntryGroups.exportsOf(group);
569
+ const held = [...exports.values()].map(({ entry, name }) => `${entry}#${name}`).join("\n");
570
+ const file = path.join(outdir, `group-${Bun.hash(`${this.#app.name}\n${held}`).toString(36)}.tsx`);
571
+ await Bun.write(file, ClientEntryGroups.source(this.#app.name, exports, scope));
572
+ membersByBuildEntry.set(path.resolve(file), exports);
573
+ return file;
574
+ }),
575
+ );
576
+ const kept = read.flatMap(({ whole }) => (whole ? [whole] : []));
577
+ return { buildEntries: [...kept, ...wrappers], originalByBuildEntry, namesByBuildEntry, membersByBuildEntry };
226
578
  }
227
579
 
228
- async #scanExportNames(absEntry: string): Promise<string[]> {
229
- return scanUseClientExports(await Bun.file(absEntry).text(), absEntry, this.#app.workspace.workspaceRoot);
580
+ //? Names one part of the file holds share a build entry. The parts are read from the file as written, and a bundle
581
+ //? may place a name elsewhere after its rewrites: then a build entry only loads more than the names it holds need.
582
+ static #exportGroups(source: string, absEntry: string, names: string[]): string[][] {
583
+ const parts = names.length > 0 ? ModuleParts.read(source, absEntry) : null;
584
+ if (!parts) return [names];
585
+ const groups = new Map<string, string[]>();
586
+ for (const name of names) groups.getOrInsert(parts.partOf(name) ?? "", []).push(name);
587
+ return [...groups.values()];
230
588
  }
231
589
 
232
590
  static normalizeNamedDefaultFunctionForFastRefresh(
@@ -317,11 +675,12 @@ export class RouteClientBuilder {
317
675
  appName: string;
318
676
  originalEntry: string;
319
677
  exportNames: string[];
678
+ scope?: ClientRuntimeScope;
320
679
  }): string {
321
680
  const originalEntry = JSON.stringify(path.resolve(args.originalEntry));
322
681
  const namedExports = args.exportNames.filter((name) => name !== "default");
323
682
  const lines = [
324
- ...StoreBootstrap.importLines(args.appName),
683
+ ...StoreBootstrap.importLines(args.appName, args.scope),
325
684
  ...(namedExports.length > 0 ? [`export { ${namedExports.join(", ")} } from ${originalEntry};`] : []),
326
685
  ];
327
686
  if (args.exportNames.includes("default")) lines.push(`export { default } from ${originalEntry};`);
@@ -333,15 +692,20 @@ export class RouteClientBuilder {
333
692
  originalByBuildEntry: Map<string, string>,
334
693
  clientReferenceIdByBuildEntry: Map<string, string> = new Map(),
335
694
  workspaceRoot = process.cwd(),
695
+ membersByBuildEntry?: ReadonlyMap<string, ReadonlyMap<string, GroupedExport>>,
336
696
  ): { buildEntry: string; originalEntry: string; name: string; key: string } | null {
337
697
  const hashIdx = manifestKey.lastIndexOf("#");
338
698
  if (hashIdx < 0) return null;
339
699
  const buildReferenceId = manifestKey.slice(0, hashIdx);
340
- const name = manifestKey.slice(hashIdx + 1);
700
+ const builtName = manifestKey.slice(hashIdx + 1);
341
701
  const buildEntry =
342
702
  [...clientReferenceIdByBuildEntry.entries()].find(([, referenceId]) => referenceId === buildReferenceId)?.[0] ??
343
703
  buildReferenceId;
344
- const originalEntry = originalByBuildEntry.get(buildEntry) ?? buildEntry;
704
+ const grouped = membersByBuildEntry?.get(buildEntry);
705
+ const member = grouped?.get(builtName);
706
+ if (grouped && !member) return null;
707
+ const name = member?.name ?? builtName;
708
+ const originalEntry = member?.entry ?? originalByBuildEntry.get(buildEntry) ?? buildEntry;
345
709
  const originalReferenceId = toClientReferencePath(originalEntry, workspaceRoot);
346
710
  return { buildEntry, originalEntry, name, key: `${originalReferenceId}#${name}` };
347
711
  }