@akanjs/devkit 3.3.0-rc.8 → 3.3.0-rc.80

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 (356) hide show
  1. package/DEV_RUNTIME_KNOBS.md +1 -1
  2. package/README.ko.md +7 -1
  3. package/README.md +7 -1
  4. package/akanApp/akanApp.host.test.ts +3 -1
  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 +307 -18
  13. package/akanConfig/akanConfig.ts +104 -210
  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 +233 -0
  20. package/akanConfig/index.ts +3 -0
  21. package/akanConfig/nativeFileSettings.ts +33 -0
  22. package/akanConfig/types.ts +4 -0
  23. package/app/appBin.test.ts +63 -0
  24. package/app/appBin.ts +50 -0
  25. package/app/applicationBuildReporter.test.ts +51 -1
  26. package/app/applicationBuildReporter.ts +6 -1
  27. package/app/applicationBuildRunner.test.ts +436 -5
  28. package/app/applicationBuildRunner.ts +237 -37
  29. package/app/clientServerBoundary.test.ts +115 -0
  30. package/app/clientServerBoundary.ts +89 -0
  31. package/app/dictionarySizes.test.ts +40 -0
  32. package/app/dictionarySizes.ts +95 -0
  33. package/app/routeFilesReport.test.ts +59 -0
  34. package/app/routeFilesReport.ts +46 -0
  35. package/app/routeJsBudget.ts +18 -4
  36. package/artifact/implicitRootLayout.test.ts +19 -0
  37. package/artifact/implicitRootLayout.ts +16 -2
  38. package/artifact/implicitRootLayoutRender.test.tsx +7 -2
  39. package/artifact/storeBootstrap.test.ts +28 -0
  40. package/artifact/storeBootstrap.ts +64 -8
  41. package/biome.base.json +7 -5
  42. package/codeAgent/index.ts +1 -34
  43. package/codeAgent/skills/akan-agent/SKILL.md +2 -2
  44. package/codeAgent/skills/akan-debug/SKILL.md +11 -5
  45. package/codeAgent/skills/akan-deps/SKILL.md +10 -3
  46. package/codeAgent/skills/akan-err/SKILL.md +13 -8
  47. package/codeAgent/skills/akan-mcp/SKILL.md +1 -1
  48. package/codeAgent/skills/akan-module/SKILL.md +2 -2
  49. package/codeAgent/skills/akan-page/SKILL.md +65 -30
  50. package/codeAgent/skills/akan-query/SKILL.md +13 -20
  51. package/codeAgent/skills/akan-runtime/SKILL.md +21 -1
  52. package/codeAgent/skills/akan-service/SKILL.md +21 -20
  53. package/codeAgent/skills/akan-transport/SKILL.md +5 -14
  54. package/codeAgent/skills/akan-ui/SKILL.md +16 -21
  55. package/codeAgent/skills/akan-validate/SKILL.md +8 -2
  56. package/commandDecorators/command.ts +28 -12
  57. package/commandDecorators/commandBuilder.ts +8 -1
  58. package/commandDecorators/commandDecorators.test.ts +70 -3
  59. package/commandDecorators/helpFormatter.ts +14 -12
  60. package/context/akanContext.ts +2 -0
  61. package/csrE2e/devHmrLatency.e2e.test.ts +1 -1
  62. package/csrE2e/ssrRegistry.e2e.test.ts +108 -22
  63. package/docs/apiReference.test.ts +25 -0
  64. package/docs/apiReference.ts +38 -5
  65. package/docs/declarationReader.ts +30 -0
  66. package/executors/appExecutor.ts +26 -12
  67. package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
  68. package/executors/clientRuntimeKeys.fixture.json +393 -0
  69. package/executors/clientRuntimeKeys.test.ts +1690 -0
  70. package/executors/executor.ts +14 -6
  71. package/executors/executors.test.ts +155 -1
  72. package/executors/pkgExecutor.ts +2 -1
  73. package/executors/sysExecutor.ts +112 -8
  74. package/executors/workspaceExecutor.ts +7 -4
  75. package/frontendBuild/allRoutesBuilder.ts +99 -7
  76. package/frontendBuild/autoImportSync.ts +3 -2
  77. package/frontendBuild/buildRouteClient.test.ts +684 -6
  78. package/frontendBuild/clientBuildTypes.ts +26 -0
  79. package/frontendBuild/clientEntriesBundler.test.ts +79 -0
  80. package/frontendBuild/clientEntriesBundler.ts +70 -1
  81. package/frontendBuild/clientEntryDiscovery.test.ts +308 -1
  82. package/frontendBuild/clientEntryDiscovery.ts +134 -12
  83. package/frontendBuild/clientEntryGroups.test.ts +77 -0
  84. package/frontendBuild/clientEntryGroups.ts +61 -0
  85. package/frontendBuild/csrDevArtifactWriter.ts +2 -2
  86. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  87. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  88. package/frontendBuild/csrDevPatcher.test.ts +4 -5
  89. package/frontendBuild/csrDevPatcher.ts +37 -11
  90. package/frontendBuild/csrDevTypes.ts +9 -0
  91. package/frontendBuild/cssCandidateCache.test.ts +12 -0
  92. package/frontendBuild/cssCandidateCache.ts +5 -3
  93. package/frontendBuild/cssCompiler.test.ts +14 -0
  94. package/frontendBuild/devBarrelImports.test.ts +124 -0
  95. package/frontendBuild/devBarrelImports.ts +81 -21
  96. package/frontendBuild/devChangePlanner.ts +0 -1
  97. package/frontendBuild/devRegistryBundler.ts +4 -2
  98. package/frontendBuild/devRouteRuntime.test.ts +492 -0
  99. package/frontendBuild/devRouteRuntime.ts +167 -0
  100. package/frontendBuild/dictionaryAssetBuilder.test.ts +408 -0
  101. package/frontendBuild/dictionaryAssetBuilder.ts +185 -17
  102. package/frontendBuild/dictionaryConstants.ts +136 -0
  103. package/frontendBuild/dictionaryOwnParts.ts +88 -0
  104. package/frontendBuild/dictionaryPackState.ts +131 -0
  105. package/frontendBuild/dictionaryPacking.test.ts +207 -0
  106. package/frontendBuild/dictionaryPacking.ts +160 -0
  107. package/frontendBuild/dictionaryRoutes.test.ts +251 -0
  108. package/frontendBuild/dictionaryRoutes.ts +227 -0
  109. package/frontendBuild/frontendBuild.test.ts +5 -3
  110. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  111. package/frontendBuild/pagesBundleBuilder.ts +78 -2
  112. package/frontendBuild/precompressArtifacts.test.ts +22 -0
  113. package/frontendBuild/precompressArtifacts.ts +34 -8
  114. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  115. package/frontendBuild/renderedEntries.ts +144 -0
  116. package/frontendBuild/routeClientBuilder.ts +407 -43
  117. package/frontendBuild/routeHandoffs.test.ts +155 -0
  118. package/frontendBuild/routeHandoffs.ts +117 -0
  119. package/frontendBuild/routeModulePreloads.test.ts +32 -0
  120. package/frontendBuild/routeModulePreloads.ts +20 -11
  121. package/frontendBuild/routeRuntimeCheck.test.ts +280 -0
  122. package/frontendBuild/routeRuntimeCheck.ts +248 -0
  123. package/frontendBuild/routeRuntimePays.test.ts +143 -0
  124. package/frontendBuild/routeRuntimePays.ts +117 -0
  125. package/frontendBuild/ssrBaseArtifactBuilder.ts +30 -35
  126. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  127. package/frontendBuild/ssrDevBundler.ts +66 -11
  128. package/frontendBuild/vendorFileImports.test.ts +254 -0
  129. package/frontendBuild/vendorFileImports.ts +163 -0
  130. package/frontendBuild/vendorNarrowing.test.ts +47 -3
  131. package/frontendBuild/vendorNarrowing.ts +38 -2
  132. package/frontendBuild/vendorSpecifiers.ts +2 -0
  133. package/frontendBuild/workerChunks.ts +61 -0
  134. package/guideline/agentAssets.ts +1 -1
  135. package/incrementalBuilder/buildBatch.proc.ts +27 -1
  136. package/incrementalBuilder/buildBatchProtocol.ts +1 -0
  137. package/incrementalBuilder/builderWatch.ts +11 -1
  138. package/incrementalBuilder/incrementalBuilder.proc.test.ts +159 -0
  139. package/incrementalBuilder/incrementalBuilder.proc.ts +31 -3
  140. package/incrementalBuilder/pendingMetadata.test.ts +27 -0
  141. package/incrementalBuilder/pendingMetadata.ts +19 -0
  142. package/integration/devResourceProbe.ts +14 -0
  143. package/integration/devStability.integration.test.ts +46 -21
  144. package/integration/renderAdmissionSoak.ts +6 -0
  145. package/integration/ssrMemoryProbe.ts +5 -0
  146. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  147. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  148. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  149. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  150. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  151. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  152. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  153. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  154. package/lint/biomeBase.test.ts +50 -3
  155. package/lint/biomeBase.ts +1 -1
  156. package/lint/biomeCheck.test.ts +162 -0
  157. package/lint/biomeCheck.ts +131 -0
  158. package/lint/linter.test.ts +16 -11
  159. package/lint/no-arbitrary-color.grit +5 -0
  160. package/lint/no-conditional-st-hook.grit +5 -1
  161. package/lint/no-daisyui-legacy-class.grit +8 -0
  162. package/lint/no-document-cookie.grit +3 -0
  163. package/lint/no-inline-color.grit +10 -2
  164. package/lint/no-oversized-list-limit.grit +2 -0
  165. package/lint/no-raw-palette-class.grit +7 -0
  166. package/lint/no-unpublished-form-setter.grit +2 -0
  167. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  168. package/lint/no-web-storage.grit +3 -0
  169. package/lint/withheldEnvFile.ts +17 -0
  170. package/mobile/desktopBin.ts +2 -2
  171. package/mobile/desktopServerStage.test.ts +18 -3
  172. package/mobile/desktopServerStage.ts +7 -2
  173. package/mobile/nativeApp.test.ts +13 -5
  174. package/mobile/nativeApp.ts +9 -4
  175. package/mobile/nativeConfig.test.ts +17 -1
  176. package/mobile/nativeConfig.ts +11 -6
  177. package/mobile/nativePublicEnv.ts +1 -1
  178. package/mobile/serverBundleSecrets.ts +43 -0
  179. package/package.json +11 -12
  180. package/packageExports.test.ts +3 -2
  181. package/preview/PreviewView.ts +43 -6
  182. package/preview/previewView.test.ts +31 -0
  183. package/quality/dictionaryKeys.test.ts +356 -0
  184. package/quality/dictionaryKeys.ts +488 -0
  185. package/quality/objectImportReport.test.ts +36 -0
  186. package/quality/objectImportReport.ts +105 -0
  187. package/quality/qualityScanner.ts +1 -1
  188. package/quality/routeRuntimeReport.test.ts +91 -0
  189. package/quality/routeRuntimeReport.ts +121 -0
  190. package/quality/runtimeConstantFacts.ts +71 -0
  191. package/quality/runtimeConstantGraph.ts +123 -0
  192. package/quality/runtimeConstantReads.ts +116 -0
  193. package/quality/runtimeImports.test.ts +190 -0
  194. package/quality/runtimeImports.ts +233 -0
  195. package/quality/runtimeKeyNames.ts +46 -0
  196. package/quality/runtimeLexicalScope.ts +132 -0
  197. package/quality/runtimeMarkerReach.test.ts +84 -0
  198. package/quality/runtimeMarkerReach.ts +255 -0
  199. package/quality/runtimeModuleFacts.ts +290 -0
  200. package/quality/runtimeNameTable.test.ts +172 -0
  201. package/quality/runtimeNameTable.ts +477 -0
  202. package/quality/runtimeScopeReport.test.ts +123 -0
  203. package/quality/runtimeScopeReport.ts +167 -0
  204. package/quality/runtimeSliceKey.ts +269 -0
  205. package/quality/runtimeSyntax.ts +133 -0
  206. package/quality/runtimeTable.fixture.ts +189 -0
  207. package/quality/runtimeUse.test.ts +737 -0
  208. package/quality/runtimeUse.ts +696 -0
  209. package/quality/runtimeUseReadable.test.ts +393 -0
  210. package/quality/ssrScanner.test.ts +13 -0
  211. package/quality/ssrScanner.ts +1 -1
  212. package/quality/translatorBindings.ts +187 -0
  213. package/test/fakeTerminal.ts +45 -0
  214. package/test/secretEnvFixture.ts +134 -0
  215. package/test/testHelpers.ts +11 -0
  216. package/transforms/barrelAnalyzer.ts +24 -2
  217. package/transforms/barrelImportsPlugin.ts +121 -32
  218. package/transforms/exportReach.test.ts +162 -0
  219. package/transforms/exportReach.ts +308 -0
  220. package/transforms/frameworkObjects.fixture.tsx +58 -0
  221. package/transforms/frameworkObjects.test.ts +54 -0
  222. package/transforms/modelReference.test.ts +196 -0
  223. package/transforms/modelReference.ts +39 -0
  224. package/transforms/moduleParts.test.ts +225 -0
  225. package/transforms/moduleParts.ts +418 -0
  226. package/transforms/objectImportEdits.ts +150 -0
  227. package/transforms/objectMemberImports.test.ts +633 -0
  228. package/transforms/objectMemberImports.ts +571 -0
  229. package/transforms/objectMemberLookup.ts +150 -0
  230. package/transforms/objectModule.test.ts +307 -0
  231. package/transforms/objectModule.ts +482 -0
  232. package/transforms/objectModuleAnalyzer.ts +104 -0
  233. package/transforms/partImports.test.ts +76 -0
  234. package/transforms/partImports.ts +110 -0
  235. package/transforms/partModules.test.ts +187 -0
  236. package/transforms/partModules.ts +90 -0
  237. package/transforms/partPurity.ts +124 -0
  238. package/transforms/reactIconImports.test.ts +231 -0
  239. package/transforms/reactIconImports.ts +325 -0
  240. package/transforms/routeConstants.ts +122 -0
  241. package/transforms/routeRuntime.test.ts +835 -0
  242. package/transforms/routeRuntime.ts +703 -0
  243. package/transforms/routeRuntimeEdits.ts +92 -0
  244. package/transforms/routeRuntimeGraph.ts +66 -0
  245. package/transforms/routeRuntimePlan.ts +244 -0
  246. package/transforms/secretEnvDeclaration.test.ts +211 -0
  247. package/transforms/secretEnvDeclaration.ts +219 -0
  248. package/transforms/secretEnvFile.test.ts +117 -0
  249. package/transforms/secretEnvFile.ts +113 -0
  250. package/transforms/secretEnvName.test.ts +54 -0
  251. package/transforms/secretEnvName.ts +29 -0
  252. package/transforms/secretEnvSource.test.ts +152 -0
  253. package/transforms/secretEnvSource.ts +197 -0
  254. package/transforms/serverEnvEvaluationError.ts +11 -0
  255. package/transforms/serverEnvPlugin.test.ts +155 -1
  256. package/transforms/serverEnvPlugin.ts +123 -19
  257. package/transforms/serverEnvProfile.test.ts +129 -2
  258. package/transforms/serverEnvProfile.ts +133 -43
  259. package/transforms/serverEnvSecrets.test.ts +268 -0
  260. package/transforms/signalDescriptors.test.ts +280 -0
  261. package/transforms/signalDescriptors.ts +227 -0
  262. package/transforms/thisFreeExports.ts +87 -0
  263. package/transforms/transforms.test.ts +177 -0
  264. package/transforms/tsconfigPackageResolver.test.ts +1 -0
  265. package/tunnel/createTunnel.ts +5 -1
  266. package/tunnel/ssh2Module.test.ts +37 -0
  267. package/tunnel/ssh2Module.ts +28 -0
  268. package/tunnel/sshTunnel.ts +4 -2
  269. package/typecheck/projectTypecheck.test.ts +32 -1
  270. package/typecheck/projectTypecheck.ts +3 -3
  271. package/typecheck/typeChecker.test.ts +49 -0
  272. package/typecheck/typeChecker.ts +9 -7
  273. package/typecheck/withheldDiagnostics.ts +41 -0
  274. package/util/devInstallCommand.ts +7 -0
  275. package/util/jsonFormatter.test.ts +13 -9
  276. package/workflow/executor.ts +6 -2
  277. package/workflow/index.ts +1 -0
  278. package/workflow/plan.ts +36 -7
  279. package/workflow/types.ts +1 -1
  280. package/workflow/uiTarget.ts +50 -0
  281. package/workspace/envSeed.test.ts +30 -1
  282. package/workspace/envSeed.ts +30 -1
  283. package/workspace/mainCheckout.test.ts +55 -0
  284. package/workspace/mainCheckout.ts +38 -0
  285. package/workspace/scanInfo.test.ts +39 -0
  286. package/workspace/scanInfo.ts +55 -6
  287. package/workspace/slicePlanner.ts +2 -1
  288. package/workspace/workspaceLayout.test.ts +22 -1
  289. package/workspace/workspaceLayout.ts +3 -3
  290. package/CHANGELOG.md +0 -2903
  291. package/codeAgent/agent/AkanCodeCompaction.ts +0 -49
  292. package/codeAgent/agent/AkanCodeServices.ts +0 -122
  293. package/codeAgent/agent/AkanContextFiles.ts +0 -94
  294. package/codeAgent/agent/CodeAgent.ts +0 -626
  295. package/codeAgent/agent/CodeAgentAllowed.ts +0 -35
  296. package/codeAgent/agent/CodeAgentAsks.ts +0 -66
  297. package/codeAgent/agent/CodeAgentCommandLine.ts +0 -372
  298. package/codeAgent/agent/CodeAgentEventMapper.ts +0 -225
  299. package/codeAgent/agent/CodeAgentGate.ts +0 -258
  300. package/codeAgent/agent/CodeAgentProxy.ts +0 -83
  301. package/codeAgent/agent/CodeAgentRpcHost.ts +0 -109
  302. package/codeAgent/agent/CodeAgentRpcListener.ts +0 -195
  303. package/codeAgent/agent/CodeAgentStreamPrinter.ts +0 -86
  304. package/codeAgent/agent/CodeAgentSuspended.ts +0 -85
  305. package/codeAgent/agent/CodeAgentUi.ts +0 -47
  306. package/codeAgent/agent/CodeMailbox.ts +0 -148
  307. package/codeAgent/agent/CodeSessionFork.ts +0 -56
  308. package/codeAgent/agent/CodeSessionIndex.ts +0 -78
  309. package/codeAgent/agent/SubagentPool.ts +0 -219
  310. package/codeAgent/agent/WorkspaceTrust.ts +0 -200
  311. package/codeAgent/agent/akanCodeCompaction.test.ts +0 -36
  312. package/codeAgent/agent/akanCodeModel.ts +0 -47
  313. package/codeAgent/agent/akanCodeServices.test.ts +0 -54
  314. package/codeAgent/agent/akanContextFiles.test.ts +0 -116
  315. package/codeAgent/agent/akanSystemPrompt.ts +0 -50
  316. package/codeAgent/agent/codeAgent.test.ts +0 -337
  317. package/codeAgent/agent/codeAgentCommandLine.test.ts +0 -212
  318. package/codeAgent/agent/codeAgentContract.test.ts +0 -755
  319. package/codeAgent/agent/codeAgentHosts.ts +0 -30
  320. package/codeAgent/agent/codeAgentProxy.test.ts +0 -126
  321. package/codeAgent/agent/codeAgentRpcListener.test.ts +0 -215
  322. package/codeAgent/agent/codeAgentSuspended.test.ts +0 -47
  323. package/codeAgent/agent/codeMailbox.test.ts +0 -76
  324. package/codeAgent/agent/codeSessionFork.test.ts +0 -58
  325. package/codeAgent/agent/codeSessionIndex.test.ts +0 -77
  326. package/codeAgent/agent/consoleToStderr.ts +0 -8
  327. package/codeAgent/agent/jsonLines.ts +0 -29
  328. package/codeAgent/agent/stringArg.ts +0 -5
  329. package/codeAgent/feedback/DevLogFeedback.ts +0 -82
  330. package/codeAgent/feedback/PreviewFeedback.ts +0 -46
  331. package/codeAgent/feedback/TurnFeedback.ts +0 -98
  332. package/codeAgent/feedback/VerifyFeedback.ts +0 -39
  333. package/codeAgent/tools/AkanCli.ts +0 -51
  334. package/codeAgent/tools/AkanCodePlugins.ts +0 -142
  335. package/codeAgent/tools/AkanEditScope.ts +0 -53
  336. package/codeAgent/tools/AkanEnvKeys.ts +0 -50
  337. package/codeAgent/tools/AkanToolPack.ts +0 -86
  338. package/codeAgent/tools/AkanVerifier.ts +0 -30
  339. package/codeAgent/tools/AskToolPack.ts +0 -99
  340. package/codeAgent/tools/DeepSeekWeb.ts +0 -127
  341. package/codeAgent/tools/MailToolPack.ts +0 -76
  342. package/codeAgent/tools/McpClient.ts +0 -209
  343. package/codeAgent/tools/McpOAuth.ts +0 -233
  344. package/codeAgent/tools/McpOAuthLoopback.ts +0 -64
  345. package/codeAgent/tools/McpServerConfig.ts +0 -131
  346. package/codeAgent/tools/McpSignIn.ts +0 -158
  347. package/codeAgent/tools/McpTokenStore.ts +0 -128
  348. package/codeAgent/tools/McpToolPack.ts +0 -206
  349. package/codeAgent/tools/SessionToolPack.ts +0 -91
  350. package/codeAgent/tools/WebToolPack.ts +0 -315
  351. package/codeAgent/tools/akanCodePlugins.test.ts +0 -954
  352. package/codeAgent/tools/askToolPack.test.ts +0 -116
  353. package/codeAgent/tools/deepSeekWeb.test.ts +0 -113
  354. package/codeAgent/tools/mcpOAuth.test.ts +0 -648
  355. package/codeAgent/tools/mcpServerConfig.test.ts +0 -341
  356. package/piDependencyPins.test.ts +0 -45
@@ -0,0 +1,248 @@
1
+ import path from "node:path";
2
+ import type { ClientBundleGraph } from "./clientBuildTypes";
3
+
4
+ export interface RouteRuntimeNarrowed {
5
+ //? Build entry to the source entry it wraps, for each entry built to load only the modules its code names.
6
+ entries: ReadonlyMap<string, string>;
7
+ wholeReaders: ReadonlySet<string>;
8
+ //? The files `akan quality runtime` names for keeping every constant; only through one may a page reach `lib/cnst.ts`.
9
+ wholeConstantReaders?: ReadonlySet<string>;
10
+ routes?: ReadonlyMap<string, readonly string[]>;
11
+ }
12
+
13
+ const repeatable = [
14
+ {
15
+ whole: /^((?:apps|libs)\/[^/]+)\/lib\/useClient\.ts$/,
16
+ piece: /^((?:apps|libs)\/[^/]+)\/lib\/__client\/[^/]+\.fetch\.ts$/,
17
+ },
18
+ {
19
+ whole: /^((?:apps|libs)\/[^/]+)\/lib\/cnst\.ts$/,
20
+ piece: /^((?:apps|libs)\/[^/]+)\/lib\/__client\/[^/]+\.cnst\.ts$/,
21
+ },
22
+ ];
23
+
24
+ const pieceFile = /^(?:apps|libs)\/[^/]+\/lib\/__client\/[^/]+\.ts$/;
25
+ const constantPiece = /^(?:apps|libs)\/[^/]+\/lib\/__client\/[^/]+\.cnst\.ts$/;
26
+ const wholeFile = /^(?:apps|libs)\/[^/]+\/lib\/(?:useClient|st)\.ts$/;
27
+ const constantsFile = /^(?:apps|libs)\/[^/]+\/lib\/cnst\.ts$/;
28
+ const storeFile = /^(?:apps|libs)\/[^/]+\/lib\/_?[^/]+\/[^/]+\.store\.ts$/;
29
+ const consequence =
30
+ "Every page of this build loads the whole client runtime instead, not only what it uses. This is a bug in akan: report it with the lines above.";
31
+
32
+ //* What a build loading per module proves about its own output before it is served: each runtime piece loads before
33
+ //* the module importing it, no store file or registration piece is imported back by what it loads, and no page built
34
+ //* to load pieces reaches a file that needs the whole runtime, or every constant for no named reason.
35
+ export class RouteRuntimeCheck {
36
+ static readonly shown = 5;
37
+ readonly #workspaceRoot: string;
38
+ readonly #graph: ClientBundleGraph;
39
+ readonly #narrowed: RouteRuntimeNarrowed | null;
40
+ readonly #reached = new Map<string, Set<string>>();
41
+
42
+ constructor(workspaceRoot: string, graph: ClientBundleGraph, narrowed: RouteRuntimeNarrowed | null = null) {
43
+ this.#workspaceRoot = workspaceRoot;
44
+ this.#graph = graph;
45
+ this.#narrowed = narrowed;
46
+ }
47
+
48
+ get failures(): string[] {
49
+ return [...this.#unordered(), ...this.#cycles(), ...this.#unanswered()];
50
+ }
51
+
52
+ get refusal(): string | null {
53
+ const failures = this.failures;
54
+ if (failures.length === 0) return null;
55
+ const more = failures.length - RouteRuntimeCheck.shown;
56
+ return [
57
+ "[client-runtime] loading per module, this build would not load its modules in order:",
58
+ ...failures.slice(0, RouteRuntimeCheck.shown).map((failure) => ` - ${failure}`),
59
+ ...(more > 0 ? [` - and ${more} more`] : []),
60
+ consequence,
61
+ ].join("\n");
62
+ }
63
+
64
+ //* Each scope file a route loads with a piece of the same scope beside it that repeats part of it. A piece repeats
65
+ //* nothing where the file takes that part from the piece, or the piece answers from the file: one imports the other.
66
+ get repeated(): string[] {
67
+ const routesOf = new Map<string, string[]>();
68
+ for (const [route, entries] of this.#narrowed?.routes ?? []) {
69
+ const loaded = new Set(entries);
70
+ for (const module of loaded)
71
+ for (const { path: imported } of this.#graph.importsByModule.get(module) ?? []) loaded.add(imported);
72
+ const names = new Map([...loaded].map((module) => [module, this.#nameOf(module)]));
73
+ for (const { whole, piece } of repeatable)
74
+ for (const [file, fileName] of names) {
75
+ const scope = fileName.match(whole)?.[1];
76
+ if (!scope) continue;
77
+ for (const [other, otherName] of names) {
78
+ if (otherName.match(piece)?.[1] !== scope) continue;
79
+ if (this.#staticImportsOf(file).includes(other) || this.#staticImportsOf(other).includes(file)) continue;
80
+ const pair = `${fileName} and ${otherName}`;
81
+ routesOf.set(pair, [...(routesOf.get(pair) ?? []), route]);
82
+ }
83
+ }
84
+ }
85
+ return [...routesOf].map(
86
+ ([pair, routes]) =>
87
+ `${pair} both load on ${routes.length} route(s), the first ${routes[0]}: the piece holds again what the file holds`,
88
+ );
89
+ }
90
+
91
+ #nameOf(absPath: string) {
92
+ return path.relative(this.#workspaceRoot, absPath).split(path.sep).join("/");
93
+ }
94
+
95
+ #isPiece(absPath: string) {
96
+ return pieceFile.test(this.#nameOf(absPath));
97
+ }
98
+
99
+ #staticImportsOf(module: string): string[] {
100
+ return (this.#graph.importsByModule.get(module) ?? []).filter(({ lazy }) => !lazy).map((imported) => imported.path);
101
+ }
102
+
103
+ #reachedBy(chunk: string): Set<string> {
104
+ const known = this.#reached.get(chunk);
105
+ if (known) return known;
106
+ const reached = new Set([chunk]);
107
+ for (const next of reached)
108
+ for (const imported of this.#graph.importsByChunk.get(next) ?? []) reached.add(imported);
109
+ this.#reached.set(chunk, reached);
110
+ return reached;
111
+ }
112
+
113
+ //? A registration piece answering from `lib/cnst.ts` is a bare re-export, which the bundler may leave in a chunk
114
+ //? nothing imports: what has to load first is the file it re-exports.
115
+ #loadedFirstFor(piece: string): string[] {
116
+ const answered = constantPiece.test(this.#nameOf(piece)) && this.#narrowed?.wholeConstantReaders?.has(piece);
117
+ return answered ? this.#staticImportsOf(piece) : [piece];
118
+ }
119
+
120
+ #unordered(): string[] {
121
+ const failures: string[] = [];
122
+ const linked =
123
+ this.#graph.linked ??
124
+ [...this.#graph.chunksByModule].map(([module, chunks]) => ({
125
+ module,
126
+ chunks,
127
+ imports: this.#graph.importsByModule.get(module) ?? [],
128
+ }));
129
+ for (const { module, chunks, imports } of linked)
130
+ for (const { path: piece, lazy } of imports) {
131
+ if (lazy || !this.#isPiece(piece)) continue;
132
+ const holdersOf = this.#loadedFirstFor(piece).map((first) => this.#graph.chunksByModule.get(first) ?? []);
133
+ const unlinked = chunks.find((chunk) =>
134
+ holdersOf.some((holders) => !holders.some((holder) => this.#reachedBy(chunk).has(holder))),
135
+ );
136
+ if (!unlinked) continue;
137
+ failures.push(
138
+ `${this.#nameOf(module)} needs ${this.#nameOf(piece)} loaded first, but its chunk ${path.basename(unlinked)} does not import the chunk holding that piece`,
139
+ );
140
+ }
141
+ return failures;
142
+ }
143
+
144
+ #cycles(): string[] {
145
+ const failures: string[] = [];
146
+ for (const component of this.#components()) {
147
+ const members = new Set(component);
148
+ const store = component.find((module) => storeFile.test(this.#nameOf(module)));
149
+ const registration = component.find(
150
+ (module) => constantPiece.test(this.#nameOf(module)) && !this.#narrowed?.wholeConstantReaders?.has(module),
151
+ );
152
+ if (!store && registration) {
153
+ const importer = component.find((module) => this.#staticImportsOf(module).includes(registration)) ?? "";
154
+ failures.push(
155
+ `${this.#nameOf(registration)} loads files that import it back through ${this.#nameOf(importer)}, which reads the model before it is registered`,
156
+ );
157
+ }
158
+ if (!store || !component.some((module) => this.#isPiece(module))) continue;
159
+ const pieceOf = (module: string) =>
160
+ this.#staticImportsOf(module).find((imported) => members.has(imported) && this.#isPiece(imported));
161
+ const importer = component.find((module) => !this.#isPiece(module) && pieceOf(module));
162
+ const piece = importer ? pieceOf(importer) : undefined;
163
+ failures.push(
164
+ importer && piece
165
+ ? `${this.#nameOf(store)} imports ${this.#nameOf(importer)}, which loads ${this.#nameOf(piece)}, and that piece imports the store file back before it is defined: move what ${this.#nameOf(importer)} reads from the store out of the files a store file imports`
166
+ : `${this.#nameOf(store)} is imported back by a runtime piece it loads`,
167
+ );
168
+ }
169
+ return failures;
170
+ }
171
+
172
+ #unanswered(): string[] {
173
+ if (!this.#narrowed) return [];
174
+ const failures: string[] = [];
175
+ const { entries, wholeReaders, wholeConstantReaders = new Set<string>() } = this.#narrowed;
176
+ for (const [buildEntry, entry] of entries) {
177
+ const importerOf = this.#importersFrom([buildEntry]);
178
+ const narrowed = `${this.#nameOf(entry)} was built to load only the modules its code names`;
179
+ const reader = [...importerOf.keys()].find((module) => wholeReaders.has(module));
180
+ const whole = [...importerOf.keys()].find((module) => wholeFile.test(this.#nameOf(module)));
181
+ const constantsOf = this.#importersFrom([buildEntry], wholeConstantReaders);
182
+ //? An entry no route holds takes its models from pieces answering from `lib/cnst.ts`, and their constant files
183
+ //? stay as written: what a named file already loads costs the page nothing by another path.
184
+ const named = this.#importersFrom([...constantsOf.keys()].filter((module) => wholeConstantReaders.has(module)));
185
+ const constants = [...constantsOf.keys()].find(
186
+ (module) => constantsFile.test(this.#nameOf(module)) && !named.has(module),
187
+ );
188
+ if (reader) failures.push(`${narrowed}, but it reaches ${this.#nameOf(reader)}, which needs every module`);
189
+ else if (whole)
190
+ failures.push(
191
+ `${narrowed}, but ${this.#nameOf(importerOf.get(whole) ?? whole)} imports ${this.#nameOf(whole)}, the runtime of every module`,
192
+ );
193
+ else if (constants)
194
+ failures.push(
195
+ `${narrowed}, but ${this.#nameOf(constantsOf.get(constants) ?? constants)} imports ${this.#nameOf(constants)}, the constants of every model, for no reason \`akan quality runtime\` names`,
196
+ );
197
+ }
198
+ return failures;
199
+ }
200
+
201
+ #importersFrom(roots: string[], stops: ReadonlySet<string> = new Set()): Map<string, string> {
202
+ const importerOf = new Map(roots.map((root) => [root, root]));
203
+ for (const module of importerOf.keys()) {
204
+ if (stops.has(module)) continue;
205
+ for (const imported of this.#staticImportsOf(module))
206
+ if (!importerOf.has(imported)) importerOf.set(imported, module);
207
+ }
208
+ return importerOf;
209
+ }
210
+
211
+ //? Tarjan's algorithm with its own stack: a real import chain is deeper than the call stack allows.
212
+ #components(): string[][] {
213
+ const index = new Map<string, number>();
214
+ const low = new Map<string, number>();
215
+ const open: string[] = [];
216
+ const onStack = new Set<string>();
217
+ const components: string[][] = [];
218
+ for (const root of this.#graph.importsByModule.keys()) {
219
+ if (index.has(root)) continue;
220
+ const frames: { module: string; imports: string[]; next: number }[] = [];
221
+ const enter = (module: string) => {
222
+ index.set(module, index.size);
223
+ low.set(module, index.size - 1);
224
+ open.push(module);
225
+ onStack.add(module);
226
+ frames.push({ module, imports: this.#staticImportsOf(module), next: 0 });
227
+ };
228
+ enter(root);
229
+ while (frames.length > 0) {
230
+ const frame = frames[frames.length - 1];
231
+ if (!frame) break;
232
+ const imported = frame.imports[frame.next++];
233
+ const lowOf = (module: string) => low.get(module) ?? 0;
234
+ if (imported === undefined) {
235
+ frames.pop();
236
+ const parent = frames[frames.length - 1];
237
+ if (parent) low.set(parent.module, Math.min(lowOf(parent.module), lowOf(frame.module)));
238
+ if (lowOf(frame.module) !== index.get(frame.module)) continue;
239
+ const component = open.splice(open.lastIndexOf(frame.module));
240
+ for (const module of component) onStack.delete(module);
241
+ if (component.length > 1) components.push(component);
242
+ } else if (!index.has(imported)) enter(imported);
243
+ else if (onStack.has(imported)) low.set(frame.module, Math.min(lowOf(frame.module), index.get(imported) ?? 0));
244
+ }
245
+ }
246
+ return components;
247
+ }
248
+ }
@@ -0,0 +1,143 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import path from "node:path";
3
+ import { tempDirs, writeText } from "../test/testHelpers";
4
+ import { chunkBrotliBytesOf } from "./precompressArtifacts";
5
+ import { RouteRuntimePays } from "./routeRuntimePays";
6
+
7
+ const makeTempRoot = tempDirs("akan-devkit-route-pays-");
8
+
9
+ interface Measured {
10
+ routes: Record<string, string[]>;
11
+ whole: Record<string, number>;
12
+ measured: Record<string, number>;
13
+ kept?: string[];
14
+ refused?: string[];
15
+ }
16
+
17
+ const decide = ({ routes, whole, measured, kept = [], refused = [] }: Measured) =>
18
+ RouteRuntimePays.decide({
19
+ entriesByRoute: new Map(Object.entries(routes)),
20
+ isKept: (entry) => kept.includes(entry),
21
+ isRefused: (entry) => refused.includes(entry),
22
+ whole: new Map(Object.entries(whole)),
23
+ measured: new Map(Object.entries(measured)),
24
+ });
25
+
26
+ describe("which entries keep the whole runtime because per module made a page no smaller", () => {
27
+ test("a route smaller per module keeps loading per module", () => {
28
+ expect(decide({ routes: { "/memo": ["Memo"] }, whole: { "/memo": 900 }, measured: { "/memo": 400 } })).toEqual([]);
29
+ });
30
+
31
+ test("a route no smaller per module keeps the whole runtime in the entries only such routes hold", () => {
32
+ const verdicts = decide({
33
+ routes: { "/board": ["Board", "Frame"], "/memo": ["Memo"] },
34
+ whole: { "/board": 900, "/memo": 900 },
35
+ measured: { "/board": 900, "/memo": 400 },
36
+ });
37
+ expect(verdicts).toEqual([
38
+ { entry: "Board", route: "/board", whole: 900, perModule: 900 },
39
+ { entry: "Frame", route: "/board", whole: 900, perModule: 900 },
40
+ ]);
41
+ });
42
+
43
+ test("an entry shared with a route that got smaller stays narrowed while that route gained more than the others lose", () => {
44
+ const routes = { "/board": ["Frame"], "/memo": ["Frame", "Memo"] };
45
+ const whole = { "/board": 900, "/memo": 900 };
46
+ expect(decide({ routes, whole, measured: { "/board": 950, "/memo": 400 } })).toEqual([]);
47
+ expect(decide({ routes, whole, measured: { "/board": 1_500, "/memo": 850 } })).toEqual([
48
+ { entry: "Frame", route: "/board", whole: 900, perModule: 1_500 },
49
+ ]);
50
+ });
51
+
52
+ test("a route an entry already keeps whole is not judged, so judging the same sizes again after keeping changes nothing", () => {
53
+ const measured = {
54
+ routes: { "/board": ["Board", "Frame"], "/memo": ["Frame", "Memo"] },
55
+ whole: { "/board": 900, "/memo": 900 },
56
+ measured: { "/board": 950, "/memo": 400 },
57
+ };
58
+ const first = decide(measured);
59
+ expect(first.map(({ entry }) => entry)).toEqual(["Board"]);
60
+ expect(decide({ ...measured, kept: first.map(({ entry }) => entry) })).toEqual([]);
61
+ });
62
+
63
+ test("an entry a build tried keeping, where a page came out larger, is not named again", () => {
64
+ const measured = {
65
+ routes: { "/board": ["Board", "Frame"], "/memo": ["Memo"] },
66
+ whole: { "/board": 900, "/memo": 900 },
67
+ measured: { "/board": 950, "/memo": 950 },
68
+ };
69
+ expect(decide(measured).map(({ entry }) => entry)).toEqual(["Board", "Frame", "Memo"]);
70
+ expect(decide({ ...measured, refused: ["Board", "Frame"] }).map(({ entry }) => entry)).toEqual(["Memo"]);
71
+ });
72
+
73
+ describe("the build that kept the named entries, against the one before it", () => {
74
+ const routes = { "/board": ["Board"], "/memo": ["Memo"], "/plain": ["Plain"] };
75
+ const larger = (after: Record<string, number>, was: string[] = []) =>
76
+ RouteRuntimePays.larger({
77
+ entriesByRoute: new Map(Object.entries(routes)),
78
+ wasKept: (entry) => was.includes(entry),
79
+ isKept: (entry) => ["Board", "Memo"].includes(entry),
80
+ before: new Map(Object.entries({ "/board": 950, "/memo": 950, "/plain": 400 })),
81
+ after: new Map(Object.entries(after)),
82
+ });
83
+
84
+ test("stands where every route it moved to the whole runtime came out smaller", () => {
85
+ expect(larger({ "/board": 900, "/memo": 949, "/plain": 400 })).toEqual([]);
86
+ });
87
+
88
+ test("names the routes it moved that came out no smaller", () => {
89
+ expect(larger({ "/board": 900, "/memo": 950, "/plain": 400 })).toEqual(["/memo"]);
90
+ expect(larger({ "/board": 1_200, "/memo": 990, "/plain": 300 })).toEqual(["/board", "/memo"]);
91
+ });
92
+
93
+ test("names every route it moved where they shrank and the routes together did not", () => {
94
+ expect(larger({ "/board": 940, "/memo": 940, "/plain": 420 })).toEqual(["/board", "/memo"]);
95
+ });
96
+
97
+ test("judges no route that kept the whole runtime before it", () => {
98
+ expect(larger({ "/board": 900, "/memo": 960, "/plain": 400 }, ["Memo"])).toEqual([]);
99
+ });
100
+ });
101
+
102
+ test("a route is sized by the chunks its entries import statically, a chunk two entries share counted once", async () => {
103
+ const root = await makeTempRoot();
104
+ const chunk = async (name: string, bytes: number) => {
105
+ const file = path.join(root, name);
106
+ await writeText(file, "x".repeat(bytes));
107
+ return file;
108
+ };
109
+ const [board, memo, shared, lazy] = await Promise.all([
110
+ chunk("board.js", 100),
111
+ chunk("memo.js", 200),
112
+ chunk("shared.js", 400),
113
+ chunk("lazy.js", 800),
114
+ ]);
115
+ const sizes = await new RouteRuntimePays().sizesOf(
116
+ {
117
+ entryOutputAbsByAbsPath: new Map([
118
+ ["Board", board],
119
+ ["Memo", memo],
120
+ ]),
121
+ graph: {
122
+ importsByModule: new Map(),
123
+ chunksByModule: new Map(),
124
+ importsByChunk: new Map([
125
+ [board, [shared]],
126
+ [memo, [shared]],
127
+ [lazy, []],
128
+ ]),
129
+ },
130
+ },
131
+ new Map([
132
+ ["/both", ["Board", "Memo"]],
133
+ ["/memo", ["Memo"]],
134
+ ]),
135
+ );
136
+ const served = (bytes: number) => chunkBrotliBytesOf(new TextEncoder().encode("x".repeat(bytes)));
137
+ expect(served(100)).toBeLessThan(100);
138
+ expect(Object.fromEntries(sizes)).toEqual({
139
+ "/both": served(100) + served(200) + served(400),
140
+ "/memo": served(200) + served(400),
141
+ });
142
+ });
143
+ });
@@ -0,0 +1,117 @@
1
+ import type { BundleClientEntriesResult } from "./clientBuildTypes";
2
+ import { chunkBrotliBytesOf } from "./precompressArtifacts";
3
+
4
+ export interface RoutePaysInput {
5
+ //? Every entry a route may load: one of them kept makes the route load the whole runtime.
6
+ entriesByRoute: ReadonlyMap<string, readonly string[]>;
7
+ isKept: (entry: string) => boolean;
8
+ //? An entry a build already tried keeping whole, where a page it holds came out larger: it is never tried again.
9
+ isRefused?: (entry: string) => boolean;
10
+ //? Brotli bytes of the chunks a route loads first, in a build where every entry keeps the whole runtime.
11
+ whole: ReadonlyMap<string, number>;
12
+ //? The same in the build being judged.
13
+ measured: ReadonlyMap<string, number>;
14
+ }
15
+
16
+ export interface RoutePaysVerdict {
17
+ entry: string;
18
+ route: string;
19
+ whole: number;
20
+ perModule: number;
21
+ }
22
+
23
+ export interface RoutePaidInput {
24
+ entriesByRoute: ReadonlyMap<string, readonly string[]>;
25
+ wasKept: (entry: string) => boolean;
26
+ isKept: (entry: string) => boolean;
27
+ before: ReadonlyMap<string, number>;
28
+ after: ReadonlyMap<string, number>;
29
+ }
30
+
31
+ export class RouteRuntimePays {
32
+ readonly #sizes = new Map<string, number>();
33
+
34
+ //* An entry only pages that got no smaller hold is kept. One shared with a page that did get smaller is kept only
35
+ //* where the pages it would spare lose more bytes than the pages it takes the whole runtime to had gained.
36
+ static decide({ entriesByRoute, isKept, isRefused, whole, measured }: RoutePaysInput): RoutePaysVerdict[] {
37
+ const lossOf = (route: string) => (measured.get(route) ?? 0) - (whole.get(route) ?? 0);
38
+ const perModule = [...entriesByRoute].filter(([, entries]) => entries.length > 0 && !entries.some(isKept));
39
+ const gaining = new Map(perModule.filter(([route]) => lossOf(route) < 0));
40
+ const losing = new Map(perModule.filter(([route]) => lossOf(route) >= 0));
41
+ const verdicts = new Map<string, RoutePaysVerdict>();
42
+ const keep = (entry: string, route: string) => {
43
+ if (verdicts.has(entry) || isRefused?.(entry)) return;
44
+ verdicts.set(entry, { entry, route, whole: whole.get(route) ?? 0, perModule: measured.get(route) ?? 0 });
45
+ for (const [other, entries] of gaining) if (entries.includes(entry)) gaining.delete(other);
46
+ for (const [other, entries] of losing) if (entries.includes(entry)) losing.delete(other);
47
+ };
48
+ const heldByGaining = () => new Set([...gaining.values()].flat());
49
+ const shared = heldByGaining();
50
+ for (const [route, entries] of [...losing]) for (const entry of entries) if (!shared.has(entry)) keep(entry, route);
51
+ for (;;) {
52
+ const scores = new Map<string, { score: number; route: string }>();
53
+ for (const [route, entries] of losing)
54
+ for (const entry of entries) {
55
+ const known = scores.get(entry) ?? { score: 0, route };
56
+ scores.set(entry, { score: known.score + lossOf(route), route: known.route });
57
+ }
58
+ for (const [route, entries] of gaining)
59
+ for (const entry of entries) {
60
+ const known = scores.get(entry);
61
+ if (known) known.score += lossOf(route);
62
+ }
63
+ const [best] = [...scores]
64
+ .filter(([entry, { score }]) => score > 0 && !isRefused?.(entry))
65
+ .sort(([a, x], [b, y]) => y.score - x.score || (a < b ? -1 : a > b ? 1 : 0));
66
+ if (!best) break;
67
+ keep(best[0], best[1].route);
68
+ }
69
+ return [...verdicts.values()];
70
+ }
71
+
72
+ //* The all-whole build only nominates: among pages that share chunks, a page kept whole is not the size it has
73
+ //* where every page is. So the build keeping the nominated entries is measured too, and this names the routes it
74
+ //* moved to the whole runtime that came out no smaller than they were, all of them where the routes together did.
75
+ static larger({ entriesByRoute, wasKept, isKept, before, after }: RoutePaidInput): string[] {
76
+ const sizeIn = (sizes: ReadonlyMap<string, number>, route: string) => sizes.get(route) ?? 0;
77
+ const moved = [...entriesByRoute]
78
+ .filter(([, entries]) => !entries.some(wasKept) && entries.some(isKept))
79
+ .map(([route]) => route);
80
+ const larger = moved.filter((route) => sizeIn(after, route) >= sizeIn(before, route));
81
+ if (larger.length > 0) return larger;
82
+ const total = (sizes: ReadonlyMap<string, number>) =>
83
+ [...entriesByRoute.keys()].reduce((sum, route) => sum + sizeIn(sizes, route), 0);
84
+ return total(after) >= total(before) ? moved : [];
85
+ }
86
+
87
+ //? Only what a route's entries import statically counts: a chunk asked for with `import()` is not its first load.
88
+ async sizesOf(
89
+ bundle: Pick<BundleClientEntriesResult, "entryOutputAbsByAbsPath" | "graph">,
90
+ buildEntriesByRoute: ReadonlyMap<string, readonly string[]>,
91
+ ): Promise<Map<string, number>> {
92
+ const sizes = new Map<string, number>();
93
+ for (const [route, buildEntries] of buildEntriesByRoute) {
94
+ const chunks = new Set<string>();
95
+ for (const entry of buildEntries) {
96
+ const output = bundle.entryOutputAbsByAbsPath.get(entry);
97
+ if (output) chunks.add(output);
98
+ }
99
+ for (const chunk of chunks)
100
+ for (const imported of bundle.graph.importsByChunk.get(chunk) ?? []) chunks.add(imported);
101
+ let total = 0;
102
+ for (const chunk of chunks) total += await this.#sizeOf(chunk);
103
+ sizes.set(route, total);
104
+ }
105
+ return sizes;
106
+ }
107
+
108
+ async #sizeOf(chunk: string): Promise<number> {
109
+ const bytes = await Bun.file(chunk).bytes();
110
+ const key = `${bytes.byteLength}:${Bun.hash(bytes).toString(36)}`;
111
+ const known = this.#sizes.get(key);
112
+ if (known !== undefined) return known;
113
+ const size = chunkBrotliBytesOf(bytes);
114
+ this.#sizes.set(key, size);
115
+ return size;
116
+ }
117
+ }
@@ -40,10 +40,12 @@ export class SsrBaseArtifactBuilder {
40
40
  #started = Date.now();
41
41
  #serverEnv: BunPlugin | undefined;
42
42
  #vendorExports: Partial<Record<VendorSpecifier, readonly string[]>>;
43
+ #dictionaryRoutes?: ReadonlyMap<string, readonly string[]>;
43
44
 
44
45
  /**
45
46
  * `serverEnv`: the build's server env plugin, so the route bundle carries the env files the backend does and no more.
46
47
  * `vendorExports`: the only names a vendor entry exports, for a build whose every client module is already bundled.
48
+ * `dictionaryRoutes`: the dictionary groups each route can show, for a build that cuts the page dictionary by route.
47
49
  */
48
50
  constructor(
49
51
  app: App,
@@ -51,12 +53,18 @@ export class SsrBaseArtifactBuilder {
51
53
  {
52
54
  serverEnv,
53
55
  vendorExports = {},
54
- }: { serverEnv?: BunPlugin; vendorExports?: Partial<Record<VendorSpecifier, readonly string[]>> } = {},
56
+ dictionaryRoutes,
57
+ }: {
58
+ serverEnv?: BunPlugin;
59
+ vendorExports?: Partial<Record<VendorSpecifier, readonly string[]>>;
60
+ dictionaryRoutes?: ReadonlyMap<string, readonly string[]>;
61
+ } = {},
55
62
  ) {
56
63
  this.#app = app;
57
64
  this.#command = command;
58
65
  this.#serverEnv = serverEnv;
59
66
  this.#vendorExports = vendorExports;
67
+ this.#dictionaryRoutes = dictionaryRoutes;
60
68
  this.#artifactDir = `${command === "build" ? app.dist.cwdPath : app.cwdPath}/.akan/artifact`;
61
69
  this.#absArtifactDir = path.resolve(this.#artifactDir);
62
70
  }
@@ -80,7 +88,7 @@ export class SsrBaseArtifactBuilder {
80
88
  };
81
89
  const { rscClientUrl, rscRuntimeClientManifest, rscRuntimeSsrManifest, vendorMap, runtimeChunks } = await timed(
82
90
  "runtime",
83
- () => this.#buildRuntimeClientEntries(),
91
+ () => this.buildRuntimeClientEntries(),
84
92
  );
85
93
  const pageEntries = await timed("routes", async () => {
86
94
  const pageKeys = await this.#app.getPageKeys();
@@ -88,9 +96,11 @@ export class SsrBaseArtifactBuilder {
88
96
  return await resolveSsrPageEntriesForApp(this.#app, pageKeys);
89
97
  });
90
98
  const { cssCompiler, optimizedFonts, cssAssets } = await timed("styles", () => this.#buildStyleAssets());
91
- const dictAssets = await timed("dictionary", () =>
92
- new DictionaryAssetBuilder(this.#app, this.#absArtifactDir).build(akanConfig.i18n),
93
- );
99
+ const {
100
+ assets: dictAssets,
101
+ routes: dictRoutes,
102
+ groups: dictGroups,
103
+ } = await timed("dictionary", () => this.buildDictionaries());
94
104
  const pagesBundle = await timed("pages", () =>
95
105
  new PagesBundleBuilder(this.#app, this.#command, pageEntries, this.#serverEnv).build(),
96
106
  );
@@ -113,6 +123,8 @@ export class SsrBaseArtifactBuilder {
113
123
  vendorMap,
114
124
  cssAssets,
115
125
  dictAssets,
126
+ ...(dictRoutes ? { dictRoutes } : {}),
127
+ ...(dictGroups ? { dictGroups } : {}),
116
128
  pagesBundlePath:
117
129
  this.#command === "build"
118
130
  ? path.relative(this.#absArtifactDir, pagesBundle.bundlePath)
@@ -145,6 +157,17 @@ export class SsrBaseArtifactBuilder {
145
157
  return { artifact, seedIndex, cssCompiler, optimizedFonts, runtimeChunks, phaseMs };
146
158
  }
147
159
 
160
+ //? A dev build worker runs it again for a signal or dictionary save, in a process of its own: `lib/dict.ts` imported
161
+ //? into a long-lived one stays cached after its file changes.
162
+ async buildDictionaries(): ReturnType<DictionaryAssetBuilder["buildAll"]> {
163
+ const akanConfig = await this.#app.getConfig();
164
+ return await new DictionaryAssetBuilder(this.#app, this.#absArtifactDir).buildAll(akanConfig.i18n, {
165
+ splitApi: true,
166
+ routes: this.#dictionaryRoutes,
167
+ everyGroupAlone: this.#command === "start",
168
+ });
169
+ }
170
+
148
171
  //? Renamed into place, last: a dev backend booted beside this build starts on the file the moment it exists.
149
172
  static async writeArtifact(absArtifactDir: string, artifact: BaseBuildArtifact): Promise<void> {
150
173
  const artifactPath = path.join(absArtifactDir, "base-artifact.json");
@@ -152,13 +175,13 @@ export class SsrBaseArtifactBuilder {
152
175
  await rename(`${artifactPath}.tmp`, artifactPath);
153
176
  }
154
177
 
155
- async #buildRuntimeClientEntries(): Promise<
178
+ async buildRuntimeClientEntries(): Promise<
156
179
  Pick<BaseBuildArtifact, "rscClientUrl" | "rscRuntimeClientManifest" | "rscRuntimeSsrManifest"> & {
157
180
  vendorMap: Record<VendorSpecifier, string>;
158
181
  runtimeChunks: RuntimeChunks;
159
182
  }
160
183
  > {
161
- const akanServerPath = await this.#resolveAkanServerPath();
184
+ const akanServerPath = await VendorNarrowing.akanServerPath(this.#app.workspace.workspaceRoot);
162
185
  const rscClientEntry = path.resolve(akanServerPath, "rscClient.tsx");
163
186
  const rscSegmentOutletEntry = path.resolve(akanServerPath, "rscSegmentOutlet.tsx");
164
187
  const vendorEntries = VendorNarrowing.entriesIn(akanServerPath);
@@ -222,34 +245,6 @@ export class SsrBaseArtifactBuilder {
222
245
  return moduleMap;
223
246
  }
224
247
 
225
- async #resolveAkanServerPath() {
226
- const candidates: string[] = [];
227
- try {
228
- candidates.push(path.dirname(Bun.resolveSync("akanjs/server", this.#app.workspace.workspaceRoot)));
229
- } catch {
230
- // Source workspaces and bundled CLI execution have different resolution roots; try explicit candidates below.
231
- }
232
- candidates.push(
233
- path.join(this.#app.workspace.workspaceRoot, "pkgs/akanjs/server"),
234
- path.join(this.#app.workspace.workspaceRoot, "node_modules/akanjs/server"),
235
- );
236
- try {
237
- candidates.push(path.dirname(Bun.resolveSync("akanjs/server", path.dirname(Bun.main))));
238
- } catch {
239
- // Published CLI installs may hoist dependencies differently; explicit Bun.main candidates cover that.
240
- }
241
- candidates.push(
242
- path.join(path.dirname(Bun.main), "node_modules/akanjs/server"),
243
- path.join(path.dirname(Bun.main), "../../akanjs/server"),
244
- path.resolve(import.meta.dir, "../../server"),
245
- path.resolve(import.meta.dir, "../server"),
246
- );
247
- for (const candidate of candidates) {
248
- if (await Bun.file(path.join(candidate, "rscClient.tsx")).exists()) return candidate;
249
- }
250
- throw new Error(`[base-artifact] failed to locate akanjs/server; looked in: ${candidates.join(", ")}`);
251
- }
252
-
253
248
  async #buildStyleAssets(): Promise<{
254
249
  cssCompiler: CssCompiler;
255
250
  optimizedFonts: Awaited<ReturnType<FontOptimizer["optimize"]>>;