@akanjs/devkit 3.2.0-rc.9 → 3.3.0-rc.0

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 (341) hide show
  1. package/CHANGELOG.md +57 -516
  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 +132 -3
  7. package/akanApp/akanApp.host.ts +146 -1216
  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/devIdleSuspend.test.ts +221 -0
  17. package/akanApp/devIdleSuspend.ts +192 -0
  18. package/akanApp/devIdleSuspend.watcher.test.ts +120 -0
  19. package/akanApp/devRecycler.test.ts +66 -0
  20. package/akanApp/devRecycler.ts +305 -0
  21. package/akanApp/processRss.ts +61 -0
  22. package/akanConfig/akanConfig.test.ts +45 -17
  23. package/akanConfig/akanConfig.ts +10 -10
  24. package/akanConfig/akanWorkspaceConfig.ts +1 -1
  25. package/akanConfig/productionLockfile.ts +1 -1
  26. package/apiReport/apiReport.test.ts +34 -3
  27. package/apiReport/apiReportDiff.ts +35 -1
  28. package/apiReport/apiReportPolicy.ts +3 -2
  29. package/{applicationBuildReporter.ts → app/applicationBuildReporter.ts} +2 -49
  30. package/{applicationBuildRunner.test.ts → app/applicationBuildRunner.test.ts} +71 -8
  31. package/{applicationBuildRunner.ts → app/applicationBuildRunner.ts} +60 -21
  32. package/{applicationTestPreload.ts → app/applicationTestPreload.ts} +1 -1
  33. package/{routeJsBudget.test.ts → app/routeJsBudget.test.ts} +17 -1
  34. package/{routeJsBudget.ts → app/routeJsBudget.ts} +9 -3
  35. package/{routeSourceValidator.test.ts → app/routeSourceValidator.test.ts} +17 -0
  36. package/{routeSourceValidator.ts → app/routeSourceValidator.ts} +5 -1
  37. package/artifact/implicitRootLayout.test.ts +71 -3
  38. package/artifact/implicitRootLayout.ts +9 -3
  39. package/artifact/implicitRootLayoutRender.test.tsx +297 -0
  40. package/biome.base.json +2 -1
  41. package/cloud/cloudApi.test.ts +1 -1
  42. package/cloud/configLock.test.ts +1 -1
  43. package/cloud/globalConfig.test.ts +1 -1
  44. package/cloud/globalConfig.ts +1 -1
  45. package/cloud/updatePackUpload.test.ts +1 -1
  46. package/codeAgent/agent/AkanCodeEnv.ts +1 -1
  47. package/codeAgent/agent/AkanCodeServices.ts +23 -0
  48. package/codeAgent/agent/akanCodePaths.ts +1 -1
  49. package/codeAgent/agent/akanCodeServices.test.ts +54 -0
  50. package/codeAgent/agent/akanSystemPrompt.ts +1 -1
  51. package/codeAgent/agent/codeAgent.test.ts +1 -1
  52. package/codeAgent/skills/akan-debug/SKILL.md +8 -5
  53. package/codeAgent/skills/akan-err/SKILL.md +7 -0
  54. package/codeAgent/skills/akan-mcp/SKILL.md +19 -1
  55. package/codeAgent/skills/akan-scaffold/SKILL.md +1 -1
  56. package/codeAgent/skills/akan-validate/SKILL.md +3 -3
  57. package/codeAgent/tools/AkanCli.ts +1 -1
  58. package/codeAgent/tools/AkanToolPack.ts +2 -2
  59. package/codeAgent/tools/akanCodePlugins.test.ts +1 -1
  60. package/commandDecorators/command.ts +35 -6
  61. package/commandDecorators/commandBuilder.ts +1 -1
  62. package/commandDecorators/commandDecorators.test.ts +107 -6
  63. package/commandDecorators/targetMeta.ts +2 -0
  64. package/commandDecorators/workspaceVersionCheck.test.ts +70 -1
  65. package/commandDecorators/workspaceVersionCheck.ts +64 -14
  66. package/context/akanContext.ts +576 -0
  67. package/context/akanContextInspection.ts +296 -0
  68. package/{akanMcpContract.test.ts → context/akanMcpContract.test.ts} +1 -1
  69. package/{akanMcpContract.ts → context/akanMcpContract.ts} +16 -256
  70. package/context/doctor/agentGuideCheck.ts +81 -0
  71. package/context/doctor/configLeftoverCheck.ts +35 -0
  72. package/context/doctor/doctorFindings.ts +70 -0
  73. package/context/doctor/generatedFreshness.ts +56 -0
  74. package/context/doctor/moduleShapeCheck.ts +88 -0
  75. package/context/doctor/recipeDuplicateCheck.ts +42 -0
  76. package/context/doctor/recipeIndexCheck.ts +87 -0
  77. package/context/doctor/rootShapeCheck.ts +55 -0
  78. package/context/doctor/workflowScope.ts +97 -0
  79. package/{recipeScanner.test.ts → context/recipeScanner.test.ts} +1 -1
  80. package/context/safeRead.ts +9 -0
  81. package/csrE2e/csrE2eHarness.fixture.ts +1 -1
  82. package/devkitUtils.test.ts +39 -5
  83. package/{apiReference.test.ts → docs/apiReference.test.ts} +4 -4
  84. package/{apiReference.ts → docs/apiReference.ts} +2 -2
  85. package/docs/errorCodeReference.test.ts +282 -0
  86. package/docs/errorCodeReference.ts +71 -0
  87. package/docs/errorCodeScan.ts +551 -0
  88. package/{frameworkGraph.test.ts → docs/frameworkGraph.test.ts} +1 -1
  89. package/executors/appExecutor.ts +448 -0
  90. package/executors/commandExecutionError.ts +53 -0
  91. package/executors/executor.ts +527 -0
  92. package/{executors.linkFallback.test.ts → executors/executors.linkFallback.test.ts} +1 -1
  93. package/{executors.test.ts → executors/executors.test.ts} +76 -15
  94. package/executors/index.ts +8 -0
  95. package/executors/libExecutor.ts +23 -0
  96. package/executors/moduleExecutor.ts +18 -0
  97. package/executors/pkgExecutor.ts +129 -0
  98. package/executors/sysExecutor.ts +301 -0
  99. package/executors/workspaceExecutor.ts +277 -0
  100. package/frontendBuild/allRoutesBuilder.test.ts +1 -1
  101. package/frontendBuild/autoImportSync.test.ts +1 -1
  102. package/frontendBuild/autoImportSync.ts +1 -1
  103. package/frontendBuild/buildRouteClient.test.ts +1 -1
  104. package/frontendBuild/clientEntriesBundler.test.ts +1 -1
  105. package/frontendBuild/csrArtifactBuilder.test.ts +1 -1
  106. package/frontendBuild/csrDevArtifactWriter.ts +1 -1
  107. package/frontendBuild/cssCompiler.test.ts +3 -2
  108. package/frontendBuild/devGeneratedIndexSync.test.ts +1 -1
  109. package/frontendBuild/devGeneratedIndexSync.ts +7 -38
  110. package/frontendBuild/dictionaryAssetBuilder.test.ts +1 -1
  111. package/frontendBuild/fontOptimizer.test.ts +1 -1
  112. package/frontendBuild/fontPruner.test.ts +1 -1
  113. package/frontendBuild/frontendBuild.test.ts +3 -3
  114. package/frontendBuild/hmrWatcher.stop.test.ts +63 -0
  115. package/frontendBuild/hmrWatcher.test.ts +1 -1
  116. package/frontendBuild/hmrWatcher.ts +22 -1
  117. package/frontendBuild/mcpAppViewBuilder.test.ts +1 -1
  118. package/frontendBuild/mcpAppViewBuilder.ts +1 -1
  119. package/frontendBuild/nativeCore.test.ts +1 -1
  120. package/frontendBuild/optionalPeers.test.ts +36 -8
  121. package/frontendBuild/pagesBundleBuilder.test.ts +2 -3
  122. package/frontendBuild/pagesBundleBuilder.ts +1 -1
  123. package/frontendBuild/precompressArtifacts.test.ts +1 -1
  124. package/frontendBuild/precompressArtifacts.ts +19 -6
  125. package/frontendBuild/serverGraphFile.ts +1 -1
  126. package/frontendBuild/sourceMtimeIndex.test.ts +1 -1
  127. package/frontendBuild/ssrDevBundler.test.ts +1 -1
  128. package/frontendBuild/vendorImportScanner.test.ts +1 -1
  129. package/frontendBuild/vendorNarrowing.test.ts +1 -1
  130. package/frontendBuild/watchRootResolver.test.ts +1 -1
  131. package/{agentAssets.test.ts → guideline/agentAssets.test.ts} +1 -1
  132. package/{agentAssets.ts → guideline/agentAssets.ts} +2 -2
  133. package/{agentsIndex.test.ts → guideline/agentsIndex.test.ts} +2 -2
  134. package/{agentsIndex.ts → guideline/agentsIndex.ts} +13 -10
  135. package/{conventionSet.test.ts → guideline/conventionSet.test.ts} +7 -4
  136. package/{conventionSet.ts → guideline/conventionSet.ts} +1 -1
  137. package/{prompter.ts → guideline/prompter.ts} +2 -3
  138. package/incrementalBuilder/buildBatch.proc.ts +14 -4
  139. package/incrementalBuilder/buildBatchProtocol.ts +2 -0
  140. package/incrementalBuilder/buildBatchRunner.test.ts +122 -2
  141. package/incrementalBuilder/buildBatchRunner.ts +17 -4
  142. package/incrementalBuilder/builderBoot.ts +106 -0
  143. package/incrementalBuilder/builderBuildStatus.ts +23 -0
  144. package/incrementalBuilder/builderChannel.test.ts +1 -1
  145. package/incrementalBuilder/builderChannel.ts +11 -0
  146. package/incrementalBuilder/builderGraphPayloads.ts +3 -3
  147. package/incrementalBuilder/builderLanes.ts +157 -0
  148. package/incrementalBuilder/builderWatch.ts +213 -0
  149. package/incrementalBuilder/csrRegistry.ts +234 -0
  150. package/incrementalBuilder/incrementalBuilder.proc.test.ts +101 -7
  151. package/incrementalBuilder/incrementalBuilder.proc.ts +81 -823
  152. package/incrementalBuilder/ssrRegistry.ts +282 -0
  153. package/index.ts +22 -22
  154. package/integration/devStability.integration.test.ts +62 -56
  155. package/integration/devStabilityHarness.test.ts +1 -1
  156. package/lint/__fixtures__/no-import-common-err/bad.tsx +13 -0
  157. package/lint/__fixtures__/no-import-common-err/good.tsx +12 -0
  158. package/{biomeBase.test.ts → lint/biomeBase.test.ts} +1 -1
  159. package/lint/gritRules.test.ts +1 -1
  160. package/{linter.test.ts → lint/linter.test.ts} +1 -1
  161. package/lint/no-import-common-err.grit +31 -0
  162. package/lint/no-init-fetch-in-client.grit +1 -1
  163. package/mobile/desktopBin.test.ts +1 -1
  164. package/mobile/desktopRelease.test.ts +1 -1
  165. package/mobile/desktopServerStage.test.ts +2 -2
  166. package/mobile/desktopServerStage.ts +1 -1
  167. package/mobile/nativeApi.test.ts +1 -1
  168. package/mobile/nativeApp.test.ts +1 -1
  169. package/mobile/nativeConfig.test.ts +1 -1
  170. package/mobile/nativePluginFolders.test.ts +1 -1
  171. package/mobile/nativePublicEnv.test.ts +1 -1
  172. package/mobile/nativeWebDir.test.ts +1 -1
  173. package/mobile/serverBundleSecrets.test.ts +1 -1
  174. package/mobile/tarWriter.test.ts +1 -1
  175. package/mobile/updatePackFolder.test.ts +1 -1
  176. package/package.json +173 -9
  177. package/packageExports.test.ts +20 -2
  178. package/piDependencyPins.test.ts +1 -1
  179. package/pipeline/PipelineDefinition.ts +1 -1
  180. package/platformTest/IdleWatchedProcess.test.ts +1 -1
  181. package/platformTest/LinuxDockerTarget.ts +1 -1
  182. package/platformTest/PlatformTestRun.test.ts +1 -1
  183. package/platformTest/TestSnapshot.test.ts +1 -1
  184. package/platformTest/WindowsSshTarget.ts +1 -1
  185. package/preview/previewView.test.ts +23 -1
  186. package/{abstractDoc.test.ts → quality/abstractDoc.test.ts} +2 -2
  187. package/{abstractDoc.ts → quality/abstractDoc.ts} +1 -1
  188. package/quality/bareErrorScanner.ts +126 -0
  189. package/{maintainabilityBaseline.test.ts → quality/maintainabilityBaseline.test.ts} +73 -0
  190. package/{maintainabilityBaseline.ts → quality/maintainabilityBaseline.ts} +97 -9
  191. package/{maintainabilityContract.test.ts → quality/maintainabilityContract.test.ts} +383 -2
  192. package/{maintainabilityContract.ts → quality/maintainabilityContract.ts} +151 -29
  193. package/{maintainabilityExceptionScanner.test.ts → quality/maintainabilityExceptionScanner.test.ts} +15 -1
  194. package/{maintainabilityExceptionScanner.ts → quality/maintainabilityExceptionScanner.ts} +5 -1
  195. package/{maintainabilityLimits.ts → quality/maintainabilityLimits.ts} +12 -0
  196. package/{maintainabilityReport.ts → quality/maintainabilityReport.ts} +20 -3
  197. package/{qualityScanner.test.ts → quality/qualityScanner.test.ts} +41 -1
  198. package/{qualityScanner.ts → quality/qualityScanner.ts} +25 -91
  199. package/{storeAccessScanner.ts → quality/storeAccessScanner.ts} +15 -2
  200. package/quality/workspaceSourceFiles.ts +82 -0
  201. package/{subspace.test.ts → subspace/subspace.test.ts} +25 -4
  202. package/{subspace.ts → subspace/subspace.ts} +5 -5
  203. package/{subspaceClone.ts → subspace/subspaceClone.ts} +8 -8
  204. package/{subspaceConfig.ts → subspace/subspaceConfig.ts} +5 -1
  205. package/{testHelpers.ts → test/testHelpers.ts} +37 -1
  206. package/transforms/barrelAnalyzer.ts +31 -10
  207. package/transforms/browserDirnamePlugin.test.ts +1 -1
  208. package/transforms/externalizeFrameworkPlugin.test.ts +1 -1
  209. package/transforms/mcpAppPageTrimmer.test.ts +1 -1
  210. package/transforms/pureLazyMarker.test.ts +1 -1
  211. package/transforms/serverEnvPlugin.test.ts +1 -1
  212. package/transforms/serverEnvProfile.test.ts +1 -1
  213. package/transforms/sideEffectImportOrder.test.ts +1 -1
  214. package/transforms/transforms.test.ts +52 -2
  215. package/transforms/tsconfigPackageResolver.test.ts +1 -1
  216. package/{createTunnel.test.ts → tunnel/createTunnel.test.ts} +1 -1
  217. package/{createTunnel.ts → tunnel/createTunnel.ts} +2 -2
  218. package/{sshHostKeys.ts → tunnel/sshHostKeys.ts} +2 -2
  219. package/typecheck/projectTypecheck.test.ts +23 -1
  220. package/typecheck/projectTypecheck.ts +10 -2
  221. package/{typeChecker.test.ts → typecheck/typeChecker.test.ts} +1 -1
  222. package/{typeChecker.ts → typecheck/typeChecker.ts} +5 -4
  223. package/typecheck/typecheck.proc.ts +6 -2
  224. package/typecheck/typecheckFailure.ts +1 -1
  225. package/util/errorReport.ts +66 -0
  226. package/{jsonFormatter.test.ts → util/jsonFormatter.test.ts} +1 -1
  227. package/workflow/constantSource.ts +187 -0
  228. package/workflow/dictionarySource.ts +184 -0
  229. package/workflow/executor.ts +6 -9
  230. package/workflow/fieldExpression.ts +153 -0
  231. package/workflow/fieldLabel.ts +61 -0
  232. package/workflow/fieldOrder.ts +117 -0
  233. package/workflow/fieldType.ts +2 -1
  234. package/workflow/guardCatalog.test.ts +1 -1
  235. package/workflow/keyRename.ts +1 -1
  236. package/workflow/moduleIndex.test.ts +2 -2
  237. package/workflow/moduleIndex.ts +2 -2
  238. package/workflow/modulePaths.ts +27 -0
  239. package/workflow/mutationScaffold.ts +7 -15
  240. package/workflow/mutationSource.ts +2 -1
  241. package/workflow/plan.ts +2 -1
  242. package/workflow/primitiveReport.ts +78 -0
  243. package/workflow/rolloutGate.test.ts +1 -1
  244. package/workflow/rolloutGate.ts +1 -1
  245. package/workflow/serviceSource.ts +33 -0
  246. package/workflow/signalSource.ts +96 -0
  247. package/workflow/source.ts +50 -1100
  248. package/workflow/sourceAst.ts +30 -0
  249. package/workflow/sourceImports.ts +105 -0
  250. package/workflow/sourceText.ts +13 -0
  251. package/workflow/templateSource.ts +30 -0
  252. package/workflow/testSource.ts +31 -0
  253. package/workflow/types.ts +1 -1
  254. package/workflow/uiPolicy.ts +1 -1
  255. package/{appSelectionMemory.ts → workspace/appSelectionMemory.ts} +1 -1
  256. package/{codegenLock.test.ts → workspace/codegenLock.test.ts} +1 -1
  257. package/{dependencyScanner.test.ts → workspace/dependencyScanner.test.ts} +1 -1
  258. package/{dependencyScanner.ts → workspace/dependencyScanner.ts} +2 -2
  259. package/{envSeed.test.ts → workspace/envSeed.test.ts} +2 -2
  260. package/{envSeed.ts → workspace/envSeed.ts} +1 -1
  261. package/{libSource.test.ts → workspace/libSource.test.ts} +2 -2
  262. package/{libSource.ts → workspace/libSource.ts} +1 -1
  263. package/{scanInfo.ts → workspace/scanInfo.ts} +21 -10
  264. package/{slicePlanner.test.ts → workspace/slicePlanner.test.ts} +2 -2
  265. package/{slicePlanner.ts → workspace/slicePlanner.ts} +1 -1
  266. package/{workspaceGraph.test.ts → workspace/workspaceGraph.test.ts} +1 -1
  267. package/{workspaceGraph.ts → workspace/workspaceGraph.ts} +1 -1
  268. package/{workspaceLayout.test.ts → workspace/workspaceLayout.test.ts} +1 -1
  269. package/{workspaceLayout.ts → workspace/workspaceLayout.ts} +3 -1
  270. package/akanContext.ts +0 -1083
  271. package/executors.ts +0 -1749
  272. /package/{applicationBuildReporter.test.ts → app/applicationBuildReporter.test.ts} +0 -0
  273. /package/{akanMcpToolError.ts → context/akanMcpToolError.ts} +0 -0
  274. /package/{moduleFieldNames.test.ts → context/moduleFieldNames.test.ts} +0 -0
  275. /package/{moduleFieldNames.ts → context/moduleFieldNames.ts} +0 -0
  276. /package/{recipeScanner.ts → context/recipeScanner.ts} +0 -0
  277. /package/{declarationReader.ts → docs/declarationReader.ts} +0 -0
  278. /package/{frameworkGraph.ts → docs/frameworkGraph.ts} +0 -0
  279. /package/{biomeBase.ts → lint/biomeBase.ts} +0 -0
  280. /package/{linter.ts → lint/linter.ts} +0 -0
  281. /package/{commentDensityScanner.test.ts → quality/commentDensityScanner.test.ts} +0 -0
  282. /package/{commentDensityScanner.ts → quality/commentDensityScanner.ts} +0 -0
  283. /package/{componentSizeScanner.test.ts → quality/componentSizeScanner.test.ts} +0 -0
  284. /package/{componentSizeScanner.ts → quality/componentSizeScanner.ts} +0 -0
  285. /package/{componentWriteChainScanner.test.ts → quality/componentWriteChainScanner.test.ts} +0 -0
  286. /package/{componentWriteChainScanner.ts → quality/componentWriteChainScanner.ts} +0 -0
  287. /package/{deprecatedCommentScanner.test.ts → quality/deprecatedCommentScanner.test.ts} +0 -0
  288. /package/{deprecatedCommentScanner.ts → quality/deprecatedCommentScanner.ts} +0 -0
  289. /package/{endpointReach.test.ts → quality/endpointReach.test.ts} +0 -0
  290. /package/{endpointReach.ts → quality/endpointReach.ts} +0 -0
  291. /package/{formSetterScanner.test.ts → quality/formSetterScanner.test.ts} +0 -0
  292. /package/{formSetterScanner.ts → quality/formSetterScanner.ts} +0 -0
  293. /package/{kindBranchScanner.test.ts → quality/kindBranchScanner.test.ts} +0 -0
  294. /package/{kindBranchScanner.ts → quality/kindBranchScanner.ts} +0 -0
  295. /package/{maintainabilityReport.test.ts → quality/maintainabilityReport.test.ts} +0 -0
  296. /package/{renderMutationScanner.test.ts → quality/renderMutationScanner.test.ts} +0 -0
  297. /package/{renderMutationScanner.ts → quality/renderMutationScanner.ts} +0 -0
  298. /package/{serviceLoopCallScanner.test.ts → quality/serviceLoopCallScanner.test.ts} +0 -0
  299. /package/{serviceLoopCallScanner.ts → quality/serviceLoopCallScanner.ts} +0 -0
  300. /package/{signalMutationIndex.test.ts → quality/signalMutationIndex.test.ts} +0 -0
  301. /package/{signalMutationIndex.ts → quality/signalMutationIndex.ts} +0 -0
  302. /package/{sourceComments.test.ts → quality/sourceComments.test.ts} +0 -0
  303. /package/{sourceComments.ts → quality/sourceComments.ts} +0 -0
  304. /package/{ssrScanner.test.ts → quality/ssrScanner.test.ts} +0 -0
  305. /package/{ssrScanner.ts → quality/ssrScanner.ts} +0 -0
  306. /package/{storeAccessScanner.test.ts → quality/storeAccessScanner.test.ts} +0 -0
  307. /package/{storeSource.ts → quality/storeSource.ts} +0 -0
  308. /package/{storeWriteScanner.test.ts → quality/storeWriteScanner.test.ts} +0 -0
  309. /package/{storeWriteScanner.ts → quality/storeWriteScanner.ts} +0 -0
  310. /package/{structureScanner.test.ts → quality/structureScanner.test.ts} +0 -0
  311. /package/{structureScanner.ts → quality/structureScanner.ts} +0 -0
  312. /package/{testOnlyExportScanner.test.ts → quality/testOnlyExportScanner.test.ts} +0 -0
  313. /package/{testOnlyExportScanner.ts → quality/testOnlyExportScanner.ts} +0 -0
  314. /package/{writePath.test.ts → quality/writePath.test.ts} +0 -0
  315. /package/{writePath.ts → quality/writePath.ts} +0 -0
  316. /package/{writePlacementScanner.test.ts → quality/writePlacementScanner.test.ts} +0 -0
  317. /package/{writePlacementScanner.ts → quality/writePlacementScanner.ts} +0 -0
  318. /package/{writingActionIndex.test.ts → quality/writingActionIndex.test.ts} +0 -0
  319. /package/{writingActionIndex.ts → quality/writingActionIndex.ts} +0 -0
  320. /package/{subspaceReport.ts → subspace/subspaceReport.ts} +0 -0
  321. /package/{sshTunnel.ts → tunnel/sshTunnel.ts} +0 -0
  322. /package/{fileEditor.ts → util/fileEditor.ts} +0 -0
  323. /package/{fileSys.test.ts → util/fileSys.test.ts} +0 -0
  324. /package/{fileSys.ts → util/fileSys.ts} +0 -0
  325. /package/{jsonFormatter.ts → util/jsonFormatter.ts} +0 -0
  326. /package/{selectModel.ts → util/selectModel.ts} +0 -0
  327. /package/{semver.test.ts → util/semver.test.ts} +0 -0
  328. /package/{semver.ts → util/semver.ts} +0 -0
  329. /package/{shellOnlyEnv.test.ts → util/shellOnlyEnv.test.ts} +0 -0
  330. /package/{shellOnlyEnv.ts → util/shellOnlyEnv.ts} +0 -0
  331. /package/{spinner.test.ts → util/spinner.test.ts} +0 -0
  332. /package/{spinner.ts → util/spinner.ts} +0 -0
  333. /package/{stripAnsi.ts → util/stripAnsi.ts} +0 -0
  334. /package/{codegenLock.ts → workspace/codegenLock.ts} +0 -0
  335. /package/{getRelatedCnsts.ts → workspace/getRelatedCnsts.ts} +0 -0
  336. /package/{gitRevision.test.ts → workspace/gitRevision.test.ts} +0 -0
  337. /package/{gitRevision.ts → workspace/gitRevision.ts} +0 -0
  338. /package/{manifestDependencies.ts → workspace/manifestDependencies.ts} +0 -0
  339. /package/{packageExportsMap.ts → workspace/packageExportsMap.ts} +0 -0
  340. /package/{repoIdentity.ts → workspace/repoIdentity.ts} +0 -0
  341. /package/{types.ts → workspace/types.ts} +0 -0
@@ -0,0 +1,277 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { AkanWorkspaceConfig } from "../akanConfig";
4
+ import { FileSys } from "../util/fileSys";
5
+ import { resolveRepoName } from "../workspace/repoIdentity";
6
+ import { WorkspaceInfo } from "../workspace/scanInfo";
7
+ import type { BaseDevEnv, TsConfigJson } from "../workspace/types";
8
+ import { Executor, execEmoji } from "./executor";
9
+ import { SysExecutor } from "./sysExecutor";
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.
12
+ const parseEnvValue = (value: string) => {
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));
17
+ };
18
+
19
+ export const parseEnvFile = (envPath: string): Record<string, string> => {
20
+ const env: Record<string, string> = {};
21
+ const content = (() => {
22
+ try {
23
+ return readFileSync(envPath, "utf8");
24
+ } catch {
25
+ return "";
26
+ }
27
+ })();
28
+ for (const line of content.split(/\r?\n/)) {
29
+ const trimmed = line.trim();
30
+ if (!trimmed || trimmed.startsWith("#")) continue;
31
+ const normalized = trimmed.startsWith("export ") ? trimmed.slice("export ".length).trim() : trimmed;
32
+ const separatorIndex = normalized.indexOf("=");
33
+ if (separatorIndex <= 0) continue;
34
+ const key = normalized.slice(0, separatorIndex).trim();
35
+ env[key] = parseEnvValue(normalized.slice(separatorIndex + 1).trim());
36
+ }
37
+ return env;
38
+ };
39
+
40
+ interface ExecutorOptions {
41
+ workspaceRoot: string;
42
+ repoName: string;
43
+ }
44
+ export class WorkspaceExecutor extends Executor {
45
+ workspaceRoot: string;
46
+ repoName: string;
47
+ override emoji = execEmoji.workspace;
48
+ constructor({ workspaceRoot, repoName }: ExecutorOptions) {
49
+ super("workspace", workspaceRoot);
50
+ this.workspaceRoot = workspaceRoot;
51
+ this.repoName = repoName;
52
+ }
53
+
54
+ static fromRoot({
55
+ workspaceRoot = process.cwd(),
56
+ repoName = resolveRepoName(workspaceRoot),
57
+ }: {
58
+ workspaceRoot?: string;
59
+ repoName?: string;
60
+ } = {}) {
61
+ return new WorkspaceExecutor({ workspaceRoot, repoName });
62
+ }
63
+ /** The public env a native build was told to reproduce (`--public-env`): it outranks the shell, which outranks `.env`. */
64
+ static publicEnvPin: Record<string, string> | null = null;
65
+ static readonly localServeDomain = "localhost";
66
+ static getBaseDevEnv(envPath?: string) {
67
+ // Bun auto-loads .env, so we use process.env directly
68
+ const sourceEnv = {
69
+ ...(envPath ? parseEnvFile(envPath) : {}),
70
+ //? An empty export reads as unset, unlike in dotenv, so it can't blank a key the .env sets.
71
+ ...Object.fromEntries(Object.entries(process.env).filter(([, value]) => value)),
72
+ ...WorkspaceExecutor.publicEnvPin,
73
+ };
74
+
75
+ const appName = sourceEnv.AKAN_PUBLIC_APP_NAME;
76
+ const workspaceRoot = sourceEnv.AKAN_WORKSPACE_ROOT;
77
+ const workspaceId = sourceEnv.AKAN_WORKSPACE_ID;
78
+
79
+ const repoName =
80
+ sourceEnv.AKAN_PUBLIC_REPO_NAME ||
81
+ resolveRepoName(envPath ? path.dirname(envPath) : (workspaceRoot ?? process.cwd()));
82
+ const serveDomain = sourceEnv.AKAN_PUBLIC_SERVE_DOMAIN || WorkspaceExecutor.localServeDomain;
83
+ const defaulted = (["AKAN_PUBLIC_REPO_NAME", "AKAN_PUBLIC_SERVE_DOMAIN"] as const).filter((key) => !sourceEnv[key]);
84
+
85
+ const portOffset = parseInt(sourceEnv.PORT_OFFSET ?? "0");
86
+
87
+ const env = (sourceEnv.AKAN_PUBLIC_ENV ?? "debug") as
88
+ | "testing"
89
+ | "debug"
90
+ | "develop"
91
+ | "main"
92
+ | "local"
93
+ | undefined;
94
+ if (!env) throw new Error("AKAN_PUBLIC_ENV is not set");
95
+ return {
96
+ ...(appName ? { appName } : {}),
97
+ workspaceRoot,
98
+ repoName,
99
+ serveDomain,
100
+ env,
101
+ portOffset,
102
+ workspaceId,
103
+ defaulted,
104
+ };
105
+ }
106
+ //? A clone has no `.env` (gitignored for its secrets): it runs local, as a new workspace and env.server.ts do, not debug.
107
+ static defaultCloneToLocalEnv(workspaceRoot: string) {
108
+ if (!existsSync(path.join(workspaceRoot, ".env"))) process.env.AKAN_PUBLIC_ENV ??= "local";
109
+ }
110
+ //? A build or tunnel for a real environment carries these into an image, a bundle or a host name it dials.
111
+ static assertDeployableEnv(baseDevEnv: BaseDevEnv, environment: string, purpose: string) {
112
+ const defaulted = environment === "local" ? [] : (baseDevEnv.defaulted ?? []);
113
+ if (!defaulted.length) return;
114
+ const values = { AKAN_PUBLIC_REPO_NAME: baseDevEnv.repoName, AKAN_PUBLIC_SERVE_DOMAIN: baseDevEnv.serveDomain };
115
+ const standIns = defaulted.map((key) => `${key} (would be "${values[key]}")`).join(" and ");
116
+ throw new Error(
117
+ `${purpose} for the "${environment}" environment needs ${standIns} set, not a local default. ` +
118
+ `Set ${defaulted.length > 1 ? "them" : "it"} in the workspace .env or the shell, or use AKAN_PUBLIC_ENV=local.`,
119
+ );
120
+ }
121
+ getWorkspaceId<AllowEmpty extends boolean = false>({
122
+ allowEmpty,
123
+ }: {
124
+ allowEmpty?: AllowEmpty;
125
+ } = {}): AllowEmpty extends true ? string | undefined : string {
126
+ const { workspaceId } = WorkspaceExecutor.getBaseDevEnv();
127
+ if (!workspaceId && !allowEmpty) throw new Error("Workspace ID is not found");
128
+ return workspaceId as AllowEmpty extends true ? string | undefined : string;
129
+ }
130
+ async scan(): Promise<WorkspaceInfo> {
131
+ return await WorkspaceInfo.fromExecutor(this);
132
+ }
133
+ #akanConfig: AkanWorkspaceConfig | null = null;
134
+ async getConfig({ refresh }: { refresh?: boolean } = {}) {
135
+ if (this.#akanConfig && !refresh) return this.#akanConfig;
136
+ this.#akanConfig = await AkanWorkspaceConfig.from(this, { bustImportCache: refresh });
137
+ return this.#akanConfig;
138
+ }
139
+ async getApps() {
140
+ return await this.#getDirHasFile(`${this.workspaceRoot}/apps`, "akan.config.ts");
141
+ }
142
+ async getLibs() {
143
+ return await this.#getDirHasFile(`${this.workspaceRoot}/libs`, "akan.config.ts");
144
+ }
145
+ async getSyss() {
146
+ const [appNames, libNames] = await Promise.all([this.getApps(), this.getLibs()]);
147
+ return [appNames, libNames] as [string[], string[]];
148
+ }
149
+ async getPkgs() {
150
+ return await this.#getDirHasFile(`${this.workspaceRoot}/pkgs`, "package.json");
151
+ }
152
+ async getExecs() {
153
+ const [appNames, libNames, pkgNames] = await Promise.all([this.getApps(), this.getLibs(), this.getPkgs()]);
154
+ return [appNames, libNames, pkgNames] as [string[], string[], string[]];
155
+ }
156
+ async setPkgTsPaths(name: string) {
157
+ const rootTsConfig = (await this.readJson("tsconfig.json")) as TsConfigJson;
158
+ rootTsConfig.compilerOptions.paths ??= {};
159
+ rootTsConfig.compilerOptions.paths[name] = [`./pkgs/${name}/index.ts`];
160
+ rootTsConfig.compilerOptions.paths[`${name}/*`] = [`./pkgs/${name}/*`];
161
+ if (rootTsConfig.references) {
162
+ if (!rootTsConfig.references.some((ref) => ref.path === `./pkgs/${name}/tsconfig.json`))
163
+ rootTsConfig.references.push({ path: `./pkgs/${name}/tsconfig.json` });
164
+ }
165
+ await this.writeJson("tsconfig.json", rootTsConfig);
166
+ return this;
167
+ }
168
+ async unsetPkgTsPaths(name: string) {
169
+ const rootTsConfig = (await this.readJson("tsconfig.json")) as TsConfigJson;
170
+ const filteredKeys = Object.keys(rootTsConfig.compilerOptions.paths ?? {}).filter(
171
+ (key) => key !== name && key !== `${name}/*`,
172
+ );
173
+ rootTsConfig.compilerOptions.paths = Object.fromEntries(
174
+ filteredKeys.map((key) => [key, rootTsConfig.compilerOptions.paths?.[key] ?? []]),
175
+ );
176
+ if (rootTsConfig.references) {
177
+ rootTsConfig.references = rootTsConfig.references.filter(
178
+ (ref) => ref.path !== `./pkgs/${name}/tsconfig.json`,
179
+ ) as TsConfigJson["references"];
180
+ }
181
+ await this.writeJson("tsconfig.json", rootTsConfig);
182
+ return this;
183
+ }
184
+ async getDirInModule(basePath: string, name: string) {
185
+ const AVOID_DIRS = ["__lib", "__scalar", `_`, `_${name}`];
186
+ const getDirs = async (dirname: string, maxDepth = 3, results: string[] = [], prefix = "") => {
187
+ const dirs = await this.readdir(dirname);
188
+ await Promise.all(
189
+ dirs.map(async (dir) => {
190
+ if (dir.includes("_") || AVOID_DIRS.includes(dir)) return;
191
+ const dirPath = path.join(dirname, dir);
192
+ if (await FileSys.dirExists(this.getPath(dirPath))) {
193
+ results.push(`${prefix}${dir}`);
194
+ if (maxDepth > 0) await getDirs(dirPath, maxDepth - 1, results, `${prefix}${dir}/`);
195
+ }
196
+ }),
197
+ );
198
+ return results;
199
+ };
200
+ return await getDirs(basePath);
201
+ }
202
+ async commit(
203
+ message: string,
204
+ {
205
+ init = false,
206
+ add = true,
207
+ identity,
208
+ }: { init?: boolean; add?: boolean; identity?: { name: string; email: string } } = {},
209
+ ) {
210
+ if (init) await this.spawn("git", ["init", "--quiet"]);
211
+ if (add) await this.spawn("git", ["add", "."]);
212
+ const author = identity ? ["-c", `user.name=${identity.name}`, "-c", `user.email=${identity.email}`] : [];
213
+ // Argument vector, not a shell string: a message carrying a double quote breaks the interpolated form.
214
+ await this.spawn("git", [...author, "commit", "--quiet", "-m", message]);
215
+ }
216
+ /** `git commit` exits non-zero on an empty index, so a re-runnable caller has to ask first. */
217
+ async hasChanges() {
218
+ return !!(await this.spawn("git", ["status", "--porcelain"])).trim();
219
+ }
220
+ /** Sorted workspace-relative paths; `untracked` adds uncommitted files, still honoring `.gitignore`. */
221
+ async listGitFiles(paths: string[], { untracked = false }: { untracked?: boolean } = {}) {
222
+ if (!paths.length) return [];
223
+ const mode = untracked ? ["--cached", "--others", "--exclude-standard"] : ["--cached"];
224
+ const stdout = await this.spawn("git", ["ls-files", "-z", ...mode, "--", ...paths]);
225
+ return stdout
226
+ .split("\0")
227
+ .filter((file) => !!file)
228
+ .sort();
229
+ }
230
+ async #getDirHasFile(basePath: string, targetFilename: string) {
231
+ if (!(await FileSys.dirExists(basePath))) return [];
232
+ //? `local/` is gitignored scratch: a test's temporary workspace there has a package.json of its own.
233
+ const AVOID_DIRS = ["node_modules", "dist", "public", "webkit", "local"];
234
+ const getDirs = async (dirname: string, maxDepth = 3, results: string[] = [], prefix = "") => {
235
+ const dirs = await this.readdir(dirname);
236
+ await Promise.all(
237
+ dirs.map(async (dir) => {
238
+ if (AVOID_DIRS.includes(dir)) return;
239
+ const dirPath = path.join(dirname, dir);
240
+ //* Not `stat`: a dangling symlink would throw, and this walk backs `getApps`, i.e. every command.
241
+ if (await FileSys.dirExists(dirPath)) {
242
+ const hasTargetFile = await FileSys.fileExists(path.join(dirPath, targetFilename));
243
+ if (hasTargetFile) results.push(`${prefix}${dir}`);
244
+ if (maxDepth > 0) await getDirs(dirPath, maxDepth - 1, results, `${prefix}${dir}/`);
245
+ }
246
+ }),
247
+ );
248
+ return results;
249
+ };
250
+ return (await getDirs(basePath)).sort((a, b) => a.localeCompare(b));
251
+ }
252
+
253
+ async #fromEverySys<T>(read: (sys: SysExecutor) => Promise<T[]>): Promise<T[]> {
254
+ const [appNames, libNames] = await this.getSyss();
255
+ //? Plain SysExecutors: AppExecutor and LibExecutor extend SysExecutor, which imports this file, so importing them here
256
+ //? would load a subclass before its base. None of the readers below is overridden there.
257
+ const fromApps = await Promise.all(
258
+ appNames.map((name) => read(new SysExecutor({ workspace: this, name, type: "app" }))),
259
+ );
260
+ const fromLibs = await Promise.all(
261
+ libNames.map((name) => read(new SysExecutor({ workspace: this, name, type: "lib" }))),
262
+ );
263
+ return [...fromApps.flat(), ...fromLibs.flat()];
264
+ }
265
+ async getScalarConstantFiles() {
266
+ return await this.#fromEverySys((sys) => sys.getScalarConstantFiles());
267
+ }
268
+ async getConstantFiles() {
269
+ return await this.#fromEverySys((sys) => sys.getConstantFiles());
270
+ }
271
+ async getDictionaryFiles() {
272
+ return await this.#fromEverySys((sys) => sys.getDictionaryFiles());
273
+ }
274
+ async getViewFiles() {
275
+ return await this.#fromEverySys((sys) => sys.getViewsSourceCode());
276
+ }
277
+ }
@@ -1,7 +1,7 @@
1
1
  import { describe, expect, test } from "bun:test";
2
2
  import { mkdir, realpath, symlink } from "node:fs/promises";
3
3
  import path from "node:path";
4
- import { tempDirs, writeText as write } from "../testHelpers";
4
+ import { tempDirs, writeText as write } from "../test/testHelpers";
5
5
  import { AllRoutesBuilder } from "./allRoutesBuilder";
6
6
 
7
7
  const makeTempRoot = tempDirs("akan-all-routes-");
@@ -1,7 +1,7 @@
1
1
  import { describe, expect, test } from "bun:test";
2
2
  import { mkdir, readFile, writeFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
- import { tempDirs } from "../testHelpers";
4
+ import { tempDirs } from "../test/testHelpers";
5
5
  import { AutoImportSync, transformSource } from "./autoImportSync";
6
6
 
7
7
  const makeTempRoot = tempDirs("akan-auto-import-");
@@ -1,7 +1,7 @@
1
1
  import { readdir, readFile, stat } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import ts from "typescript";
4
- import { FileSys } from "../fileSys";
4
+ import { FileSys } from "../util/fileSys";
5
5
 
6
6
  //* Closed-registry scan (no type information); writes only on a real diff, or the watcher loops on its own edits.
7
7
 
@@ -1,7 +1,7 @@
1
1
  import { describe, expect, test } from "bun:test";
2
2
  import { realpath } from "node:fs/promises";
3
3
  import path from "node:path";
4
- import { tempDirs, writeText as write } from "../testHelpers";
4
+ import { tempDirs, writeText as write } from "../test/testHelpers";
5
5
  import { createTsconfigPackageResolver } from "../transforms/barrelImportsPlugin";
6
6
  import { CLIENT_BUNDLE_NAMING } from "./clientBuildTypes";
7
7
  import { ClientEntriesBundler } from "./clientEntriesBundler";
@@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test";
2
2
  import fs from "node:fs";
3
3
  import { realpath } from "node:fs/promises";
4
4
  import path from "node:path";
5
- import { tempDirs, writeText } from "../testHelpers";
5
+ import { tempDirs, writeText } from "../test/testHelpers";
6
6
  import { ClientEntriesBundler } from "./clientEntriesBundler";
7
7
 
8
8
  const makeTempRoot = tempDirs("akan-client-entries-");
@@ -1,6 +1,6 @@
1
1
  import { describe, expect, test } from "bun:test";
2
2
  import path from "node:path";
3
- import { tempDirs, writeText } from "../testHelpers";
3
+ import { tempDirs, writeText } from "../test/testHelpers";
4
4
  import { CsrArtifactBuilder } from "./csrArtifactBuilder";
5
5
 
6
6
  const makeTempRoot = tempDirs("akan-csr-artifact-");
@@ -11,7 +11,7 @@ import {
11
11
  type CsrDevManifest,
12
12
  csrDevModuleFile,
13
13
  } from "akanjs/server/hmr/csrDevManifest";
14
- import { FileSys } from "../fileSys";
14
+ import { FileSys } from "../util/fileSys";
15
15
  import { CsrDevPaths } from "./csrDevPaths";
16
16
  import type { CsrDevCode, CsrDevCompiledModule, CsrDevGraph } from "./csrDevTypes";
17
17
 
@@ -1,6 +1,6 @@
1
1
  import { describe, expect, test } from "bun:test";
2
2
  import path from "node:path";
3
- import { tempDirs, writeText as write } from "../testHelpers";
3
+ import { tempDirs, writeText as write } from "../test/testHelpers";
4
4
  import { CssCompiler, declaredCustomProperties } from "./cssCompiler";
5
5
 
6
6
  const makeTempRoot = tempDirs("akan-css-compiler-");
@@ -102,7 +102,8 @@ describe("CssCompiler.discoverCssAndSources", () => {
102
102
 
103
103
  const { sourcePaths } = await new CssCompiler(app as never).discoverCssAndSources({ pageKeys: ["_index.tsx"] });
104
104
 
105
- expect(sourcePaths.map((file) => path.relative(root, file)).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))).toEqual([
105
+ const relativePaths = sourcePaths.map((file) => path.relative(root, file).split(path.sep).join("/"));
106
+ expect(relativePaths.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))).toEqual([
106
107
  "apps/demo/lib/memo/Memo.Zone.tsx",
107
108
  "apps/demo/lib/memo/index.ts",
108
109
  "apps/demo/lib/st.ts",
@@ -1,7 +1,7 @@
1
1
  import { describe, expect, test } from "bun:test";
2
2
  import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
- import { tempDirs } from "../testHelpers";
4
+ import { tempDirs } from "../test/testHelpers";
5
5
  import { DevGeneratedIndexSync } from "./devGeneratedIndexSync";
6
6
 
7
7
  const makeTempRoot = tempDirs("akan-generated-index-");
@@ -1,13 +1,9 @@
1
1
  import { mkdir, readdir, readFile, rm, stat } from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { capitalize } from "akanjs/common";
4
- import { FileSys } from "../fileSys";
5
-
6
- const BARREL_FACETS = new Set(["common", "srvkit", "ui", "webkit", "plugin"]);
7
- const FACET_SOURCE_FILE_RE = /\.(ts|tsx)$/;
8
- const FACET_EXCLUDED_FILE_RE = /(^index\.tsx?$|\.d\.ts$|\.(test|spec)\.(ts|tsx)$|\.css$|\.scss$|\.sass$)/;
9
- const FACET_PASCAL_CASE_RE = /^[A-Z][A-Za-z0-9]*$/;
10
- const FACET_CAMEL_CASE_RE = /^[a-z][A-Za-z0-9]*$/;
3
+ import { barrelFacetDirs, capitalize, facetBarrelOf } from "akanjs/common";
4
+ import { FileSys } from "../util/fileSys";
5
+
6
+ const BARREL_FACETS = new Set<string>(barrelFacetDirs);
11
7
  const MODULE_UI_TYPES = ["Template", "Unit", "Util", "View", "Zone"] as const;
12
8
  const SERVICE_UI_TYPES = ["Util", "Zone"] as const;
13
9
  const SCALAR_UI_TYPES = ["Template", "Unit"] as const;
@@ -113,22 +109,11 @@ export class DevGeneratedIndexSync {
113
109
  }
114
110
 
115
111
  async #facetContent(dir: string): Promise<string | null> {
116
- const nameCasePattern = path.basename(dir) === "ui" ? FACET_PASCAL_CASE_RE : FACET_CAMEL_CASE_RE;
117
112
  const entries = await readdir(dir, { withFileTypes: true }).catch(() => null);
118
113
  if (!entries) return null;
119
- const exportNames = entries
120
- .flatMap((entry) => {
121
- const name = entry.name;
122
- if (name.startsWith(".")) return [];
123
- if (entry.isDirectory()) return nameCasePattern.test(name) ? [name] : [];
124
- if (!entry.isFile()) return [];
125
- if (!FACET_SOURCE_FILE_RE.test(name) || FACET_EXCLUDED_FILE_RE.test(name)) return [];
126
- const exportName = name.replace(FACET_SOURCE_FILE_RE, "");
127
- return nameCasePattern.test(exportName) ? [exportName] : [];
128
- })
129
- .sort(compareExportNames);
130
- if (exportNames.length === 0) return "export {};\n";
131
- return `${exportNames.map((name) => `export * from "./${name}";`).join("\n")}\n`;
114
+ const files = entries.filter((entry) => entry.isFile()).map((entry) => entry.name);
115
+ const dirs = entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
116
+ return facetBarrelOf(path.basename(dir), files, dirs);
132
117
  }
133
118
 
134
119
  async #moduleContent(dir: string): Promise<string | null> {
@@ -154,22 +139,6 @@ export class DevGeneratedIndexSync {
154
139
  }
155
140
  }
156
141
 
157
- //? Biome's organizeImports order, or `akan lint` reorders the barrel: A < a < B < b, a digit before a letter, and a
158
- //? run of digits compared by its length first. The facetIndex template sorts the same way.
159
- const letterRankOf = (char: string) => char.toLowerCase().charCodeAt(0) * 2 + (char === char.toLowerCase() ? 1 : 0);
160
- const digitRunAt = (name: string, idx: number) => /^\d+/.exec(name.slice(idx))?.[0] ?? "";
161
- const compareExportNames = (a: string, b: string) => {
162
- for (let idx = 0; idx < a.length && idx < b.length; ) {
163
- const [runA, runB] = [digitRunAt(a, idx), digitRunAt(b, idx)];
164
- if (runA && runB && runA !== runB) return runA.length - runB.length || (runA < runB ? -1 : 1);
165
- if (runA && runB) idx += runA.length;
166
- else if (runA || runB) return runA ? -1 : 1;
167
- else if (a.charAt(idx) !== b.charAt(idx)) return letterRankOf(a.charAt(idx)) - letterRankOf(b.charAt(idx));
168
- else idx++;
169
- }
170
- return a.length - b.length;
171
- };
172
-
173
142
  const exists = async (file: string) =>
174
143
  stat(file)
175
144
  .then(() => true)
@@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test";
2
2
  import { mkdir, readdir, writeFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import type { App } from "../commandDecorators";
5
- import { tempDirs } from "../testHelpers";
5
+ import { tempDirs } from "../test/testHelpers";
6
6
  import { DictionaryAssetBuilder } from "./dictionaryAssetBuilder";
7
7
 
8
8
  const tempRoot = tempDirs("akan-devkit-dict-asset-");
@@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test";
2
2
  import { mkdir, rm, stat, writeFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import type { App } from "../commandDecorators";
5
- import { tempDirs } from "../testHelpers";
5
+ import { tempDirs } from "../test/testHelpers";
6
6
  import { FontOptimizer } from "./fontOptimizer";
7
7
 
8
8
  const SOURCE_FONT = path.resolve(import.meta.dir, "../../../../libs/shared/public/fonts/Assistant-Regular.woff2");
@@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test";
2
2
  import { mkdir, rm, writeFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import type { App } from "../commandDecorators";
5
- import { tempDirs } from "../testHelpers";
5
+ import { tempDirs } from "../test/testHelpers";
6
6
  import { FontPruner } from "./fontPruner";
7
7
 
8
8
  const tempRoot = tempDirs("akan-devkit-font-prune-");
@@ -3,7 +3,7 @@ import { readFile, rm } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import type { RoutesManifest } from "akanjs/server";
6
- import { tempDirs, writeText as write } from "../testHelpers";
6
+ import { tempDirs, writeText as write } from "../test/testHelpers";
7
7
  import { CsrArtifactBuilder } from "./csrArtifactBuilder";
8
8
  import { CssCompiler, declaredCustomProperties, isIgnoredNodeModuleSource } from "./cssCompiler";
9
9
  import { CssImportResolver } from "./cssImportResolver";
@@ -123,7 +123,7 @@ describe("PagesBundleBuilder", () => {
123
123
  "",
124
124
  "const dictionary = {};",
125
125
  "const pageProto = makePageProto<typeof dict>(dictionary);",
126
- "const fetchProto = FetchClient.build<typeof signal>(cnst, getSerializedSignal(), { Err: pageProto.Err });",
126
+ "const fetchProto = FetchClient.build<typeof signal>(cnst, getSerializedSignal());",
127
127
  'export const runtime = registerClientRuntime({ ...pageProto, ...fetchProto }, { scope: "app" });',
128
128
  "",
129
129
  ].join("\n");
@@ -132,7 +132,7 @@ describe("PagesBundleBuilder", () => {
132
132
 
133
133
  expect(transformed).toContain('import { fetch as serverFetch } from "./sig";');
134
134
  expect(transformed).toContain(
135
- "const fetchProto = FetchClient.build<typeof signal>(cnst, serverFetch.serializedSignal, { Err: pageProto.Err, base: serverFetch });",
135
+ "const fetchProto = FetchClient.build<typeof signal>(cnst, serverFetch.serializedSignal, { base: serverFetch });",
136
136
  );
137
137
  expect(transformed).not.toContain("getSerializedSignal");
138
138
  expect(transformed).not.toContain('with { type: "macro" }');
@@ -0,0 +1,63 @@
1
+ import { describe, expect, mock, test } from "bun:test";
2
+ import path from "node:path";
3
+ import type { Logger } from "akanjs/common";
4
+ import { heldMtimeIndex, saveUntil, tempDirs, writeText } from "../test/testHelpers";
5
+ import type { ChangeBatch } from "./hmrWatcher";
6
+
7
+ const held = heldMtimeIndex();
8
+ mock.module("./sourceMtimeIndex", () => ({ SourceMtimeIndex: held.SourceMtimeIndex }));
9
+
10
+ const { HmrWatcher } = await import("./hmrWatcher");
11
+
12
+ const logger = {
13
+ verbose: () => undefined,
14
+ info: () => undefined,
15
+ warn: () => undefined,
16
+ error: () => undefined,
17
+ } as unknown as Logger;
18
+ const makeRoot = tempDirs("akan-hmr-watcher-stop-");
19
+ const tick = () => new Promise((resolve) => setTimeout(resolve, 0));
20
+
21
+ describe("HmrWatcher stopped while a scan runs", () => {
22
+ test("hands over no batch, though the scan settles with an edit made while it primed", async () => {
23
+ const root = await makeRoot();
24
+ const source = path.join(root, "lib/a.ts");
25
+ await writeText(source, "export const x = 0;\n");
26
+ const batches: ChangeBatch[] = [];
27
+ const watcher = new HmrWatcher({ roots: [root], logger, onBatch: (batch) => void batches.push(batch) });
28
+ const starting = watcher.start();
29
+ expect(await saveUntil(source, () => held.scans.length > 0)).toBe(true);
30
+ watcher.stop();
31
+ held.primes[0].resolve();
32
+ await starting;
33
+ held.scans[0].resolve([]);
34
+ await new Promise((resolve) => setTimeout(resolve, 0));
35
+ expect(batches).toEqual([]);
36
+ }, 15_000);
37
+
38
+ test("close hands back what the scan it interrupted found, though a later scan settles first", async () => {
39
+ held.primes.length = 0;
40
+ held.scans.length = 0;
41
+ const root = await makeRoot();
42
+ const source = path.join(root, "lib/a.ts");
43
+ const config = path.join(root, "akan.config.ts");
44
+ await writeText(source, "export const x = 0;\n");
45
+ const batches: ChangeBatch[] = [];
46
+ const watcher = new HmrWatcher({ roots: [root], logger, onBatch: (batch) => void batches.push(batch) });
47
+ const starting = watcher.start();
48
+ held.primes[0].resolve();
49
+ await starting;
50
+ expect(await saveUntil(source, () => held.scans.length > 0)).toBe(true);
51
+ const closing = watcher.close();
52
+ const settleLaterScans = async () => {
53
+ await tick();
54
+ for (const scan of held.scans.slice(1)) scan.resolve([]);
55
+ await tick();
56
+ };
57
+ await settleLaterScans();
58
+ held.scans[0].resolve([config]);
59
+ await settleLaterScans();
60
+ expect(await closing).toEqual({ files: [config], kinds: new Set(["config"]) });
61
+ expect(batches).toEqual([]);
62
+ }, 15_000);
63
+ });
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test";
2
2
  import { chmod, mkdir, writeFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import type { Logger } from "akanjs/common";
5
- import { tempDirs } from "../testHelpers";
5
+ import { tempDirs } from "../test/testHelpers";
6
6
  import { type ChangeBatch, HmrWatcher } from "./hmrWatcher";
7
7
 
8
8
  // The real Bun watcher, not a fake: the dropped-event behaviour under test only exists there.
@@ -29,6 +29,7 @@ export class HmrWatcher {
29
29
  readonly #hinted = new Set<string>();
30
30
  readonly #classifier = new HmrChangeClassifier();
31
31
  readonly #index: SourceMtimeIndex;
32
+ readonly #scans = new Set<Promise<void>>();
32
33
  #timer: ReturnType<typeof setTimeout> | null = null;
33
34
  #verifyTimer: ReturnType<typeof setTimeout> | null = null;
34
35
  #windowStartedAt: number | null = null;
@@ -98,6 +99,18 @@ export class HmrWatcher {
98
99
  }
99
100
  }
100
101
 
102
+ //? A scan stop() interrupts keeps its finds unreported, and the scan has already moved their mtime baseline.
103
+ async close(): Promise<ChangeBatch | null> {
104
+ this.stop();
105
+ await Promise.all(this.#scans);
106
+ await this.#mergeDetectedChanges();
107
+ if (this.#pending.size === 0) return null;
108
+ const batch = { files: Array.from(this.#pending.keys()), kinds: new Set(this.#pending.values()) };
109
+ this.#pending.clear();
110
+ this.#hinted.clear();
111
+ return batch;
112
+ }
113
+
101
114
  /** Baseline the batch handler's own writes so the verification scan does not rebuild them a second time. */
102
115
  async absorb(paths: string[]): Promise<void> {
103
116
  if (paths.length === 0) return;
@@ -143,6 +156,8 @@ export class HmrWatcher {
143
156
  try {
144
157
  while (!this.#stopped) {
145
158
  await this.#mergeDetectedChanges();
159
+ //? stop() can land while the scan runs; a batch handed over after it reaches an owner that has moved on.
160
+ if (this.#stopped) break;
146
161
  if (this.#pending.size === 0) {
147
162
  this.#windowStartedAt = null;
148
163
  break;
@@ -167,7 +182,13 @@ export class HmrWatcher {
167
182
  }
168
183
  }
169
184
 
170
- async #mergeDetectedChanges(): Promise<void> {
185
+ #mergeDetectedChanges(): Promise<void> {
186
+ const scan = this.#collectDetectedChanges().finally(() => this.#scans.delete(scan));
187
+ this.#scans.add(scan);
188
+ return scan;
189
+ }
190
+
191
+ async #collectDetectedChanges(): Promise<void> {
171
192
  const detected = await this.#index.collectChanges().catch((err) => {
172
193
  this.#logger.error(`[hmr] mtime scan failed: ${(err as Error).message}`);
173
194
  return [] as string[];
@@ -1,6 +1,6 @@
1
1
  import { describe, expect, test } from "bun:test";
2
2
  import path from "node:path";
3
- import { tempDirs, writeText as write } from "../testHelpers";
3
+ import { tempDirs, writeText as write } from "../test/testHelpers";
4
4
  import { CsrArtifactBuilder } from "./csrArtifactBuilder";
5
5
  import { McpAppViewBuilder } from "./mcpAppViewBuilder";
6
6
 
@@ -115,7 +115,7 @@ export class McpAppViewBuilder {
115
115
 
116
116
  /** Every `.app()` the pages declare, read off their sources without evaluating them. */
117
117
  static async discover(pageEntries: PageEntry[], basePaths: string[]): Promise<McpAppView[]> {
118
- const { RouteSourceValidator } = await import("../routeSourceValidator");
118
+ const { RouteSourceValidator } = await import("../app/routeSourceValidator");
119
119
  const roots = pageEntries.filter((entry) => parseRouteModuleKey(entry.key).isInternalRootLayout);
120
120
  const overrides = pageEntries.filter((entry) => parseRouteModuleKey(entry.key).kind === "overrides");
121
121
  const layoutNodes = new Set(
@@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test";
2
2
  import { existsSync } from "node:fs";
3
3
  import { mkdir, realpath, symlink } from "node:fs/promises";
4
4
  import path from "node:path";
5
- import { tempDirs, writeText as write } from "../testHelpers";
5
+ import { tempDirs, writeText as write } from "../test/testHelpers";
6
6
  import { createBarrelImportsPlugin } from "../transforms/barrelImportsPlugin";
7
7
 
8
8
  const makeTempRoot = tempDirs("akan-native-core-");