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

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
@@ -149,20 +149,28 @@ export class Executor {
149
149
  const readPath = this.getPath(dirPath);
150
150
  try {
151
151
  const glob = new Bun.Glob("*");
152
- return Array.from(glob.scanSync({ cwd: readPath, onlyFiles: false })).sort();
152
+ return Array.from(glob.scanSync({ cwd: readPath, onlyFiles: false })).sort((a, b) =>
153
+ a < b ? -1 : a > b ? 1 : 0,
154
+ );
153
155
  } catch {
154
156
  return [];
155
157
  }
156
158
  }
157
159
  async getAllFiles(pattern = "**/*", { cwd }: { cwd?: string } = {}): Promise<string[]> {
158
160
  const glob = new Bun.Glob(pattern);
159
- return Array.from(glob.scanSync({ cwd: cwd ?? this.cwdPath, onlyFiles: true })).sort();
161
+ return Array.from(glob.scanSync({ cwd: cwd ?? this.cwdPath, onlyFiles: true })).sort((a, b) =>
162
+ a < b ? -1 : a > b ? 1 : 0,
163
+ );
160
164
  }
161
165
  async getFilesAndDirs(dirPath: string): Promise<{ files: string[]; dirs: string[] }> {
162
166
  const fullDirPath = this.getPath(dirPath);
163
167
  const glob = new Bun.Glob("*");
164
- const files = Array.from(glob.scanSync({ cwd: fullDirPath, onlyFiles: true })).sort();
165
- const allEntries = Array.from(glob.scanSync({ cwd: fullDirPath, onlyFiles: false })).sort();
168
+ const files = Array.from(glob.scanSync({ cwd: fullDirPath, onlyFiles: true })).sort((a, b) =>
169
+ a < b ? -1 : a > b ? 1 : 0,
170
+ );
171
+ const allEntries = Array.from(glob.scanSync({ cwd: fullDirPath, onlyFiles: false })).sort((a, b) =>
172
+ a < b ? -1 : a > b ? 1 : 0,
173
+ );
166
174
  const dirs = allEntries.filter((entry) => !files.includes(entry));
167
175
  return { files, dirs };
168
176
  }
@@ -209,8 +217,8 @@ export class Executor {
209
217
  }
210
218
  return { filePath: writePath, content: contentStr, written };
211
219
  }
212
- async writeJson(filePath: string, content: object) {
213
- await this.writeFile(filePath, content);
220
+ async writeJson(filePath: string, content: object, options: { silent?: boolean } = {}) {
221
+ await this.writeFile(filePath, content, options);
214
222
  }
215
223
  async getLocalFile(targetPath: string) {
216
224
  const filePath = path.isAbsolute(targetPath) ? targetPath : targetPath.replace(this.cwdPath, "");
@@ -1,9 +1,10 @@
1
1
  import { describe, expect, spyOn, test } from "bun:test";
2
2
  import { existsSync } from "node:fs";
3
- import { lstat, mkdir, readFile, readlink, rm, stat, utimes, writeFile } from "node:fs/promises";
3
+ import { lstat, mkdir, readFile, readlink, rm, stat, symlink, utimes, writeFile } from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { AkanAppConfig } from "../akanConfig";
6
6
  import { DevGeneratedIndexSync } from "../frontendBuild/devGeneratedIndexSync";
7
+ import { RouteRuntimeReport } from "../quality/routeRuntimeReport";
7
8
  import {
8
9
  createTempApp,
9
10
  createTempLib,
@@ -629,6 +630,7 @@ describe("Workspace and app executor environment contracts", () => {
629
630
  "cache/cssCandidates.json",
630
631
  "cache/fontCache.json",
631
632
  "cache/fonts/Assistant-400-normal-abc.woff2",
633
+ path.relative(".akan", RouteRuntimeReport.file),
632
634
  ];
633
635
  const removed = [
634
636
  "artifact/client/app.js",
@@ -776,6 +778,76 @@ describe("Workspace and app executor environment contracts", () => {
776
778
  ]);
777
779
  });
778
780
 
781
+ test("a route's own syncPageLibs decides which lib pages its basePath mounts", async () => {
782
+ const { app, appRoot } = await makeAppWithLibPages("pages-route-libs", {
783
+ config: [
784
+ "export default {",
785
+ " syncPageLibs: true,",
786
+ " routes: [",
787
+ ' { basePath: "admin", domains: {} },',
788
+ ' { basePath: "edge", domains: {}, syncPageLibs: false },',
789
+ ' { basePath: "shop", domains: {}, syncPageLibs: ["social"] },',
790
+ " ],",
791
+ "};",
792
+ "",
793
+ ].join("\n"),
794
+ libs: { shared: ["about"], social: ["feed"] },
795
+ });
796
+ expect(await app.syncPages(["shared", "social"])).toBe(true);
797
+
798
+ expect(await app.getPageKeys({ refresh: true })).toEqual([
799
+ "./admin/(libs)/(shared)/about/_index.tsx",
800
+ "./admin/(libs)/(social)/feed/_index.tsx",
801
+ "./shop/(libs)/(social)/feed/_index.tsx",
802
+ ]);
803
+ expect(await lstat(path.join(appRoot, "page/edge/(libs)")).catch(() => null)).toBeNull();
804
+ expect(await app.syncPages(["shared", "social"])).toBe(false);
805
+ });
806
+
807
+ test("refuses a route that sets syncPageLibs without a basePath", async () => {
808
+ const { app } = await makeAppWithLibPages("pages-route-libs-root", {
809
+ config: "export default { routes: [{ domains: {}, syncPageLibs: false }] };\n",
810
+ });
811
+ await expect(app.syncPages(["shared"])).rejects.toThrow("sets syncPageLibs without a basePath");
812
+ });
813
+
814
+ test("refuses two routes of one basePath that set different syncPageLibs", async () => {
815
+ const { app } = await makeAppWithLibPages("pages-route-libs-twice", {
816
+ config: [
817
+ "export default {",
818
+ " routes: [",
819
+ ' { basePath: "shop", domains: {}, syncPageLibs: ["shared"] },',
820
+ ' { basePath: "shop", domains: {}, syncPageLibs: false },',
821
+ " ],",
822
+ "};",
823
+ "",
824
+ ].join("\n"),
825
+ });
826
+ await expect(app.syncPages(["shared"])).rejects.toThrow('share basePath "shop" and set different syncPageLibs');
827
+ });
828
+
829
+ test("names the route whose syncPageLibs lists an unknown lib, and checks the app's list no route uses", async () => {
830
+ const { app } = await makeAppWithLibPages("pages-route-libs-unknown", {
831
+ config: 'export default { routes: [{ basePath: "shop", domains: {}, syncPageLibs: ["missing"] }] };\n',
832
+ });
833
+ await expect(app.syncPages(["shared"])).rejects.toThrow(
834
+ `app "pages-route-libs-unknown"'s route "shop" lists lib "missing"`,
835
+ );
836
+
837
+ const { app: unused } = await makeAppWithLibPages("pages-route-libs-unused", {
838
+ config: [
839
+ "export default {",
840
+ ' syncPageLibs: ["missing"],',
841
+ ' routes: [{ basePath: "shop", domains: {}, syncPageLibs: false }],',
842
+ "};",
843
+ "",
844
+ ].join("\n"),
845
+ });
846
+ await expect(unused.syncPages(["shared"])).rejects.toThrow(
847
+ 'app "pages-route-libs-unused" lists lib "missing" but the app does not depend on it',
848
+ );
849
+ });
850
+
779
851
  test("rejects a lib route that collides with an app route", async () => {
780
852
  const { app, appRoot } = await makeAppWithLibPages("pages-collide", {
781
853
  config: "export default { syncPageLibs: true };\n",
@@ -961,6 +1033,7 @@ describe("Workspace and app executor environment contracts", () => {
961
1033
  process.env.AKAN_PUBLIC_SERVE_DOMAIN = "example.com";
962
1034
  process.env.AKAN_PUBLIC_ENV = "local";
963
1035
  process.env.PORT_OFFSET = "0";
1036
+ delete process.env.PORT;
964
1037
  await writeJson(path.join(root, "package.json"), rootPackageJson());
965
1038
  for (const name of names) {
966
1039
  await mkdir(path.join(root, "apps", name), { recursive: true });
@@ -1001,6 +1074,26 @@ describe("Workspace and app executor environment contracts", () => {
1001
1074
  expect(await app.getDevPort()).toBe(12345);
1002
1075
  });
1003
1076
 
1077
+ test("PORT pins it as it does a built server, and AKAN_DEV_PORT outranks it", async () => {
1078
+ const workspace = await makeWorkspaceWithApps(["env-a", "env-b"]);
1079
+ const app = AppExecutor.from(workspace, "env-b");
1080
+ delete process.env.AKAN_DEV_PORT;
1081
+ process.env.PORT = "28284";
1082
+ try {
1083
+ expect(await app.getDevPort()).toBe(28284);
1084
+ expect((await app.prepareCommand("start")).env.PORT).toBe("28284");
1085
+
1086
+ process.env.AKAN_DEV_PORT = "12345";
1087
+ expect(await app.getDevPort()).toBe(12345);
1088
+
1089
+ process.env.AKAN_DEV_PORT = "nope";
1090
+ expect(await app.getDevPort()).toBe(28284);
1091
+ } finally {
1092
+ delete process.env.PORT;
1093
+ delete process.env.AKAN_DEV_PORT;
1094
+ }
1095
+ });
1096
+
1004
1097
  test("ignores an unusable AKAN_DEV_PORT rather than binding a nonsense port", async () => {
1005
1098
  const workspace = await makeWorkspaceWithApps(["bad-a"]);
1006
1099
  const app = AppExecutor.from(workspace, "bad-a");
@@ -1158,6 +1251,7 @@ describe("Workspace and app executor environment contracts", () => {
1158
1251
  process.env.AKAN_PUBLIC_REPO_NAME = "repo";
1159
1252
  process.env.AKAN_PUBLIC_SERVE_DOMAIN = "example.com";
1160
1253
  process.env.AKAN_PUBLIC_ENV = "local";
1254
+ for (const key of ["PORT", "AKAN_DEV_PORT"]) delete process.env[key];
1161
1255
 
1162
1256
  await writeJson(path.join(root, "package.json"), rootPackageJson());
1163
1257
  for (const appName of ["minimal", "akan"]) {
@@ -1260,6 +1354,21 @@ describe("PkgExecutor package generation", () => {
1260
1354
  expect(await Bun.file(path.join(root, "dist/pkgs/@sample/tool/package.json")).json()).toEqual(distPackageJson);
1261
1355
  expect(await Bun.file(path.join(root, "pkgs/@sample/tool/package.json")).json()).toEqual(distPackageJson);
1262
1356
  });
1357
+
1358
+ test("names a sibling the root links as workspace:* at the sibling's own version", async () => {
1359
+ const root = await makeTempRoot();
1360
+ await writeJson(
1361
+ path.join(root, "package.json"),
1362
+ rootPackageJson({ devDependencies: { typescript: "6.0.0", "@sample/core": "workspace:*" } }),
1363
+ );
1364
+ await writeJson(path.join(root, "pkgs/@sample/core/package.json"), { name: "@sample/core", version: "0.2.0" });
1365
+ await writeJson(path.join(root, "pkgs/@sample/tool/package.json"), { name: "@sample/tool", version: "0.2.0" });
1366
+
1367
+ const workspace = new WorkspaceExecutor({ workspaceRoot: root, repoName: "repo" });
1368
+ const distPackageJson = await PkgExecutor.from(workspace, "@sample/tool").generateDistPackageJson(["@sample/core"]);
1369
+
1370
+ expect(distPackageJson.dependencies).toEqual({ "@sample/core": "0.2.0" });
1371
+ });
1263
1372
  });
1264
1373
 
1265
1374
  describe("scan info construction", () => {
@@ -1571,6 +1680,51 @@ describe("SysExecutor scan", () => {
1571
1680
  },
1572
1681
  );
1573
1682
 
1683
+ test("removes a module folder holding only its generated index.ts, names it, and keeps every other folder", async () => {
1684
+ const leftoverOf = (Model: string, types: string[]) =>
1685
+ `${types.map((type) => `import * as ${type} from "./${Model}.${type}";`).join("\n")}\n\nexport const ${Model} = { ${types.join(", ")} };\n`;
1686
+ const leftover = leftoverOf("Person", ["Template", "Unit", "Util", "View", "Zone"]);
1687
+ const { lib, libDir } = await createScannableLib("leftovermodules", {
1688
+ files: {
1689
+ "lib/person/index.ts": leftover,
1690
+ "lib/_camera/index.ts": leftoverOf("Camera", ["Util", "Zone"]),
1691
+ "lib/__scalar/address/index.ts": leftoverOf("Address", ["Unit"]),
1692
+ "lib/_kept/index.ts": leftover,
1693
+ "lib/_kept/kept.service.ts": "export const kept = 1;\n",
1694
+ "lib/noted/index.ts": leftover,
1695
+ "lib/noted/.gitkeep": "",
1696
+ "lib/_written/index.ts": 'export const written = "by hand";\n',
1697
+ "lib/_reexport/index.ts": 'export * from "./person.constant";\n',
1698
+ },
1699
+ });
1700
+ await mkdir(path.join(libDir, "lib", "empty"));
1701
+ const linked = path.join(libDir, "..", "leftovermodules-linked");
1702
+ await mkdir(linked);
1703
+ await writeFile(path.join(linked, "index.ts"), leftover);
1704
+ await symlink(linked, path.join(libDir, "lib", "_linked"));
1705
+ const info = spyOn(lib.logger, "info").mockImplementation(() => undefined);
1706
+
1707
+ await lib.scan();
1708
+
1709
+ for (const dir of ["lib/person", "lib/_camera", "lib/__scalar/address"])
1710
+ expect(existsSync(path.join(libDir, dir))).toBe(false);
1711
+ for (const kept of [
1712
+ "lib/_kept/kept.service.ts",
1713
+ "lib/noted/.gitkeep",
1714
+ "lib/empty",
1715
+ "lib/__scalar",
1716
+ "lib/_written/index.ts",
1717
+ "lib/_reexport/index.ts",
1718
+ "lib/_linked/index.ts",
1719
+ ])
1720
+ expect(existsSync(path.join(libDir, kept))).toBe(true);
1721
+ expect(info.mock.calls.map(([message]) => message).sort()).toEqual([
1722
+ "Removed libs/leftovermodules/lib/__scalar/address: its generated index.ts was all that was left of the module",
1723
+ "Removed libs/leftovermodules/lib/_camera: its generated index.ts was all that was left of the module",
1724
+ "Removed libs/leftovermodules/lib/person: its generated index.ts was all that was left of the module",
1725
+ ]);
1726
+ });
1727
+
1574
1728
  test("refuses a hand-written ui/index.tsx beside the generated barrel, naming the file and the fix", async () => {
1575
1729
  const { lib } = await createScannableLib("shadowedbarrel", {
1576
1730
  files: {
@@ -33,7 +33,8 @@ export class PkgExecutor extends Executor {
33
33
  ...rootPackageJson.devDependencies,
34
34
  };
35
35
  const rootVersion = rootDeps[dep];
36
- if (rootVersion) return rootVersion;
36
+ //? A `workspace:` range resolves only inside this repo, so a sibling package is published at its own version.
37
+ if (rootVersion && !rootVersion.startsWith("workspace:")) return rootVersion;
37
38
  // Overrides never reach a consumer's install, so a pinned transitive dep is published as a dependency.
38
39
  const overrideVersion = rootPackageJson.overrides?.[dep];
39
40
  if (typeof overrideVersion === "string") return overrideVersion;
@@ -1,7 +1,8 @@
1
1
  import { existsSync } from "node:fs";
2
+ import { lstat, readdir, readFile, rmdir, unlink } from "node:fs/promises";
2
3
  import path from "node:path";
3
4
  import { capitalize, getPageSourceFileViolation } from "akanjs/common";
4
- import { AkanAppConfig, AkanLibConfig } from "../akanConfig";
5
+ import { AkanAppConfig, AkanLibConfig, AkanWorkers } from "../akanConfig";
5
6
  import {
6
7
  renderScopeAgentBlock,
7
8
  renderScopeAgentsMd,
@@ -76,6 +77,15 @@ export class SysExecutor extends Executor {
76
77
  if (!this.hasScanInfo() && !allowEmpty) throw new Error("Scan info is not available");
77
78
  return this.#scanInfo as AllowEmpty extends true ? AppInfo | LibInfo | null : AppInfo | LibInfo;
78
79
  }
80
+ async selectWorkers() {
81
+ const scanInfo = this.#scanInfo ?? (await this.scan({ write: false }));
82
+ const own = { owner: `${this.type}s/${this.name}/akan.config.ts`, workers: (await this.getConfig()).workers };
83
+ const libWorkers = [...scanInfo.getLibInfos()].map(([lib, { akanConfig }]) => ({
84
+ lib,
85
+ workers: akanConfig.workers,
86
+ }));
87
+ return AkanWorkers.select(own, libWorkers, scanInfo.getLibs());
88
+ }
79
89
  async #seedEnvFiles(): Promise<FileContent[]> {
80
90
  const envDir = path.join(this.cwdPath, "env");
81
91
  const missing = await new EnvSeed(envDir).missing();
@@ -85,9 +95,69 @@ export class SysExecutor extends Executor {
85
95
  this.writeFile(path.join(envDir, fileName), content, { overwrite: false, silent: true }),
86
96
  ),
87
97
  );
88
- this.logger.info(
89
- `${missing.map(({ fileName }) => `env/${fileName}`).join(", ")} were missing (gitignored, so a clone has none) and now hold local defaults: put this machine's values in them, or fetch the team's with \`akan download-env\`.`,
90
- );
98
+ for (const notice of EnvSeed.notices(missing)) this.logger.info(notice);
99
+ return written;
100
+ }
101
+ //? `synced` is the app or lib whose sync this is: a lib's files are written by the sync of each app mounting it.
102
+ async #syncClientPieces(scanInfo: AppInfo | LibInfo, synced: SysExecutor): Promise<FileContent[]> {
103
+ const pieceDir = "lib/__client";
104
+ const modulesOf = (info: AppInfo | LibInfo): string[] => [
105
+ ...[...info.getLibInfos().values()].flatMap(modulesOf),
106
+ ...info.getDatabaseModules(),
107
+ ...info.getServiceModules(),
108
+ ];
109
+ const scope = `${this.type}s/${this.name}`;
110
+ const scopesOf = (info: AppInfo | LibInfo, own: string): string[] => [
111
+ ...[...info.getLibInfos().values()].flatMap((libInfo) => scopesOf(libInfo, `libs/${libInfo.name}`)),
112
+ own,
113
+ ];
114
+ const { RuntimeNameTable } = await import("../quality/runtimeNameTable");
115
+ const { RuntimeConstantGraph } = await import("../quality/runtimeConstantGraph");
116
+ const table = await RuntimeNameTable.readScopes(this.workspace.workspaceRoot, [
117
+ ...new Set(scopesOf(scanInfo, scope)),
118
+ ]).catch((error: unknown) => {
119
+ if (synced.type === "app")
120
+ this.logger.warn(
121
+ `[client-runtime] The modules of ${scope} could not be read (${error instanceof Error ? error.message : String(error)}), so no store file under ${scope}/${pieceDir} loads the upload module's descriptors first, and a page naming only that store has no upload action. Run \`akan sync ${this.name}\` again once that is fixed.`,
122
+ );
123
+ return null;
124
+ });
125
+ const constants = table ? RuntimeConstantGraph.ofDisk(this.workspace.workspaceRoot, table) : null;
126
+ const written = (
127
+ await Promise.all([
128
+ this._applyTemplate({ basePath: pieceDir, template: "clientPiece/scope", scanInfo }),
129
+ ...[...new Set(modulesOf(scanInfo))].map((model) =>
130
+ this._applyTemplate({
131
+ basePath: pieceDir,
132
+ template: "clientPiece/module",
133
+ scanInfo,
134
+ dict: {
135
+ model,
136
+ Model: capitalize(model),
137
+ descriptorsFirst: (table?.dependenciesOf(scope, model) ?? []).map(({ module }) => module).join(","),
138
+ },
139
+ options: {
140
+ constants: constants?.fetchNeedsOf(model) ?? undefined,
141
+ registration: constants?.modelOf(model) ?? undefined,
142
+ },
143
+ }),
144
+ ),
145
+ ...(constants
146
+ ? [...scanInfo.getDatabaseModules(), ...scanInfo.getScalarModules()].map((model) =>
147
+ this._applyTemplate({
148
+ basePath: pieceDir,
149
+ template: "clientPiece/constant",
150
+ scanInfo,
151
+ dict: { model, Model: capitalize(model) },
152
+ options: constants.piecesBefore({ scope, module: model }),
153
+ }),
154
+ )
155
+ : []),
156
+ ])
157
+ ).flat();
158
+ const kept = new Set(written.map(({ filePath }) => path.basename(filePath)));
159
+ const stale = (await this.readdir(pieceDir)).filter((file) => !kept.has(file));
160
+ await Promise.all(stale.map((file) => this.remove(`${pieceDir}/${file}`)));
91
161
  return written;
92
162
  }
93
163
  #getScanTemplateTasks(scanInfo: AppInfo | LibInfo): (Promise<FileContent[]> | null)[] {
@@ -115,6 +185,35 @@ export class SysExecutor extends Executor {
115
185
  ),
116
186
  ];
117
187
  }
188
+ static readonly #generatedModuleIndex =
189
+ /^(?:import \* as (?:Template|Unit|Util|View|Zone) from "\.\/\w+\.(?:Template|Unit|Util|View|Zone)";\r?\n)+\r?\nexport const \w+ = \{ [\w, ]+ \};\s*$/;
190
+ //? Git keeps an ignored file when a merge or checkout takes a module's sources away, so the folder outlives them.
191
+ async #removeLeftoverModuleDirs() {
192
+ const moduleDirs = [
193
+ ...(await this.readdir("lib")).filter((name) => !name.startsWith("__")).map((name) => `lib/${name}`),
194
+ ...(await this.readdir("lib/__scalar")).map((name) => `lib/__scalar/${name}`),
195
+ ];
196
+ for (const dir of moduleDirs) {
197
+ const dirPath = path.join(this.cwdPath, dir);
198
+ if (!(await lstat(dirPath).catch(() => null))?.isDirectory()) continue;
199
+ const entries = await readdir(dirPath).catch(() => [] as string[]);
200
+ if (entries.filter((entry) => entry !== ".DS_Store").join() !== "index.ts") continue;
201
+ //? `lib/*/index.ts` is git-ignored: one a person wrote there has no other copy, so only the generated shape goes.
202
+ if (!SysExecutor.#generatedModuleIndex.test(await readFile(path.join(dirPath, "index.ts"), "utf8"))) continue;
203
+ await Promise.all(entries.map((entry) => unlink(path.join(dirPath, entry))));
204
+ //? Not recursive: a file that landed since the listing keeps its folder.
205
+ if (
206
+ !(await rmdir(dirPath).then(
207
+ () => true,
208
+ () => false,
209
+ ))
210
+ )
211
+ continue;
212
+ this.logger.info(
213
+ `Removed ${this.type}s/${this.name}/${dir}: its generated index.ts was all that was left of the module`,
214
+ );
215
+ }
216
+ }
118
217
  async scan({
119
218
  refresh = false,
120
219
  write = true,
@@ -133,16 +232,21 @@ export class SysExecutor extends Executor {
133
232
  : await LibInfo.fromExecutor(this as unknown as LibExecutor, {
134
233
  refresh,
135
234
  });
235
+ scanInfo.orderLibDeps();
136
236
  //* Locked: `writeLib` rewrites dependency-lib barrels that other dev servers regenerate and watch too.
137
237
  if (write)
138
238
  await CodegenLock.run(this.workspace.workspaceRoot, `scan:${this.name}`, async () => {
239
+ const libInfos = writeLib ? [...scanInfo.getLibInfos().values()] : [];
240
+ await Promise.all([this, ...libInfos.map((libInfo) => libInfo.exec)].map((e) => e.#removeLeftoverModuleDirs()));
139
241
  await Promise.all(this.#getScanTemplateTasks(scanInfo));
140
242
  await this.writeJson(`akan.${this.type}.json`, scanInfo.getScanResult());
141
243
  await this.#updateDependencies(scanInfo);
142
- if (writeLib) {
143
- const libInfos = [...scanInfo.getLibInfos().values()];
144
- await Promise.all(libInfos.flatMap((libInfo) => libInfo.exec.#getScanTemplateTasks(libInfo)));
145
- }
244
+ await Promise.all(libInfos.flatMap((libInfo) => libInfo.exec.#getScanTemplateTasks(libInfo)));
245
+ //? A piece is shaped by each scope's generated `lib/cnst.ts`, which a new checkout has only once the above ran.
246
+ await Promise.all([
247
+ this.#syncClientPieces(scanInfo, this),
248
+ ...libInfos.map((libInfo) => libInfo.exec.#syncClientPieces(libInfo, this)),
249
+ ]);
146
250
  await this.syncAgentsIndex(scanInfo);
147
251
  });
148
252
  this.#scanInfo = scanInfo;
@@ -8,12 +8,15 @@ import type { BaseDevEnv, TsConfigJson } from "../workspace/types";
8
8
  import { Executor, execEmoji } from "./executor";
9
9
  import { SysExecutor } from "./sysExecutor";
10
10
 
11
- //? As Bun's own .env loader reads it (1.4.4), which fills process.env too: `#` ends an unquoted value even mid-word.
11
+ //? As Bun's .env loader reads it (1.4.4), which fills process.env too: `#` ends an unquoted value mid-word, `\$` is `$`.
12
12
  const parseEnvValue = (value: string) => {
13
13
  const [, quote, inner] = value.match(/^(["'`])((?:\\.|(?!\1)[^\\])*)\1/) ?? [];
14
- if (!quote) return value.replace(/#.*/, "").trim();
15
- if (quote !== '"') return inner;
16
- return inner.replace(/\\(.)/g, (pair, char: string) => (char === "n" ? "\n" : char === "r" ? "\r" : pair));
14
+ const text = !quote
15
+ ? value.replace(/#.*/, "").trim()
16
+ : quote !== '"'
17
+ ? inner
18
+ : inner.replace(/\\(.)/g, (pair, char: string) => (char === "n" ? "\n" : char === "r" ? "\r" : pair));
19
+ return text.replaceAll("\\$", "$");
17
20
  };
18
21
 
19
22
  export const parseEnvFile = (envPath: string): Record<string, string> => {
@@ -7,10 +7,20 @@ import {
7
7
  resolveSsrPageEntriesForApp,
8
8
  } from "../artifact/implicitRootLayout";
9
9
  import { computeRouteSeedIndex, type RouteSeedIndex } from "../artifact/routeSeedIndex";
10
+ import { StoreBootstrap } from "../artifact/storeBootstrap";
10
11
  import type { App } from "../commandDecorators";
11
- import type { ClientEntryDiscovery } from "./clientBuildTypes";
12
+ import {
13
+ type RouteRuntimeBuildReport,
14
+ type RouteRuntimeDictionaryFallback,
15
+ RouteRuntimeReport,
16
+ } from "../quality/routeRuntimeReport";
17
+ import { ModelReference } from "../transforms/modelReference";
18
+ import { RouteRuntime } from "../transforms/routeRuntime";
19
+ import type { AskedExports, ClientEntryDiscovery } from "./clientBuildTypes";
12
20
  import { GraphClientEntryDiscovery } from "./clientEntryDiscovery";
21
+ import { DictionaryRoutes } from "./dictionaryRoutes";
13
22
  import { type BuildRouteClientResult, RouteClientBuilder } from "./routeClientBuilder";
23
+ import { RouteHandoffs } from "./routeHandoffs";
14
24
  import { RouteModulePreloads, type RuntimeChunks } from "./routeModulePreloads";
15
25
  import { RoutesManifestArtifactSerializer } from "./routesManifestArtifactSerializer";
16
26
 
@@ -18,6 +28,9 @@ export interface BuildAllRoutesResult {
18
28
  manifest: RoutesManifest;
19
29
  manifestPath: string;
20
30
  seedIndex: RouteSeedIndex;
31
+ /** A production build: the dictionary groups each route can show; a route left out loads every group. */
32
+ dictionaryRoutes?: Map<string, string[]>;
33
+ runtimeReport?: RouteRuntimeBuildReport;
21
34
  }
22
35
 
23
36
  export class AllRoutesBuilder {
@@ -32,6 +45,9 @@ export class AllRoutesBuilder {
32
45
  #knownSet = new Set<string>();
33
46
  #routeIds: string[] = [];
34
47
  #ssrEntriesByRoute = new Map<string, string[]>();
48
+ #entriesByRoute = new Map<string, string[]>();
49
+ #askedByRoute = new Map<string, AskedExports>();
50
+ #serverModulesByRoute = new Map<string, string[]>();
35
51
  #externalsByChunkUrl: Record<string, string[]> = {};
36
52
  #discovery: ClientEntryDiscovery | null = null;
37
53
 
@@ -46,9 +62,12 @@ export class AllRoutesBuilder {
46
62
  const pageEntries = await resolveSsrPageEntriesForApp(this.#app, pageKeys);
47
63
  const seedIndex = computeRouteSeedIndex(pageEntries);
48
64
  this.#app.verbose(`[build-all] discovered ${seedIndex.entries.length} routes`);
49
- const discovery = await GraphClientEntryDiscovery.create(this.#app);
65
+ const discovery = await GraphClientEntryDiscovery.create(this.#app, { byExport: this.#command === "build" });
50
66
  this.#discovery = discovery;
51
- const importsAs = await this.#ssrImportsAs(discovery, pageEntries);
67
+ const { importsAs, rendering } = await this.#ssrImportsAs(discovery, pageEntries);
68
+ const handoffs = await this.#readHandoffs();
69
+ const dictionary = this.#command === "build";
70
+ const unread = new Map<string, string[]>();
52
71
 
53
72
  // Every route's entries go into one Bun.build: chunk splitting only dedupes within a single build.
54
73
  const allEntries = new Set<string>();
@@ -56,13 +75,34 @@ export class AllRoutesBuilder {
56
75
  const seeds = Array.from(new Set([...seedIndex.globalLayoutFiles, ...entry.seeds]));
57
76
  const routeEntries = await discovery.discover(seeds);
58
77
  for (const discovered of routeEntries) allEntries.add(discovered);
59
- this.#ssrEntriesByRoute.set(entry.routeId, await discovery.discover(seeds, { importsAs }));
78
+ const serverModules = dictionary ? await discovery.serverModules(seeds, { importsAs }) : undefined;
79
+ const asked = await discovery.discoverAsked(seeds, { importsAs, serverModules });
80
+ const ssrEntries = [...asked.keys()].sort();
81
+ this.#askedByRoute.set(entry.routeId, asked);
82
+ if (serverModules) this.#serverModulesByRoute.set(entry.routeId, serverModules);
83
+ const handed = handoffs
84
+ ? await handoffs.read(await discovery.serverModules(seeds, { importsAs: rendering }))
85
+ : undefined;
86
+ const loaded = [...new Set([...ssrEntries, ...(handed?.referenceFiles ?? [])])].sort();
87
+ this.#ssrEntriesByRoute.set(entry.routeId, loaded);
88
+ const besidesReferences = handed ? routeEntries.filter((file) => !ModelReference.isFile(file)) : routeEntries;
89
+ this.#entriesByRoute.set(entry.routeId, [...new Set([...besidesReferences, ...loaded])]);
90
+ if (handed?.unread) {
91
+ const pinned = `${handed.unread.file} (${handed.unread.why})`;
92
+ unread.set(pinned, [...(unread.get(pinned) ?? []), entry.routeId]);
93
+ }
60
94
  this.#routeIds.push(entry.routeId);
61
95
  }
96
+ for (const [pinned, routeIds] of unread)
97
+ this.#app.logger.warn(
98
+ `[client-runtime] ${routeIds.length} route(s) count every model's runtime in the route table: what ${pinned} hands to client components cannot be read. Routes: ${routeIds.join(", ")}`,
99
+ );
62
100
  this.#app.verbose(`[build-all] ${allEntries.size} client entries across ${this.#routeIds.length} routes`);
63
101
 
64
102
  const delta = await this.#buildEntries([...allEntries]);
65
103
  this.#mergeDelta(delta);
104
+ const dictionaryRoutes =
105
+ dictionary && delta.clientGraph ? await this.#readDictionaryRoutes(delta.clientGraph) : null;
66
106
  this.#merged.knownEntries = Array.from(this.#knownSet);
67
107
  this.#externalsByChunkUrl = delta.externalsByChunkUrl ?? {};
68
108
 
@@ -75,24 +115,73 @@ export class AllRoutesBuilder {
75
115
  `[build-all] wrote ${manifestPath} routes=${this.#routeIds.length} entries=${this.#merged.knownEntries.length}`,
76
116
  );
77
117
 
78
- return { manifest, manifestPath, seedIndex };
118
+ return {
119
+ manifest,
120
+ manifestPath,
121
+ seedIndex,
122
+ ...(dictionaryRoutes ? { dictionaryRoutes } : {}),
123
+ ...(delta.runtimeReport ? { runtimeReport: delta.runtimeReport } : {}),
124
+ };
125
+ }
126
+
127
+ async #readDictionaryRoutes(importsByModule: NonNullable<BuildRouteClientResult["clientGraph"]>) {
128
+ const { workspaceRoot } = this.#app.workspace;
129
+ const reader = await DictionaryRoutes.forApp(workspaceRoot, `apps/${this.#app.name}`, { importsByModule });
130
+ const groupsByRoute = new Map<string, string[]>();
131
+ const whole = new Map<string, RouteRuntimeDictionaryFallback>();
132
+ for (const routeId of this.#routeIds) {
133
+ const entries = this.#entriesByRoute.get(routeId) ?? [];
134
+ const read = reader.read({ entries, serverModules: this.#serverModulesByRoute.get(routeId) });
135
+ if (!read.whole) groupsByRoute.set(routeId, read.groups);
136
+ else {
137
+ const pinned = DictionaryRoutes.pinned(read.whole);
138
+ const known = whole.get(pinned) ?? { ...read.whole, routes: [] };
139
+ whole.set(pinned, { ...known, routes: [...known.routes, routeId] });
140
+ }
141
+ }
142
+ for (const [pinned, { routes, line: key }] of whole) {
143
+ const line = `[dictionary] ${routes.length} route(s) load the whole page dictionary: ${pinned}. Routes: ${routes.join(", ")}`;
144
+ if (key !== undefined) this.#app.logger.warn(line);
145
+ else this.#app.verbose(line);
146
+ }
147
+ await RouteRuntimeReport.addDictionary(this.#app.cwdPath, [...whole.values()]);
148
+ return groupsByRoute;
79
149
  }
80
150
 
81
151
  async #ssrImportsAs(discovery: GraphClientEntryDiscovery, pageEntries: PageEntry[]) {
82
152
  const { specifier, ssrShell, importsNoSsrPageRenders } = ROOT_LAYOUT_SYSTEM;
83
153
  const importsAs = new Map<string, ReadonlyMap<string, string | null>>();
84
- const toShell = new Map([[specifier, ssrShell]]);
154
+ //? The root layout registers every model's reference; a route loads only those its own server modules hand over.
155
+ const toShell = new Map<string, string | null>([
156
+ [specifier, ssrShell],
157
+ [ModelReference.registrySpecifier(this.#app.name), null],
158
+ ]);
85
159
  for (const { key, moduleAbsPath } of pageEntries)
86
160
  if (isImplicitRootLayoutKey(key)) importsAs.set(path.resolve(moduleAbsPath), toShell);
87
161
  const system = await discovery.resolveImport(specifier, this.#app.cwdPath);
88
162
  if (system) importsAs.set(system, new Map(importsNoSsrPageRenders.map((spec) => [spec, null])));
89
- return importsAs;
163
+ //? The root layout also imports every store so the server holds them; no route's own render runs through one.
164
+ const stores = StoreBootstrap.serverSpecifiers(this.#app.name).map((spec) => [spec, null] as const);
165
+ const rendering = new Map(importsAs);
166
+ for (const { key, moduleAbsPath } of pageEntries)
167
+ if (isImplicitRootLayoutKey(key)) rendering.set(path.resolve(moduleAbsPath), new Map([...toShell, ...stores]));
168
+ return { importsAs, rendering };
169
+ }
170
+
171
+ async #readHandoffs(): Promise<RouteHandoffs | null> {
172
+ if (this.#command !== "build" || (await StoreBootstrap.scopeOf(this.#app)) !== "page") return null;
173
+ const { workspaceRoot } = this.#app.workspace;
174
+ const scope = `apps/${this.#app.name}`;
175
+ const runtime = await RouteRuntime.read(workspaceRoot, scope).catch(() => null);
176
+ if (!runtime) return null;
177
+ return new RouteHandoffs(workspaceRoot, runtime, await ModelReference.filesOf(workspaceRoot, scope));
90
178
  }
91
179
 
92
180
  async writeModulePreloads(runtimeChunks: RuntimeChunks): Promise<RouteModulePreloads> {
93
181
  const preloads = new RouteModulePreloads({
94
182
  runtimeChunks,
95
183
  entriesByRoute: this.#ssrEntriesByRoute,
184
+ askedByRoute: this.#askedByRoute,
96
185
  clientManifest: this.#merged.clientManifest,
97
186
  externalsByChunkUrl: this.#externalsByChunkUrl,
98
187
  workspaceRoot: this.#app.workspace.workspaceRoot,
@@ -133,6 +222,9 @@ export class AllRoutesBuilder {
133
222
  knownEntries: this.#knownSet,
134
223
  discovery: this.#discovery,
135
224
  command: this.#command,
225
+ entriesByRoute: this.#entriesByRoute,
226
+ sizedEntriesByRoute: this.#ssrEntriesByRoute,
227
+ askedByRoute: this.#askedByRoute,
136
228
  }).build();
137
229
  this.#app.verbose(`[build-all] bundled ${delta.newEntries.length} entries (${Date.now() - started}ms)`);
138
230
  return delta;
@@ -232,8 +232,9 @@ export class AutoImportSync {
232
232
  const parts = rel.split(path.sep).filter(Boolean);
233
233
  const [scope, project, facet] = parts;
234
234
  if ((scope !== "apps" && scope !== "libs") || !project || !facet) return null;
235
- //* `lib/__lib/` is rewritten by every `akan sync`, so an edit there is discarded; `lib/__scalar/` is real source.
236
- if (facet === "lib" && parts[3] === "__lib") return null;
235
+ //* `lib/__lib/` and `lib/__client/` are rewritten by every `akan sync`, so an edit there is discarded;
236
+ //* `lib/__scalar/` is real source.
237
+ if (facet === "lib" && (parts[3] === "__lib" || parts[3] === "__client")) return null;
237
238
  const role = roleFor(facet, base);
238
239
  if (!role) return null;
239
240