@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
@@ -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-");
@@ -1,8 +1,8 @@
1
1
  import { describe, expect, test } from "bun:test";
2
- import { mkdir, rm, stat, writeFile } from "node:fs/promises";
2
+ import { chmod, mkdir, rm, stat, utimes, 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");
@@ -17,15 +17,17 @@ const makeApp = async (layoutSource: string) => {
17
17
  await writeFile(path.join(cwdPath, "page/_layout.tsx"), layoutSource);
18
18
  await Bun.write(path.join(cwdPath, "public/fonts/Assistant-Regular.woff2"), Bun.file(SOURCE_FONT));
19
19
  const warnings: string[] = [];
20
+ const verboses: string[] = [];
20
21
  const app = {
21
22
  cwdPath,
22
23
  dist: { cwdPath: path.join(root, "dist/apps/demo") },
23
24
  workspace: { workspaceRoot: root },
24
25
  getPageKeys: async () => ["./_layout.tsx"],
25
- verbose: () => undefined,
26
+ verbose: (message: string) => verboses.push(message),
26
27
  logger: { warn: (message: string) => warnings.push(message) },
27
28
  } as unknown as App;
28
- return { app, cwdPath, warnings };
29
+ const reusedCount = () => verboses.filter((message) => message.startsWith("[font] reused")).length;
30
+ return { app, cwdPath, root, warnings, reusedCount };
29
31
  };
30
32
 
31
33
  const layoutWith = (extra = "") => `
@@ -125,6 +127,145 @@ describe("FontOptimizer cache", () => {
125
127
  expect(await Bun.file(second.files[0]).exists()).toBe(true);
126
128
  });
127
129
 
130
+ test("reuses the subset on the next akan start, which wipes the artifact folder", async () => {
131
+ const { app, cwdPath, reusedCount } = await makeApp(layoutWith());
132
+ const first = await optimize(app);
133
+ const firstBytes = await Bun.file(first.files[0]).bytes();
134
+ await rm(path.join(cwdPath, ".akan/artifact"), { recursive: true, force: true });
135
+
136
+ const second = await optimize(app);
137
+ expect(reusedCount()).toBe(1);
138
+ expect(second.files).toEqual(first.files);
139
+ expect(second.css).toBe(first.css);
140
+ expect(await Bun.file(second.files[0]).bytes()).toEqual(firstBytes);
141
+ });
142
+
143
+ test.each(["akanjs", "bun", "code"])("resubsets when the cache was written by another %s version", async (field) => {
144
+ const { app, cwdPath, reusedCount } = await makeApp(layoutWith());
145
+ await optimize(app);
146
+ const indexPath = path.join(cwdPath, ".akan/cache/fontCache.json");
147
+ const index = await Bun.file(indexPath).json();
148
+ await Bun.write(indexPath, JSON.stringify({ ...index, [field]: "0.0.1-other" }));
149
+
150
+ await optimize(app);
151
+ expect(reusedCount()).toBe(0);
152
+ expect((await Bun.file(indexPath).json())[field]).toBe(index[field]);
153
+ });
154
+
155
+ test("resubsets when the lockfile changes, since a font tool version may have moved", async () => {
156
+ const { app, root, reusedCount } = await makeApp(layoutWith());
157
+ await writeFile(path.join(root, "bun.lock"), '{ "lockfileVersion": 1 }\n');
158
+ await optimize(app);
159
+ await optimize(app);
160
+ expect(reusedCount()).toBe(1);
161
+
162
+ await writeFile(path.join(root, "bun.lock"), '{ "lockfileVersion": 1, "packages": {} }\n');
163
+ await optimize(app);
164
+ expect(reusedCount()).toBe(1);
165
+ });
166
+
167
+ test("rebuilds a cached font file that was cut short", async () => {
168
+ const { app, cwdPath, reusedCount } = await makeApp(layoutWith());
169
+ const first = await optimize(app);
170
+ const firstBytes = await Bun.file(first.files[0]).bytes();
171
+ const cachedPath = path.join(
172
+ cwdPath,
173
+ ".akan/cache",
174
+ path.relative(path.join(cwdPath, ".akan/artifact"), first.files[0]),
175
+ );
176
+ await Bun.write(cachedPath, firstBytes.subarray(0, firstBytes.byteLength / 2));
177
+ await rm(path.join(cwdPath, ".akan/artifact"), { recursive: true, force: true });
178
+
179
+ const second = await optimize(app);
180
+ expect(reusedCount()).toBe(0);
181
+ expect(await Bun.file(second.files[0]).bytes()).toEqual(firstBytes);
182
+ expect(await Bun.file(cachedPath).bytes()).toEqual(firstBytes);
183
+ });
184
+
185
+ test("replaces an artifact copy that was cut short with the cached font", async () => {
186
+ const { app, reusedCount } = await makeApp(layoutWith());
187
+ const first = await optimize(app);
188
+ const firstBytes = await Bun.file(first.files[0]).bytes();
189
+ await Bun.write(first.files[0], firstBytes.subarray(0, 16));
190
+
191
+ const second = await optimize(app);
192
+ expect(reusedCount()).toBe(1);
193
+ expect(await Bun.file(second.files[0]).bytes()).toEqual(firstBytes);
194
+ });
195
+
196
+ test("rebuilds when the cache index was cut short", async () => {
197
+ const { app, cwdPath, reusedCount } = await makeApp(layoutWith());
198
+ const first = await optimize(app);
199
+ const indexPath = path.join(cwdPath, ".akan/cache/fontCache.json");
200
+ const index = await Bun.file(indexPath).text();
201
+ await Bun.write(indexPath, index.slice(0, index.length / 2));
202
+
203
+ const second = await optimize(app);
204
+ expect(reusedCount()).toBe(0);
205
+ expect(second.css).toBe(first.css);
206
+ expect(await Bun.file(indexPath).text()).toBe(index);
207
+ });
208
+
209
+ test("drops cached font files the current entry no longer lists", async () => {
210
+ const { app, cwdPath } = await makeApp(layoutWith());
211
+ const first = await optimize(app);
212
+ const stalePath = path.join(cwdPath, ".akan/cache/fonts/Assistant-400-normal-stale.woff2");
213
+ await Bun.write(stalePath, "stale");
214
+
215
+ await writeFile(path.join(cwdPath, "page/_layout.tsx"), layoutWith(`\n className: "font-brand",`));
216
+ await optimize(app);
217
+ expect(await Bun.file(stalePath).exists()).toBe(false);
218
+ expect(
219
+ await Bun.file(
220
+ path.join(cwdPath, ".akan/cache", path.relative(path.join(cwdPath, ".akan/artifact"), first.files[0])),
221
+ ).exists(),
222
+ ).toBe(true);
223
+ });
224
+
225
+ test("still writes the fonts when the cache folder cannot be written", async () => {
226
+ const { app, cwdPath } = await makeApp(layoutWith());
227
+ const cacheDir = path.join(cwdPath, ".akan/cache");
228
+ await mkdir(cacheDir, { recursive: true });
229
+ await chmod(cacheDir, 0o500);
230
+ try {
231
+ const result = await optimize(app);
232
+ expect(result.files).toHaveLength(1);
233
+ expect(await Bun.file(result.files[0]).exists()).toBe(true);
234
+ } finally {
235
+ await chmod(cacheDir, 0o700);
236
+ }
237
+ });
238
+
239
+ test("resubsets when the source font is replaced by one of the same size and mtime", async () => {
240
+ const { app, cwdPath, reusedCount } = await makeApp(`
241
+ export const fonts = [{ name: "Gilda", paths: [{ src: "/fonts/Gilda.ttf", weight: 400 }] }];
242
+ export default function Layout() {
243
+ return null;
244
+ }
245
+ `);
246
+ const sourcePath = path.join(cwdPath, "public/fonts/Gilda.ttf");
247
+ const source = await Bun.file(path.resolve(path.dirname(SOURCE_FONT), "GildaDisplay-Regular.ttf")).bytes();
248
+ await Bun.write(sourcePath, source);
249
+ await optimize(app);
250
+ const { mtime } = await stat(sourcePath);
251
+
252
+ await Bun.write(sourcePath, renameSfntTable(source.slice(), "OS/2", "XS/2"));
253
+ await utimes(sourcePath, mtime, mtime);
254
+ await optimize(app);
255
+ expect(reusedCount()).toBe(0);
256
+ });
257
+
258
+ test("leaves a temporary file another start is still writing in the cache folder", async () => {
259
+ const { app, cwdPath } = await makeApp(layoutWith());
260
+ await optimize(app);
261
+ const tempPath = path.join(cwdPath, ".akan/cache/fonts/Assistant-400-normal-abc.woff2.123.abc.tmp");
262
+ await Bun.write(tempPath, "in progress");
263
+
264
+ await writeFile(path.join(cwdPath, "page/_layout.tsx"), layoutWith(`\n className: "font-brand",`));
265
+ await optimize(app);
266
+ expect(await Bun.file(tempPath).exists()).toBe(true);
267
+ });
268
+
128
269
  test("skips route files that never mention fonts", async () => {
129
270
  const { app } = await makeApp("export default function Layout() {\n return null;\n}\n");
130
271
  const result = await optimize(app);
@@ -1,4 +1,4 @@
1
- import { mkdir, stat } from "node:fs/promises";
1
+ import { mkdir, readdir, rm, stat } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import type {
4
4
  ReactFont,
@@ -11,6 +11,8 @@ import type {
11
11
  import type { FontCategory } from "fontaine";
12
12
  import ts from "typescript";
13
13
  import type { App } from "../commandDecorators";
14
+ import { FileSys } from "../util/fileSys";
15
+ import { type BuildCacheStamp, buildCacheStamp, isBuildCacheStamp } from "./buildCacheStamp";
14
16
 
15
17
  const FONT_URL_PREFIX = "/_akan/fonts";
16
18
  const DEFAULT_FONT_SUBSETS: ReactFontSubset[] = ["latin"];
@@ -21,11 +23,17 @@ export interface OptimizeAppFontsResult {
21
23
  files: string[];
22
24
  }
23
25
 
24
- interface FontOptimizerCache {
26
+ interface FontCacheFile {
27
+ path: string;
28
+ size: number;
29
+ sha256: string;
30
+ }
31
+
32
+ interface FontOptimizerCache extends BuildCacheStamp {
25
33
  version: number;
26
34
  key: string;
27
35
  css: string;
28
- files: string[];
36
+ files: FontCacheFile[];
29
37
  }
30
38
 
31
39
  export type FontOptimizerCommand = "build" | "start";
@@ -34,17 +42,21 @@ export class FontOptimizer {
34
42
  #app: App;
35
43
  #command: FontOptimizerCommand;
36
44
  #artifactRoot: string;
45
+ #cacheRoot: string;
46
+ #stamp = buildCacheStamp([import.meta.path]);
37
47
  #files: string[] = [];
38
48
  #cssParts: string[] = [];
39
49
  #woff2Ready: Promise<void> | null = null;
40
50
 
41
51
  static #ksX1001Text: string | null = null;
42
- static readonly #cacheVersion = 3;
52
+ static readonly #cacheVersion = 4;
43
53
 
44
54
  constructor(app: App, command: FontOptimizerCommand = "start") {
45
55
  this.#app = app;
46
56
  this.#command = command;
47
57
  this.#artifactRoot = path.join(command === "build" ? app.dist.cwdPath : app.cwdPath, ".akan/artifact");
58
+ //? A build reads fonts from fresh `dist/public` copies, whose stamps never match, so it caches beside its output.
59
+ this.#cacheRoot = command === "build" ? this.#artifactRoot : path.join(app.cwdPath, ".akan/cache");
48
60
  }
49
61
 
50
62
  async optimize(): Promise<OptimizeAppFontsResult> {
@@ -62,24 +74,25 @@ export class FontOptimizer {
62
74
  const fontUtilityCss = this.#buildFontUtilityRules(fonts);
63
75
  if (fontUtilityCss) this.#cssParts.push(fontUtilityCss);
64
76
  const result = { css: this.#cssParts.join("\n"), fonts, files: this.#files };
65
- if (cacheKey) await this.#writeCache(cacheKey, result);
77
+ // An unwritable cache is a slower start, never a failed one.
78
+ if (cacheKey) await this.#writeCache(cacheKey, result).catch(() => undefined);
66
79
  return result;
67
80
  }
68
81
 
69
82
  get #cachePath() {
70
- return path.join(this.#artifactRoot, "fontCache.json");
83
+ return path.join(this.#cacheRoot, "fontCache.json");
71
84
  }
72
85
 
73
- // null skips the cache: an unstat-able source's staleness is undetectable, and the uncached path warns about it.
86
+ // null skips the cache: an unreadable source's staleness is undetectable, and the uncached path warns about it.
74
87
  async #buildCacheKey(fonts: ReactFont[]): Promise<string | null> {
75
88
  const sources: unknown[] = [];
76
89
  for (const font of fonts) {
77
90
  if (!this.#isFontOptimizationEnabled(font)) continue;
78
91
  for (const face of this.#getFontFaces(font)) {
79
92
  const sourcePath = await this.#resolveFontSourcePath(face.src);
80
- const stamp = sourcePath ? await this.#fileStamp(sourcePath) : null;
81
- if (!stamp) return null;
82
- sources.push({ optimizedSrc: face.optimizedSrc, ...stamp });
93
+ const digest = sourcePath ? await this.#fileDigest(sourcePath) : null;
94
+ if (!digest) return null;
95
+ sources.push({ optimizedSrc: face.optimizedSrc, sourcePath, ...digest });
83
96
  }
84
97
  for (const filePath of font.subsetFiles ?? []) {
85
98
  const abs = path.isAbsolute(filePath) ? filePath : path.join(this.#app.cwdPath, filePath);
@@ -90,7 +103,31 @@ export class FontOptimizer {
90
103
  if (this.#getFontSubsets(font).includes("auto"))
91
104
  sources.push({ autoSubsetText: this.#cacheDigest(await this.#collectAutoSubsetText()) });
92
105
  }
93
- return this.#cacheDigest({ version: FontOptimizer.#cacheVersion, fonts, sources });
106
+ const lockfile = await this.#lockfileDigest();
107
+ return this.#cacheDigest({
108
+ version: FontOptimizer.#cacheVersion,
109
+ command: this.#command,
110
+ lockfile,
111
+ fonts,
112
+ sources,
113
+ });
114
+ }
115
+
116
+ //? Only the lockfile moves when the subsetter, the woff2 encoder or fontaine's metrics change version.
117
+ async #lockfileDigest() {
118
+ const root = this.#app.workspace.workspaceRoot;
119
+ const lockfiles = await Promise.all(
120
+ ["bun.lock", "bun.lockb"].map((name) =>
121
+ Bun.file(path.join(root, name))
122
+ .bytes()
123
+ .catch(() => null),
124
+ ),
125
+ );
126
+ return lockfiles.map((bytes) => (bytes ? this.#sha256(bytes) : null));
127
+ }
128
+
129
+ #sha256(bytes: Uint8Array) {
130
+ return new Bun.CryptoHasher("sha256").update(bytes).digest("hex");
94
131
  }
95
132
 
96
133
  // sha256, not #hashFontConfig's 32-bit FNV: a key collision would serve a stale subset as current.
@@ -98,6 +135,13 @@ export class FontOptimizer {
98
135
  return new Bun.CryptoHasher("sha256").update(this.#stableStringify(value)).digest("hex");
99
136
  }
100
137
 
138
+ async #fileDigest(filePath: string): Promise<{ size: number; sha256: string } | null> {
139
+ const bytes = await Bun.file(filePath)
140
+ .bytes()
141
+ .catch(() => null);
142
+ return bytes ? { size: bytes.byteLength, sha256: this.#sha256(bytes) } : null;
143
+ }
144
+
101
145
  async #fileStamp(filePath: string): Promise<{ mtimeMs: number; size: number } | null> {
102
146
  try {
103
147
  const stats = await stat(filePath);
@@ -110,23 +154,64 @@ export class FontOptimizer {
110
154
  async #readCache(key: string): Promise<{ css: string; files: string[] } | null> {
111
155
  const cache = (await Bun.file(this.#cachePath)
112
156
  .json()
113
- .catch(() => null)) as FontOptimizerCache | null;
114
- if (cache?.version !== FontOptimizer.#cacheVersion || cache.key !== key) return null;
115
- const files = cache.files.map((relativePath) => path.join(this.#artifactRoot, relativePath));
116
- for (const filePath of files) {
117
- if (!(await Bun.file(filePath).exists())) return null;
157
+ .catch(() => null)) as Partial<FontOptimizerCache> | null;
158
+ if (cache?.version !== FontOptimizer.#cacheVersion || cache.key !== key || typeof cache.css !== "string")
159
+ return null;
160
+ if (!isBuildCacheStamp(cache, this.#stamp) || !Array.isArray(cache.files)) return null;
161
+ const files: string[] = [];
162
+ for (const file of cache.files) {
163
+ const bytes = await this.#readIntact(this.#cacheRoot, file);
164
+ if (!bytes) return null;
165
+ if (this.#cacheRoot !== this.#artifactRoot && !(await this.#readIntact(this.#artifactRoot, file)))
166
+ await Bun.write(path.join(this.#artifactRoot, file.path), bytes);
167
+ files.push(path.join(this.#artifactRoot, file.path));
118
168
  }
119
169
  return { css: cache.css, files };
120
170
  }
121
171
 
172
+ // A start killed mid-write leaves a short or stale file under the name the entry lists, so the bytes must match.
173
+ async #readIntact(root: string, file: Partial<FontCacheFile> | null): Promise<Uint8Array | null> {
174
+ if (typeof file?.path !== "string" || typeof file.size !== "number") return null;
175
+ const bytes = await Bun.file(path.join(root, file.path))
176
+ .bytes()
177
+ .catch(() => null);
178
+ if (!bytes || bytes.byteLength !== file.size || this.#sha256(bytes) !== file.sha256) return null;
179
+ return bytes;
180
+ }
181
+
182
+ // The entry is written last, so a start killed before it keeps the previous entry, which its checksums then refuse.
122
183
  async #writeCache(key: string, result: OptimizeAppFontsResult): Promise<void> {
184
+ const files: FontCacheFile[] = [];
185
+ for (const filePath of result.files) {
186
+ const bytes = await Bun.file(filePath).bytes();
187
+ const relativePath = path.relative(this.#artifactRoot, filePath);
188
+ const cachedPath = path.join(this.#cacheRoot, relativePath);
189
+ if (cachedPath !== filePath) await FileSys.writeTextAtomic(cachedPath, bytes);
190
+ files.push({ path: relativePath, size: bytes.byteLength, sha256: this.#sha256(bytes) });
191
+ }
123
192
  const cache: FontOptimizerCache = {
124
193
  version: FontOptimizer.#cacheVersion,
194
+ ...this.#stamp,
125
195
  key,
126
196
  css: result.css,
127
- files: result.files.map((filePath) => path.relative(this.#artifactRoot, filePath)),
197
+ files,
128
198
  };
129
- await Bun.write(this.#cachePath, JSON.stringify(cache));
199
+ await FileSys.writeTextAtomic(this.#cachePath, JSON.stringify(cache));
200
+ await this.#pruneCachedFonts(files);
201
+ }
202
+
203
+ async #pruneCachedFonts(kept: FontCacheFile[]) {
204
+ if (this.#cacheRoot === this.#artifactRoot) return;
205
+ const dir = path.join(this.#cacheRoot, FONT_URL_PREFIX.replace(/^\/_akan\//, ""));
206
+ const keep = new Set(kept.map((file) => path.join(this.#cacheRoot, file.path)));
207
+ const names = await readdir(dir).catch(() => [] as string[]);
208
+ await Promise.all(
209
+ names
210
+ .filter((name) => !name.endsWith(".tmp"))
211
+ .map((name) => path.join(dir, name))
212
+ .filter((filePath) => !keep.has(filePath))
213
+ .map((filePath) => rm(filePath, { force: true })),
214
+ );
130
215
  }
131
216
 
132
217
  async discoverFonts(): Promise<ReactFont[]> {
@@ -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-");