@akanjs/devkit 3.2.0-rc.2 → 3.2.0-rc.20

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 (365) hide show
  1. package/CHANGELOG.md +315 -11
  2. package/DEV_RUNTIME_KNOBS.md +4 -3
  3. package/README.ko.md +3 -2
  4. package/README.md +4 -2
  5. package/akanApp/BackendImportGraph.test.ts +1 -1
  6. package/akanApp/akanApp.host.test.ts +257 -1
  7. package/akanApp/akanApp.host.ts +146 -1223
  8. package/akanApp/akanApp.host.wiring.test.ts +727 -0
  9. package/akanApp/builderGap.ts +68 -0
  10. package/akanApp/builderRequestRelay.test.ts +93 -0
  11. package/akanApp/builderRequestRelay.ts +100 -0
  12. package/akanApp/builderRssRecycler.ts +182 -0
  13. package/akanApp/devBackend.ts +392 -0
  14. package/akanApp/devBuildStatusBoard.ts +128 -0
  15. package/akanApp/devBuilder.ts +196 -0
  16. package/akanApp/devHostPolicy.test.ts +11 -11
  17. package/akanApp/devHostPolicy.ts +2 -4
  18. package/akanApp/devIdleSuspend.test.ts +221 -0
  19. package/akanApp/devIdleSuspend.ts +192 -0
  20. package/akanApp/devIdleSuspend.watcher.test.ts +120 -0
  21. package/akanApp/devRecycler.test.ts +66 -0
  22. package/akanApp/devRecycler.ts +305 -0
  23. package/akanApp/processRss.ts +61 -0
  24. package/akanConfig/akanConfig.test.ts +24 -1
  25. package/akanConfig/akanConfig.ts +10 -10
  26. package/akanConfig/akanWorkspaceConfig.ts +1 -1
  27. package/akanConfig/productionLockfile.ts +1 -1
  28. package/apiReport/apiDeclarationPrinter.ts +120 -0
  29. package/apiReport/apiReport.test.ts +526 -0
  30. package/apiReport/apiReport.ts +232 -0
  31. package/apiReport/apiReportDiff.ts +160 -0
  32. package/apiReport/apiReportPolicy.ts +65 -0
  33. package/apiReport/apiTargets.ts +311 -0
  34. package/apiReport/changesetBump.ts +19 -0
  35. package/{applicationBuildReporter.test.ts → app/applicationBuildReporter.test.ts} +21 -0
  36. package/{applicationBuildReporter.ts → app/applicationBuildReporter.ts} +10 -49
  37. package/{applicationBuildRunner.test.ts → app/applicationBuildRunner.test.ts} +74 -7
  38. package/{applicationBuildRunner.ts → app/applicationBuildRunner.ts} +20 -15
  39. package/{applicationTestPreload.ts → app/applicationTestPreload.ts} +1 -1
  40. package/{routeJsBudget.test.ts → app/routeJsBudget.test.ts} +48 -12
  41. package/{routeJsBudget.ts → app/routeJsBudget.ts} +90 -27
  42. package/{routeSourceValidator.test.ts → app/routeSourceValidator.test.ts} +17 -0
  43. package/{routeSourceValidator.ts → app/routeSourceValidator.ts} +5 -1
  44. package/artifact/implicitRootLayout.test.ts +71 -3
  45. package/artifact/implicitRootLayout.ts +21 -4
  46. package/artifact/implicitRootLayoutRender.test.tsx +297 -0
  47. package/biome.base.json +2 -1
  48. package/cloud/cloudApi.test.ts +1 -1
  49. package/cloud/configLock.test.ts +1 -1
  50. package/cloud/globalConfig.test.ts +1 -1
  51. package/cloud/globalConfig.ts +1 -1
  52. package/cloud/updatePackUpload.test.ts +1 -1
  53. package/codeAgent/agent/AkanCodeEnv.ts +1 -1
  54. package/codeAgent/agent/akanCodePaths.ts +1 -1
  55. package/codeAgent/agent/akanSystemPrompt.ts +1 -1
  56. package/codeAgent/agent/codeAgent.test.ts +1 -1
  57. package/codeAgent/skills/akan-debug/SKILL.md +10 -3
  58. package/codeAgent/skills/akan-err/SKILL.md +7 -0
  59. package/codeAgent/skills/akan-mcp/SKILL.md +10 -1
  60. package/codeAgent/skills/akan-scaffold/SKILL.md +2 -2
  61. package/codeAgent/skills/akan-transport/SKILL.md +2 -0
  62. package/codeAgent/skills/akan-validate/SKILL.md +1 -0
  63. package/codeAgent/tools/AkanCli.ts +1 -1
  64. package/codeAgent/tools/AkanToolPack.ts +1 -1
  65. package/codeAgent/tools/McpClient.ts +28 -6
  66. package/codeAgent/tools/McpToolPack.ts +1 -1
  67. package/codeAgent/tools/akanCodePlugins.test.ts +14 -2
  68. package/commandDecorators/argMeta.ts +4 -0
  69. package/commandDecorators/cliError.ts +72 -0
  70. package/commandDecorators/command.ts +165 -91
  71. package/commandDecorators/commandBuilder.ts +1 -1
  72. package/commandDecorators/commandDecorators.test.ts +191 -16
  73. package/commandDecorators/exitCodeError.ts +6 -7
  74. package/commandDecorators/index.ts +1 -0
  75. package/commandDecorators/targetMeta.ts +1 -0
  76. package/commandDecorators/workspaceVersionCheck.test.ts +1 -1
  77. package/commandDecorators/workspaceVersionCheck.ts +1 -1
  78. package/context/akanContext.ts +576 -0
  79. package/context/akanContextInspection.ts +296 -0
  80. package/{akanMcpContract.test.ts → context/akanMcpContract.test.ts} +1 -1
  81. package/{akanMcpContract.ts → context/akanMcpContract.ts} +33 -263
  82. package/context/akanMcpToolError.ts +16 -0
  83. package/context/doctor/agentGuideCheck.ts +81 -0
  84. package/context/doctor/configLeftoverCheck.ts +35 -0
  85. package/context/doctor/doctorFindings.ts +70 -0
  86. package/context/doctor/generatedFreshness.ts +56 -0
  87. package/context/doctor/moduleShapeCheck.ts +88 -0
  88. package/context/doctor/recipeDuplicateCheck.ts +39 -0
  89. package/context/doctor/recipeIndexCheck.ts +87 -0
  90. package/context/doctor/rootShapeCheck.ts +55 -0
  91. package/context/doctor/workflowScope.ts +97 -0
  92. package/{constantFieldNames.test.ts → context/moduleFieldNames.test.ts} +24 -2
  93. package/context/moduleFieldNames.ts +25 -0
  94. package/{recipeScanner.test.ts → context/recipeScanner.test.ts} +1 -1
  95. package/context/safeRead.ts +9 -0
  96. package/csrE2e/csrE2eHarness.fixture.ts +1 -1
  97. package/devkitUtils.test.ts +39 -5
  98. package/{apiReference.test.ts → docs/apiReference.test.ts} +4 -4
  99. package/{apiReference.ts → docs/apiReference.ts} +2 -2
  100. package/docs/errorCodeReference.test.ts +282 -0
  101. package/docs/errorCodeReference.ts +71 -0
  102. package/docs/errorCodeScan.ts +551 -0
  103. package/{frameworkGraph.test.ts → docs/frameworkGraph.test.ts} +1 -1
  104. package/executors/appExecutor.ts +448 -0
  105. package/executors/commandExecutionError.ts +53 -0
  106. package/executors/executor.ts +527 -0
  107. package/{executors.linkFallback.test.ts → executors/executors.linkFallback.test.ts} +1 -1
  108. package/{executors.test.ts → executors/executors.test.ts} +76 -15
  109. package/executors/index.ts +8 -0
  110. package/executors/libExecutor.ts +23 -0
  111. package/executors/moduleExecutor.ts +18 -0
  112. package/executors/pkgExecutor.ts +129 -0
  113. package/executors/sysExecutor.ts +301 -0
  114. package/executors/workspaceExecutor.ts +277 -0
  115. package/frontendBuild/allRoutesBuilder.test.ts +17 -5
  116. package/frontendBuild/allRoutesBuilder.ts +24 -6
  117. package/frontendBuild/autoImportSync.test.ts +1 -1
  118. package/frontendBuild/autoImportSync.ts +1 -1
  119. package/frontendBuild/buildRouteClient.test.ts +1 -1
  120. package/frontendBuild/bundleDefine.ts +2 -0
  121. package/frontendBuild/clientBuildTypes.ts +5 -2
  122. package/frontendBuild/clientEntriesBundler.test.ts +1 -1
  123. package/frontendBuild/clientEntryDiscovery.test.ts +58 -0
  124. package/frontendBuild/clientEntryDiscovery.ts +25 -6
  125. package/frontendBuild/csrArtifactBuilder.test.ts +1 -1
  126. package/frontendBuild/csrDevArtifactWriter.ts +1 -1
  127. package/frontendBuild/cssCompiler.test.ts +1 -1
  128. package/frontendBuild/devGeneratedIndexSync.test.ts +1 -1
  129. package/frontendBuild/devGeneratedIndexSync.ts +7 -38
  130. package/frontendBuild/dictionaryAssetBuilder.test.ts +1 -1
  131. package/frontendBuild/fontOptimizer.test.ts +1 -1
  132. package/frontendBuild/fontPruner.test.ts +1 -1
  133. package/frontendBuild/frontendBuild.test.ts +3 -3
  134. package/frontendBuild/hmrWatcher.stop.test.ts +63 -0
  135. package/frontendBuild/hmrWatcher.test.ts +1 -1
  136. package/frontendBuild/hmrWatcher.ts +22 -1
  137. package/frontendBuild/mcpAppViewBuilder.test.ts +1 -1
  138. package/frontendBuild/mcpAppViewBuilder.ts +1 -1
  139. package/frontendBuild/nativeCore.test.ts +148 -0
  140. package/frontendBuild/optionalPeers.test.ts +36 -8
  141. package/frontendBuild/pagesBundleBuilder.test.ts +2 -3
  142. package/frontendBuild/pagesBundleBuilder.ts +1 -1
  143. package/frontendBuild/precompressArtifacts.test.ts +1 -1
  144. package/frontendBuild/precompressArtifacts.ts +1 -1
  145. package/frontendBuild/serverGraphFile.ts +1 -1
  146. package/frontendBuild/sourceMtimeIndex.test.ts +1 -1
  147. package/frontendBuild/ssrBaseArtifactBuilder.test.ts +26 -0
  148. package/frontendBuild/ssrBaseArtifactBuilder.ts +23 -19
  149. package/frontendBuild/ssrDevBundler.test.ts +1 -1
  150. package/frontendBuild/vendorImportScanner.test.ts +25 -4
  151. package/frontendBuild/vendorImportScanner.ts +25 -10
  152. package/frontendBuild/vendorNarrowing.test.ts +1 -1
  153. package/frontendBuild/watchRootResolver.test.ts +1 -1
  154. package/{agentAssets.test.ts → guideline/agentAssets.test.ts} +1 -1
  155. package/{agentAssets.ts → guideline/agentAssets.ts} +2 -2
  156. package/{agentsIndex.test.ts → guideline/agentsIndex.test.ts} +2 -2
  157. package/{agentsIndex.ts → guideline/agentsIndex.ts} +13 -10
  158. package/{conventionSet.test.ts → guideline/conventionSet.test.ts} +7 -4
  159. package/{conventionSet.ts → guideline/conventionSet.ts} +1 -1
  160. package/{prompter.ts → guideline/prompter.ts} +2 -3
  161. package/incrementalBuilder/buildBatch.proc.ts +14 -4
  162. package/incrementalBuilder/buildBatchProtocol.ts +2 -0
  163. package/incrementalBuilder/buildBatchRunner.test.ts +108 -1
  164. package/incrementalBuilder/buildBatchRunner.ts +17 -4
  165. package/incrementalBuilder/builderBoot.ts +106 -0
  166. package/incrementalBuilder/builderBuildStatus.ts +23 -0
  167. package/incrementalBuilder/builderChannel.test.ts +1 -1
  168. package/incrementalBuilder/builderChannel.ts +11 -0
  169. package/incrementalBuilder/builderGraphPayloads.ts +3 -3
  170. package/incrementalBuilder/builderLanes.ts +157 -0
  171. package/incrementalBuilder/builderWatch.ts +213 -0
  172. package/incrementalBuilder/csrRegistry.ts +234 -0
  173. package/incrementalBuilder/incrementalBuilder.host.test.ts +30 -1
  174. package/incrementalBuilder/incrementalBuilder.host.ts +10 -22
  175. package/incrementalBuilder/incrementalBuilder.proc.test.ts +93 -2
  176. package/incrementalBuilder/incrementalBuilder.proc.ts +81 -823
  177. package/incrementalBuilder/ssrRegistry.ts +278 -0
  178. package/index.ts +22 -22
  179. package/integration/devStability.integration.test.ts +62 -56
  180. package/integration/devStabilityHarness.test.ts +1 -1
  181. package/lint/__fixtures__/no-import-common-err/bad.tsx +13 -0
  182. package/lint/__fixtures__/no-import-common-err/good.tsx +12 -0
  183. package/{biomeBase.test.ts → lint/biomeBase.test.ts} +1 -1
  184. package/lint/gritRules.test.ts +1 -1
  185. package/{linter.test.ts → lint/linter.test.ts} +1 -1
  186. package/lint/no-import-common-err.grit +31 -0
  187. package/lint/no-init-fetch-in-client.grit +1 -1
  188. package/lint/no-web-only-api-outside-webkit.grit +3 -3
  189. package/mobile/desktopBin.test.ts +1 -1
  190. package/mobile/desktopRelease.test.ts +1 -1
  191. package/mobile/desktopServerStage.test.ts +2 -2
  192. package/mobile/desktopServerStage.ts +1 -1
  193. package/mobile/nativeApi.test.ts +1 -1
  194. package/mobile/nativeApp.test.ts +1 -1
  195. package/mobile/nativeConfig.test.ts +1 -1
  196. package/mobile/nativePluginFolders.test.ts +1 -1
  197. package/mobile/nativePublicEnv.test.ts +1 -1
  198. package/mobile/nativeWebDir.test.ts +1 -1
  199. package/mobile/serverBundleSecrets.test.ts +1 -1
  200. package/mobile/tarWriter.test.ts +1 -1
  201. package/mobile/updatePackFolder.test.ts +1 -1
  202. package/package.json +167 -3
  203. package/packageExports.test.ts +20 -2
  204. package/piDependencyPins.test.ts +1 -1
  205. package/pipeline/PipelineDefinition.ts +1 -1
  206. package/platformTest/IdleWatchedProcess.test.ts +1 -1
  207. package/platformTest/PlatformTestRun.test.ts +1 -1
  208. package/platformTest/TestSnapshot.test.ts +1 -1
  209. package/preview/PreviewView.ts +32 -11
  210. package/preview/previewView.test.ts +76 -9
  211. package/{abstractDoc.test.ts → quality/abstractDoc.test.ts} +2 -2
  212. package/{abstractDoc.ts → quality/abstractDoc.ts} +1 -1
  213. package/quality/bareErrorScanner.ts +126 -0
  214. package/{maintainabilityBaseline.test.ts → quality/maintainabilityBaseline.test.ts} +73 -0
  215. package/{maintainabilityBaseline.ts → quality/maintainabilityBaseline.ts} +97 -9
  216. package/{maintainabilityContract.test.ts → quality/maintainabilityContract.test.ts} +383 -2
  217. package/{maintainabilityContract.ts → quality/maintainabilityContract.ts} +151 -29
  218. package/{maintainabilityExceptionScanner.test.ts → quality/maintainabilityExceptionScanner.test.ts} +15 -1
  219. package/{maintainabilityExceptionScanner.ts → quality/maintainabilityExceptionScanner.ts} +5 -1
  220. package/{maintainabilityLimits.ts → quality/maintainabilityLimits.ts} +12 -0
  221. package/{maintainabilityReport.ts → quality/maintainabilityReport.ts} +20 -3
  222. package/{qualityScanner.test.ts → quality/qualityScanner.test.ts} +1 -1
  223. package/{qualityScanner.ts → quality/qualityScanner.ts} +8 -8
  224. package/{storeAccessScanner.ts → quality/storeAccessScanner.ts} +15 -2
  225. package/{subspace.test.ts → subspace/subspace.test.ts} +9 -3
  226. package/{subspace.ts → subspace/subspace.ts} +5 -5
  227. package/{subspaceClone.ts → subspace/subspaceClone.ts} +8 -8
  228. package/{subspaceConfig.ts → subspace/subspaceConfig.ts} +5 -1
  229. package/{testHelpers.ts → test/testHelpers.ts} +37 -1
  230. package/transforms/barrelAnalyzer.ts +26 -8
  231. package/transforms/browserDirnamePlugin.test.ts +1 -1
  232. package/transforms/externalizeFrameworkPlugin.test.ts +1 -1
  233. package/transforms/mcpAppPageTrimmer.test.ts +1 -1
  234. package/transforms/pureLazyMarker.test.ts +1 -1
  235. package/transforms/serverEnvPlugin.test.ts +1 -1
  236. package/transforms/serverEnvProfile.test.ts +1 -1
  237. package/transforms/sideEffectImportOrder.test.ts +1 -1
  238. package/transforms/transforms.test.ts +29 -2
  239. package/transforms/tsconfigPackageResolver.test.ts +1 -1
  240. package/{createTunnel.test.ts → tunnel/createTunnel.test.ts} +1 -1
  241. package/{createTunnel.ts → tunnel/createTunnel.ts} +2 -2
  242. package/{sshHostKeys.ts → tunnel/sshHostKeys.ts} +2 -2
  243. package/typecheck/projectTypecheck.test.ts +1 -1
  244. package/typecheck/projectTypecheck.ts +6 -2
  245. package/{typeChecker.test.ts → typecheck/typeChecker.test.ts} +1 -1
  246. package/{typeChecker.ts → typecheck/typeChecker.ts} +1 -1
  247. package/typecheck/typecheck.proc.ts +4 -3
  248. package/typecheck/typecheckFailure.ts +7 -2
  249. package/util/errorReport.ts +66 -0
  250. package/{jsonFormatter.test.ts → util/jsonFormatter.test.ts} +1 -1
  251. package/workflow/artifacts.ts +8 -7
  252. package/workflow/constantSource.ts +187 -0
  253. package/workflow/dictionarySource.ts +184 -0
  254. package/workflow/executor.ts +6 -9
  255. package/workflow/fieldExpression.ts +153 -0
  256. package/workflow/fieldLabel.ts +61 -0
  257. package/workflow/fieldOrder.ts +117 -0
  258. package/workflow/fieldType.ts +93 -0
  259. package/workflow/guardCatalog.test.ts +1 -1
  260. package/workflow/index.ts +2 -0
  261. package/workflow/keyRename.ts +1 -1
  262. package/workflow/moduleIndex.test.ts +2 -2
  263. package/workflow/moduleIndex.ts +2 -2
  264. package/workflow/modulePaths.ts +27 -0
  265. package/workflow/mutationScaffold.ts +7 -15
  266. package/workflow/mutationSource.ts +2 -1
  267. package/workflow/plainName.ts +28 -0
  268. package/workflow/plan.ts +15 -9
  269. package/workflow/primitiveReport.ts +78 -0
  270. package/workflow/rolloutGate.test.ts +1 -1
  271. package/workflow/rolloutGate.ts +1 -1
  272. package/workflow/serviceSource.ts +33 -0
  273. package/workflow/signalSource.ts +96 -0
  274. package/workflow/source.ts +50 -1105
  275. package/workflow/sourceAst.ts +30 -0
  276. package/workflow/sourceImports.ts +105 -0
  277. package/workflow/sourceText.ts +13 -0
  278. package/workflow/templateSource.ts +30 -0
  279. package/workflow/testSource.ts +31 -0
  280. package/workflow/types.ts +1 -1
  281. package/workflow/uiPolicy.ts +1 -1
  282. package/{appSelectionMemory.ts → workspace/appSelectionMemory.ts} +1 -1
  283. package/{codegenLock.test.ts → workspace/codegenLock.test.ts} +1 -1
  284. package/{dependencyScanner.test.ts → workspace/dependencyScanner.test.ts} +1 -1
  285. package/{dependencyScanner.ts → workspace/dependencyScanner.ts} +2 -2
  286. package/{envSeed.test.ts → workspace/envSeed.test.ts} +2 -2
  287. package/{envSeed.ts → workspace/envSeed.ts} +1 -1
  288. package/{libSource.test.ts → workspace/libSource.test.ts} +2 -2
  289. package/{libSource.ts → workspace/libSource.ts} +1 -1
  290. package/{scanInfo.ts → workspace/scanInfo.ts} +21 -10
  291. package/{slicePlanner.test.ts → workspace/slicePlanner.test.ts} +2 -2
  292. package/{slicePlanner.ts → workspace/slicePlanner.ts} +1 -1
  293. package/{workspaceGraph.test.ts → workspace/workspaceGraph.test.ts} +85 -1
  294. package/{workspaceGraph.ts → workspace/workspaceGraph.ts} +41 -6
  295. package/{workspaceLayout.test.ts → workspace/workspaceLayout.test.ts} +1 -1
  296. package/{workspaceLayout.ts → workspace/workspaceLayout.ts} +3 -1
  297. package/akanContext.ts +0 -1084
  298. package/constantFieldNames.ts +0 -18
  299. package/executors.ts +0 -1749
  300. /package/{recipeScanner.ts → context/recipeScanner.ts} +0 -0
  301. /package/{declarationReader.ts → docs/declarationReader.ts} +0 -0
  302. /package/{frameworkGraph.ts → docs/frameworkGraph.ts} +0 -0
  303. /package/{biomeBase.ts → lint/biomeBase.ts} +0 -0
  304. /package/{linter.ts → lint/linter.ts} +0 -0
  305. /package/{commentDensityScanner.test.ts → quality/commentDensityScanner.test.ts} +0 -0
  306. /package/{commentDensityScanner.ts → quality/commentDensityScanner.ts} +0 -0
  307. /package/{componentSizeScanner.test.ts → quality/componentSizeScanner.test.ts} +0 -0
  308. /package/{componentSizeScanner.ts → quality/componentSizeScanner.ts} +0 -0
  309. /package/{componentWriteChainScanner.test.ts → quality/componentWriteChainScanner.test.ts} +0 -0
  310. /package/{componentWriteChainScanner.ts → quality/componentWriteChainScanner.ts} +0 -0
  311. /package/{deprecatedCommentScanner.test.ts → quality/deprecatedCommentScanner.test.ts} +0 -0
  312. /package/{deprecatedCommentScanner.ts → quality/deprecatedCommentScanner.ts} +0 -0
  313. /package/{endpointReach.test.ts → quality/endpointReach.test.ts} +0 -0
  314. /package/{endpointReach.ts → quality/endpointReach.ts} +0 -0
  315. /package/{formSetterScanner.test.ts → quality/formSetterScanner.test.ts} +0 -0
  316. /package/{formSetterScanner.ts → quality/formSetterScanner.ts} +0 -0
  317. /package/{kindBranchScanner.test.ts → quality/kindBranchScanner.test.ts} +0 -0
  318. /package/{kindBranchScanner.ts → quality/kindBranchScanner.ts} +0 -0
  319. /package/{maintainabilityReport.test.ts → quality/maintainabilityReport.test.ts} +0 -0
  320. /package/{renderMutationScanner.test.ts → quality/renderMutationScanner.test.ts} +0 -0
  321. /package/{renderMutationScanner.ts → quality/renderMutationScanner.ts} +0 -0
  322. /package/{serviceLoopCallScanner.test.ts → quality/serviceLoopCallScanner.test.ts} +0 -0
  323. /package/{serviceLoopCallScanner.ts → quality/serviceLoopCallScanner.ts} +0 -0
  324. /package/{signalMutationIndex.test.ts → quality/signalMutationIndex.test.ts} +0 -0
  325. /package/{signalMutationIndex.ts → quality/signalMutationIndex.ts} +0 -0
  326. /package/{sourceComments.test.ts → quality/sourceComments.test.ts} +0 -0
  327. /package/{sourceComments.ts → quality/sourceComments.ts} +0 -0
  328. /package/{ssrScanner.test.ts → quality/ssrScanner.test.ts} +0 -0
  329. /package/{ssrScanner.ts → quality/ssrScanner.ts} +0 -0
  330. /package/{storeAccessScanner.test.ts → quality/storeAccessScanner.test.ts} +0 -0
  331. /package/{storeSource.ts → quality/storeSource.ts} +0 -0
  332. /package/{storeWriteScanner.test.ts → quality/storeWriteScanner.test.ts} +0 -0
  333. /package/{storeWriteScanner.ts → quality/storeWriteScanner.ts} +0 -0
  334. /package/{structureScanner.test.ts → quality/structureScanner.test.ts} +0 -0
  335. /package/{structureScanner.ts → quality/structureScanner.ts} +0 -0
  336. /package/{testOnlyExportScanner.test.ts → quality/testOnlyExportScanner.test.ts} +0 -0
  337. /package/{testOnlyExportScanner.ts → quality/testOnlyExportScanner.ts} +0 -0
  338. /package/{writePath.test.ts → quality/writePath.test.ts} +0 -0
  339. /package/{writePath.ts → quality/writePath.ts} +0 -0
  340. /package/{writePlacementScanner.test.ts → quality/writePlacementScanner.test.ts} +0 -0
  341. /package/{writePlacementScanner.ts → quality/writePlacementScanner.ts} +0 -0
  342. /package/{writingActionIndex.test.ts → quality/writingActionIndex.test.ts} +0 -0
  343. /package/{writingActionIndex.ts → quality/writingActionIndex.ts} +0 -0
  344. /package/{subspaceReport.ts → subspace/subspaceReport.ts} +0 -0
  345. /package/{sshTunnel.ts → tunnel/sshTunnel.ts} +0 -0
  346. /package/{fileEditor.ts → util/fileEditor.ts} +0 -0
  347. /package/{fileSys.test.ts → util/fileSys.test.ts} +0 -0
  348. /package/{fileSys.ts → util/fileSys.ts} +0 -0
  349. /package/{jsonFormatter.ts → util/jsonFormatter.ts} +0 -0
  350. /package/{selectModel.ts → util/selectModel.ts} +0 -0
  351. /package/{semver.test.ts → util/semver.test.ts} +0 -0
  352. /package/{semver.ts → util/semver.ts} +0 -0
  353. /package/{shellOnlyEnv.test.ts → util/shellOnlyEnv.test.ts} +0 -0
  354. /package/{shellOnlyEnv.ts → util/shellOnlyEnv.ts} +0 -0
  355. /package/{spinner.test.ts → util/spinner.test.ts} +0 -0
  356. /package/{spinner.ts → util/spinner.ts} +0 -0
  357. /package/{stripAnsi.ts → util/stripAnsi.ts} +0 -0
  358. /package/{codegenLock.ts → workspace/codegenLock.ts} +0 -0
  359. /package/{getRelatedCnsts.ts → workspace/getRelatedCnsts.ts} +0 -0
  360. /package/{gitRevision.test.ts → workspace/gitRevision.test.ts} +0 -0
  361. /package/{gitRevision.ts → workspace/gitRevision.ts} +0 -0
  362. /package/{manifestDependencies.ts → workspace/manifestDependencies.ts} +0 -0
  363. /package/{packageExportsMap.ts → workspace/packageExportsMap.ts} +0 -0
  364. /package/{repoIdentity.ts → workspace/repoIdentity.ts} +0 -0
  365. /package/{types.ts → workspace/types.ts} +0 -0
@@ -1,23 +1,12 @@
1
- import { rm } from "node:fs/promises";
2
1
  import path from "node:path";
3
2
  // Module paths, never a barrel: the devkit and `frontendBuild` barrels would hold tailwindcss (~40MB), ssh2, ink
4
3
  // and the cloud stack for the whole dev session (`entryModuleGraph.test.ts` enforces it).
5
- import { ApplicationBuildReporter } from "@akanjs/devkit/applicationBuildReporter";
6
- import { CodegenLock } from "@akanjs/devkit/codegenLock";
4
+ import { ApplicationBuildReporter } from "@akanjs/devkit/app/applicationBuildReporter";
7
5
  import type { App } from "@akanjs/devkit/commandDecorators";
8
6
  import { AppExecutor, type PageRoot, WorkspaceExecutor } from "@akanjs/devkit/executors";
9
- import { AutoImportSync } from "@akanjs/devkit/frontendBuild/autoImportSync";
10
7
  import type { ClientEntryDiscovery } from "@akanjs/devkit/frontendBuild/clientBuildTypes";
11
8
  import { GraphClientEntryDiscovery } from "@akanjs/devkit/frontendBuild/clientEntryDiscovery";
12
- import { CsrDevBundler } from "@akanjs/devkit/frontendBuild/csrDevBundler";
13
- import { CsrDevPatcher } from "@akanjs/devkit/frontendBuild/csrDevPatcher";
14
- import { DevChangePlanner } from "@akanjs/devkit/frontendBuild/devChangePlanner";
15
- import { DevGeneratedIndexSync } from "@akanjs/devkit/frontendBuild/devGeneratedIndexSync";
16
- import { HmrWatcher } from "@akanjs/devkit/frontendBuild/hmrWatcher";
17
9
  import { RouteClientBuilder } from "@akanjs/devkit/frontendBuild/routeClientBuilder";
18
- import { ServerGraphFile } from "@akanjs/devkit/frontendBuild/serverGraphFile";
19
- import { SsrDevBundler } from "@akanjs/devkit/frontendBuild/ssrDevBundler";
20
- import { WatchRootResolver } from "@akanjs/devkit/frontendBuild/watchRootResolver";
21
10
  import { Logger } from "akanjs/common";
22
11
  import type {
23
12
  BaseBuildArtifact,
@@ -26,30 +15,20 @@ import type {
26
15
  BuilderMessage,
27
16
  BuilderReq,
28
17
  BuilderRes,
29
- BuildPhase,
30
18
  BuildRouteResultPayload,
31
19
  ChangeBatch,
32
- HmrTrace,
33
20
  } from "akanjs/server";
34
- import { CSR_DEV_PATCHING_MARKER } from "akanjs/server/hmr/csrDevManifest";
35
- import type { BuildBatchNeed, BuildBatchRequest, BuildBatchResult, OptimizedFonts } from "./buildBatchProtocol";
21
+ import type { BatchWork, BuildBatchRequest, BuildBatchResult, OptimizedFonts } from "./buildBatchProtocol";
36
22
  import { BuildBatchRunner } from "./buildBatchRunner";
23
+ import { BuilderBoot, type IncrementalBuilderOptions } from "./builderBoot";
24
+ import { sendBuildStatus } from "./builderBuildStatus";
37
25
  import { BuilderChannel } from "./builderChannel";
38
26
  import { BuilderGraphPayloads } from "./builderGraphPayloads";
39
- import { type BatchJob, BuilderWorkQueue, type DiscoveryJob } from "./builderWorkQueue";
40
- import { prepareDevWatchBatch } from "./devWatchBatch";
41
-
42
- interface IncrementalBuilderOptions {
43
- app: App;
44
- artifact: BaseBuildArtifact;
45
- watch: boolean;
46
- optimizedFonts: OptimizedFonts;
47
- discovery: ClientEntryDiscovery;
48
- initialGeneration?: number;
49
- }
50
-
51
- type IncrementalBuilderBootDeps = Pick<IncrementalBuilderOptions, "artifact" | "optimizedFonts" | "discovery">;
52
- type BatchWork = Pick<BuildBatchRequest, "generation" | "needs" | "changedFiles" | "trace">;
27
+ import { BuilderLanes } from "./builderLanes";
28
+ import { BuilderWatch } from "./builderWatch";
29
+ import type { BatchJob, DiscoveryJob } from "./builderWorkQueue";
30
+ import { CsrRegistry } from "./csrRegistry";
31
+ import { SsrRegistry } from "./ssrRegistry";
53
32
 
54
33
  class IncrementalBuilder {
55
34
  #logger = new Logger("IncrementalBuilder");
@@ -60,56 +39,15 @@ class IncrementalBuilder {
60
39
  #optimizedFonts: OptimizedFonts;
61
40
  #discovery: ClientEntryDiscovery;
62
41
  #batchRunner: BuildBatchRunner;
63
- #changePlanner: DevChangePlanner;
64
- #generatedIndexSync: DevGeneratedIndexSync;
65
- #autoImportSync: AutoImportSync;
66
- #watcher: HmrWatcher | null = null;
67
42
  #generation = 0;
68
- #shellKey: string | null = null;
69
43
  readonly #graphPayloads: BuilderGraphPayloads;
70
44
  #discoveredThrough = 0;
71
- #csrActive = IncrementalBuilder.#csrArmedByEnv();
72
- #csrBundler: CsrDevBundler;
73
- /** Null when `AKAN_DEV_CSR_PATCHER=off`: every CSR save then goes to a build worker, as before the patcher. */
74
- #patcher: CsrDevPatcher | null;
75
- /** A worker's full CSR build (arming, re-arming) that a patch must not race for the csr-dev directory. */
76
- #csrGate: Promise<void> = Promise.resolve();
77
- #csrArming = false;
78
- #csrArms = 0;
79
- #crashRetryTimer: ReturnType<typeof setTimeout> | null = null;
80
- readonly #crashRetryEntries = new Set<string>();
81
- #csrWasActive = false;
82
- #csrArmSucceeded = false;
83
- /** Where SSR pages load their client code from in dev; route builds bundle only its server half. */
84
- #ssrBundler: SsrDevBundler;
85
- /** Null when `AKAN_DEV_CSR_PATCHER=off`: every registry save then goes to a build worker. */
86
- #ssrPatcher: CsrDevPatcher | null;
87
- //* Serializes everything that writes ssr-dev: a save's patch (fast lane), a route build adding the entries it names,
88
- //* a queued worker batch with the ssr need, and the boot build. Never held while awaiting the slow lane.
89
- #ssrLock: Promise<void> = Promise.resolve();
90
45
  /** How often each reason sent a registry save to a build worker this session: the resident patcher's miss rate. */
91
46
  readonly #delegations = new Map<string, number>();
92
- /** The boot build of the SSR registry while it runs; it holds every entry the routes reach once it lands. */
93
- #ssrArming: Promise<void> | null = null;
94
- //* A registry build that failed on the user's code fails again until the code changes, so route builds do not retry
95
- //* it; the next attempt that touches the registry (a save's patch, a worker batch) settles it. A worker that died
96
- //* before reporting (an OOM kill) route builds do retry, at most every `#crashRetryMs`.
97
- #ssrBroken = false;
98
- #ssrCrashedAt: number | null = null;
99
- static readonly #crashRetryMs = 10_000;
100
- /** Arming and the route entries deferred behind it run beside both lanes; a recycle waits for them too. */
101
- readonly #beside = new Set<Promise<void>>();
102
- #barrelFailed = false;
103
- //* Two lanes: a save's codegen and CSR patch in the fast one, which the watcher waits for; build workers, route
104
- //* builds and discovery in the slow one, which folds queued batches. A save no longer waits behind pages and css.
105
- #fastQueue: Promise<void> = Promise.resolve();
106
- #workQueue: BuilderWorkQueue;
107
- #inFlight = 0;
108
- #workCount = 0;
109
- #shuttingDown = false;
110
- #cssRebuildQueue: Promise<void> = Promise.resolve();
111
- #cssRebuildTimer: ReturnType<typeof setTimeout> | null = null;
112
- #pendingCssRebuild: { generation?: number; changedFiles?: string[] } | null = null;
47
+ readonly #lanes: BuilderLanes;
48
+ readonly #csr: CsrRegistry;
49
+ readonly #ssr: SsrRegistry;
50
+ readonly #watcher: BuilderWatch;
113
51
  constructor(options: IncrementalBuilderOptions) {
114
52
  this.#app = options.app;
115
53
  this.#artifact = options.artifact;
@@ -123,23 +61,31 @@ class IncrementalBuilder {
123
61
  workspaceRoot: options.app.workspace.workspaceRoot,
124
62
  cwd: options.app.cwdPath,
125
63
  });
126
- this.#changePlanner = new DevChangePlanner({ workspaceRoot: options.app.workspace.workspaceRoot });
127
- this.#generatedIndexSync = new DevGeneratedIndexSync({ workspaceRoot: options.app.workspace.workspaceRoot });
128
- this.#autoImportSync = new AutoImportSync({ workspaceRoot: options.app.workspace.workspaceRoot });
129
- this.#csrBundler = new CsrDevBundler(options.app);
130
- this.#patcher =
131
- process.env.AKAN_DEV_CSR_PATCHER === "off" ? null : new CsrDevPatcher(this.#csrBundler, { resident: true });
132
- this.#ssrBundler = new SsrDevBundler(options.app, { discovery: () => this.#discovery });
133
- this.#ssrPatcher =
134
- process.env.AKAN_DEV_CSR_PATCHER === "off" ? null : new CsrDevPatcher(this.#ssrBundler, { resident: true });
135
- this.#workQueue = new BuilderWorkQueue({
136
- runBatch: async (batch) => await this.#runQueuedBatch(batch),
137
- onSettled: (label, ms) => {
138
- this.#workCount += 1;
139
- this.#logger.verbose(`[work-queue] ${label} finished in ${ms}ms`);
140
- this.#reportMetrics();
141
- },
142
- });
64
+ const logger = this.#logger;
65
+ const generation = () => this.#generation;
66
+ const countDelegation = (registry: "csr" | "ssr", reason: string) => this.#countDelegation(registry, reason);
67
+ const runBatch = (work: BatchWork) => this.#runBatch(work);
68
+ this.#lanes = new BuilderLanes(
69
+ options.app,
70
+ { logger },
71
+ { generation, runQueuedBatch: (batch) => this.#runQueuedBatch(batch), runBatch },
72
+ );
73
+ const lanes = this.#lanes;
74
+ this.#csr = new CsrRegistry(
75
+ options.app,
76
+ { logger, lanes, batchRunner: this.#batchRunner },
77
+ { generation, artifact: () => this.#artifact, batchRequest: (work) => this.#batchRequest(work), countDelegation },
78
+ );
79
+ this.#ssr = new SsrRegistry(
80
+ options.app,
81
+ { logger, lanes, artifactDir: this.#artifactDir },
82
+ { generation, discovery: () => this.#discovery, runBatch, countDelegation },
83
+ );
84
+ this.#watcher = new BuilderWatch(
85
+ options.app,
86
+ { logger, lanes, csr: this.#csr, ssr: this.#ssr, graphPayloads: this.#graphPayloads },
87
+ { nextGeneration: () => ++this.#generation, refreshDiscovery: (job) => this.#refreshDiscovery(job) },
88
+ );
143
89
  }
144
90
 
145
91
  get #artifactDir() {
@@ -148,7 +94,7 @@ class IncrementalBuilder {
148
94
 
149
95
  // The reply is part of the work item on purpose: `shutdown` drains the queue, so "drained" must mean "answered".
150
96
  async handleBuildRoute(msg: BuilderReq): Promise<void> {
151
- await this.#workQueue.enqueue(`build-route:${msg.routeId}`, async () =>
97
+ await this.#lanes.workQueue.enqueue(`build-route:${msg.routeId}`, async () =>
152
98
  BuilderChannel.send(await this.#handleBuildRoute(msg)),
153
99
  );
154
100
  }
@@ -166,11 +112,11 @@ class IncrementalBuilder {
166
112
  discovery: this.#discovery,
167
113
  browser: "registry",
168
114
  }).build();
169
- await this.#ensureSsrEntries(delta.registryEntries ?? []);
115
+ await this.#ssr.ensureSsrEntries(delta.registryEntries ?? []);
170
116
  this.#logger.verbose(`build-route ok routeId=${msg.routeId} newEntries=${delta.newEntries.length}`);
171
117
  //? The builder's generation, not the route cache's: the cache's does not move when a fixed file maps to no entry,
172
118
  //? so the rebuild's ok would carry the failure's own number.
173
- this.#sendBuildStatus("route", { generation: this.#generation, ok: true, files: msg.seeds, scope: msg.routeId });
119
+ sendBuildStatus("route", { generation: this.#generation, ok: true, files: msg.seeds, scope: msg.routeId });
174
120
  return {
175
121
  type: "build-route-res",
176
122
  id: msg.id,
@@ -190,7 +136,7 @@ class IncrementalBuilder {
190
136
  } catch (err) {
191
137
  const errMsg = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
192
138
  this.#logger.error(`build-route failed routeId=${msg.routeId}: ${errMsg}`);
193
- this.#sendBuildStatus("route", {
139
+ sendBuildStatus("route", {
194
140
  generation: this.#generation,
195
141
  ok: false,
196
142
  files: msg.seeds,
@@ -200,82 +146,17 @@ class IncrementalBuilder {
200
146
  return { type: "build-route-res", id: msg.id, ok: false, error: errMsg };
201
147
  }
202
148
  }
203
- #sendBuildStatus(
204
- phase: BuildPhase,
205
- {
206
- generation,
207
- ok,
208
- files,
209
- message,
210
- scope,
211
- }: { generation?: number; ok: boolean; files?: string[]; message?: string; scope?: string },
212
- ): void {
213
- if (typeof generation !== "number") return;
214
- BuilderChannel.emit({
215
- type: "build-status",
216
- data: { generation, phase, ok, files: files ?? [], message, ...(scope !== undefined ? { scope } : {}) },
217
- });
218
- }
219
- async #enqueueFast<T>(label: string, fn: () => Promise<T>): Promise<T> {
220
- const started = Date.now();
221
- this.#inFlight += 1;
222
- const run = this.#fastQueue.then(fn, fn);
223
- this.#fastQueue = run.then(() => undefined).catch(() => undefined);
224
- try {
225
- return await run;
226
- } finally {
227
- this.#inFlight -= 1;
228
- this.#workCount += 1;
229
- this.#logger.verbose(`[fast-queue] ${label} finished in ${Date.now() - started}ms`);
230
- this.#reportMetrics();
231
- }
232
- }
233
-
234
- get #idle(): boolean {
235
- return this.#inFlight === 0 && this.#workQueue.size === 0 && this.#cssRebuildTimer === null;
236
- }
237
-
238
- // Callers catch their own errors: the promise handed in never rejects.
239
- #runBeside(work: Promise<void>): Promise<void> {
240
- this.#inFlight += 1;
241
- const tracked: Promise<void> = work.finally(() => {
242
- this.#inFlight -= 1;
243
- this.#beside.delete(tracked);
244
- this.#reportMetrics();
245
- });
246
- this.#beside.add(tracked);
247
- return tracked;
248
- }
249
-
250
- // Idle only: the host recycles on these metrics, and a recycle decided mid-work would truncate it or race the drain.
251
- #reportMetrics(): void {
252
- if (!this.#idle || this.#shuttingDown) return;
253
- BuilderChannel.emit({
254
- type: "builder-metrics",
255
- data: { rssBytes: process.memoryUsage.rss(), generation: this.#generation, workCount: this.#workCount },
256
- });
257
- }
258
149
 
259
150
  // Exits so the OS reclaims the bundler arenas; the host spawns the replacement.
260
151
  async shutdown(reason: string): Promise<void> {
261
- if (this.#shuttingDown) return;
262
- this.#shuttingDown = true;
152
+ if (this.#lanes.shuttingDown) return;
153
+ this.#lanes.markShuttingDown();
263
154
  const started = Date.now();
264
- this.#logger.debug(`shutdown requested (${reason}); draining ${this.#inFlight} work item(s)`);
155
+ this.#logger.debug(`shutdown requested (${reason}); draining ${this.#lanes.inFlight} work item(s)`);
265
156
  // Before the drain: a save landing mid-drain would queue behind the awaited tail and `process.exit` would cut
266
157
  // its artifacts off half-written; the replacement's boot build redoes that work anyway.
267
- this.#watcher?.stop();
268
- if (this.#cssRebuildTimer) {
269
- // Only if css landed after the idle report; the replacement's boot build recompiles css, so nothing is lost.
270
- clearTimeout(this.#cssRebuildTimer);
271
- this.#cssRebuildTimer = null;
272
- this.#pendingCssRebuild = null;
273
- }
274
- // The fast lane first: a save it is still handling may queue a batch in the slow one.
275
- await this.#fastQueue.catch(() => undefined);
276
- await this.#workQueue.drain();
277
- await this.#cssRebuildQueue.catch(() => undefined);
278
- while (this.#beside.size > 0) await Promise.all([...this.#beside]);
158
+ this.#watcher.stop();
159
+ await this.#lanes.drain();
279
160
  if (this.#delegations.size > 0)
280
161
  this.#logger.verbose(
281
162
  `registry saves handed to build workers this session: ${[...this.#delegations].map(([reason, count]) => `${reason}=${count}`).join(", ")}`,
@@ -289,371 +170,23 @@ class IncrementalBuilder {
289
170
  }
290
171
 
291
172
  get shuttingDown(): boolean {
292
- return this.#shuttingDown;
293
- }
294
- //* Watch events carry real paths: synced lib pages match by `realDir`, their keys keep the `(libs)/(<lib>)` prefix.
295
- static #matchPageRoot(roots: PageRoot[], abs: string): PageRoot | null {
296
- for (const root of roots) {
297
- const absRoot = path.resolve(root.realDir);
298
- if (abs === absRoot || abs.startsWith(`${absRoot}${path.sep}`)) return root;
299
- }
300
- return null;
173
+ return this.#lanes.shuttingDown;
301
174
  }
302
175
  batchTouchesPagesTree(roots: PageRoot[], batch: ChangeBatch): boolean {
303
- for (const f of batch.files) {
304
- const abs = path.resolve(f);
305
- if (!IncrementalBuilder.#matchPageRoot(roots, abs)) continue;
306
- if (/\.(tsx|ts|jsx|js)$/.test(abs)) return true;
307
- }
308
- return false;
176
+ return this.#watcher.batchTouchesPagesTree(roots, batch);
309
177
  }
310
- async batchMayChangePageKeys(roots: PageRoot[], batch: ChangeBatch): Promise<boolean> {
311
- const pageKeys = new Set((await this.#app.getPageKeys()).map((key) => path.normalize(key)));
312
- for (const f of batch.files) {
313
- const abs = path.resolve(f);
314
- const root = IncrementalBuilder.#matchPageRoot(roots, abs);
315
- if (!root) continue;
316
- if (!/\.(tsx|ts|jsx|js)$/.test(abs)) continue;
317
- const rel = path.normalize(`${root.keyPrefix}${path.relative(path.resolve(root.realDir), abs)}`);
318
- if (!(await Bun.file(abs).exists()) || !pageKeys.has(rel)) return true;
319
- }
320
- return false;
178
+ batchMayChangePageKeys(roots: PageRoot[], batch: ChangeBatch): Promise<boolean> {
179
+ return this.#watcher.batchMayChangePageKeys(roots, batch);
321
180
  }
322
- scheduleCssRebuild({ generation, changedFiles }: { generation?: number; changedFiles?: string[] }) {
323
- this.#pendingCssRebuild = { generation, changedFiles };
324
- if (this.#cssRebuildTimer) clearTimeout(this.#cssRebuildTimer);
325
- this.#cssRebuildTimer = setTimeout(() => {
326
- this.#cssRebuildTimer = null;
327
- const next = this.#pendingCssRebuild;
328
- this.#pendingCssRebuild = null;
329
- if (!next) return;
330
- this.#inFlight += 1;
331
- this.#cssRebuildQueue = this.#cssRebuildQueue
332
- .then(async () => {
333
- await this.#runBatch({
334
- generation: next.generation ?? this.#generation,
335
- needs: ["css"],
336
- changedFiles: next.changedFiles ?? [],
337
- });
338
- })
339
- .catch((err) => {
340
- const message = err instanceof Error ? err.message : String(err);
341
- this.#logger.error(`css-rebuild failed: ${message}`);
342
- this.#sendBuildStatus("css", {
343
- generation: next.generation,
344
- ok: false,
345
- files: next.changedFiles,
346
- message,
347
- });
348
- })
349
- .finally(() => {
350
- this.#inFlight -= 1;
351
- this.#reportMetrics();
352
- });
353
- }, 150);
181
+ scheduleCssRebuild(rebuild: { generation?: number; changedFiles?: string[] }) {
182
+ this.#lanes.scheduleCssRebuild(rebuild);
354
183
  }
355
- async installWatcher() {
356
- const roots = await new WatchRootResolver(this.#app).resolve();
357
- const watcher = new HmrWatcher({
358
- roots,
359
- logger: this.#logger,
360
- onBatch: async (batch: ChangeBatch) => {
361
- await this.#enqueueFast("hmr-batch", async () => this.#handleWatchBatch(batch));
362
- },
363
- });
364
- await watcher.start();
365
- this.#watcher = watcher;
366
- this.#logger.verbose(`watching ${roots.length} roots`);
184
+ installWatcher(): Promise<void> {
185
+ return this.#watcher.installWatcher();
367
186
  }
368
187
 
369
- async #handleWatchBatch(batch: ChangeBatch) {
370
- this.#graphPayloads.touched(batch.files);
371
- const rawKinds = new Set(batch.kinds);
372
- if (rawKinds.size === 0) return;
373
- const generation = ++this.#generation;
374
- const trace = { ...batch.trace, batchAt: Date.now() };
375
- //* Auto-import edits touch only this batch's files, so they rebuild in this same generation.
376
- const [autoImport, indexSync] = await CodegenLock.run(
377
- this.#app.workspace.workspaceRoot,
378
- `hmr-batch:${this.#app.name}`,
379
- async () => {
380
- const auto = await this.#autoImportSync.syncForBatch(batch.files);
381
- return [auto, await this.#generatedIndexSync.syncForBatch(batch.files)] as const;
382
- },
383
- );
384
- for (const error of autoImport.errors) this.#logger.error(error);
385
- if (autoImport.changedFiles.length > 0)
386
- this.#logger.verbose(`[auto-import] inserted imports into ${autoImport.changedFiles.length} file(s)`);
387
- //* Absorbed so the watcher's verification scan does not replay these writes as a user edit next generation.
388
- await this.#watcher?.absorb([...autoImport.changedFiles, ...indexSync.changedFiles]);
389
- const { files, kinds, expandedBatch, devPlan, event, hasSyncErrors } = prepareDevWatchBatch({
390
- generation,
391
- batch,
392
- indexSync,
393
- changePlanner: this.#changePlanner,
394
- });
395
- this.#logger.verbose(
396
- `[hmr] batch generation=${generation} kinds=${kinds.join(",")} files=${files.length} generated=${indexSync.changedFiles.length} roles=${devPlan.roles.join(",") || "(none)"} actions=${devPlan.actions.join(",") || "(none)"}`,
397
- );
398
- for (const error of indexSync.errors) this.#logger.error(error);
399
-
400
- // Invalidated in the slow lane, under the route builds that read it; a registry check reading it beside them caches
401
- // nothing a walk began before the invalidation (the discovery's epoch).
402
- const discovery = kinds.includes("code") ? { files, refresh: kinds.includes("config"), generation } : undefined;
403
-
404
- if (hasSyncErrors) {
405
- this.#barrelFailed = true;
406
- this.#sendBuildStatus("barrel", { generation, ok: false, files, message: indexSync.errors.join("\n") });
407
- BuilderChannel.emit(event);
408
- if (discovery)
409
- void this.#workQueue
410
- .enqueue("discovery", async () => await this.#refreshDiscovery(discovery))
411
- .catch(this.#slowLaneFailed("discovery"));
412
- return;
413
- }
414
- // After a failure too, where nothing changed on disk: the host re-sends a phase still failing to every new tab.
415
- if (indexSync.changedFiles.length > 0 || this.#barrelFailed)
416
- this.#sendBuildStatus("barrel", { generation, ok: true, files });
417
- this.#barrelFailed = false;
418
-
419
- // Server-only generations skip the client: a fresh pages buildId would rsc-refresh browsers for no visible change.
420
- const rebuildClient = devPlan.actions.includes("rebuild-client");
421
- if (kinds.includes("code") && !rebuildClient) {
422
- this.#logger.verbose(`client rebuild skipped; devPlan actions=${devPlan.actions.join(",") || "(none)"}`);
423
- }
424
-
425
- const pageRoots = await this.#app.getPageRoots();
426
- if (kinds.includes("code") && rebuildClient && (await this.batchMayChangePageKeys(pageRoots, expandedBatch))) {
427
- const started = Date.now();
428
- await this.#app.getPageKeys({ refresh: true });
429
- this.#logger.verbose(`pageKeys updated, app pageKeys are refreshed (${Date.now() - started}ms)`);
430
- } else if (kinds.includes("code") && rebuildClient && this.batchTouchesPagesTree(pageRoots, expandedBatch)) {
431
- this.#logger.verbose("pageKeys refresh skipped; changed page source cannot add/remove a route key");
432
- }
433
-
434
- BuilderChannel.emit(event);
435
-
436
- if (kinds.includes("code") && rebuildClient) {
437
- // Css rides the pages batch rather than its own debounce: the slow lane folds a burst of saves into one batch.
438
- const needs: BuildBatchNeed[] = ["pages", "css"];
439
- if (!this.#csrActive)
440
- this.#logger.verbose(
441
- `csr-rebundle skipped; request /__csr or ?csr=true (or set AKAN_DEV_CSR_REBUILD=1) to enable per-save CSR rebuilds`,
442
- );
443
- //? One after the other, since two compiles side by side slow both. CSR goes first unless its build is being armed:
444
- //? a CSR patch then waits behind #csrGate, which SSR tabs must not.
445
- const patchCsr = async () => (this.#csrActive ? await this.#patchCsr(generation, files, trace) : false);
446
- const patchSsr = async () => await this.#patchSsr(generation, files, trace);
447
- let csrToWorker: boolean;
448
- let ssrToWorker: boolean;
449
- if (this.#csrArming) {
450
- ssrToWorker = await patchSsr();
451
- csrToWorker = await patchCsr();
452
- } else {
453
- csrToWorker = await patchCsr();
454
- ssrToWorker = await patchSsr();
455
- }
456
- if (csrToWorker) needs.unshift("csr");
457
- if (ssrToWorker) needs.unshift("ssr");
458
- const batch: BatchJob = { generation, needs, changedFiles: files, trace, ...(discovery ? { discovery } : {}) };
459
- // A worker's registry build rewrites the directory its patcher reads, so the next save waits for it.
460
- if (needs.includes("csr") || needs.includes("ssr")) await this.#workQueue.enqueueBatch(batch);
461
- else void this.#workQueue.enqueueBatch(batch).catch(this.#slowLaneFailed("batch"));
462
- return;
463
- }
464
- if (discovery)
465
- void this.#workQueue
466
- .enqueue("discovery", async () => await this.#refreshDiscovery(discovery))
467
- .catch(this.#slowLaneFailed("discovery"));
468
- // Css-only batches keep the debounce: they arrive in bursts while a stylesheet is edited.
469
- if (kinds.includes("css")) {
470
- this.scheduleCssRebuild({ generation, changedFiles: files });
471
- this.#logger.verbose(`css-rebuild scheduled generation=${generation}`);
472
- }
473
- }
474
-
475
- // True when the save has to go to a build worker: the patcher handed it back, or threw (the worker reports why).
476
- async #patchCsr(generation: number, files: string[], trace: HmrTrace): Promise<boolean> {
477
- const patcher = this.#patcher;
478
- if (!patcher) return true;
479
- await this.#csrGate;
480
- // The arming build this save waited for failed: CSR is off again, and the next request arms it anew.
481
- if (!this.#csrActive) return false;
482
- const started = Date.now();
483
- const marker = path.join(this.#csrBundler.outDir, CSR_DEV_PATCHING_MARKER);
484
- await Bun.write(marker, String(process.pid));
485
- try {
486
- const result = await patcher.update(files, {
487
- announce: (update) => {
488
- const now = Date.now();
489
- BuilderChannel.emit({
490
- type: "csr-updated",
491
- data: {
492
- generation: update.generation,
493
- mode: "registry",
494
- reload: update.reload,
495
- reason: update.reason,
496
- patchUrl: update.patchUrl,
497
- changedIds: update.changedIds,
498
- trace: { ...trace, patchAt: now, sentAt: now },
499
- },
500
- });
501
- },
502
- });
503
- if (result.kind === "delegate") {
504
- this.#logger.verbose(
505
- `csr-patch handed to a build worker (${this.#countDelegation("csr", result.reason)}): ${result.reason}`,
506
- );
507
- return true;
508
- }
509
- this.#sendBuildStatus("csr", { generation, ok: true, files });
510
- this.#logger.verbose(
511
- result.kind === "unchanged"
512
- ? `csr-patch unchanged (${Date.now() - started}ms)`
513
- : `csr-patch generation=${result.update.generation} ${result.update.reload ? `reload (${result.update.reason})` : `patch modules=${result.update.changedIds.length}`} (${Date.now() - started}ms)`,
514
- );
515
- return false;
516
- } catch (err) {
517
- const message = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
518
- if (IncrementalBuilder.#isCompileError(err)) {
519
- this.#sendBuildStatus("csr", { generation, ok: false, files, message });
520
- return false;
521
- }
522
- this.#logger.verbose(`csr-patch threw; a build worker takes this save: ${message}`);
523
- patcher.forget();
524
- return true;
525
- } finally {
526
- await rm(marker, { force: true });
527
- }
528
- }
529
-
530
- // True when the save has to go to a build worker, as for CSR.
531
- async #patchSsr(generation: number, files: string[], trace: HmrTrace): Promise<boolean> {
532
- const patcher = this.#ssrPatcher;
533
- if (!patcher) return true;
534
- const hold = await ServerGraphFile.touches(await ServerGraphFile.read(this.#artifactDir), files, (file) =>
535
- ServerGraphFile.clientExportsOf(file),
536
- );
537
- //? Ahead of this save's own discovery job in the slow lane: which client entries a page still names decides which
538
- //? pending roots this patch keeps.
539
- this.#discovery.invalidate?.(files);
540
- return await this.#withSsrLock(
541
- async () => await this.#runSsrPatcher(patcher, files, { trace, hold, batchGeneration: generation }),
542
- );
543
- }
544
-
545
- //* Adds the entries a route build names to the registry, since the tab requires them by id. A registry that cannot
546
- //* take them fails no route build: the page answers, and its tab waits for the registry while the overlay says why.
547
- async #ensureSsrEntries(entries: string[], { crashRetry = false }: { crashRetry?: boolean } = {}): Promise<void> {
548
- if (entries.length === 0) return;
549
- //? The boot build takes every entry the routes reach, so the first page answers now and its tab waits for the
550
- //? registry (boot.json) instead; whatever that build missed is added right after it lands.
551
- const arming = this.#ssrArming;
552
- if (arming) {
553
- void this.#runBeside(
554
- arming
555
- .then(async () => await this.#ensureSsrEntries(entries, { crashRetry }))
556
- .catch(this.#slowLaneFailed("ssr-ensure")),
557
- );
558
- return;
559
- }
560
- await this.#withSsrLock(async () => {
561
- const patcher = this.#ssrPatcher;
562
- // The builder's generation, not the request's: its build-status joins the saves' `ssr` ones.
563
- const generation = this.#generation;
564
- if (
565
- patcher &&
566
- !(await this.#runSsrPatcher(patcher, [], { roots: entries, onlyRoots: true, batchGeneration: generation }))
567
- )
568
- return;
569
- //? Read, not compiled: with the patcher off, the save's own worker batch already built every entry.
570
- if (!patcher && (await this.#ssrBundler.holds(entries))) return;
571
- //? Not retried per route build: the save that fixes the error rebuilds it, where each route build retrying held
572
- //? the SSR lock that save's patch waits on.
573
- if (this.#ssrBroken) return;
574
- if (this.#ssrCrashedAt !== null && Date.now() - this.#ssrCrashedAt < IncrementalBuilder.#crashRetryMs) {
575
- //? Handed over just now with nothing run for them: the retry must find them to hand over again.
576
- patcher?.releaseHandedOver();
577
- this.#retryAfterCrash(this.#ssrCrashedAt, entries);
578
- return;
579
- }
580
- await this.#runSsrWorker(generation).catch((err: unknown) => {
581
- this.#logger.error(
582
- `ssr-registry could not take a route's entries; the save that fixes it rebuilds it: ${ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot)}`,
583
- );
584
- });
585
- //? A worker that died took these entries with it and left them pending nowhere: they are tried once more after the
586
- //? crash window, but a retry that crashes again waits for the next route build or save.
587
- if (this.#ssrCrashedAt !== null && !crashRetry) this.#retryAfterCrash(this.#ssrCrashedAt, entries);
588
- });
589
- }
590
-
591
- //? Once the crash window closes, for the entries skipped in it: later route builds may name none (the first one
592
- //? announced every entry to the route cache), so without this a tab could wait on boot.json until the next save.
593
- #retryAfterCrash(crashedAt: number, entries: string[]): void {
594
- for (const entry of entries) this.#crashRetryEntries.add(entry);
595
- if (this.#crashRetryTimer) return;
596
- const timer = setTimeout(
597
- () => {
598
- this.#crashRetryTimer = null;
599
- const retried = [...this.#crashRetryEntries];
600
- this.#crashRetryEntries.clear();
601
- if (this.shuttingDown || retried.length === 0) return;
602
- void this.#runBeside(this.#ensureSsrEntries(retried, { crashRetry: true })).catch(
603
- this.#slowLaneFailed("ssr-crash-retry"),
604
- );
605
- },
606
- Math.max(0, crashedAt + IncrementalBuilder.#crashRetryMs - Date.now()),
607
- );
608
- timer.unref?.();
609
- this.#crashRetryTimer = timer;
610
- }
611
-
612
- //* The boot build of the SSR registry runs beside the slow lane, holding only the SSR lock: the first page's route
613
- //* build bundles meanwhile instead of queueing behind it (on apps/akan it cost the first page about a second).
614
- async armSsrRegistry(): Promise<void> {
615
- //? `AKAN_DEV_SSR_ARM_DELAY_MS` is a test hook: an E2E has a tab reconnect before the boot build has run.
616
- const delayMs = Number(process.env.AKAN_DEV_SSR_ARM_DELAY_MS);
617
- if (Number.isInteger(delayMs) && delayMs > 0) await Bun.sleep(delayMs);
618
- const arm = async () =>
619
- await this.#withSsrLock(async () => {
620
- const generation = this.#generation;
621
- if (this.#ssrPatcher && !(await this.#runSsrPatcher(this.#ssrPatcher, [], { batchGeneration: generation })))
622
- return;
623
- await this.#runSsrWorker(generation);
624
- }).catch((err: unknown) => {
625
- this.#logger.error(
626
- `ssr-registry boot build failed; the next save retries it: ${ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot)}`,
627
- );
628
- });
629
- const arming = this.#runBeside(
630
- (async () => {
631
- await arm();
632
- //? A boot build whose worker was killed (a small container's OOM) is tried once more before `boot-armed` lets
633
- //? the next app boot: retried after that, the two biggest workers of a boot would run side by side.
634
- const crashedAt = this.#ssrCrashedAt;
635
- if (crashedAt === null) return;
636
- while (!this.shuttingDown && Date.now() < crashedAt + IncrementalBuilder.#crashRetryMs) await Bun.sleep(250);
637
- if (!this.shuttingDown) await arm();
638
- })(),
639
- );
640
- this.#ssrArming = arming;
641
- await arming;
642
- this.#ssrArming = null;
643
- }
644
-
645
- //? A save the user broke fails the same way in a worker, so it is reported here and the patcher keeps its state: the
646
- //? modules it could not compile stay pending in the graph and the fixing save compiles them.
647
- static #isCompileError(error: unknown): boolean {
648
- return error instanceof AggregateError;
649
- }
650
-
651
- // Voided so the fast lane need not wait; unhandled, a rejection would exit the builder and drop the watcher with it.
652
- #slowLaneFailed(label: string) {
653
- return (error: unknown) =>
654
- this.#logger.error(
655
- `${label} failed in the slow lane: ${ApplicationBuildReporter.formatError(error, this.#app.workspace.workspaceRoot)}`,
656
- );
188
+ armSsrRegistry(): Promise<void> {
189
+ return this.#ssr.armSsrRegistry();
657
190
  }
658
191
 
659
192
  // A reason's own detail (which import) follows its first colon, so saves of one kind count together.
@@ -664,103 +197,6 @@ class IncrementalBuilder {
664
197
  return `#${count} for this reason`;
665
198
  }
666
199
 
667
- async #withSsrLock<T>(fn: () => Promise<T>): Promise<T> {
668
- const run = this.#ssrLock.then(fn, fn);
669
- this.#ssrLock = run.then(
670
- () => undefined,
671
- () => undefined,
672
- );
673
- return await run;
674
- }
675
-
676
- // Runs the worker directly, under the SSR lock its callers hold: queueing it could wait on a batch that waits on them.
677
- async #runSsrWorker(generation: number): Promise<void> {
678
- let result: BuildBatchResult;
679
- try {
680
- result = await this.#runBatch({ generation, needs: ["ssr"], changedFiles: [] });
681
- } finally {
682
- this.#ssrPatcher?.forget();
683
- }
684
- this.#noteSsrWorker(result);
685
- if (result.errors.ssr) throw new Error(result.errors.ssr);
686
- }
687
-
688
- #noteSsrWorker(result: BuildBatchResult): void {
689
- const crashed = !!result.crashed && (result.crashedNeeds ?? ["ssr"]).includes("ssr");
690
- this.#ssrBroken = !!result.errors.ssr && !crashed;
691
- this.#ssrCrashedAt = crashed ? Date.now() : null;
692
- }
693
-
694
- async #runSsrPatcher(
695
- patcher: CsrDevPatcher,
696
- files: string[],
697
- {
698
- roots,
699
- onlyRoots,
700
- trace,
701
- hold,
702
- batchGeneration,
703
- }: { roots?: string[]; onlyRoots?: boolean; trace?: HmrTrace; hold?: boolean; batchGeneration?: number } = {},
704
- ): Promise<boolean> {
705
- const started = Date.now();
706
- const marker = path.join(this.#ssrBundler.outDir, CSR_DEV_PATCHING_MARKER);
707
- await Bun.write(marker, String(process.pid));
708
- try {
709
- const result = await patcher.update(files, {
710
- roots,
711
- onlyRoots,
712
- announce: (update) => {
713
- const now = Date.now();
714
- BuilderChannel.emit({
715
- type: "ssr-updated",
716
- data: {
717
- generation: update.generation,
718
- reload: update.reload,
719
- reason: update.reason,
720
- patchUrl: update.patchUrl,
721
- changedIds: update.changedIds,
722
- ...(trace ? { trace: { ...trace, patchAt: now, sentAt: now } } : {}),
723
- ...(hold ? { hold } : {}),
724
- ...(batchGeneration !== undefined ? { batchGeneration } : {}),
725
- ...(update.epoch !== undefined ? { epoch: update.epoch } : {}),
726
- ...(update.first ? { first: true } : {}),
727
- },
728
- });
729
- },
730
- });
731
- if (result.kind === "delegate") {
732
- this.#logger.verbose(
733
- `ssr-patch handed to a build worker (${this.#countDelegation("ssr", result.reason)}): ${result.reason}`,
734
- );
735
- return true;
736
- }
737
- //? A route build's check reports only a failure: it compiles the roots the registry lacks and nothing else, so
738
- //? its ok, of the builder's current generation, would read as the fix of a save that broke something else.
739
- if (!onlyRoots) {
740
- this.#ssrBroken = false;
741
- this.#ssrCrashedAt = null;
742
- this.#sendBuildStatus("ssr", { generation: batchGeneration, ok: true, files });
743
- }
744
- this.#logger.verbose(
745
- result.kind === "unchanged"
746
- ? `ssr-patch unchanged (${Date.now() - started}ms)`
747
- : `ssr-patch generation=${result.update.generation} ${result.update.reload ? `reload (${result.update.reason})` : `patch modules=${result.update.changedIds.length}`} (${Date.now() - started}ms)`,
748
- );
749
- return false;
750
- } catch (err) {
751
- const message = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
752
- if (IncrementalBuilder.#isCompileError(err)) {
753
- this.#sendBuildStatus("ssr", { generation: batchGeneration, ok: false, files, message });
754
- return false;
755
- }
756
- this.#logger.verbose(`ssr-patch threw; a build worker takes it: ${message}`);
757
- patcher.forget();
758
- return true;
759
- } finally {
760
- await rm(marker, { force: true });
761
- }
762
- }
763
-
764
200
  async #runQueuedBatch({ discovery, ...work }: BatchJob): Promise<void> {
765
201
  if (discovery) await this.#refreshDiscovery(discovery);
766
202
  //? The slow lane runs in order, so every batch up to this one has had its discovery job.
@@ -769,16 +205,16 @@ class IncrementalBuilder {
769
205
  //? Forgotten inside the lock: a route build's check waiting on it would patch the old state over the worker's.
770
206
  try {
771
207
  if (work.needs.includes("ssr"))
772
- await this.#withSsrLock(async () => {
208
+ await this.#ssr.withSsrLock(async () => {
773
209
  try {
774
- this.#noteSsrWorker(await this.#runBatch(work));
210
+ this.#ssr.noteSsrWorker(await this.#runBatch(work));
775
211
  } finally {
776
- this.#ssrPatcher?.forget();
212
+ this.#ssr.ssrPatcher?.forget();
777
213
  }
778
214
  });
779
215
  else await this.#runBatch(work);
780
216
  } finally {
781
- if (work.needs.includes("csr")) this.#patcher?.forget();
217
+ if (work.needs.includes("csr")) this.#csr.patcher?.forget();
782
218
  }
783
219
  }
784
220
 
@@ -800,12 +236,12 @@ class IncrementalBuilder {
800
236
  if (result.crashed) {
801
237
  const crashedNeeds = result.crashedNeeds ?? needs;
802
238
  //? A worker that died wrote no failure for the roots handed to it: they must not wait on one that never comes.
803
- if (crashedNeeds.includes("csr")) this.#patcher?.releaseHandedOver();
804
- if (crashedNeeds.includes("ssr")) this.#ssrPatcher?.releaseHandedOver();
805
- // `base` is not a `BuildPhase` and never comes through here: `#buildBootDeps` throws into the degraded boot.
239
+ if (crashedNeeds.includes("csr")) this.#csr.patcher?.releaseHandedOver();
240
+ if (crashedNeeds.includes("ssr")) this.#ssr.ssrPatcher?.releaseHandedOver();
241
+ // `base` is not a `BuildPhase` and never comes through here: `buildBootDeps` throws into the degraded boot.
806
242
  for (const need of crashedNeeds)
807
243
  if (need !== "base" && need !== "shell")
808
- this.#sendBuildStatus(need, {
244
+ sendBuildStatus(need, {
809
245
  generation,
810
246
  ok: false,
811
247
  files: changedFiles,
@@ -834,14 +270,14 @@ class IncrementalBuilder {
834
270
 
835
271
  async boot(): Promise<void> {
836
272
  if (this.#watch) await this.installWatcher();
837
- BuilderChannel.emit({ type: "builder-ready" });
273
+ await BuilderChannel.announceReady(this.#logger);
838
274
  this.#logger.verbose(`ready (watch=${this.#watch})`);
839
275
  }
840
276
 
841
277
  // The backend still serves the last-good bundle after a degraded boot; push fresh pages/css without another edit.
842
278
  async announceRecoveredState(changedFiles: string[]): Promise<void> {
843
279
  const generation = ++this.#generation;
844
- await this.#workQueue.enqueue("boot-recovered", async () => {
280
+ await this.#lanes.workQueue.enqueue("boot-recovered", async () => {
845
281
  await this.#runBatch({ generation, needs: ["pages", "css"], changedFiles });
846
282
  });
847
283
  }
@@ -889,190 +325,12 @@ class IncrementalBuilder {
889
325
  }
890
326
  }
891
327
 
892
- // On demand: dev serves CSR only via the opt-in `/__csr` and `?csr=true` routes; once built, it rebuilds every save.
893
- async handleBuildCsr(msg: BuilderCsrReq): Promise<void> {
894
- if (msg.shell) {
895
- await this.#buildShell(msg);
896
- return;
897
- }
898
- //? Armed now, not when the build lands: a save handled meanwhile then patches CSR behind #csrGate instead of skipping.
899
- this.#beginCsrArm();
900
- this.#csrActive = true;
901
- const armed = this.#workQueue.enqueue("build-csr", async (): Promise<void> => {
902
- const started = Date.now();
903
- let error: string | undefined;
904
- try {
905
- // Not relayed: an on-demand CSR build is request/response, and its error travels in the response.
906
- const result = await this.#batchRunner.run(
907
- await this.#batchRequest({ generation: this.#generation, needs: ["csr"], changedFiles: [] }),
908
- );
909
- error = result.errors.csr;
910
- } catch (err) {
911
- error = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
912
- }
913
- if (error) {
914
- this.#logger.error(`csr-build failed: ${error}`);
915
- await BuilderChannel.send({ type: "build-csr-res", id: msg.id, ok: false, error });
916
- return;
917
- }
918
- this.#csrArmSucceeded = true;
919
- this.#patcher?.forget();
920
- this.#logger.info(`csr-build ok on demand (${Date.now() - started}ms); rebuilding CSR on every save now`);
921
- await BuilderChannel.send({ type: "build-csr-res", id: msg.id, ok: true });
922
- });
923
- this.#csrGate = this.#armingCsr(armed);
924
- await armed;
925
- }
926
-
927
- // Asked on every view read and rebuilt only when a save moved the generation or the css it inlines, instead of armed
928
- // per save: a restarted builder has no last build to trust, and so rebuilds once on the next read.
929
- async #buildShell(msg: BuilderCsrReq): Promise<void> {
930
- await this.#workQueue.enqueue("build-shell", async (): Promise<void> => {
931
- const generation = this.#generation;
932
- //? A save moves the generation before its css compile lands, so a shell built in between holds the old css.
933
- const shellKey = `${generation}:${JSON.stringify(this.#artifact.cssAssets)}`;
934
- let error: string | undefined;
935
- if (this.#shellKey !== shellKey)
936
- try {
937
- const result = await this.#batchRunner.run(
938
- await this.#batchRequest({ generation, needs: ["shell"], changedFiles: [] }),
939
- );
940
- error = result.errors.shell;
941
- if (!error) this.#shellKey = shellKey;
942
- } catch (err) {
943
- error = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
944
- }
945
- await BuilderChannel.send(
946
- error
947
- ? { type: "build-csr-res", id: msg.id, ok: false, error }
948
- : { type: "build-csr-res", id: msg.id, ok: true },
949
- );
950
- });
951
- }
952
-
953
- //? Settled by the last of the arming builds in flight, not by each: two requests that both fail would otherwise leave
954
- //? CSR on (the second saw the first's optimistic flag as where it started), and the first to finish would let saves
955
- //? patch CSR first while the second still builds.
956
- #beginCsrArm(): void {
957
- if (this.#csrArms === 0) {
958
- this.#csrWasActive = this.#csrActive;
959
- this.#csrArmSucceeded = false;
960
- }
961
- this.#csrArms += 1;
962
- this.#csrArming = true;
963
- }
964
-
965
- #armingCsr(armed: Promise<void>): Promise<void> {
966
- const settle = () => {
967
- this.#csrArms -= 1;
968
- if (this.#csrArms > 0) return;
969
- this.#csrArming = false;
970
- this.#csrActive = this.#csrWasActive || this.#csrArmSucceeded;
971
- };
972
- return armed.then(settle, settle);
973
- }
974
-
975
- static #csrArmedByEnv() {
976
- return process.env.AKAN_DEV_CSR_REBUILD === "1";
977
- }
978
-
979
- // Discovery stays in-process because route builds need it live; it is free at boot, building its graph lazily.
980
- static async #buildBootDeps(app: App, runner: BuildBatchRunner): Promise<IncrementalBuilderBootDeps> {
981
- const result = await runner.run({
982
- appName: app.name,
983
- workspaceRoot: app.workspace.workspaceRoot,
984
- repoName: app.workspace.repoName,
985
- generation: 0,
986
- needs: ["base"],
987
- changedFiles: [],
988
- pageKeys: null,
989
- optimizedFonts: null,
990
- cssAssets: null,
991
- artifactDir: path.resolve(`${app.cwdPath}/.akan/artifact`),
992
- });
993
- // Throws rather than degrading quietly: `main` catches it to enter degraded watch mode.
994
- if (result.errors.base) throw new Error(result.errors.base);
995
- if (!result.artifact || !result.optimizedFonts)
996
- throw new Error("boot build reported success without an artifact; the build worker likely died");
997
- const discovery = await GraphClientEntryDiscovery.create(app);
998
- return { artifact: result.artifact, optimizedFonts: result.optimizedFonts, discovery };
328
+ handleBuildCsr(msg: BuilderCsrReq): Promise<void> {
329
+ return this.#csr.handleBuildCsr(msg);
999
330
  }
1000
331
 
1001
- // The env flag carries an armed CSR session across builder restarts, so the replacement rebuilds it after ready.
1002
- async rearmCsrFromEnv(): Promise<void> {
1003
- if (!IncrementalBuilder.#csrArmedByEnv()) return;
1004
- this.#beginCsrArm();
1005
- this.#csrActive = true;
1006
- //? The env keeps CSR armed whatever this build does, as it did before the builder restarted.
1007
- this.#csrArmSucceeded = true;
1008
- const rearmed = this.#workQueue.enqueue("build-csr-rearm", async () => {
1009
- //? Relayed, unlike an on-demand build: a rebuild for a metadata save must reach the CSR tabs as their reload.
1010
- const result = await this.#batchRunner.run(
1011
- await this.#batchRequest({ generation: this.#generation, needs: ["csr"], changedFiles: [] }),
1012
- (msg) => BuilderChannel.emit(msg),
1013
- );
1014
- this.#patcher?.forget();
1015
- if (result.errors.csr) this.#logger.error(`csr-rearm failed: ${result.errors.csr}`);
1016
- else this.#logger.verbose("csr-rearm ok; this session had CSR armed before the builder restarted");
1017
- });
1018
- this.#csrGate = this.#armingCsr(rearmed);
1019
- await rearmed.catch((err: unknown) =>
1020
- this.#logger.error(
1021
- `csr-rearm failed: ${ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot)}`,
1022
- ),
1023
- );
1024
- }
1025
-
1026
- // A boot compile error must not kill the builder, the dev server's only file watcher: report it, emit builder-ready
1027
- // so the backend keeps the last-good artifact, and retry the boot build on every change.
1028
- static #recoverBoot(
1029
- app: App,
1030
- bootError: unknown,
1031
- logger: Logger,
1032
- runner: BuildBatchRunner,
1033
- initialGeneration: number,
1034
- ): Promise<{ builder: IncrementalBuilder; changedFiles: string[] }> {
1035
- const firstMessage = bootError instanceof Error ? bootError.message : String(bootError);
1036
- logger.error(`boot build failed; entering degraded watch mode until the error is fixed: ${firstMessage}`);
1037
- let generation = initialGeneration;
1038
- const sendFailure = (files: string[], message: string) => {
1039
- BuilderChannel.emit({
1040
- type: "build-status",
1041
- data: { generation, phase: "pages", ok: false, files, message: `Boot build failed: ${message}` },
1042
- });
1043
- };
1044
- sendFailure([], firstMessage);
1045
- BuilderChannel.emit({ type: "builder-ready" });
1046
- // Nothing builds until a save fixes the boot, so the next app's boot need not wait for this one.
1047
- BuilderChannel.emit({ type: "boot-armed" });
1048
- return new Promise((resolve, reject) => {
1049
- void (async () => {
1050
- const roots = await new WatchRootResolver(app).resolve();
1051
- const watcher = new HmrWatcher({
1052
- roots,
1053
- logger,
1054
- onBatch: async (batch) => {
1055
- generation += 1;
1056
- const files = [...batch.files].sort();
1057
- try {
1058
- // A broken akan.config.ts caches its import failure; re-import it before rebuilding.
1059
- if (new Set(batch.kinds).has("config")) await app.getConfig({ refresh: true });
1060
- const deps = await IncrementalBuilder.#buildBootDeps(app, runner);
1061
- const builder = new IncrementalBuilder({ app, watch: true, initialGeneration: generation, ...deps });
1062
- watcher.stop();
1063
- logger.info(`boot build recovered generation=${generation}`);
1064
- resolve({ builder, changedFiles: files });
1065
- } catch (err) {
1066
- const message = err instanceof Error ? err.message : String(err);
1067
- logger.error(`boot build retry failed: ${message}`);
1068
- sendFailure(files, message);
1069
- }
1070
- },
1071
- });
1072
- await watcher.start();
1073
- logger.warn(`[degraded] watching ${roots.length} roots for a fix`);
1074
- })().catch(reject);
1075
- });
332
+ rearmCsrFromEnv(): Promise<void> {
333
+ return this.#csr.rearmCsrFromEnv();
1076
334
  }
1077
335
 
1078
336
  static async main(): Promise<void> {
@@ -1120,13 +378,20 @@ class IncrementalBuilder {
1120
378
  });
1121
379
  let recoveredFiles: string[] | null = null;
1122
380
  const bootRunner = new BuildBatchRunner({ workspaceRoot, cwd: app.cwdPath });
1123
- const initialGeneration = IncrementalBuilder.#initialGeneration();
381
+ const initialGeneration = BuilderBoot.initialGeneration();
1124
382
  try {
1125
- const deps = await IncrementalBuilder.#buildBootDeps(app, bootRunner);
383
+ const deps = await BuilderBoot.buildBootDeps(app, bootRunner);
1126
384
  builder = new IncrementalBuilder({ app, watch, initialGeneration, ...deps });
1127
385
  } catch (err) {
1128
386
  if (!watch) throw err;
1129
- const recovered = await IncrementalBuilder.#recoverBoot(app, err, logger, bootRunner, initialGeneration);
387
+ const recovered = await BuilderBoot.recoverBoot(
388
+ app,
389
+ err,
390
+ logger,
391
+ bootRunner,
392
+ initialGeneration,
393
+ (options) => new IncrementalBuilder(options),
394
+ );
1130
395
  builder = recovered.builder;
1131
396
  recoveredFiles = recovered.changedFiles;
1132
397
  }
@@ -1136,13 +401,6 @@ class IncrementalBuilder {
1136
401
  await Promise.all([builder.rearmCsrFromEnv(), builder.armSsrRegistry()]);
1137
402
  BuilderChannel.emit({ type: "boot-armed" });
1138
403
  }
1139
-
1140
- //? A replacement builder continues past the host's last generation: from 0, the save fixing an error read older than
1141
- //? the failure the tabs hold, and from that generation itself its arming builds' ok did not read as the fix either.
1142
- static #initialGeneration(): number {
1143
- const generation = Number(process.env.AKAN_BUILDER_INITIAL_GENERATION);
1144
- return Number.isInteger(generation) && generation > 0 ? generation + 1 : 0;
1145
- }
1146
404
  }
1147
405
 
1148
406
  // Awaited, not voided: on Windows Bun exits during a missing file's `Bun.file` read unless an entry await is pending.