@akanjs/devkit 3.2.0-rc.9 → 3.2.1-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 (353) hide show
  1. package/CHANGELOG.md +0 -529
  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 +152 -6
  7. package/akanApp/akanApp.host.ts +187 -1220
  8. package/akanApp/akanApp.host.wiring.test.ts +931 -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 +394 -0
  14. package/akanApp/devBuildStatusBoard.ts +128 -0
  15. package/akanApp/devBuilder.ts +200 -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/devStartTimeline.test.ts +115 -0
  22. package/akanApp/devStartTimeline.ts +69 -0
  23. package/akanApp/processRss.ts +61 -0
  24. package/akanConfig/akanConfig.test.ts +45 -17
  25. package/akanConfig/akanConfig.ts +10 -10
  26. package/akanConfig/akanWorkspaceConfig.ts +1 -1
  27. package/akanConfig/productionLockfile.ts +1 -1
  28. package/apiReport/apiReport.test.ts +34 -3
  29. package/apiReport/apiReportDiff.ts +35 -1
  30. package/apiReport/apiReportPolicy.ts +3 -2
  31. package/{applicationBuildReporter.ts → app/applicationBuildReporter.ts} +2 -49
  32. package/{applicationBuildRunner.test.ts → app/applicationBuildRunner.test.ts} +71 -8
  33. package/{applicationBuildRunner.ts → app/applicationBuildRunner.ts} +60 -21
  34. package/{applicationTestPreload.ts → app/applicationTestPreload.ts} +1 -1
  35. package/{routeJsBudget.test.ts → app/routeJsBudget.test.ts} +17 -1
  36. package/{routeJsBudget.ts → app/routeJsBudget.ts} +9 -3
  37. package/{routeSourceValidator.test.ts → app/routeSourceValidator.test.ts} +17 -0
  38. package/{routeSourceValidator.ts → app/routeSourceValidator.ts} +5 -1
  39. package/artifact/implicitRootLayout.test.ts +71 -3
  40. package/artifact/implicitRootLayout.ts +9 -3
  41. package/artifact/implicitRootLayoutRender.test.tsx +297 -0
  42. package/biome.base.json +2 -1
  43. package/cloud/cloudApi.test.ts +1 -1
  44. package/cloud/configLock.test.ts +1 -1
  45. package/cloud/globalConfig.test.ts +1 -1
  46. package/cloud/globalConfig.ts +1 -1
  47. package/cloud/updatePackUpload.test.ts +1 -1
  48. package/codeAgent/agent/AkanCodeEnv.ts +1 -1
  49. package/codeAgent/agent/AkanCodeServices.ts +23 -0
  50. package/codeAgent/agent/akanCodePaths.ts +1 -1
  51. package/codeAgent/agent/akanCodeServices.test.ts +54 -0
  52. package/codeAgent/agent/akanSystemPrompt.ts +1 -1
  53. package/codeAgent/agent/codeAgent.test.ts +1 -1
  54. package/codeAgent/skills/akan-debug/SKILL.md +8 -5
  55. package/codeAgent/skills/akan-err/SKILL.md +7 -0
  56. package/codeAgent/skills/akan-mcp/SKILL.md +19 -1
  57. package/codeAgent/skills/akan-scaffold/SKILL.md +1 -1
  58. package/codeAgent/skills/akan-validate/SKILL.md +3 -3
  59. package/codeAgent/tools/AkanCli.ts +1 -1
  60. package/codeAgent/tools/AkanToolPack.ts +2 -2
  61. package/codeAgent/tools/akanCodePlugins.test.ts +1 -1
  62. package/commandDecorators/command.ts +35 -6
  63. package/commandDecorators/commandBuilder.ts +1 -1
  64. package/commandDecorators/commandDecorators.test.ts +107 -6
  65. package/commandDecorators/targetMeta.ts +2 -0
  66. package/commandDecorators/workspaceVersionCheck.test.ts +70 -1
  67. package/commandDecorators/workspaceVersionCheck.ts +64 -14
  68. package/context/akanContext.ts +576 -0
  69. package/context/akanContextInspection.ts +296 -0
  70. package/{akanMcpContract.test.ts → context/akanMcpContract.test.ts} +1 -1
  71. package/{akanMcpContract.ts → context/akanMcpContract.ts} +16 -256
  72. package/context/doctor/agentGuideCheck.ts +81 -0
  73. package/context/doctor/configLeftoverCheck.ts +35 -0
  74. package/context/doctor/doctorFindings.ts +70 -0
  75. package/context/doctor/generatedFreshness.ts +56 -0
  76. package/context/doctor/moduleShapeCheck.ts +88 -0
  77. package/context/doctor/recipeDuplicateCheck.ts +42 -0
  78. package/context/doctor/recipeIndexCheck.ts +87 -0
  79. package/context/doctor/rootShapeCheck.ts +55 -0
  80. package/context/doctor/workflowScope.ts +97 -0
  81. package/{recipeScanner.test.ts → context/recipeScanner.test.ts} +1 -1
  82. package/context/safeRead.ts +9 -0
  83. package/csrE2e/csrE2eHarness.fixture.ts +1 -1
  84. package/devkitUtils.test.ts +39 -5
  85. package/{apiReference.test.ts → docs/apiReference.test.ts} +4 -4
  86. package/{apiReference.ts → docs/apiReference.ts} +2 -2
  87. package/docs/errorCodeReference.test.ts +282 -0
  88. package/docs/errorCodeReference.ts +71 -0
  89. package/docs/errorCodeScan.ts +551 -0
  90. package/{frameworkGraph.test.ts → docs/frameworkGraph.test.ts} +1 -1
  91. package/executors/appExecutor.ts +463 -0
  92. package/executors/commandExecutionError.ts +53 -0
  93. package/executors/executor.ts +527 -0
  94. package/{executors.linkFallback.test.ts → executors/executors.linkFallback.test.ts} +1 -1
  95. package/{executors.test.ts → executors/executors.test.ts} +106 -18
  96. package/executors/index.ts +8 -0
  97. package/executors/libExecutor.ts +23 -0
  98. package/executors/moduleExecutor.ts +18 -0
  99. package/executors/pkgExecutor.ts +129 -0
  100. package/executors/sysExecutor.ts +301 -0
  101. package/executors/workspaceExecutor.ts +277 -0
  102. package/frontendBuild/allRoutesBuilder.test.ts +1 -1
  103. package/frontendBuild/autoImportSync.test.ts +1 -1
  104. package/frontendBuild/autoImportSync.ts +1 -1
  105. package/frontendBuild/buildCacheStamp.test.ts +42 -0
  106. package/frontendBuild/buildCacheStamp.ts +23 -0
  107. package/frontendBuild/buildRouteClient.test.ts +1 -1
  108. package/frontendBuild/clientEntriesBundler.test.ts +1 -1
  109. package/frontendBuild/csrArtifactBuilder.test.ts +1 -1
  110. package/frontendBuild/csrDevArtifactWriter.ts +1 -1
  111. package/frontendBuild/cssCandidateCache.test.ts +70 -1
  112. package/frontendBuild/cssCandidateCache.ts +17 -10
  113. package/frontendBuild/cssCompiler.test.ts +3 -2
  114. package/frontendBuild/devGeneratedIndexSync.test.ts +1 -1
  115. package/frontendBuild/devGeneratedIndexSync.ts +7 -38
  116. package/frontendBuild/dictionaryAssetBuilder.test.ts +1 -1
  117. package/frontendBuild/fontOptimizer.test.ts +145 -4
  118. package/frontendBuild/fontOptimizer.ts +103 -18
  119. package/frontendBuild/fontPruner.test.ts +1 -1
  120. package/frontendBuild/frontendBuild.test.ts +3 -3
  121. package/frontendBuild/hmrWatcher.stop.test.ts +63 -0
  122. package/frontendBuild/hmrWatcher.test.ts +1 -1
  123. package/frontendBuild/hmrWatcher.ts +22 -1
  124. package/frontendBuild/mcpAppViewBuilder.test.ts +1 -1
  125. package/frontendBuild/mcpAppViewBuilder.ts +1 -1
  126. package/frontendBuild/nativeCore.test.ts +1 -1
  127. package/frontendBuild/optionalPeers.test.ts +36 -8
  128. package/frontendBuild/pagesBundleBuilder.test.ts +2 -3
  129. package/frontendBuild/pagesBundleBuilder.ts +1 -1
  130. package/frontendBuild/precompressArtifacts.test.ts +1 -1
  131. package/frontendBuild/precompressArtifacts.ts +19 -6
  132. package/frontendBuild/serverGraphFile.ts +1 -1
  133. package/frontendBuild/sourceMtimeIndex.test.ts +1 -1
  134. package/frontendBuild/ssrBaseArtifactBuilder.test.ts +30 -1
  135. package/frontendBuild/ssrBaseArtifactBuilder.ts +40 -12
  136. package/frontendBuild/ssrDevBundler.test.ts +1 -1
  137. package/frontendBuild/vendorImportScanner.test.ts +1 -1
  138. package/frontendBuild/vendorNarrowing.test.ts +1 -1
  139. package/frontendBuild/watchRootResolver.test.ts +1 -1
  140. package/{agentAssets.test.ts → guideline/agentAssets.test.ts} +1 -1
  141. package/{agentAssets.ts → guideline/agentAssets.ts} +2 -2
  142. package/{agentsIndex.test.ts → guideline/agentsIndex.test.ts} +2 -2
  143. package/{agentsIndex.ts → guideline/agentsIndex.ts} +13 -10
  144. package/{conventionSet.test.ts → guideline/conventionSet.test.ts} +7 -4
  145. package/{conventionSet.ts → guideline/conventionSet.ts} +1 -1
  146. package/{prompter.ts → guideline/prompter.ts} +2 -3
  147. package/incrementalBuilder/buildBatch.proc.ts +16 -5
  148. package/incrementalBuilder/buildBatchProtocol.ts +3 -0
  149. package/incrementalBuilder/buildBatchRunner.test.ts +122 -2
  150. package/incrementalBuilder/buildBatchRunner.ts +17 -4
  151. package/incrementalBuilder/builderBoot.ts +113 -0
  152. package/incrementalBuilder/builderBuildStatus.ts +23 -0
  153. package/incrementalBuilder/builderChannel.test.ts +1 -1
  154. package/incrementalBuilder/builderChannel.ts +19 -2
  155. package/incrementalBuilder/builderGraphPayloads.ts +3 -3
  156. package/incrementalBuilder/builderLanes.ts +157 -0
  157. package/incrementalBuilder/builderWatch.ts +213 -0
  158. package/incrementalBuilder/csrRegistry.ts +234 -0
  159. package/incrementalBuilder/incrementalBuilder.host.test.ts +16 -0
  160. package/incrementalBuilder/incrementalBuilder.host.ts +7 -1
  161. package/incrementalBuilder/incrementalBuilder.proc.test.ts +142 -7
  162. package/incrementalBuilder/incrementalBuilder.proc.ts +82 -823
  163. package/incrementalBuilder/ssrRegistry.ts +282 -0
  164. package/index.ts +22 -22
  165. package/integration/devStability.integration.test.ts +62 -56
  166. package/integration/devStabilityHarness.test.ts +1 -1
  167. package/lint/__fixtures__/no-import-common-err/bad.tsx +13 -0
  168. package/lint/__fixtures__/no-import-common-err/good.tsx +12 -0
  169. package/{biomeBase.test.ts → lint/biomeBase.test.ts} +1 -1
  170. package/lint/gritRules.test.ts +1 -1
  171. package/{linter.test.ts → lint/linter.test.ts} +1 -1
  172. package/lint/no-import-common-err.grit +31 -0
  173. package/lint/no-init-fetch-in-client.grit +1 -1
  174. package/mobile/desktopBin.test.ts +1 -1
  175. package/mobile/desktopRelease.test.ts +1 -1
  176. package/mobile/desktopServerStage.test.ts +2 -2
  177. package/mobile/desktopServerStage.ts +1 -1
  178. package/mobile/nativeApi.test.ts +1 -1
  179. package/mobile/nativeApp.test.ts +1 -1
  180. package/mobile/nativeConfig.test.ts +1 -1
  181. package/mobile/nativePluginFolders.test.ts +1 -1
  182. package/mobile/nativePublicEnv.test.ts +1 -1
  183. package/mobile/nativePublicEnv.ts +2 -1
  184. package/mobile/nativeWebDir.test.ts +1 -1
  185. package/mobile/serverBundleSecrets.test.ts +1 -1
  186. package/mobile/tarWriter.test.ts +1 -1
  187. package/mobile/updatePackFolder.test.ts +1 -1
  188. package/package.json +173 -9
  189. package/packageExports.test.ts +20 -2
  190. package/piDependencyPins.test.ts +1 -1
  191. package/pipeline/PipelineDefinition.ts +1 -1
  192. package/platformTest/IdleWatchedProcess.test.ts +1 -1
  193. package/platformTest/LinuxDockerTarget.ts +1 -1
  194. package/platformTest/PlatformTestRun.test.ts +1 -1
  195. package/platformTest/TestSnapshot.test.ts +1 -1
  196. package/platformTest/WindowsSshTarget.ts +1 -1
  197. package/preview/previewView.test.ts +23 -1
  198. package/{abstractDoc.test.ts → quality/abstractDoc.test.ts} +2 -2
  199. package/{abstractDoc.ts → quality/abstractDoc.ts} +1 -1
  200. package/quality/bareErrorScanner.ts +126 -0
  201. package/{maintainabilityBaseline.test.ts → quality/maintainabilityBaseline.test.ts} +73 -0
  202. package/{maintainabilityBaseline.ts → quality/maintainabilityBaseline.ts} +97 -9
  203. package/{maintainabilityContract.test.ts → quality/maintainabilityContract.test.ts} +383 -2
  204. package/{maintainabilityContract.ts → quality/maintainabilityContract.ts} +151 -29
  205. package/{maintainabilityExceptionScanner.test.ts → quality/maintainabilityExceptionScanner.test.ts} +15 -1
  206. package/{maintainabilityExceptionScanner.ts → quality/maintainabilityExceptionScanner.ts} +5 -1
  207. package/{maintainabilityLimits.ts → quality/maintainabilityLimits.ts} +12 -0
  208. package/{maintainabilityReport.ts → quality/maintainabilityReport.ts} +20 -3
  209. package/{qualityScanner.test.ts → quality/qualityScanner.test.ts} +41 -1
  210. package/{qualityScanner.ts → quality/qualityScanner.ts} +25 -91
  211. package/{storeAccessScanner.ts → quality/storeAccessScanner.ts} +15 -2
  212. package/quality/workspaceSourceFiles.ts +82 -0
  213. package/{subspace.test.ts → subspace/subspace.test.ts} +25 -4
  214. package/{subspace.ts → subspace/subspace.ts} +5 -5
  215. package/{subspaceClone.ts → subspace/subspaceClone.ts} +8 -8
  216. package/{subspaceConfig.ts → subspace/subspaceConfig.ts} +5 -1
  217. package/{testHelpers.ts → test/testHelpers.ts} +37 -1
  218. package/transforms/barrelAnalyzer.ts +31 -10
  219. package/transforms/browserDirnamePlugin.test.ts +1 -1
  220. package/transforms/externalizeFrameworkPlugin.test.ts +1 -1
  221. package/transforms/mcpAppPageTrimmer.test.ts +1 -1
  222. package/transforms/pureLazyMarker.test.ts +1 -1
  223. package/transforms/serverEnvPlugin.test.ts +1 -1
  224. package/transforms/serverEnvProfile.test.ts +1 -1
  225. package/transforms/sideEffectImportOrder.test.ts +1 -1
  226. package/transforms/transforms.test.ts +52 -2
  227. package/transforms/tsconfigPackageResolver.test.ts +1 -1
  228. package/{createTunnel.test.ts → tunnel/createTunnel.test.ts} +1 -1
  229. package/{createTunnel.ts → tunnel/createTunnel.ts} +2 -2
  230. package/{sshHostKeys.ts → tunnel/sshHostKeys.ts} +2 -2
  231. package/typecheck/projectTypecheck.test.ts +23 -1
  232. package/typecheck/projectTypecheck.ts +10 -2
  233. package/{typeChecker.test.ts → typecheck/typeChecker.test.ts} +1 -1
  234. package/{typeChecker.ts → typecheck/typeChecker.ts} +5 -4
  235. package/typecheck/typecheck.proc.ts +6 -2
  236. package/typecheck/typecheckFailure.ts +1 -1
  237. package/util/errorReport.ts +66 -0
  238. package/{fileSys.test.ts → util/fileSys.test.ts} +13 -0
  239. package/{fileSys.ts → util/fileSys.ts} +2 -2
  240. package/{jsonFormatter.test.ts → util/jsonFormatter.test.ts} +1 -1
  241. package/workflow/constantSource.ts +187 -0
  242. package/workflow/dictionarySource.ts +184 -0
  243. package/workflow/executor.ts +6 -9
  244. package/workflow/fieldExpression.ts +153 -0
  245. package/workflow/fieldLabel.ts +61 -0
  246. package/workflow/fieldOrder.ts +117 -0
  247. package/workflow/fieldType.ts +2 -1
  248. package/workflow/guardCatalog.test.ts +1 -1
  249. package/workflow/keyRename.ts +1 -1
  250. package/workflow/moduleIndex.test.ts +2 -2
  251. package/workflow/moduleIndex.ts +2 -2
  252. package/workflow/modulePaths.ts +27 -0
  253. package/workflow/mutationScaffold.ts +7 -15
  254. package/workflow/mutationSource.ts +2 -1
  255. package/workflow/plan.ts +2 -1
  256. package/workflow/primitiveReport.ts +78 -0
  257. package/workflow/rolloutGate.test.ts +1 -1
  258. package/workflow/rolloutGate.ts +1 -1
  259. package/workflow/serviceSource.ts +33 -0
  260. package/workflow/signalSource.ts +96 -0
  261. package/workflow/source.ts +50 -1100
  262. package/workflow/sourceAst.ts +30 -0
  263. package/workflow/sourceImports.ts +105 -0
  264. package/workflow/sourceText.ts +13 -0
  265. package/workflow/templateSource.ts +30 -0
  266. package/workflow/testSource.ts +31 -0
  267. package/workflow/types.ts +1 -1
  268. package/workflow/uiPolicy.ts +1 -1
  269. package/{appSelectionMemory.ts → workspace/appSelectionMemory.ts} +1 -1
  270. package/{codegenLock.test.ts → workspace/codegenLock.test.ts} +1 -1
  271. package/{dependencyScanner.test.ts → workspace/dependencyScanner.test.ts} +1 -1
  272. package/{dependencyScanner.ts → workspace/dependencyScanner.ts} +2 -2
  273. package/{envSeed.test.ts → workspace/envSeed.test.ts} +2 -2
  274. package/{envSeed.ts → workspace/envSeed.ts} +1 -1
  275. package/{libSource.test.ts → workspace/libSource.test.ts} +2 -2
  276. package/{libSource.ts → workspace/libSource.ts} +1 -1
  277. package/{scanInfo.ts → workspace/scanInfo.ts} +21 -10
  278. package/{slicePlanner.test.ts → workspace/slicePlanner.test.ts} +2 -2
  279. package/{slicePlanner.ts → workspace/slicePlanner.ts} +1 -1
  280. package/{workspaceGraph.test.ts → workspace/workspaceGraph.test.ts} +1 -1
  281. package/{workspaceGraph.ts → workspace/workspaceGraph.ts} +1 -1
  282. package/{workspaceLayout.test.ts → workspace/workspaceLayout.test.ts} +1 -1
  283. package/{workspaceLayout.ts → workspace/workspaceLayout.ts} +3 -1
  284. package/akanContext.ts +0 -1083
  285. package/executors.ts +0 -1749
  286. /package/{applicationBuildReporter.test.ts → app/applicationBuildReporter.test.ts} +0 -0
  287. /package/{akanMcpToolError.ts → context/akanMcpToolError.ts} +0 -0
  288. /package/{moduleFieldNames.test.ts → context/moduleFieldNames.test.ts} +0 -0
  289. /package/{moduleFieldNames.ts → context/moduleFieldNames.ts} +0 -0
  290. /package/{recipeScanner.ts → context/recipeScanner.ts} +0 -0
  291. /package/{declarationReader.ts → docs/declarationReader.ts} +0 -0
  292. /package/{frameworkGraph.ts → docs/frameworkGraph.ts} +0 -0
  293. /package/{biomeBase.ts → lint/biomeBase.ts} +0 -0
  294. /package/{linter.ts → lint/linter.ts} +0 -0
  295. /package/{commentDensityScanner.test.ts → quality/commentDensityScanner.test.ts} +0 -0
  296. /package/{commentDensityScanner.ts → quality/commentDensityScanner.ts} +0 -0
  297. /package/{componentSizeScanner.test.ts → quality/componentSizeScanner.test.ts} +0 -0
  298. /package/{componentSizeScanner.ts → quality/componentSizeScanner.ts} +0 -0
  299. /package/{componentWriteChainScanner.test.ts → quality/componentWriteChainScanner.test.ts} +0 -0
  300. /package/{componentWriteChainScanner.ts → quality/componentWriteChainScanner.ts} +0 -0
  301. /package/{deprecatedCommentScanner.test.ts → quality/deprecatedCommentScanner.test.ts} +0 -0
  302. /package/{deprecatedCommentScanner.ts → quality/deprecatedCommentScanner.ts} +0 -0
  303. /package/{endpointReach.test.ts → quality/endpointReach.test.ts} +0 -0
  304. /package/{endpointReach.ts → quality/endpointReach.ts} +0 -0
  305. /package/{formSetterScanner.test.ts → quality/formSetterScanner.test.ts} +0 -0
  306. /package/{formSetterScanner.ts → quality/formSetterScanner.ts} +0 -0
  307. /package/{kindBranchScanner.test.ts → quality/kindBranchScanner.test.ts} +0 -0
  308. /package/{kindBranchScanner.ts → quality/kindBranchScanner.ts} +0 -0
  309. /package/{maintainabilityReport.test.ts → quality/maintainabilityReport.test.ts} +0 -0
  310. /package/{renderMutationScanner.test.ts → quality/renderMutationScanner.test.ts} +0 -0
  311. /package/{renderMutationScanner.ts → quality/renderMutationScanner.ts} +0 -0
  312. /package/{serviceLoopCallScanner.test.ts → quality/serviceLoopCallScanner.test.ts} +0 -0
  313. /package/{serviceLoopCallScanner.ts → quality/serviceLoopCallScanner.ts} +0 -0
  314. /package/{signalMutationIndex.test.ts → quality/signalMutationIndex.test.ts} +0 -0
  315. /package/{signalMutationIndex.ts → quality/signalMutationIndex.ts} +0 -0
  316. /package/{sourceComments.test.ts → quality/sourceComments.test.ts} +0 -0
  317. /package/{sourceComments.ts → quality/sourceComments.ts} +0 -0
  318. /package/{ssrScanner.test.ts → quality/ssrScanner.test.ts} +0 -0
  319. /package/{ssrScanner.ts → quality/ssrScanner.ts} +0 -0
  320. /package/{storeAccessScanner.test.ts → quality/storeAccessScanner.test.ts} +0 -0
  321. /package/{storeSource.ts → quality/storeSource.ts} +0 -0
  322. /package/{storeWriteScanner.test.ts → quality/storeWriteScanner.test.ts} +0 -0
  323. /package/{storeWriteScanner.ts → quality/storeWriteScanner.ts} +0 -0
  324. /package/{structureScanner.test.ts → quality/structureScanner.test.ts} +0 -0
  325. /package/{structureScanner.ts → quality/structureScanner.ts} +0 -0
  326. /package/{testOnlyExportScanner.test.ts → quality/testOnlyExportScanner.test.ts} +0 -0
  327. /package/{testOnlyExportScanner.ts → quality/testOnlyExportScanner.ts} +0 -0
  328. /package/{writePath.test.ts → quality/writePath.test.ts} +0 -0
  329. /package/{writePath.ts → quality/writePath.ts} +0 -0
  330. /package/{writePlacementScanner.test.ts → quality/writePlacementScanner.test.ts} +0 -0
  331. /package/{writePlacementScanner.ts → quality/writePlacementScanner.ts} +0 -0
  332. /package/{writingActionIndex.test.ts → quality/writingActionIndex.test.ts} +0 -0
  333. /package/{writingActionIndex.ts → quality/writingActionIndex.ts} +0 -0
  334. /package/{subspaceReport.ts → subspace/subspaceReport.ts} +0 -0
  335. /package/{sshTunnel.ts → tunnel/sshTunnel.ts} +0 -0
  336. /package/{fileEditor.ts → util/fileEditor.ts} +0 -0
  337. /package/{jsonFormatter.ts → util/jsonFormatter.ts} +0 -0
  338. /package/{selectModel.ts → util/selectModel.ts} +0 -0
  339. /package/{semver.test.ts → util/semver.test.ts} +0 -0
  340. /package/{semver.ts → util/semver.ts} +0 -0
  341. /package/{shellOnlyEnv.test.ts → util/shellOnlyEnv.test.ts} +0 -0
  342. /package/{shellOnlyEnv.ts → util/shellOnlyEnv.ts} +0 -0
  343. /package/{spinner.test.ts → util/spinner.test.ts} +0 -0
  344. /package/{spinner.ts → util/spinner.ts} +0 -0
  345. /package/{stripAnsi.ts → util/stripAnsi.ts} +0 -0
  346. /package/{codegenLock.ts → workspace/codegenLock.ts} +0 -0
  347. /package/{getRelatedCnsts.ts → workspace/getRelatedCnsts.ts} +0 -0
  348. /package/{gitRevision.test.ts → workspace/gitRevision.test.ts} +0 -0
  349. /package/{gitRevision.ts → workspace/gitRevision.ts} +0 -0
  350. /package/{manifestDependencies.ts → workspace/manifestDependencies.ts} +0 -0
  351. /package/{packageExportsMap.ts → workspace/packageExportsMap.ts} +0 -0
  352. /package/{repoIdentity.ts → workspace/repoIdentity.ts} +0 -0
  353. /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
 
@@ -0,0 +1,42 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { appendFile, utimes, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { tempDirs } from "../test/testHelpers";
5
+ import { buildCacheStamp, isBuildCacheStamp } from "./buildCacheStamp";
6
+
7
+ const tempRoot = tempDirs("akan-devkit-stamp-");
8
+
9
+ const makeProducer = async () => {
10
+ const file = path.join(await tempRoot(), "producer.ts");
11
+ await writeFile(file, "export const regex = /x/;\n");
12
+ await utimes(file, new Date(1_700_000_000_000), new Date(1_700_000_000_000));
13
+ return file;
14
+ };
15
+
16
+ describe("buildCacheStamp", () => {
17
+ test("matches a stamp taken from the same producing file", async () => {
18
+ const file = await makeProducer();
19
+ expect(isBuildCacheStamp(buildCacheStamp([file]), buildCacheStamp([file]))).toBe(true);
20
+ });
21
+
22
+ test("misses when the producing file's mtime moves", async () => {
23
+ const file = await makeProducer();
24
+ const before = buildCacheStamp([file]);
25
+ await utimes(file, new Date(1_700_000_001_000), new Date(1_700_000_001_000));
26
+ expect(isBuildCacheStamp(before, buildCacheStamp([file]))).toBe(false);
27
+ });
28
+
29
+ test("misses when the producing file's size changes under the same mtime", async () => {
30
+ const file = await makeProducer();
31
+ const before = buildCacheStamp([file]);
32
+ await appendFile(file, "export const more = 1;\n");
33
+ await utimes(file, new Date(1_700_000_000_000), new Date(1_700_000_000_000));
34
+ expect(isBuildCacheStamp(before, buildCacheStamp([file]))).toBe(false);
35
+ });
36
+
37
+ test("misses an entry written before the stamp named its producing files", async () => {
38
+ const file = await makeProducer();
39
+ const { code: _, ...older } = buildCacheStamp([file]);
40
+ expect(isBuildCacheStamp(older, buildCacheStamp([file]))).toBe(false);
41
+ });
42
+ });
@@ -0,0 +1,23 @@
1
+ import { statSync } from "node:fs";
2
+ import { AkanAppConfig } from "../akanConfig/akanConfig";
3
+
4
+ export interface BuildCacheStamp {
5
+ akanjs: string;
6
+ bun: string;
7
+ code: string;
8
+ }
9
+
10
+ //? Kept across starts, so another akanjs, Bun or edit of the producing module (run from source) must read as a miss.
11
+ export const buildCacheStamp = (producers: string[]): BuildCacheStamp => ({
12
+ akanjs: AkanAppConfig.akanVersion,
13
+ bun: `${Bun.version}+${Bun.revision}`,
14
+ code: producers
15
+ .map((file) => {
16
+ const stats = statSync(file, { throwIfNoEntry: false });
17
+ return stats ? `${stats.mtimeMs}:${stats.size}` : "missing";
18
+ })
19
+ .join(","),
20
+ });
21
+
22
+ export const isBuildCacheStamp = (value: Partial<BuildCacheStamp> | null | undefined, stamp: BuildCacheStamp) =>
23
+ value?.akanjs === stamp.akanjs && value.bun === stamp.bun && value.code === stamp.code;
@@ -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,7 +1,8 @@
1
1
  import { describe, expect, test } from "bun:test";
2
- import { mkdtemp, writeFile } from "node:fs/promises";
2
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import path from "node:path";
5
+ import type { BuildCacheStamp } from "./buildCacheStamp";
5
6
  import { CssCandidateCache } from "./cssCandidateCache";
6
7
 
7
8
  const scan = async (source: string) => {
@@ -56,3 +57,71 @@ describe("CssCandidateCache token extraction", () => {
56
57
  expect(candidates.filter((candidate) => candidate.startsWith("["))).toEqual([]);
57
58
  });
58
59
  });
60
+
61
+ describe("CssCandidateCache persistence", () => {
62
+ const writeCache = async (stamp: BuildCacheStamp) => {
63
+ const dir = await mkdtemp(path.join(tmpdir(), "css-candidate-"));
64
+ const file = path.join(dir, "probe.tsx");
65
+ const cachePath = path.join(dir, "cache.json");
66
+ await writeFile(file, `const c = "w-full";`);
67
+ const cache = await new CssCandidateCache(cachePath, stamp).load();
68
+ await cache.candidatesFor(file);
69
+ await cache.save(new Set([file]));
70
+ return { file, cachePath };
71
+ };
72
+
73
+ test("reuses an entry the same akanjs and Bun wrote", async () => {
74
+ const { file, cachePath } = await writeCache({ akanjs: "1.0.0", bun: "1.0.0+a", code: "1:1" });
75
+ const cache = await new CssCandidateCache(cachePath, { akanjs: "1.0.0", bun: "1.0.0+a", code: "1:1" }).load();
76
+ expect(await cache.candidatesFor(file)).toContain("w-full");
77
+ expect([cache.reused, cache.rescanned]).toEqual([1, 0]);
78
+ });
79
+
80
+ test.each([
81
+ ["akanjs", { akanjs: "1.0.1", bun: "1.0.0+a", code: "1:1" }],
82
+ ["Bun", { akanjs: "1.0.0", bun: "1.0.0+b", code: "1:1" }],
83
+ ["scanner build", { akanjs: "1.0.0", bun: "1.0.0+a", code: "2:1" }],
84
+ ])("rescans an entry another %s wrote", async (_, stamp) => {
85
+ const { file, cachePath } = await writeCache({ akanjs: "1.0.0", bun: "1.0.0+a", code: "1:1" });
86
+ const cache = await new CssCandidateCache(cachePath, stamp).load();
87
+ expect(await cache.candidatesFor(file)).toContain("w-full");
88
+ expect([cache.reused, cache.rescanned]).toEqual([0, 1]);
89
+ });
90
+
91
+ test("keeps another base path's entries, so each base path reuses its scan on the next start", async () => {
92
+ const stamp = { akanjs: "1.0.0", bun: "1.0.0+a", code: "1:1" };
93
+ const dir = await mkdtemp(path.join(tmpdir(), "css-candidate-"));
94
+ const cachePath = path.join(dir, "cache.json");
95
+ const [rootFile, adminFile] = [path.join(dir, "root.tsx"), path.join(dir, "admin.tsx")];
96
+ await writeFile(rootFile, `const c = "w-full";`);
97
+ await writeFile(adminFile, `const c = "h-full";`);
98
+ const scanBasePath = async (file: string) => {
99
+ const cache = await new CssCandidateCache(cachePath, stamp).load();
100
+ await cache.candidatesFor(file);
101
+ await cache.save(new Set([file]));
102
+ return cache;
103
+ };
104
+ await scanBasePath(rootFile);
105
+ await scanBasePath(adminFile);
106
+
107
+ const [root, admin] = [await scanBasePath(rootFile), await scanBasePath(adminFile)];
108
+ expect([root.reused, admin.reused]).toEqual([1, 1]);
109
+ });
110
+
111
+ test("drops the entry of a source file that was deleted", async () => {
112
+ const stamp = { akanjs: "1.0.0", bun: "1.0.0+a", code: "1:1" };
113
+ const { file, cachePath } = await writeCache(stamp);
114
+ await rm(file);
115
+ await new CssCandidateCache(cachePath, stamp).load().then((cache) => cache.save(new Set()));
116
+ expect(Object.keys((await Bun.file(cachePath).json()).files)).toEqual([]);
117
+ });
118
+
119
+ test("rescans when the cache file was cut short", async () => {
120
+ const { file, cachePath } = await writeCache({ akanjs: "1.0.0", bun: "1.0.0+a", code: "1:1" });
121
+ const text = await Bun.file(cachePath).text();
122
+ await writeFile(cachePath, text.slice(0, text.length / 2));
123
+ const cache = await new CssCandidateCache(cachePath, { akanjs: "1.0.0", bun: "1.0.0+a", code: "1:1" }).load();
124
+ expect(await cache.candidatesFor(file)).toContain("w-full");
125
+ expect([cache.reused, cache.rescanned]).toEqual([0, 1]);
126
+ });
127
+ });
@@ -1,4 +1,6 @@
1
1
  import { stat } from "node:fs/promises";
2
+ import { FileSys } from "../util/fileSys";
3
+ import { type BuildCacheStamp, buildCacheStamp, isBuildCacheStamp } from "./buildCacheStamp";
2
4
 
3
5
  // The leading `[` alternation keeps arbitrary variants (`[&_td]:px-3`) whole, and a bracket may hold one nested
4
6
  // bracket (`[&_[data-slot=x]]:p-2`, `has-[[aria-expanded=true]]:x`), or the candidate is cut at the inner `]` and the
@@ -14,7 +16,7 @@ interface CachedFile {
14
16
  candidates: string[];
15
17
  }
16
18
 
17
- interface CacheFile {
19
+ interface CacheFile extends BuildCacheStamp {
18
20
  version: number;
19
21
  files: Record<string, CachedFile>;
20
22
  }
@@ -22,15 +24,17 @@ interface CacheFile {
22
24
  /** Tailwind candidates per source file, on disk: the batch worker that compiles CSS exits before the next save. */
23
25
  export class CssCandidateCache {
24
26
  // Bump when the token regex or the entry shape changes, so stale extractions are not reused.
25
- static readonly #version = 5;
27
+ static readonly #version = 6;
26
28
  readonly #path: string;
29
+ readonly #stamp: BuildCacheStamp;
27
30
  readonly #entries = new Map<string, CachedFile>();
28
31
  #dirty = false;
29
32
  #reused = 0;
30
33
  #rescanned = 0;
31
34
 
32
- constructor(cachePath: string) {
35
+ constructor(cachePath: string, stamp = buildCacheStamp([import.meta.path])) {
33
36
  this.#path = cachePath;
37
+ this.#stamp = stamp;
34
38
  }
35
39
 
36
40
  get reused(): number {
@@ -44,8 +48,8 @@ export class CssCandidateCache {
44
48
  async load(): Promise<this> {
45
49
  const raw = (await Bun.file(this.#path)
46
50
  .json()
47
- .catch(() => null)) as CacheFile | null;
48
- if (!raw || raw.version !== CssCandidateCache.#version || typeof raw.files !== "object") return this;
51
+ .catch(() => null)) as Partial<CacheFile> | null;
52
+ if (raw?.version !== CssCandidateCache.#version || !isBuildCacheStamp(raw, this.#stamp) || !raw.files) return this;
49
53
  for (const [file, entry] of Object.entries(raw.files)) {
50
54
  if (typeof entry?.mtimeMs !== "number" || !Array.isArray(entry.candidates)) continue;
51
55
  this.#entries.set(file, entry);
@@ -71,20 +75,23 @@ export class CssCandidateCache {
71
75
  return candidates;
72
76
  }
73
77
 
78
+ // Each base path scans its own files into the same cache, so only an entry whose file is gone is dropped.
74
79
  async save(present: Set<string>): Promise<void> {
75
- for (const file of [...this.#entries.keys()]) {
76
- if (present.has(file)) continue;
80
+ const absent = [...this.#entries.keys()].filter((file) => !present.has(file));
81
+ const exists = await Promise.all(absent.map((file) => Bun.file(file).exists()));
82
+ absent.forEach((file, index) => {
83
+ if (exists[index]) return;
77
84
  this.#entries.delete(file);
78
85
  this.#dirty = true;
79
- }
86
+ });
80
87
  if (!this.#dirty) return;
81
88
  this.#dirty = false;
82
89
  const files: Record<string, CachedFile> = {};
83
90
  for (const [file, entry] of this.#entries) files[file] = entry;
84
91
  // An unwritable cache is a slow build, not a failed one: a read-only checkout must still compile.
85
- await Bun.write(
92
+ await FileSys.writeTextAtomic(
86
93
  this.#path,
87
- JSON.stringify({ version: CssCandidateCache.#version, files } satisfies CacheFile),
94
+ JSON.stringify({ version: CssCandidateCache.#version, ...this.#stamp, files } satisfies CacheFile),
88
95
  ).catch(() => undefined);
89
96
  }
90
97
  }
@@ -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-");