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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (347) hide show
  1. package/DEV_RUNTIME_KNOBS.md +1 -1
  2. package/README.ko.md +7 -1
  3. package/README.md +7 -1
  4. package/akanApp/akanApp.host.test.ts +3 -1
  5. package/akanApp/akanApp.host.ts +26 -2
  6. package/akanApp/akanApp.host.wiring.test.ts +111 -0
  7. package/akanApp/devHostPolicy.ts +5 -0
  8. package/akanApp/devMetadataRestart.ts +93 -0
  9. package/akanApp/devRecycler.test.ts +2 -0
  10. package/akanApp/devRecycler.ts +9 -0
  11. package/akanConfig/akanBin.ts +4 -0
  12. package/akanConfig/akanConfig.test.ts +269 -18
  13. package/akanConfig/akanConfig.ts +104 -210
  14. package/akanConfig/akanPreview.test.ts +28 -0
  15. package/akanConfig/akanPreview.ts +24 -0
  16. package/akanConfig/akanWorkers.test.ts +73 -0
  17. package/akanConfig/akanWorkers.ts +61 -0
  18. package/akanConfig/desktopServerConfig.ts +96 -0
  19. package/akanConfig/dockerImage.ts +212 -0
  20. package/akanConfig/index.ts +3 -0
  21. package/akanConfig/nativeFileSettings.ts +33 -0
  22. package/akanConfig/types.ts +4 -0
  23. package/app/appBin.test.ts +63 -0
  24. package/app/appBin.ts +50 -0
  25. package/app/applicationBuildReporter.test.ts +51 -1
  26. package/app/applicationBuildReporter.ts +6 -1
  27. package/app/applicationBuildRunner.test.ts +358 -5
  28. package/app/applicationBuildRunner.ts +221 -31
  29. package/app/clientServerBoundary.test.ts +115 -0
  30. package/app/clientServerBoundary.ts +89 -0
  31. package/app/dictionarySizes.test.ts +40 -0
  32. package/app/dictionarySizes.ts +95 -0
  33. package/app/routeFilesReport.test.ts +59 -0
  34. package/app/routeFilesReport.ts +46 -0
  35. package/app/routeJsBudget.ts +18 -4
  36. package/artifact/implicitRootLayout.test.ts +19 -0
  37. package/artifact/implicitRootLayout.ts +16 -2
  38. package/artifact/implicitRootLayoutRender.test.tsx +4 -1
  39. package/artifact/storeBootstrap.test.ts +28 -0
  40. package/artifact/storeBootstrap.ts +64 -8
  41. package/biome.base.json +7 -5
  42. package/codeAgent/index.ts +1 -34
  43. package/codeAgent/skills/akan-agent/SKILL.md +2 -2
  44. package/codeAgent/skills/akan-debug/SKILL.md +8 -3
  45. package/codeAgent/skills/akan-deps/SKILL.md +10 -3
  46. package/codeAgent/skills/akan-err/SKILL.md +13 -8
  47. package/codeAgent/skills/akan-mcp/SKILL.md +1 -1
  48. package/codeAgent/skills/akan-module/SKILL.md +2 -2
  49. package/codeAgent/skills/akan-page/SKILL.md +65 -30
  50. package/codeAgent/skills/akan-query/SKILL.md +13 -20
  51. package/codeAgent/skills/akan-runtime/SKILL.md +21 -1
  52. package/codeAgent/skills/akan-service/SKILL.md +21 -20
  53. package/codeAgent/skills/akan-transport/SKILL.md +5 -14
  54. package/codeAgent/skills/akan-ui/SKILL.md +16 -21
  55. package/codeAgent/skills/akan-validate/SKILL.md +8 -2
  56. package/commandDecorators/command.ts +28 -12
  57. package/commandDecorators/commandBuilder.ts +8 -1
  58. package/commandDecorators/commandDecorators.test.ts +70 -3
  59. package/commandDecorators/helpFormatter.ts +14 -12
  60. package/context/akanContext.ts +2 -0
  61. package/csrE2e/devHmrLatency.e2e.test.ts +1 -1
  62. package/csrE2e/ssrRegistry.e2e.test.ts +108 -22
  63. package/docs/apiReference.test.ts +25 -0
  64. package/docs/apiReference.ts +38 -5
  65. package/docs/declarationReader.ts +30 -0
  66. package/executors/appExecutor.ts +26 -12
  67. package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
  68. package/executors/clientRuntimeKeys.fixture.json +393 -0
  69. package/executors/clientRuntimeKeys.test.ts +1690 -0
  70. package/executors/executor.ts +14 -6
  71. package/executors/executors.test.ts +155 -1
  72. package/executors/pkgExecutor.ts +2 -1
  73. package/executors/sysExecutor.ts +112 -8
  74. package/executors/workspaceExecutor.ts +7 -4
  75. package/frontendBuild/allRoutesBuilder.ts +99 -7
  76. package/frontendBuild/autoImportSync.ts +3 -2
  77. package/frontendBuild/buildRouteClient.test.ts +684 -6
  78. package/frontendBuild/clientBuildTypes.ts +26 -0
  79. package/frontendBuild/clientEntriesBundler.ts +49 -1
  80. package/frontendBuild/clientEntryDiscovery.test.ts +308 -1
  81. package/frontendBuild/clientEntryDiscovery.ts +134 -12
  82. package/frontendBuild/clientEntryGroups.test.ts +77 -0
  83. package/frontendBuild/clientEntryGroups.ts +61 -0
  84. package/frontendBuild/csrDevArtifactWriter.ts +2 -2
  85. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  86. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  87. package/frontendBuild/csrDevPatcher.test.ts +4 -5
  88. package/frontendBuild/csrDevPatcher.ts +37 -11
  89. package/frontendBuild/csrDevTypes.ts +9 -0
  90. package/frontendBuild/devBarrelImports.test.ts +124 -0
  91. package/frontendBuild/devBarrelImports.ts +81 -21
  92. package/frontendBuild/devChangePlanner.ts +0 -1
  93. package/frontendBuild/devRegistryBundler.ts +4 -2
  94. package/frontendBuild/devRouteRuntime.test.ts +492 -0
  95. package/frontendBuild/devRouteRuntime.ts +167 -0
  96. package/frontendBuild/dictionaryAssetBuilder.test.ts +408 -0
  97. package/frontendBuild/dictionaryAssetBuilder.ts +185 -17
  98. package/frontendBuild/dictionaryConstants.ts +136 -0
  99. package/frontendBuild/dictionaryOwnParts.ts +88 -0
  100. package/frontendBuild/dictionaryPackState.ts +131 -0
  101. package/frontendBuild/dictionaryPacking.test.ts +207 -0
  102. package/frontendBuild/dictionaryPacking.ts +160 -0
  103. package/frontendBuild/dictionaryRoutes.test.ts +251 -0
  104. package/frontendBuild/dictionaryRoutes.ts +227 -0
  105. package/frontendBuild/frontendBuild.test.ts +5 -3
  106. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  107. package/frontendBuild/pagesBundleBuilder.ts +78 -2
  108. package/frontendBuild/precompressArtifacts.test.ts +22 -0
  109. package/frontendBuild/precompressArtifacts.ts +34 -8
  110. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  111. package/frontendBuild/renderedEntries.ts +144 -0
  112. package/frontendBuild/routeClientBuilder.ts +407 -43
  113. package/frontendBuild/routeHandoffs.test.ts +155 -0
  114. package/frontendBuild/routeHandoffs.ts +117 -0
  115. package/frontendBuild/routeModulePreloads.test.ts +32 -0
  116. package/frontendBuild/routeModulePreloads.ts +20 -11
  117. package/frontendBuild/routeRuntimeCheck.test.ts +280 -0
  118. package/frontendBuild/routeRuntimeCheck.ts +248 -0
  119. package/frontendBuild/routeRuntimePays.test.ts +143 -0
  120. package/frontendBuild/routeRuntimePays.ts +117 -0
  121. package/frontendBuild/ssrBaseArtifactBuilder.ts +30 -35
  122. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  123. package/frontendBuild/ssrDevBundler.ts +66 -11
  124. package/frontendBuild/vendorFileImports.test.ts +254 -0
  125. package/frontendBuild/vendorFileImports.ts +163 -0
  126. package/frontendBuild/vendorNarrowing.test.ts +47 -3
  127. package/frontendBuild/vendorNarrowing.ts +38 -2
  128. package/frontendBuild/vendorSpecifiers.ts +2 -0
  129. package/guideline/agentAssets.ts +1 -1
  130. package/incrementalBuilder/buildBatch.proc.ts +27 -1
  131. package/incrementalBuilder/buildBatchProtocol.ts +1 -0
  132. package/incrementalBuilder/builderWatch.ts +11 -1
  133. package/incrementalBuilder/incrementalBuilder.proc.test.ts +159 -0
  134. package/incrementalBuilder/incrementalBuilder.proc.ts +31 -3
  135. package/incrementalBuilder/pendingMetadata.test.ts +27 -0
  136. package/incrementalBuilder/pendingMetadata.ts +19 -0
  137. package/integration/devStability.integration.test.ts +46 -21
  138. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  139. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  140. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  141. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  142. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  143. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  144. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  145. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  146. package/lint/biomeBase.test.ts +50 -3
  147. package/lint/biomeBase.ts +1 -1
  148. package/lint/biomeCheck.test.ts +162 -0
  149. package/lint/biomeCheck.ts +131 -0
  150. package/lint/linter.test.ts +16 -11
  151. package/lint/no-arbitrary-color.grit +5 -0
  152. package/lint/no-conditional-st-hook.grit +5 -1
  153. package/lint/no-daisyui-legacy-class.grit +8 -0
  154. package/lint/no-document-cookie.grit +3 -0
  155. package/lint/no-inline-color.grit +10 -2
  156. package/lint/no-oversized-list-limit.grit +2 -0
  157. package/lint/no-raw-palette-class.grit +7 -0
  158. package/lint/no-unpublished-form-setter.grit +2 -0
  159. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  160. package/lint/no-web-storage.grit +3 -0
  161. package/lint/withheldEnvFile.ts +17 -0
  162. package/mobile/desktopBin.ts +2 -2
  163. package/mobile/desktopServerStage.test.ts +18 -3
  164. package/mobile/desktopServerStage.ts +7 -2
  165. package/mobile/nativeApp.test.ts +7 -5
  166. package/mobile/nativeApp.ts +2 -2
  167. package/mobile/nativeConfig.test.ts +17 -1
  168. package/mobile/nativeConfig.ts +11 -6
  169. package/mobile/nativePublicEnv.ts +1 -1
  170. package/mobile/serverBundleSecrets.ts +43 -0
  171. package/package.json +11 -12
  172. package/packageExports.test.ts +3 -2
  173. package/preview/PreviewView.ts +25 -3
  174. package/quality/dictionaryKeys.test.ts +356 -0
  175. package/quality/dictionaryKeys.ts +488 -0
  176. package/quality/objectImportReport.test.ts +36 -0
  177. package/quality/objectImportReport.ts +105 -0
  178. package/quality/qualityScanner.ts +1 -1
  179. package/quality/routeRuntimeReport.test.ts +91 -0
  180. package/quality/routeRuntimeReport.ts +121 -0
  181. package/quality/runtimeConstantFacts.ts +71 -0
  182. package/quality/runtimeConstantGraph.ts +123 -0
  183. package/quality/runtimeConstantReads.ts +116 -0
  184. package/quality/runtimeImports.test.ts +190 -0
  185. package/quality/runtimeImports.ts +233 -0
  186. package/quality/runtimeKeyNames.ts +46 -0
  187. package/quality/runtimeLexicalScope.ts +132 -0
  188. package/quality/runtimeMarkerReach.test.ts +84 -0
  189. package/quality/runtimeMarkerReach.ts +255 -0
  190. package/quality/runtimeModuleFacts.ts +290 -0
  191. package/quality/runtimeNameTable.test.ts +172 -0
  192. package/quality/runtimeNameTable.ts +477 -0
  193. package/quality/runtimeScopeReport.test.ts +123 -0
  194. package/quality/runtimeScopeReport.ts +167 -0
  195. package/quality/runtimeSliceKey.ts +269 -0
  196. package/quality/runtimeSyntax.ts +133 -0
  197. package/quality/runtimeTable.fixture.ts +189 -0
  198. package/quality/runtimeUse.test.ts +737 -0
  199. package/quality/runtimeUse.ts +696 -0
  200. package/quality/runtimeUseReadable.test.ts +393 -0
  201. package/quality/ssrScanner.test.ts +13 -0
  202. package/quality/ssrScanner.ts +1 -1
  203. package/quality/translatorBindings.ts +187 -0
  204. package/test/fakeTerminal.ts +45 -0
  205. package/test/secretEnvFixture.ts +134 -0
  206. package/test/testHelpers.ts +11 -0
  207. package/transforms/barrelAnalyzer.ts +24 -2
  208. package/transforms/barrelImportsPlugin.ts +121 -32
  209. package/transforms/exportReach.test.ts +162 -0
  210. package/transforms/exportReach.ts +308 -0
  211. package/transforms/frameworkObjects.fixture.tsx +58 -0
  212. package/transforms/frameworkObjects.test.ts +54 -0
  213. package/transforms/modelReference.test.ts +196 -0
  214. package/transforms/modelReference.ts +39 -0
  215. package/transforms/moduleParts.test.ts +225 -0
  216. package/transforms/moduleParts.ts +418 -0
  217. package/transforms/objectImportEdits.ts +150 -0
  218. package/transforms/objectMemberImports.test.ts +633 -0
  219. package/transforms/objectMemberImports.ts +571 -0
  220. package/transforms/objectMemberLookup.ts +150 -0
  221. package/transforms/objectModule.test.ts +307 -0
  222. package/transforms/objectModule.ts +482 -0
  223. package/transforms/objectModuleAnalyzer.ts +104 -0
  224. package/transforms/partImports.test.ts +76 -0
  225. package/transforms/partImports.ts +110 -0
  226. package/transforms/partModules.test.ts +187 -0
  227. package/transforms/partModules.ts +90 -0
  228. package/transforms/partPurity.ts +124 -0
  229. package/transforms/reactIconImports.test.ts +231 -0
  230. package/transforms/reactIconImports.ts +325 -0
  231. package/transforms/routeConstants.ts +122 -0
  232. package/transforms/routeRuntime.test.ts +835 -0
  233. package/transforms/routeRuntime.ts +703 -0
  234. package/transforms/routeRuntimeEdits.ts +92 -0
  235. package/transforms/routeRuntimeGraph.ts +66 -0
  236. package/transforms/routeRuntimePlan.ts +244 -0
  237. package/transforms/secretEnvDeclaration.test.ts +208 -0
  238. package/transforms/secretEnvDeclaration.ts +213 -0
  239. package/transforms/secretEnvFile.test.ts +117 -0
  240. package/transforms/secretEnvFile.ts +113 -0
  241. package/transforms/secretEnvName.test.ts +54 -0
  242. package/transforms/secretEnvName.ts +29 -0
  243. package/transforms/secretEnvSource.test.ts +148 -0
  244. package/transforms/secretEnvSource.ts +166 -0
  245. package/transforms/serverEnvEvaluationError.ts +11 -0
  246. package/transforms/serverEnvPlugin.test.ts +2 -1
  247. package/transforms/serverEnvPlugin.ts +13 -0
  248. package/transforms/serverEnvProfile.test.ts +129 -2
  249. package/transforms/serverEnvProfile.ts +126 -40
  250. package/transforms/serverEnvSecrets.test.ts +292 -0
  251. package/transforms/signalDescriptors.test.ts +280 -0
  252. package/transforms/signalDescriptors.ts +227 -0
  253. package/transforms/thisFreeExports.ts +87 -0
  254. package/transforms/transforms.test.ts +177 -0
  255. package/transforms/tsconfigPackageResolver.test.ts +1 -0
  256. package/tunnel/createTunnel.ts +5 -1
  257. package/tunnel/ssh2Module.test.ts +37 -0
  258. package/tunnel/ssh2Module.ts +28 -0
  259. package/tunnel/sshTunnel.ts +4 -2
  260. package/typecheck/projectTypecheck.test.ts +32 -1
  261. package/typecheck/projectTypecheck.ts +3 -3
  262. package/typecheck/typeChecker.test.ts +49 -0
  263. package/typecheck/typeChecker.ts +9 -7
  264. package/typecheck/withheldDiagnostics.ts +41 -0
  265. package/util/devInstallCommand.ts +7 -0
  266. package/util/jsonFormatter.test.ts +13 -9
  267. package/workflow/executor.ts +6 -2
  268. package/workflow/index.ts +1 -0
  269. package/workflow/plan.ts +36 -7
  270. package/workflow/types.ts +1 -1
  271. package/workflow/uiTarget.ts +50 -0
  272. package/workspace/envSeed.test.ts +30 -1
  273. package/workspace/envSeed.ts +30 -1
  274. package/workspace/mainCheckout.test.ts +55 -0
  275. package/workspace/mainCheckout.ts +38 -0
  276. package/workspace/scanInfo.test.ts +39 -0
  277. package/workspace/scanInfo.ts +55 -6
  278. package/workspace/slicePlanner.ts +2 -1
  279. package/workspace/workspaceLayout.test.ts +22 -1
  280. package/workspace/workspaceLayout.ts +3 -3
  281. package/CHANGELOG.md +0 -2904
  282. package/codeAgent/agent/AkanCodeCompaction.ts +0 -49
  283. package/codeAgent/agent/AkanCodeServices.ts +0 -122
  284. package/codeAgent/agent/AkanContextFiles.ts +0 -94
  285. package/codeAgent/agent/CodeAgent.ts +0 -626
  286. package/codeAgent/agent/CodeAgentAllowed.ts +0 -35
  287. package/codeAgent/agent/CodeAgentAsks.ts +0 -66
  288. package/codeAgent/agent/CodeAgentCommandLine.ts +0 -372
  289. package/codeAgent/agent/CodeAgentEventMapper.ts +0 -225
  290. package/codeAgent/agent/CodeAgentGate.ts +0 -258
  291. package/codeAgent/agent/CodeAgentProxy.ts +0 -83
  292. package/codeAgent/agent/CodeAgentRpcHost.ts +0 -109
  293. package/codeAgent/agent/CodeAgentRpcListener.ts +0 -195
  294. package/codeAgent/agent/CodeAgentStreamPrinter.ts +0 -86
  295. package/codeAgent/agent/CodeAgentSuspended.ts +0 -85
  296. package/codeAgent/agent/CodeAgentUi.ts +0 -47
  297. package/codeAgent/agent/CodeMailbox.ts +0 -148
  298. package/codeAgent/agent/CodeSessionFork.ts +0 -56
  299. package/codeAgent/agent/CodeSessionIndex.ts +0 -78
  300. package/codeAgent/agent/SubagentPool.ts +0 -219
  301. package/codeAgent/agent/WorkspaceTrust.ts +0 -200
  302. package/codeAgent/agent/akanCodeCompaction.test.ts +0 -36
  303. package/codeAgent/agent/akanCodeModel.ts +0 -47
  304. package/codeAgent/agent/akanCodeServices.test.ts +0 -54
  305. package/codeAgent/agent/akanContextFiles.test.ts +0 -116
  306. package/codeAgent/agent/akanSystemPrompt.ts +0 -50
  307. package/codeAgent/agent/codeAgent.test.ts +0 -337
  308. package/codeAgent/agent/codeAgentCommandLine.test.ts +0 -212
  309. package/codeAgent/agent/codeAgentContract.test.ts +0 -755
  310. package/codeAgent/agent/codeAgentHosts.ts +0 -30
  311. package/codeAgent/agent/codeAgentProxy.test.ts +0 -126
  312. package/codeAgent/agent/codeAgentRpcListener.test.ts +0 -215
  313. package/codeAgent/agent/codeAgentSuspended.test.ts +0 -47
  314. package/codeAgent/agent/codeMailbox.test.ts +0 -76
  315. package/codeAgent/agent/codeSessionFork.test.ts +0 -58
  316. package/codeAgent/agent/codeSessionIndex.test.ts +0 -77
  317. package/codeAgent/agent/consoleToStderr.ts +0 -8
  318. package/codeAgent/agent/jsonLines.ts +0 -29
  319. package/codeAgent/agent/stringArg.ts +0 -5
  320. package/codeAgent/feedback/DevLogFeedback.ts +0 -82
  321. package/codeAgent/feedback/PreviewFeedback.ts +0 -46
  322. package/codeAgent/feedback/TurnFeedback.ts +0 -98
  323. package/codeAgent/feedback/VerifyFeedback.ts +0 -39
  324. package/codeAgent/tools/AkanCli.ts +0 -51
  325. package/codeAgent/tools/AkanCodePlugins.ts +0 -142
  326. package/codeAgent/tools/AkanEditScope.ts +0 -53
  327. package/codeAgent/tools/AkanEnvKeys.ts +0 -50
  328. package/codeAgent/tools/AkanToolPack.ts +0 -86
  329. package/codeAgent/tools/AkanVerifier.ts +0 -30
  330. package/codeAgent/tools/AskToolPack.ts +0 -99
  331. package/codeAgent/tools/DeepSeekWeb.ts +0 -127
  332. package/codeAgent/tools/MailToolPack.ts +0 -76
  333. package/codeAgent/tools/McpClient.ts +0 -209
  334. package/codeAgent/tools/McpOAuth.ts +0 -233
  335. package/codeAgent/tools/McpOAuthLoopback.ts +0 -64
  336. package/codeAgent/tools/McpServerConfig.ts +0 -131
  337. package/codeAgent/tools/McpSignIn.ts +0 -158
  338. package/codeAgent/tools/McpTokenStore.ts +0 -128
  339. package/codeAgent/tools/McpToolPack.ts +0 -206
  340. package/codeAgent/tools/SessionToolPack.ts +0 -91
  341. package/codeAgent/tools/WebToolPack.ts +0 -315
  342. package/codeAgent/tools/akanCodePlugins.test.ts +0 -954
  343. package/codeAgent/tools/askToolPack.test.ts +0 -116
  344. package/codeAgent/tools/deepSeekWeb.test.ts +0 -113
  345. package/codeAgent/tools/mcpOAuth.test.ts +0 -648
  346. package/codeAgent/tools/mcpServerConfig.test.ts +0 -341
  347. package/piDependencyPins.test.ts +0 -45
@@ -0,0 +1,92 @@
1
+ import ts from "typescript";
2
+ import { RuntimeImports } from "../quality/runtimeImports";
3
+ import { type ConstantRewrite, RouteConstants } from "./routeConstants";
4
+
5
+ export interface RouteRuntimeTextEdit {
6
+ start: number;
7
+ end: number;
8
+ text: string;
9
+ }
10
+
11
+ const handleNames = new Set(["fetch", "sig", "st"]);
12
+ //? The tab's one store: a scope's `lib/st.ts` exports this same object, and a key answers once its module has loaded.
13
+ const tabStore = '"akanjs/store"';
14
+
15
+ export class RouteRuntimeEdits {
16
+ //? `handlesOnly`: in a file whose names cannot be told, an import is repointed only where it takes nothing but handles.
17
+ static importEdit(
18
+ statement: ts.Statement,
19
+ sourceFile: ts.SourceFile,
20
+ fileName: string,
21
+ { handlesOnly = false, constants = null }: { handlesOnly?: boolean; constants?: ConstantRewrite | null } = {},
22
+ ): RouteRuntimeTextEdit[] {
23
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) return [];
24
+ const clause = statement.importClause;
25
+ const target = RuntimeImports.targetOf(statement.moduleSpecifier.text, fileName);
26
+ if (!target?.scope || !clause || clause.isTypeOnly) return [];
27
+ const pageRuntime = JSON.stringify(`@${target.scope}/lib/usePage`);
28
+ const specifier = statement.moduleSpecifier;
29
+ const named = !clause.name && clause.namedBindings && ts.isNamedImports(clause.namedBindings);
30
+ const onlyStore =
31
+ named &&
32
+ (clause.namedBindings as ts.NamedImports).elements.every(
33
+ (element) => element.isTypeOnly || (element.propertyName ?? element.name).text === "st",
34
+ );
35
+ if (handlesOnly && ((target.kind === "st" && !onlyStore) || (target.kind === "useClient" && !named))) return [];
36
+ if (target.kind === "useClient" || target.kind === "st")
37
+ return [
38
+ {
39
+ start: specifier.getStart(sourceFile),
40
+ end: specifier.end,
41
+ text: target.kind === "st" ? tabStore : pageRuntime,
42
+ },
43
+ ];
44
+ if (target.kind !== "client" || clause.name || !clause.namedBindings || !ts.isNamedImports(clause.namedBindings))
45
+ return [];
46
+ const { elements } = clause.namedBindings;
47
+ const handleOf = (element: ts.ImportSpecifier) =>
48
+ element.isTypeOnly ? "" : (element.propertyName ?? element.name).text;
49
+ const isHandle = (element: ts.ImportSpecifier) => handleNames.has(handleOf(element));
50
+ const [handles, rest] = [elements.filter(isHandle), elements.filter((element) => !isHandle(element))];
51
+ const typedCnst = (element: ts.ImportSpecifier) => !!constants && handleOf(element) === "cnst";
52
+ if (!handles.length)
53
+ return constants ? RouteConstants.typedEdits(statement, sourceFile, (imported) => imported === "cnst") : [];
54
+ const namesOf = (list: ts.ImportSpecifier[]) => list.map((element) => element.getText(sourceFile)).join(", ");
55
+ const typesOnly = rest.every((element) => element.isTypeOnly || typedCnst(element));
56
+ const restNames = typesOnly
57
+ ? rest.map((element) => element.getText(sourceFile).replace(/^type\s+/, "")).join(", ")
58
+ : rest.map((element) => `${typedCnst(element) ? "type " : ""}${element.getText(sourceFile)}`).join(", ");
59
+ const [stores, descriptors] = [
60
+ handles.filter((element) => handleOf(element) === "st"),
61
+ handles.filter((element) => handleOf(element) !== "st"),
62
+ ];
63
+ const lines = [
64
+ ...(descriptors.length ? [`import { ${namesOf(descriptors)} } from ${pageRuntime};`] : []),
65
+ ...(stores.length ? [`import { ${namesOf(stores)} } from ${tabStore};`] : []),
66
+ ...(rest.length
67
+ ? [`import ${typesOnly ? "type " : ""}{ ${restNames} } from ${specifier.getText(sourceFile)};`]
68
+ : []),
69
+ ];
70
+ const [start, end] = [statement.getStart(sourceFile), statement.end];
71
+ const newlines = sourceFile.text.slice(start, end).split("\n").length - 1;
72
+ return [{ start, end, text: `${lines.join(" ")}${"\n".repeat(newlines)}` }];
73
+ }
74
+
75
+ //? After the directives, on the first statement's own line: `"use client"` stays first and no line moves.
76
+ static leading(sourceFile: ts.SourceFile, imports: string[]): RouteRuntimeTextEdit {
77
+ const first = sourceFile.statements.find(
78
+ (statement) => !ts.isExpressionStatement(statement) || !ts.isStringLiteral(statement.expression),
79
+ );
80
+ const at = first ? first.getStart(sourceFile) : sourceFile.text.length;
81
+ return { start: at, end: at, text: `${imports.join(" ")} ` };
82
+ }
83
+
84
+ static apply(source: string, edits: RouteRuntimeTextEdit[]) {
85
+ return [...edits]
86
+ .sort((a, b) => b.start - a.start || b.end - a.end)
87
+ .reduce(
88
+ (text, { start, end, text: replacement }) => text.slice(0, start) + replacement + text.slice(end),
89
+ source,
90
+ );
91
+ }
92
+ }
@@ -0,0 +1,66 @@
1
+ export interface RouteRuntimeImport {
2
+ path: string;
3
+ lazy: boolean;
4
+ }
5
+
6
+ export interface RouteRuntimeBundle {
7
+ //? Absolute paths, from a bundle of the same entries in which every entry loads the whole runtime.
8
+ importsByModule: ReadonlyMap<string, readonly RouteRuntimeImport[]>;
9
+ entries: readonly string[];
10
+ //? The entries each route renders first; where they are told, an entry of no route keeps the whole runtime.
11
+ entriesByRoute?: ReadonlyMap<string, readonly string[]>;
12
+ }
13
+
14
+ //* The import graph the per-route runtime is planned over: what one module reaches without passing a runtime file,
15
+ //* whose own imports differ between a page loading the whole runtime and a page loading pieces.
16
+ export class RouteRuntimeGraph {
17
+ readonly #imports: ReadonlyMap<string, readonly RouteRuntimeImport[]>;
18
+ readonly #isRuntimeFile: (absPath: string) => boolean;
19
+
20
+ constructor(
21
+ imports: ReadonlyMap<string, readonly RouteRuntimeImport[]>,
22
+ isRuntimeFile: (absPath: string) => boolean,
23
+ ) {
24
+ this.#imports = imports;
25
+ this.#isRuntimeFile = isRuntimeFile;
26
+ }
27
+
28
+ get modules(): string[] {
29
+ return [...this.#imports.keys()];
30
+ }
31
+
32
+ has(absPath: string) {
33
+ return this.#imports.has(absPath);
34
+ }
35
+
36
+ importsOf(absPath: string): string[] {
37
+ return (this.#imports.get(absPath) ?? []).filter(({ lazy }) => !lazy).map(({ path }) => path);
38
+ }
39
+
40
+ lazyImportsOf(absPath: string): string[] {
41
+ return (this.#imports.get(absPath) ?? [])
42
+ .filter(({ path, lazy }) => lazy && !this.#isRuntimeFile(path))
43
+ .map(({ path }) => path);
44
+ }
45
+
46
+ //? A module asked for by `import()` loads when that call runs, so it is planned as an entry of its own.
47
+ get lazyRoots(): string[] {
48
+ return [...new Set(this.modules.flatMap((module) => this.lazyImportsOf(module)))];
49
+ }
50
+
51
+ closureOf(roots: Iterable<string>, into = new Set<string>()): Set<string> {
52
+ const queue: string[] = [];
53
+ for (const root of roots)
54
+ if (!into.has(root) && !this.#isRuntimeFile(root)) {
55
+ into.add(root);
56
+ queue.push(root);
57
+ }
58
+ for (const module of queue)
59
+ for (const imported of this.importsOf(module)) {
60
+ if (into.has(imported) || this.#isRuntimeFile(imported)) continue;
61
+ into.add(imported);
62
+ queue.push(imported);
63
+ }
64
+ return into;
65
+ }
66
+ }
@@ -0,0 +1,244 @@
1
+ import type { RouteRuntimeGraph } from "./routeRuntimeGraph";
2
+
3
+ //? `file` is the one an author can change, as a workspace path, or a path under `akanjs/` for a framework component.
4
+ export interface RouteRuntimeWhy {
5
+ file: string;
6
+ line?: number;
7
+ message: string;
8
+ }
9
+
10
+ export type RouteRuntimeKeep =
11
+ | ({ rule: "reader"; path: string } & RouteRuntimeWhy)
12
+ | { rule: "store-side"; file: string; message: string }
13
+ | { rule: "lazy"; file: string; asks: string }
14
+ | { rule: "majority"; whole: number; others: number }
15
+ | { rule: "asked" }
16
+ | { rule: "unheld" }
17
+ | { rule: "not-smaller"; route: string; whole: number; perModule: number }
18
+ //? The build every page is measured against, in which every root keeps the whole runtime.
19
+ | { rule: "reference" };
20
+
21
+ export interface RouteRuntimeCause {
22
+ rule: RouteRuntimeKeep["rule"];
23
+ file?: string;
24
+ line?: number;
25
+ message: string;
26
+ entries: string[];
27
+ routes: string[];
28
+ //? For a file a root reaches: the imports from a root down to it, one chain per file importing it.
29
+ chains: string[][];
30
+ }
31
+
32
+ const ruleMessages = {
33
+ majority:
34
+ "more pages keeping the whole runtime hold it than pages loading per module, whose pieces those pages would carry on top",
35
+ asked: "only files keeping the whole runtime ask for it with import()",
36
+ unheld: "no page loading per module holds it",
37
+ reference: "the build measured every page with the whole runtime",
38
+ } as const;
39
+
40
+ export interface RouteRuntimePlanInput {
41
+ graph: RouteRuntimeGraph;
42
+ entries: ReadonlySet<string>;
43
+ //? Null where no route was told: an entry of no route is then narrowed like any other.
44
+ routes: ReadonlyMap<string, readonly string[]> | null;
45
+ //? Why the file needs every module, or null where it loads only the modules it names.
46
+ readsWhole: (file: string) => RouteRuntimeWhy | null;
47
+ //? Why an entry a store file imports cannot be narrowed, or null.
48
+ storeSide: (root: string) => string | null;
49
+ bringsPieces: (file: string) => boolean;
50
+ nameOf: (file: string) => string;
51
+ }
52
+
53
+ //* Which roots of a build loading per module keep the whole runtime, each with the reason it does. A root is only
54
+ //* ever added: every rule keeps more as others keep more, so replaying them after a new keep ends and cannot undo one.
55
+ export class RouteRuntimePlan {
56
+ static readonly chainsShown = 3;
57
+ readonly keeps = new Map<string, RouteRuntimeKeep>();
58
+ readonly roots: string[];
59
+ readonly #input: RouteRuntimePlanInput;
60
+ readonly #closures: Map<string, Set<string>>;
61
+ readonly #lazyOf: Map<string, string[]>;
62
+
63
+ constructor(input: RouteRuntimePlanInput) {
64
+ this.#input = input;
65
+ const { graph, entries } = input;
66
+ this.roots = [...new Set([...entries, ...graph.lazyRoots])];
67
+ this.#closures = new Map(this.roots.map((root) => [root, graph.closureOf([root])]));
68
+ this.#lazyOf = new Map(
69
+ this.roots.map((root) => [root, [...this.closureOf(root)].flatMap((file) => graph.lazyImportsOf(file))]),
70
+ );
71
+ this.#keepReaders();
72
+ this.#keepAskers();
73
+ this.#keepMajority(true);
74
+ this.#settle();
75
+ }
76
+
77
+ get routes(): ReadonlyMap<string, readonly string[]> {
78
+ return this.#input.routes ?? new Map();
79
+ }
80
+
81
+ get told() {
82
+ return this.#input.routes !== null;
83
+ }
84
+
85
+ closureOf(root: string): Set<string> {
86
+ return this.#closures.get(root) ?? new Set();
87
+ }
88
+
89
+ isWhole(route: readonly string[]) {
90
+ return route.some((entry) => this.keeps.has(entry));
91
+ }
92
+
93
+ chainTo(root: string, target: string): string[] {
94
+ const { graph } = this.#input;
95
+ const parents = new Map<string, string | null>([[root, null]]);
96
+ for (const file of parents.keys()) {
97
+ if (file === target) break;
98
+ for (const imported of graph.importsOf(file)) if (!parents.has(imported)) parents.set(imported, file);
99
+ }
100
+ const chain: string[] = [];
101
+ for (let file: string | null = parents.has(target) ? target : null; file; file = parents.get(file) ?? null)
102
+ chain.unshift(file);
103
+ return chain;
104
+ }
105
+
106
+ causes(): RouteRuntimeCause[] {
107
+ const { nameOf } = this.#input;
108
+ const causes = new Map<string, RouteRuntimeCause>();
109
+ const tails = new Map<string, Set<string>>();
110
+ for (const [root, keep] of this.keeps) {
111
+ const said =
112
+ keep.rule === "reader" || keep.rule === "store-side"
113
+ ? { file: keep.file, ...("line" in keep && keep.line ? { line: keep.line } : {}), message: keep.message }
114
+ : keep.rule === "lazy"
115
+ ? { message: `asks with import() for ${keep.asks}, which keeps the whole runtime` }
116
+ : keep.rule === "not-smaller"
117
+ ? {
118
+ message: `${keep.route} is ${keep.perModule} B loading per module and ${keep.whole} B with the whole runtime`,
119
+ }
120
+ : { message: ruleMessages[keep.rule] };
121
+ const key = JSON.stringify([keep.rule, said]);
122
+ const cause = causes.get(key) ?? { rule: keep.rule, ...said, entries: [], routes: [], chains: [] };
123
+ causes.set(key, cause);
124
+ cause.entries.push(nameOf(root));
125
+ for (const [route, entries] of this.routes)
126
+ if (entries.includes(root) && !cause.routes.includes(route)) cause.routes.push(route);
127
+ if (keep.rule !== "reader") continue;
128
+ const chain = this.chainTo(root, keep.path).map(nameOf);
129
+ const seen = tails.get(key) ?? new Set<string>();
130
+ tails.set(key, seen);
131
+ const tail = chain.slice(-2).join(" ");
132
+ if (!seen.has(tail) && seen.size < RouteRuntimePlan.chainsShown) cause.chains.push(chain);
133
+ seen.add(tail);
134
+ }
135
+ return [...causes.values()].sort(
136
+ (a, b) => b.routes.length - a.routes.length || b.entries.length - a.entries.length,
137
+ );
138
+ }
139
+
140
+ keep(roots: Iterable<string>, why: RouteRuntimeKeep) {
141
+ for (const root of roots) if (!this.keeps.has(root)) this.keeps.set(root, why);
142
+ this.#settle();
143
+ }
144
+
145
+ #settle() {
146
+ for (let size = -1; size !== this.keeps.size; ) {
147
+ size = this.keeps.size;
148
+ this.#keepAskers();
149
+ this.#keepMajority(false);
150
+ this.#keepAsked();
151
+ this.#keepUnheld();
152
+ }
153
+ }
154
+
155
+ #keepReaders() {
156
+ const { readsWhole, storeSide, nameOf } = this.#input;
157
+ for (const root of this.roots) {
158
+ //? Nothing imports an entry, so no importer loads the stores a store-side entry's code names.
159
+ const side = storeSide(root);
160
+ if (side) {
161
+ this.keeps.set(root, { rule: "store-side", file: nameOf(root), message: side });
162
+ continue;
163
+ }
164
+ for (const file of this.closureOf(root)) {
165
+ const why = readsWhole(file);
166
+ if (!why) continue;
167
+ this.keeps.set(root, { rule: "reader", path: file, ...why });
168
+ break;
169
+ }
170
+ }
171
+ }
172
+
173
+ //? A module asked for by `import()` gets no entry of its own to load the whole runtime first, so its asker does.
174
+ #keepAskers() {
175
+ const { nameOf } = this.#input;
176
+ for (let more = this.roots; more.length > 0; ) {
177
+ more = this.roots.filter(
178
+ (root) => !this.keeps.has(root) && this.#lazyOf.get(root)?.some((lazy) => this.keeps.has(lazy)),
179
+ );
180
+ for (const root of more) {
181
+ const asks = this.#lazyOf.get(root)?.find((lazy) => this.keeps.has(lazy)) ?? root;
182
+ this.keeps.set(root, { rule: "lazy", file: nameOf(root), asks: nameOf(asks) });
183
+ }
184
+ }
185
+ }
186
+
187
+ //? A narrowed entry's pieces repeat what a whole-runtime page already carries; pages a kept entry makes whole recount.
188
+ //? `guessing` also keeps an entry more whole pages hold than others: once a build has measured its pages, only the
189
+ //? entry no other page holds follows, since a guess there would take the whole runtime to a page measured smaller.
190
+ #keepMajority(guessing: boolean) {
191
+ const { bringsPieces } = this.#input;
192
+ const routes = [...this.routes.values()];
193
+ const brings = new Map<string, boolean>();
194
+ const bringsOf = (root: string) => {
195
+ const known = brings.get(root);
196
+ if (known !== undefined) return known;
197
+ const answer = [...this.closureOf(root)].some(bringsPieces);
198
+ brings.set(root, answer);
199
+ return answer;
200
+ };
201
+ for (let more = this.roots; more.length > 0; ) {
202
+ const count = (held: boolean) => {
203
+ const counts = new Map<string, number>();
204
+ for (const route of routes)
205
+ if (this.isWhole(route) === held) for (const entry of route) counts.set(entry, (counts.get(entry) ?? 0) + 1);
206
+ return counts;
207
+ };
208
+ const [inWhole, inOther] = [count(true), count(false)];
209
+ more = this.roots.filter((root) => {
210
+ const [holding, others] = [inWhole.get(root) ?? 0, inOther.get(root) ?? 0];
211
+ return !this.keeps.has(root) && holding > others && (others === 0 || (guessing && bringsOf(root)));
212
+ });
213
+ for (const root of more)
214
+ this.keeps.set(root, { rule: "majority", whole: inWhole.get(root) ?? 0, others: inOther.get(root) ?? 0 });
215
+ }
216
+ }
217
+
218
+ #keepAsked() {
219
+ const { entries } = this.#input;
220
+ const askers = new Map<string, string[]>();
221
+ for (const [root, lazies] of this.#lazyOf)
222
+ for (const lazy of lazies) askers.set(lazy, [...(askers.get(lazy) ?? []), root]);
223
+ for (let more = [...askers]; more.length > 0; ) {
224
+ more = [...askers].filter(
225
+ ([lazy, askedBy]) =>
226
+ !this.keeps.has(lazy) && !entries.has(lazy) && askedBy.every((root) => this.keeps.has(root)),
227
+ );
228
+ for (const [lazy] of more) this.keeps.set(lazy, { rule: "asked" });
229
+ }
230
+ }
231
+
232
+ //? A root no page loading pieces holds or asks for would be narrowed for no page: the files it shares with a whole
233
+ //? page would then load pieces of what that page's whole runtime already holds. With no whole page there is none to
234
+ //? carry both, and a root keeping the whole runtime would split every page's chunks from the stores it reaches.
235
+ #keepUnheld() {
236
+ const routes = [...this.routes.values()];
237
+ if (!this.told || !routes.some((route) => this.isWhole(route))) return;
238
+ const live = new Set<string>();
239
+ for (const route of routes) if (!this.isWhole(route)) for (const entry of route) live.add(entry);
240
+ for (const root of live) for (const lazy of this.#lazyOf.get(root) ?? []) if (!this.keeps.has(lazy)) live.add(lazy);
241
+ for (const root of this.roots)
242
+ if (!this.keeps.has(root) && !live.has(root)) this.keeps.set(root, { rule: "unheld" });
243
+ }
244
+ }
@@ -0,0 +1,208 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import path from "node:path";
3
+ import {
4
+ computedSecretKeys,
5
+ holdsSentinel,
6
+ secretEnvFixtureNames,
7
+ secretEnvSentinels,
8
+ writeComputedSecretFixture,
9
+ writeSecretEnvFixture,
10
+ } from "../test/secretEnvFixture";
11
+ import { tempDirs, writeText } from "../test/testHelpers";
12
+ import { SecretEnvDeclaration } from "./secretEnvDeclaration";
13
+ import { SecretEnvFile } from "./secretEnvFile";
14
+
15
+ const makeTempRoot = tempDirs("akan-devkit-secret-env-");
16
+
17
+ const withShell = async <T>(variables: { [name: string]: string }, run: () => Promise<T>) => {
18
+ const before = Object.fromEntries(Object.keys(variables).map((name) => [name, process.env[name]]));
19
+ Object.assign(process.env, variables);
20
+ try {
21
+ return await run();
22
+ } finally {
23
+ for (const [name, value] of Object.entries(before)) {
24
+ if (value === undefined) delete process.env[name];
25
+ else process.env[name] = value;
26
+ }
27
+ }
28
+ };
29
+
30
+ const ownReads = [
31
+ "",
32
+ " own: {",
33
+ " apiKey: process.env.ZQ_API_KEY,",
34
+ ' token: "Bearer " + process.env.ZQ_TOKEN,',
35
+ [" url: `postgres://app:$", "{process.env.ZQ_DB_PASS}@db.example.test/app`,"].join(""),
36
+ ' privateKey: process.env.ZQ_PEM?.replace(/\\\\n/g, "\\n"),',
37
+ ' password: process.env.ZQ_PASSWORD ?? "sentinel-own-fallback-3c55",',
38
+ " },",
39
+ ].join("\n");
40
+
41
+ const shellOwn = {
42
+ ZQ_API_KEY: "shell-api-key-1d20",
43
+ ZQ_TOKEN: "abc",
44
+ ZQ_DB_PASS: "shell-db-pass-2e31",
45
+ ZQ_PEM: "-----BEGIN-----\\nshell-pem-line-3f42\\n-----END-----",
46
+ ZQ_PASSWORD: "shell-password-4a53",
47
+ };
48
+
49
+ describe("SecretEnvDeclaration", () => {
50
+ test("lists each secret of the environment's server env with its variable, kind and value, a lib's default included", async () => {
51
+ const { envDir } = await writeSecretEnvFixture(await makeTempRoot());
52
+ const { variables, unmoved } = await SecretEnvDeclaration.of(envDir, "main");
53
+ expect(unmoved).toEqual([]);
54
+ expect(variables.map(({ name }) => name)).toEqual(secretEnvFixtureNames);
55
+ expect(Object.fromEntries(variables.map(({ name, kind, path: at, value }) => [name, { kind, at, value }]))).toEqual(
56
+ {
57
+ JWT_SECRET: { kind: "string", at: "security.jwtSecret", value: secretEnvSentinels.jwt },
58
+ SECURITY__SSO__GOOGLE__CLIENT_SECRET: {
59
+ kind: "string",
60
+ at: "security.sso.google.clientSecret",
61
+ value: secretEnvSentinels.google,
62
+ },
63
+ MAILER__AUTH__PASS: { kind: "string", at: "mailer.auth.pass", value: secretEnvSentinels.libPass },
64
+ OBJECT_STORAGE__ENDPOINT: { kind: "string", at: "objectStorage.endpoint", value: secretEnvSentinels.storage },
65
+ DISCORD__TOKENS: { kind: "json", at: "discord.tokens", value: JSON.stringify(secretEnvSentinels.bots) },
66
+ DISCORD__WEBHOOK: { kind: "string", at: "discord.webhook", value: secretEnvSentinels.webhook },
67
+ PUSH_NOTI__FIREBASE__PRIVATE_KEY: {
68
+ kind: "multiline",
69
+ at: "pushNoti.firebase.private_key",
70
+ value: secretEnvSentinels.pem,
71
+ },
72
+ MESSAGE__API_SECRET: { kind: "string", at: "message.apiSecret", value: secretEnvSentinels.dollar },
73
+ MESSAGE__SENDER_PASSWORD: {
74
+ kind: "string",
75
+ at: "message.senderPassword",
76
+ value: secretEnvSentinels.apostrophe,
77
+ },
78
+ POSTGRES_URL: { kind: "string", at: "database.postgres.url", value: secretEnvSentinels.postgres },
79
+ },
80
+ );
81
+ });
82
+
83
+ test("the listing names every variable and its key, says which the shell sets, and holds no value", async () => {
84
+ const { envDir } = await writeSecretEnvFixture(await makeTempRoot());
85
+ const declared = await SecretEnvDeclaration.of(envDir, "main");
86
+ const shell = process.env.MAILER__AUTH__PASS;
87
+ process.env.MAILER__AUTH__PASS = "set-in-the-shell";
88
+ try {
89
+ const listing = SecretEnvFile.listing(declared);
90
+ expect(holdsSentinel(listing)).toBe(false);
91
+ expect(listing.split("\n")).toEqual([
92
+ "VARIABLE KIND SHELL ENV FILE KEY",
93
+ "JWT_SECRET string unset security.jwtSecret",
94
+ "SECURITY__SSO__GOOGLE__CLIENT_SECRET string unset security.sso.google.clientSecret",
95
+ "MAILER__AUTH__PASS string set mailer.auth.pass",
96
+ "OBJECT_STORAGE__ENDPOINT string unset objectStorage.endpoint",
97
+ "DISCORD__TOKENS json unset discord.tokens",
98
+ "DISCORD__WEBHOOK string unset discord.webhook",
99
+ "PUSH_NOTI__FIREBASE__PRIVATE_KEY multiline unset pushNoti.firebase.private_key",
100
+ "MESSAGE__API_SECRET string unset message.apiSecret",
101
+ "MESSAGE__SENDER_PASSWORD string unset message.senderPassword",
102
+ "POSTGRES_URL string unset database.postgres.url",
103
+ ]);
104
+ } finally {
105
+ if (shell === undefined) delete process.env.MAILER__AUTH__PASS;
106
+ else process.env.MAILER__AUTH__PASS = shell;
107
+ }
108
+ });
109
+
110
+ test("lists the environment asked for, and the env file itself where it replaced the switch", async () => {
111
+ const { envDir } = await writeSecretEnvFixture(await makeTempRoot());
112
+ const local = await SecretEnvDeclaration.of(envDir, "local");
113
+ expect(local.variables.map(({ name, value }) => [name, value])).toEqual([
114
+ ["LLM__API_KEY", secretEnvSentinels.local],
115
+ ]);
116
+ await writeText(
117
+ path.join(envDir, "env.server.ts"),
118
+ `export const env = { security: { jwtSecret: ${JSON.stringify(secretEnvSentinels.jwt)} }, hostname: "app.example.test" };\n`,
119
+ );
120
+ const replaced = await SecretEnvDeclaration.of(envDir, "main");
121
+ expect(replaced.variables.map(({ name, value }) => [name, value])).toEqual([
122
+ ["JWT_SECRET", secretEnvSentinels.jwt],
123
+ ]);
124
+ });
125
+
126
+ test("names every key whose secret the env file imports or computes, a short one and a plain-named one under a secret parent included", async () => {
127
+ const { envDir } = await writeComputedSecretFixture(await makeTempRoot());
128
+ const declared = await SecretEnvDeclaration.of(envDir, "main");
129
+ expect(declared.unmoved).toEqual(computedSecretKeys);
130
+ expect(SecretEnvFile.listing(declared)).toEndWith(
131
+ `\n\`akan build\` stops at ${computedSecretKeys.join(", ")}: secret values the env file computes or imports. Write the string at the key, or read it there yourself as \`process.env.<NAME>\`.`,
132
+ );
133
+ });
134
+
135
+ test("names a secret the env file computes as one no build can move, without its value", async () => {
136
+ const { envDir } = await writeSecretEnvFixture(await makeTempRoot(), {
137
+ mainExtra: '\n llm: { apiKey: ["sentinel", "computed", "0a73"].join("-") },',
138
+ });
139
+ const declared = await SecretEnvDeclaration.of(envDir, "main");
140
+ expect(declared.unmoved).toEqual(["llm.apiKey"]);
141
+ expect(declared.variables.map(({ name }) => name)).toEqual(secretEnvFixtureNames);
142
+ const listing = SecretEnvFile.listing(declared);
143
+ expect(holdsSentinel(listing)).toBe(false);
144
+ expect(listing).toEndWith(
145
+ "\n`akan build` stops at llm.apiKey: a secret value the env file computes or imports. Write the string at the key, or read it there yourself as `process.env.<NAME>`.",
146
+ );
147
+ });
148
+
149
+ test("a secret key the env file reads from the process env itself is nothing the build moves or holds, with the variable unset", async () => {
150
+ const { envDir } = await writeSecretEnvFixture(await makeTempRoot(), { mainExtra: ownReads });
151
+ const declared = await SecretEnvDeclaration.of(envDir, "main");
152
+ expect(declared.unmoved).toEqual([]);
153
+ expect(declared.variables.map(({ name }) => name)).toEqual([...secretEnvFixtureNames, "OWN__PASSWORD"]);
154
+ });
155
+
156
+ test("its own read is told from a computed secret also when another of its variables cannot take a made-up value", async () => {
157
+ const { envDir } = await writeSecretEnvFixture(await makeTempRoot(), {
158
+ mainExtra: `${ownReads}\n origin: new URL(process.env.ZQ_ORIGIN ?? "https://app.example.test").host,`,
159
+ });
160
+ expect((await SecretEnvDeclaration.of(envDir, "main")).unmoved).toEqual([]);
161
+ });
162
+
163
+ test("an env file that needs a variable of the shell to load is listed with it set, its own reads left alone, and named by error class and line without it", async () => {
164
+ const { envDir } = await writeSecretEnvFixture(await makeTempRoot(), {
165
+ mainExtra: `${ownReads}\n hosts: process.env.ZQ_HOSTS!.split(","),\n push: { privateKey: process.env.ZQ_PEM!.replace(/\\\\n/g, "\\n") },`,
166
+ });
167
+ const failure = await SecretEnvDeclaration.of(envDir, "main").catch((error: Error) => error.message);
168
+ expect(failure).toMatch(
169
+ /^env\.server\.ts could not be evaluated to check it for secrets: TypeError at .*env\.server\.main\.ts:\d+$/,
170
+ );
171
+ const declared = await withShell({ ...shellOwn, ZQ_HOSTS: "a.example.test,b.example.test" }, () =>
172
+ SecretEnvDeclaration.of(envDir, "main"),
173
+ );
174
+ expect(declared.unmoved).toEqual([]);
175
+ expect(declared.variables.map(({ name }) => name)).toEqual([...secretEnvFixtureNames, "OWN__PASSWORD"]);
176
+ expect(JSON.stringify(declared.variables)).not.toContain("shell-");
177
+ });
178
+
179
+ test("a value the env file imports behind its own read is still one no build can move, while the variable is unset", async () => {
180
+ const root = await makeTempRoot();
181
+ await writeText(path.join(root, "apps/demo/srvkit/keys.ts"), 'export const llmKey = "sentinel-imported-0a73";\n');
182
+ const { envDir } = await writeSecretEnvFixture(root, {
183
+ mainHead: 'import { llmKey } from "../srvkit/keys";\n',
184
+ mainExtra: "\n llm: { apiKey: process.env.ZQ_LLM_KEY ?? llmKey },",
185
+ });
186
+ expect((await SecretEnvDeclaration.of(envDir, "main")).unmoved).toEqual(["llm.apiKey"]);
187
+ });
188
+
189
+ test("says so when the server env holds no secret", async () => {
190
+ const root = await makeTempRoot();
191
+ const envDir = path.join(root, "apps/demo/env");
192
+ await writeText(path.join(envDir, "env.server.ts"), 'export const env = { hostname: "app.example.test" };\n');
193
+ expect(SecretEnvFile.listing(await SecretEnvDeclaration.of(envDir, "main"))).toBe(
194
+ "The server env holds no secret value, so a build reads none.",
195
+ );
196
+ });
197
+
198
+ test("refuses a key whose variable the platform owns, naming the file and the key and not the value", async () => {
199
+ const { envDir } = await writeSecretEnvFixture(await makeTempRoot(), {
200
+ mainExtra: '\n pwd: "sentinel-pwd-1b84",',
201
+ });
202
+ const failure = await SecretEnvDeclaration.of(envDir, "main").catch((error: Error) => error.message);
203
+ expect(failure).toContain(
204
+ "env.server.main.ts `pwd` is a secret a build would read from the environment variable PWD",
205
+ );
206
+ expect(holdsSentinel(String(failure))).toBe(false);
207
+ });
208
+ });