@akanjs/devkit 3.3.0-rc.9 → 3.3.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 (362) 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 +307 -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 +233 -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 +438 -7
  28. package/app/applicationBuildRunner.ts +237 -37
  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 +7 -2
  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 +11 -5
  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/docs/errorCodeReference.test.ts +26 -0
  67. package/docs/errorCodeScan.ts +23 -6
  68. package/executors/appExecutor.ts +26 -12
  69. package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
  70. package/executors/clientRuntimeKeys.fixture.json +393 -0
  71. package/executors/clientRuntimeKeys.test.ts +1692 -0
  72. package/executors/executor.ts +14 -6
  73. package/executors/executors.test.ts +155 -1
  74. package/executors/pkgExecutor.ts +2 -1
  75. package/executors/sysExecutor.ts +112 -8
  76. package/executors/workspaceExecutor.ts +7 -4
  77. package/frontendBuild/allRoutesBuilder.ts +99 -7
  78. package/frontendBuild/autoImportSync.ts +3 -2
  79. package/frontendBuild/buildRouteClient.test.ts +684 -6
  80. package/frontendBuild/clientBuildTypes.ts +26 -0
  81. package/frontendBuild/clientEntriesBundler.test.ts +79 -0
  82. package/frontendBuild/clientEntriesBundler.ts +70 -1
  83. package/frontendBuild/clientEntryDiscovery.test.ts +308 -1
  84. package/frontendBuild/clientEntryDiscovery.ts +134 -12
  85. package/frontendBuild/clientEntryGroups.test.ts +77 -0
  86. package/frontendBuild/clientEntryGroups.ts +61 -0
  87. package/frontendBuild/csrDevArtifactWriter.ts +2 -2
  88. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  89. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  90. package/frontendBuild/csrDevPatcher.test.ts +4 -5
  91. package/frontendBuild/csrDevPatcher.ts +37 -11
  92. package/frontendBuild/csrDevTypes.ts +9 -0
  93. package/frontendBuild/cssCandidateCache.test.ts +12 -0
  94. package/frontendBuild/cssCandidateCache.ts +5 -3
  95. package/frontendBuild/cssCompiler.test.ts +14 -0
  96. package/frontendBuild/devBarrelImports.test.ts +127 -0
  97. package/frontendBuild/devBarrelImports.ts +81 -21
  98. package/frontendBuild/devChangePlanner.ts +0 -1
  99. package/frontendBuild/devRegistryBundler.ts +4 -2
  100. package/frontendBuild/devRouteRuntime.test.ts +493 -0
  101. package/frontendBuild/devRouteRuntime.ts +167 -0
  102. package/frontendBuild/dictionaryAssetBuilder.test.ts +408 -0
  103. package/frontendBuild/dictionaryAssetBuilder.ts +185 -17
  104. package/frontendBuild/dictionaryConstants.ts +136 -0
  105. package/frontendBuild/dictionaryOwnParts.ts +88 -0
  106. package/frontendBuild/dictionaryPackState.ts +131 -0
  107. package/frontendBuild/dictionaryPacking.test.ts +207 -0
  108. package/frontendBuild/dictionaryPacking.ts +160 -0
  109. package/frontendBuild/dictionaryRoutes.test.ts +251 -0
  110. package/frontendBuild/dictionaryRoutes.ts +227 -0
  111. package/frontendBuild/frontendBuild.test.ts +5 -3
  112. package/frontendBuild/hmrWatcher.test.ts +3 -1
  113. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  114. package/frontendBuild/pagesBundleBuilder.ts +78 -2
  115. package/frontendBuild/plainStylesheet.test.ts +2 -2
  116. package/frontendBuild/precompressArtifacts.test.ts +22 -0
  117. package/frontendBuild/precompressArtifacts.ts +34 -8
  118. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  119. package/frontendBuild/renderedEntries.ts +144 -0
  120. package/frontendBuild/routeClientBuilder.ts +407 -43
  121. package/frontendBuild/routeHandoffs.test.ts +155 -0
  122. package/frontendBuild/routeHandoffs.ts +117 -0
  123. package/frontendBuild/routeModulePreloads.test.ts +32 -0
  124. package/frontendBuild/routeModulePreloads.ts +20 -11
  125. package/frontendBuild/routeRuntimeCheck.test.ts +280 -0
  126. package/frontendBuild/routeRuntimeCheck.ts +248 -0
  127. package/frontendBuild/routeRuntimePays.test.ts +143 -0
  128. package/frontendBuild/routeRuntimePays.ts +117 -0
  129. package/frontendBuild/ssrBaseArtifactBuilder.ts +30 -35
  130. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  131. package/frontendBuild/ssrDevBundler.ts +66 -11
  132. package/frontendBuild/vendorFileImports.test.ts +254 -0
  133. package/frontendBuild/vendorFileImports.ts +163 -0
  134. package/frontendBuild/vendorNarrowing.test.ts +47 -3
  135. package/frontendBuild/vendorNarrowing.ts +38 -2
  136. package/frontendBuild/vendorSpecifiers.ts +2 -0
  137. package/frontendBuild/workerChunks.ts +61 -0
  138. package/guideline/agentAssets.ts +1 -1
  139. package/incrementalBuilder/buildBatch.proc.ts +27 -1
  140. package/incrementalBuilder/buildBatchProtocol.ts +1 -0
  141. package/incrementalBuilder/builderWatch.ts +11 -1
  142. package/incrementalBuilder/incrementalBuilder.proc.test.ts +159 -0
  143. package/incrementalBuilder/incrementalBuilder.proc.ts +31 -3
  144. package/incrementalBuilder/pendingMetadata.test.ts +27 -0
  145. package/incrementalBuilder/pendingMetadata.ts +19 -0
  146. package/integration/devResourceProbe.ts +14 -0
  147. package/integration/devStability.integration.test.ts +46 -21
  148. package/integration/renderAdmissionSoak.test.ts +39 -34
  149. package/integration/renderAdmissionSoak.ts +6 -0
  150. package/integration/ssrMemoryProbe.ts +5 -0
  151. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  152. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  153. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  154. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  155. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  156. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  157. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  158. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  159. package/lint/biomeBase.test.ts +50 -3
  160. package/lint/biomeBase.ts +1 -1
  161. package/lint/biomeCheck.test.ts +173 -0
  162. package/lint/biomeCheck.ts +132 -0
  163. package/lint/linter.test.ts +16 -11
  164. package/lint/no-arbitrary-color.grit +5 -0
  165. package/lint/no-conditional-st-hook.grit +5 -1
  166. package/lint/no-daisyui-legacy-class.grit +8 -0
  167. package/lint/no-document-cookie.grit +3 -0
  168. package/lint/no-inline-color.grit +10 -2
  169. package/lint/no-oversized-list-limit.grit +2 -0
  170. package/lint/no-raw-palette-class.grit +7 -0
  171. package/lint/no-unpublished-form-setter.grit +2 -0
  172. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  173. package/lint/no-web-storage.grit +3 -0
  174. package/lint/withheldEnvFile.ts +17 -0
  175. package/mobile/desktopBin.ts +2 -2
  176. package/mobile/desktopServerStage.test.ts +18 -3
  177. package/mobile/desktopServerStage.ts +7 -2
  178. package/mobile/nativeApp.test.ts +13 -5
  179. package/mobile/nativeApp.ts +9 -4
  180. package/mobile/nativeConfig.test.ts +27 -7
  181. package/mobile/nativeConfig.ts +19 -9
  182. package/mobile/nativePublicEnv.ts +1 -1
  183. package/mobile/serverBundleSecrets.ts +43 -0
  184. package/package.json +11 -12
  185. package/packageExports.test.ts +3 -2
  186. package/preview/PreviewView.ts +43 -6
  187. package/preview/previewView.test.ts +31 -0
  188. package/quality/dictionaryKeys.test.ts +356 -0
  189. package/quality/dictionaryKeys.ts +488 -0
  190. package/quality/maintainabilityContract.test.ts +4 -1
  191. package/quality/objectImportReport.test.ts +36 -0
  192. package/quality/objectImportReport.ts +105 -0
  193. package/quality/qualityScanner.ts +1 -1
  194. package/quality/routeRuntimeReport.test.ts +91 -0
  195. package/quality/routeRuntimeReport.ts +121 -0
  196. package/quality/runtimeConstantFacts.ts +71 -0
  197. package/quality/runtimeConstantGraph.ts +123 -0
  198. package/quality/runtimeConstantReads.ts +116 -0
  199. package/quality/runtimeImports.test.ts +190 -0
  200. package/quality/runtimeImports.ts +233 -0
  201. package/quality/runtimeKeyNames.ts +46 -0
  202. package/quality/runtimeLexicalScope.ts +132 -0
  203. package/quality/runtimeMarkerReach.test.ts +86 -0
  204. package/quality/runtimeMarkerReach.ts +255 -0
  205. package/quality/runtimeModuleFacts.ts +290 -0
  206. package/quality/runtimeNameTable.test.ts +172 -0
  207. package/quality/runtimeNameTable.ts +477 -0
  208. package/quality/runtimeScopeReport.test.ts +123 -0
  209. package/quality/runtimeScopeReport.ts +167 -0
  210. package/quality/runtimeSliceKey.ts +269 -0
  211. package/quality/runtimeSyntax.ts +133 -0
  212. package/quality/runtimeTable.fixture.ts +189 -0
  213. package/quality/runtimeUse.test.ts +737 -0
  214. package/quality/runtimeUse.ts +696 -0
  215. package/quality/runtimeUseReadable.test.ts +393 -0
  216. package/quality/ssrScanner.test.ts +13 -0
  217. package/quality/ssrScanner.ts +1 -1
  218. package/quality/translatorBindings.ts +187 -0
  219. package/test/fakeTerminal.ts +45 -0
  220. package/test/secretEnvFixture.ts +147 -0
  221. package/test/testHelpers.ts +11 -0
  222. package/transforms/barrelAnalyzer.ts +24 -2
  223. package/transforms/barrelImportsPlugin.ts +121 -32
  224. package/transforms/exportReach.test.ts +162 -0
  225. package/transforms/exportReach.ts +308 -0
  226. package/transforms/frameworkObjects.fixture.tsx +58 -0
  227. package/transforms/frameworkObjects.test.ts +57 -0
  228. package/transforms/modelReference.test.ts +197 -0
  229. package/transforms/modelReference.ts +39 -0
  230. package/transforms/moduleParts.test.ts +225 -0
  231. package/transforms/moduleParts.ts +418 -0
  232. package/transforms/objectImportEdits.ts +150 -0
  233. package/transforms/objectMemberImports.test.ts +631 -0
  234. package/transforms/objectMemberImports.ts +571 -0
  235. package/transforms/objectMemberLookup.ts +150 -0
  236. package/transforms/objectModule.test.ts +307 -0
  237. package/transforms/objectModule.ts +482 -0
  238. package/transforms/objectModuleAnalyzer.ts +104 -0
  239. package/transforms/partImports.test.ts +76 -0
  240. package/transforms/partImports.ts +110 -0
  241. package/transforms/partModules.test.ts +189 -0
  242. package/transforms/partModules.ts +90 -0
  243. package/transforms/partPurity.ts +124 -0
  244. package/transforms/reactIconImports.test.ts +231 -0
  245. package/transforms/reactIconImports.ts +325 -0
  246. package/transforms/routeConstants.ts +122 -0
  247. package/transforms/routeRuntime.test.ts +834 -0
  248. package/transforms/routeRuntime.ts +703 -0
  249. package/transforms/routeRuntimeEdits.ts +92 -0
  250. package/transforms/routeRuntimeGraph.ts +66 -0
  251. package/transforms/routeRuntimePlan.ts +244 -0
  252. package/transforms/secretEnvDeclaration.test.ts +211 -0
  253. package/transforms/secretEnvDeclaration.ts +219 -0
  254. package/transforms/secretEnvFile.test.ts +117 -0
  255. package/transforms/secretEnvFile.ts +132 -0
  256. package/transforms/secretEnvName.test.ts +54 -0
  257. package/transforms/secretEnvName.ts +29 -0
  258. package/transforms/secretEnvSource.test.ts +152 -0
  259. package/transforms/secretEnvSource.ts +197 -0
  260. package/transforms/serverEnvEvaluationError.ts +11 -0
  261. package/transforms/serverEnvPlugin.test.ts +157 -1
  262. package/transforms/serverEnvPlugin.ts +123 -19
  263. package/transforms/serverEnvProfile.test.ts +129 -2
  264. package/transforms/serverEnvProfile.ts +133 -43
  265. package/transforms/serverEnvSecrets.test.ts +268 -0
  266. package/transforms/signalDescriptors.test.ts +280 -0
  267. package/transforms/signalDescriptors.ts +230 -0
  268. package/transforms/thisFreeExports.ts +87 -0
  269. package/transforms/transforms.test.ts +184 -2
  270. package/transforms/tsconfigPackageResolver.test.ts +1 -0
  271. package/tunnel/createTunnel.ts +5 -1
  272. package/tunnel/ssh2Module.test.ts +37 -0
  273. package/tunnel/ssh2Module.ts +28 -0
  274. package/tunnel/sshTunnel.ts +4 -2
  275. package/typecheck/projectTypecheck.test.ts +32 -1
  276. package/typecheck/projectTypecheck.ts +3 -3
  277. package/typecheck/typeChecker.test.ts +50 -0
  278. package/typecheck/typeChecker.ts +14 -8
  279. package/typecheck/withheldDiagnostics.ts +44 -0
  280. package/util/devInstallCommand.ts +7 -0
  281. package/util/jsonFormatter.test.ts +13 -9
  282. package/workflow/executor.ts +6 -2
  283. package/workflow/index.ts +1 -0
  284. package/workflow/plan.ts +36 -7
  285. package/workflow/types.ts +1 -1
  286. package/workflow/uiTarget.ts +50 -0
  287. package/workspace/envSeed.test.ts +30 -1
  288. package/workspace/envSeed.ts +30 -1
  289. package/workspace/mainCheckout.test.ts +55 -0
  290. package/workspace/mainCheckout.ts +38 -0
  291. package/workspace/scanInfo.test.ts +39 -0
  292. package/workspace/scanInfo.ts +55 -6
  293. package/workspace/slicePlanner.ts +2 -1
  294. package/workspace/workspaceLayout.test.ts +22 -1
  295. package/workspace/workspaceLayout.ts +3 -3
  296. package/CHANGELOG.md +0 -2904
  297. package/codeAgent/agent/AkanCodeCompaction.ts +0 -49
  298. package/codeAgent/agent/AkanCodeServices.ts +0 -122
  299. package/codeAgent/agent/AkanContextFiles.ts +0 -94
  300. package/codeAgent/agent/CodeAgent.ts +0 -626
  301. package/codeAgent/agent/CodeAgentAllowed.ts +0 -35
  302. package/codeAgent/agent/CodeAgentAsks.ts +0 -66
  303. package/codeAgent/agent/CodeAgentCommandLine.ts +0 -372
  304. package/codeAgent/agent/CodeAgentEventMapper.ts +0 -225
  305. package/codeAgent/agent/CodeAgentGate.ts +0 -258
  306. package/codeAgent/agent/CodeAgentProxy.ts +0 -83
  307. package/codeAgent/agent/CodeAgentRpcHost.ts +0 -109
  308. package/codeAgent/agent/CodeAgentRpcListener.ts +0 -195
  309. package/codeAgent/agent/CodeAgentStreamPrinter.ts +0 -86
  310. package/codeAgent/agent/CodeAgentSuspended.ts +0 -85
  311. package/codeAgent/agent/CodeAgentUi.ts +0 -47
  312. package/codeAgent/agent/CodeMailbox.ts +0 -148
  313. package/codeAgent/agent/CodeSessionFork.ts +0 -56
  314. package/codeAgent/agent/CodeSessionIndex.ts +0 -78
  315. package/codeAgent/agent/SubagentPool.ts +0 -219
  316. package/codeAgent/agent/WorkspaceTrust.ts +0 -200
  317. package/codeAgent/agent/akanCodeCompaction.test.ts +0 -36
  318. package/codeAgent/agent/akanCodeModel.ts +0 -47
  319. package/codeAgent/agent/akanCodeServices.test.ts +0 -54
  320. package/codeAgent/agent/akanContextFiles.test.ts +0 -116
  321. package/codeAgent/agent/akanSystemPrompt.ts +0 -50
  322. package/codeAgent/agent/codeAgent.test.ts +0 -337
  323. package/codeAgent/agent/codeAgentCommandLine.test.ts +0 -212
  324. package/codeAgent/agent/codeAgentContract.test.ts +0 -755
  325. package/codeAgent/agent/codeAgentHosts.ts +0 -30
  326. package/codeAgent/agent/codeAgentProxy.test.ts +0 -126
  327. package/codeAgent/agent/codeAgentRpcListener.test.ts +0 -215
  328. package/codeAgent/agent/codeAgentSuspended.test.ts +0 -47
  329. package/codeAgent/agent/codeMailbox.test.ts +0 -76
  330. package/codeAgent/agent/codeSessionFork.test.ts +0 -58
  331. package/codeAgent/agent/codeSessionIndex.test.ts +0 -77
  332. package/codeAgent/agent/consoleToStderr.ts +0 -8
  333. package/codeAgent/agent/jsonLines.ts +0 -29
  334. package/codeAgent/agent/stringArg.ts +0 -5
  335. package/codeAgent/feedback/DevLogFeedback.ts +0 -82
  336. package/codeAgent/feedback/PreviewFeedback.ts +0 -46
  337. package/codeAgent/feedback/TurnFeedback.ts +0 -98
  338. package/codeAgent/feedback/VerifyFeedback.ts +0 -39
  339. package/codeAgent/tools/AkanCli.ts +0 -51
  340. package/codeAgent/tools/AkanCodePlugins.ts +0 -142
  341. package/codeAgent/tools/AkanEditScope.ts +0 -53
  342. package/codeAgent/tools/AkanEnvKeys.ts +0 -50
  343. package/codeAgent/tools/AkanToolPack.ts +0 -86
  344. package/codeAgent/tools/AkanVerifier.ts +0 -30
  345. package/codeAgent/tools/AskToolPack.ts +0 -99
  346. package/codeAgent/tools/DeepSeekWeb.ts +0 -127
  347. package/codeAgent/tools/MailToolPack.ts +0 -76
  348. package/codeAgent/tools/McpClient.ts +0 -209
  349. package/codeAgent/tools/McpOAuth.ts +0 -233
  350. package/codeAgent/tools/McpOAuthLoopback.ts +0 -64
  351. package/codeAgent/tools/McpServerConfig.ts +0 -131
  352. package/codeAgent/tools/McpSignIn.ts +0 -158
  353. package/codeAgent/tools/McpTokenStore.ts +0 -128
  354. package/codeAgent/tools/McpToolPack.ts +0 -206
  355. package/codeAgent/tools/SessionToolPack.ts +0 -91
  356. package/codeAgent/tools/WebToolPack.ts +0 -315
  357. package/codeAgent/tools/akanCodePlugins.test.ts +0 -954
  358. package/codeAgent/tools/askToolPack.test.ts +0 -116
  359. package/codeAgent/tools/deepSeekWeb.test.ts +0 -113
  360. package/codeAgent/tools/mcpOAuth.test.ts +0 -648
  361. package/codeAgent/tools/mcpServerConfig.test.ts +0 -341
  362. package/piDependencyPins.test.ts +0 -45
@@ -1,6 +1,8 @@
1
1
  import { existsSync, realpathSync } from "node:fs";
2
2
  import path from "node:path";
3
+ import { EnvProfile } from "akanjs/server/lifecycle/envProfile";
3
4
  import type { BunPlugin, OnLoadResult } from "bun";
5
+ import { SecretEnvDeclaration } from "./secretEnvDeclaration";
4
6
  import { ServerEnvProfile } from "./serverEnvProfile";
5
7
 
6
8
  export interface ServerEnvPluginOptions {
@@ -10,12 +12,44 @@ export interface ServerEnvPluginOptions {
10
12
  environments: Iterable<string>;
11
13
  /** Bundled in place of the environment's own file: `env.server.<environment>.<profile>.ts`, read from the same folder. */
12
14
  profile?: string;
15
+ /**
16
+ * Carried beside the environment's own file, or beside `profile` when one is bundled in its place, each as
17
+ * `env.server.<environment>.<profile>.ts`: the server runs the one `AKAN_ENV_PROFILE` names when it starts.
18
+ */
19
+ profiles?: readonly string[];
13
20
  /** Under a profile, once per lib env file: whether the lib gave one of the profile's, and what was left out if not. */
14
- onLibEnv?: (file: string, report: { profileFile: boolean; stripped: string[] }) => void;
21
+ onLibEnv?: (file: string, report: { profile: string; profileFile: boolean; stripped: string[] }) => void;
22
+ /**
23
+ * Without a profile: `read` bundles each env file, a lib's included, with its secret strings replaced by reads of the
24
+ * process env. Unset, the files are bundled as written.
25
+ */
26
+ secrets?: "read";
15
27
  }
16
28
 
17
29
  const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
18
30
 
31
+ const ORIGINAL_NAMESPACE = "akan-server-env";
32
+ const ORIGINAL_PREFIX = `${ORIGINAL_NAMESPACE}:`;
33
+ //? Bun keys a module by its path whatever its namespace, so the file as written needs a path of its own.
34
+ const ORIGINAL_SUFFIX = ".original";
35
+
36
+ //? Only the env the server starts on is evaluated: the environment's own file may not load without its variables.
37
+ const selectorOf = (file: string, exports: string[], carried: { [profile: string]: string }, base?: string) => {
38
+ const names = Object.keys(carried);
39
+ const all = [...(base ? [base] : []), ...names];
40
+ const refusal = ` names a server env profile this build does not carry (it carries ${all.join(", ")}).`;
41
+ const named = `process.env.${EnvProfile.key}`;
42
+ return [
43
+ `const profile = ${base ? `${named} === ${JSON.stringify(base)} ? undefined : ${named}` : named};`,
44
+ `const carried = { ${names.map((name) => `${JSON.stringify(name)}: () => ${carried[name]}`).join(", ")} };`,
45
+ `if (profile && !Object.hasOwn(carried, profile)) throw new Error("${EnvProfile.key}=" + profile + ${JSON.stringify(refusal)});`,
46
+ `const picked = profile ? carried[profile]() : require(${JSON.stringify(`${ORIGINAL_PREFIX}${file}`)});`,
47
+ ...exports.map((name) =>
48
+ name === "default" ? "export default picked.default;" : `export const ${name} = picked[${JSON.stringify(name)}];`,
49
+ ),
50
+ ].join("\n");
51
+ };
52
+
19
53
  //* `env.server.ts` imports every environment's file, so an image would hand out the secrets of each environment it
20
54
  //* never runs. Every file but the image's own is swapped for exports that refuse to be read.
21
55
  export const createServerEnvPlugin = ({
@@ -23,7 +57,9 @@ export const createServerEnvPlugin = ({
23
57
  environment,
24
58
  environments,
25
59
  profile,
60
+ profiles = [],
26
61
  onLibEnv,
62
+ secrets,
27
63
  }: ServerEnvPluginOptions): BunPlugin => {
28
64
  const others = [...new Set(environments)].filter((name) => name !== environment);
29
65
  //? Bun hands onLoad the real path, which differs from the given one under a symlink (macOS's /var -> /private/var).
@@ -31,25 +67,74 @@ export const createServerEnvPlugin = ({
31
67
  const folder = `^(?:${[...dirs].map(escapeRegExp).join("|")})[\\\\/]env\\.server\\.`;
32
68
  const filter = new RegExp(`${folder}(?:${others.map(escapeRegExp).join("|")})\\.ts$`);
33
69
  const own = new RegExp(`${folder}${escapeRegExp(environment)}\\.ts$`);
70
+ const carriedNames = profiles.filter((name) => name !== profile);
34
71
  const libEnvs = new Map<string, Promise<OnLoadResult>>();
72
+ const libSelectors = new Map<string, Promise<OnLoadResult>>();
73
+ const once = (
74
+ cache: Map<string, Promise<OnLoadResult>>,
75
+ file: string,
76
+ load: (file: string) => Promise<OnLoadResult>,
77
+ ) => {
78
+ if (!cache.has(file)) cache.set(file, load(file));
79
+ return cache.get(file) as Promise<OnLoadResult>;
80
+ };
35
81
  const libEnv = async (file: string): Promise<OnLoadResult> => {
36
82
  const { loader, contents, profileFile, stripped } = await ServerEnvProfile.libEnvSource(file, profile ?? "");
37
- onLibEnv?.(file, { profileFile, stripped });
83
+ onLibEnv?.(file, { profile: profile ?? "", profileFile, stripped });
38
84
  return { loader, contents };
39
85
  };
86
+ const inPlace = async (file: string, name: string): Promise<OnLoadResult> => ({
87
+ loader: "ts",
88
+ contents: await ServerEnvProfile.sourceInPlaceOf(
89
+ path.join(path.dirname(file), ServerEnvProfile.fileName(environment, name)),
90
+ file,
91
+ name,
92
+ ),
93
+ });
94
+ const exportsOf = async (file: string) =>
95
+ new Bun.Transpiler({ loader: "ts" }).scan(await Bun.file(file).text()).exports;
96
+ const original = async (file: string): Promise<OnLoadResult> =>
97
+ secrets && !profile
98
+ ? await SecretEnvDeclaration.source(file, secrets)
99
+ : { loader: "ts", contents: await Bun.file(file).text() };
100
+ const base = (file: string): Promise<OnLoadResult> => {
101
+ if (!profile) return original(file);
102
+ return own.test(file) ? inPlace(file, profile) : once(libEnvs, file, libEnv);
103
+ };
104
+ const isAppEnv = (file: string) => {
105
+ const name = path.basename(file, ".ts").slice("env.server.".length);
106
+ return dirs.has(path.dirname(file)) || name === "type" || name === "example";
107
+ };
108
+ const ownSelector = async (file: string): Promise<OnLoadResult> => ({
109
+ loader: "js",
110
+ contents: selectorOf(
111
+ file,
112
+ await exportsOf(file),
113
+ Object.fromEntries(
114
+ carriedNames.map((name) => [
115
+ name,
116
+ `require(${JSON.stringify(path.join(path.dirname(file), ServerEnvProfile.fileName(environment, name)))})`,
117
+ ]),
118
+ ),
119
+ profile,
120
+ ),
121
+ });
122
+ const libSelector = async (file: string): Promise<OnLoadResult> => {
123
+ const carried: { [name: string]: string } = {};
124
+ for (const name of carriedNames) {
125
+ const { profileFile, stripped, value } = await ServerEnvProfile.libEnvSource(file, name);
126
+ onLibEnv?.(file, { profile: name, profileFile, stripped });
127
+ carried[name] = profileFile
128
+ ? `require(${JSON.stringify(ServerEnvProfile.profileFileOf(file, name))})`
129
+ : `({ env: ${JSON.stringify(value)} })`;
130
+ }
131
+ return { loader: "js", contents: selectorOf(file, await exportsOf(file), carried, profile) };
132
+ };
40
133
  return {
41
134
  name: "akan-server-env",
42
135
  setup(build) {
43
136
  //* The environment's own file never enters a profile's bundle: its contents are the profile file's.
44
- if (profile)
45
- build.onLoad({ filter: own }, async (args) => ({
46
- loader: "ts",
47
- contents: await ServerEnvProfile.sourceInPlaceOf(
48
- path.join(path.dirname(args.path), ServerEnvProfile.fileName(environment, profile)),
49
- args.path,
50
- profile,
51
- ),
52
- }));
137
+ if (profile && !carriedNames.length) build.onLoad({ filter: own }, (args) => inPlace(args.path, profile));
53
138
  if (others.length)
54
139
  build.onLoad({ filter }, async (args) => {
55
140
  const name = path.basename(args.path, ".ts").slice("env.server.".length);
@@ -64,15 +149,34 @@ export const createServerEnvPlugin = ({
64
149
  ].join("\n"),
65
150
  };
66
151
  });
67
- //? Last: the app's own env files above are taken by the handlers before it, which match them first.
68
- if (profile)
69
- build.onLoad({ filter: ServerEnvProfile.envFilePattern }, async (args) => {
70
- const name = path.basename(args.path, ".ts").slice("env.server.".length);
71
- if (dirs.has(path.dirname(args.path)) || name === "type" || name === "example")
72
- return { loader: "ts", contents: await Bun.file(args.path).text() };
73
- if (!libEnvs.has(args.path)) libEnvs.set(args.path, libEnv(args.path));
74
- return (await libEnvs.get(args.path)) as OnLoadResult;
152
+ if (carriedNames.length) {
153
+ build.onResolve({ filter: new RegExp(`^${ORIGINAL_PREFIX}`) }, (args) => ({
154
+ path: `${args.path.slice(ORIGINAL_PREFIX.length)}${ORIGINAL_SUFFIX}`,
155
+ namespace: ORIGINAL_NAMESPACE,
156
+ }));
157
+ //? A module under a namespace has no folder of its own to resolve a relative import from.
158
+ build.onResolve({ filter: /^\.{1,2}[\\/]/, namespace: ORIGINAL_NAMESPACE }, (args) => ({
159
+ path: Bun.resolveSync(args.path, path.dirname(args.importer)),
160
+ }));
161
+ build.onLoad({ filter: /.*/, namespace: ORIGINAL_NAMESPACE }, (args) =>
162
+ base(args.path.slice(0, -ORIGINAL_SUFFIX.length)),
163
+ );
164
+ build.onLoad({ filter: own }, (args) => ownSelector(args.path));
165
+ build.onLoad({ filter: ServerEnvProfile.envFilePattern }, (args) => {
166
+ return isAppEnv(args.path) ? original(args.path) : once(libSelectors, args.path, libSelector);
75
167
  });
168
+ }
169
+ //? After the stubs, which take the other environments' files first; `env.server.ts` itself is the env file where
170
+ //? a pipeline copies one over the switch.
171
+ if (secrets && !profile)
172
+ build.onLoad({ filter: ServerEnvProfile.envModulePattern }, (args) =>
173
+ SecretEnvDeclaration.source(args.path, secrets),
174
+ );
175
+ //? Last: the app's own env files above are taken by the handlers before it, which match them first.
176
+ if (profile && !carriedNames.length)
177
+ build.onLoad({ filter: ServerEnvProfile.envFilePattern }, (args) =>
178
+ isAppEnv(args.path) ? original(args.path) : once(libEnvs, args.path, libEnv),
179
+ );
76
180
  },
77
181
  };
78
182
  };
@@ -1,7 +1,9 @@
1
1
  import { describe, expect, test } from "bun:test";
2
+ import { realpathSync } from "node:fs";
2
3
  import path from "node:path";
3
4
  import { Logger } from "akanjs/common";
4
5
  import { tempDirs, writeText as write } from "../test/testHelpers";
6
+ import { ServerEnvEvaluationError } from "./serverEnvEvaluationError";
5
7
  import { ServerEnvProfile } from "./serverEnvProfile";
6
8
 
7
9
  const makeTempRoot = tempDirs("akan-devkit-server-env-profile-");
@@ -129,6 +131,34 @@ describe("ServerEnvProfile.strip", () => {
129
131
  });
130
132
  });
131
133
 
134
+ const alive = (pid: number) => {
135
+ try {
136
+ process.kill(pid, 0);
137
+ return true;
138
+ } catch {
139
+ return false;
140
+ }
141
+ };
142
+
143
+ const goneWithin = async (pid: number, ms: number) => {
144
+ for (const started = Date.now(); Date.now() - started < ms; await Bun.sleep(50)) if (!alive(pid)) return true;
145
+ return !alive(pid);
146
+ };
147
+
148
+ describe("ServerEnvProfile.leftOutNotice", () => {
149
+ test("names every lib env file and what it lost in one line, and says nothing when none lost a value", () => {
150
+ const leftOut = new Map([
151
+ ["/repo/libs/util/env/env.server.testing.ts", ["mail.password", "sms.apiKey"]],
152
+ ["/repo/libs/shared/env/env.server.testing.ts", ["security.jwtSecret"]],
153
+ ]);
154
+
155
+ expect(ServerEnvProfile.leftOutNotice("edge", "/repo", leftOut)).toBe(
156
+ 'The "edge" build leaves out the secret-named defaults of 2 lib env files: libs/shared/env/env.server.testing.ts (security.jwtSecret), libs/util/env/env.server.testing.ts (mail.password, sms.apiKey). A lib\'s env.server.testing.edge.ts says what this profile runs with.',
157
+ );
158
+ expect(ServerEnvProfile.leftOutNotice("edge", "/repo", new Map())).toBeNull();
159
+ });
160
+ });
161
+
132
162
  describe("ServerEnvProfile.evaluate", () => {
133
163
  test("says why and where an env file could not be evaluated, and never a line or a value of it", async () => {
134
164
  const root = await makeTempRoot();
@@ -155,11 +185,108 @@ describe("ServerEnvProfile.evaluate", () => {
155
185
  expect(message).not.toContain(secret);
156
186
  }
157
187
  expect(messages.reference).toMatch(
158
- /^env\.server\.reference\.ts could not be evaluated to check it for secrets: ReferenceError: undefinedVar is not defined \(at .*env\.server\.reference\.ts:3:\d+\)$/,
188
+ /^env\.server\.reference\.ts could not be evaluated to check it for secrets: ReferenceError at .*env\.server\.reference\.ts:3$/,
159
189
  );
160
- expect(messages.syntax).toMatch(/env\.server\.syntax\.ts:2:\d+\)$/);
190
+ expect(messages.syntax).toMatch(/: [A-Za-z]+ at .*env\.server\.syntax\.ts:2$/);
191
+ expect(messages.thrown).toMatch(/: Error at .*env\.server\.thrown\.ts:2$/);
192
+ expect(messages.thrownString).toEndWith(": Error, which gave no location");
161
193
  });
162
194
 
195
+ test("names the class and the place of an error whose message quotes a value another file holds, and not the message", async () => {
196
+ const root = realpathSync(await makeTempRoot());
197
+ const secret = "sentinel-imported-0123456789";
198
+ await write(
199
+ path.join(root, "srvkit/keys.ts"),
200
+ `export const key = ${JSON.stringify(secret)};\nexport const word = "sentinelpassphrase";\n`,
201
+ );
202
+ const sources = {
203
+ thrown:
204
+ 'import { key } from "../srvkit/keys";\nif (key) throw new Error("expected a longer key, got " + key);\nexport const env = {};\n',
205
+ parsed: 'import { key } from "../srvkit/keys";\nexport const env = {\n settings: JSON.parse(key),\n};\n',
206
+ framed:
207
+ 'import { key } from "../srvkit/keys";\nthrow new Error("failed\\n at " + key + ":1:1");\nexport const env = {};\n',
208
+ named:
209
+ 'import { word } from "../srvkit/keys";\nconst error = new Error("failed");\nerror.name = word;\nthrow error;\nexport const env = {};\n',
210
+ };
211
+ const messages: Record<string, string> = {};
212
+ for (const [name, source] of Object.entries(sources)) {
213
+ const file = path.join(root, `env/env.server.${name}.ts`);
214
+ await write(file, source);
215
+ messages[name] = await ServerEnvProfile.evaluate(file, root).then(
216
+ () => "",
217
+ (error: Error) => error.message,
218
+ );
219
+ }
220
+ for (const message of Object.values(messages)) expect(message).not.toContain("sentinel");
221
+ expect(messages.thrown).toBe(
222
+ `env.server.thrown.ts could not be evaluated to check it for secrets: Error at ${path.join(root, "env/env.server.thrown.ts")}:2`,
223
+ );
224
+ expect(messages.parsed).toBe(
225
+ `env.server.parsed.ts could not be evaluated to check it for secrets: SyntaxError at ${path.join(root, "env/env.server.parsed.ts")}:3`,
226
+ );
227
+ expect(messages.framed).toEndWith(`: Error at ${path.join(root, "env/env.server.framed.ts")}:2`);
228
+ expect(messages.named).toEndWith(`: Error at ${path.join(root, "env/env.server.named.ts")}:2`);
229
+ });
230
+
231
+ test("answers for an env file whose import keeps a timer running, and leaves no process behind", async () => {
232
+ const root = await makeTempRoot();
233
+ const pidFile = path.join(root, "pid");
234
+ await write(
235
+ path.join(root, "lib/ticker.ts"),
236
+ `await Bun.write(${JSON.stringify(pidFile)}, String(process.pid));\nexport const ticker = setInterval(() => undefined, 1_000);\n`,
237
+ );
238
+ const file = path.join(root, "env/env.server.main.ts");
239
+ await write(file, 'import "../lib/ticker";\nexport const env = { hostname: "app.example.test" };\n');
240
+ const started = Date.now();
241
+ expect(await ServerEnvProfile.evaluate(file, root)).toEqual({ hostname: "app.example.test" });
242
+ expect(Date.now() - started).toBeLessThan(10_000);
243
+ expect(await goneWithin(Number(await Bun.file(pidFile).text()), 3_000)).toBe(true);
244
+ });
245
+
246
+ test("stops an env file that never finishes loading, names it, and leaves no process behind", async () => {
247
+ const root = await makeTempRoot();
248
+ const pidFile = path.join(root, "pid");
249
+ const file = path.join(root, "env/env.server.main.ts");
250
+ await write(
251
+ file,
252
+ `await Bun.write(${JSON.stringify(pidFile)}, String(process.pid));\nsetInterval(() => undefined, 1_000);\nawait new Promise(() => undefined);\nexport const env = {};\n`,
253
+ );
254
+ const failure = await ServerEnvProfile.evaluate(file, root, undefined, { timeoutMs: 1_500 }).then(
255
+ () => null,
256
+ (error: unknown) => error,
257
+ );
258
+ expect(failure).toBeInstanceOf(ServerEnvEvaluationError);
259
+ expect((failure as ServerEnvEvaluationError).reason).toBe("timedOut");
260
+ expect((failure as Error).message).toStartWith(`${file} was not evaluated within 1.5s, so its process was stopped`);
261
+ expect(await goneWithin(Number(await Bun.file(pidFile).text()), 3_000)).toBe(true);
262
+ });
263
+
264
+ test("its process ends with the process that asked, even one that was killed", async () => {
265
+ const root = await makeTempRoot();
266
+ const pidFile = path.join(root, "pid");
267
+ const file = path.join(root, "env/env.server.main.ts");
268
+ await write(
269
+ file,
270
+ `await Bun.write(${JSON.stringify(pidFile)}, String(process.pid));\nsetInterval(() => undefined, 1_000);\nawait new Promise(() => undefined);\nexport const env = {};\n`,
271
+ );
272
+ const asker = path.join(root, "asker.ts");
273
+ await write(
274
+ asker,
275
+ `import { ServerEnvProfile } from ${JSON.stringify(path.join(import.meta.dir, "serverEnvProfile.ts"))};\nawait ServerEnvProfile.evaluate(${JSON.stringify(file)}, ${JSON.stringify(root)});\n`,
276
+ );
277
+ const parent = Bun.spawn([process.execPath, asker], { cwd: import.meta.dir, stdout: "ignore", stderr: "ignore" });
278
+ try {
279
+ for (let tries = 0; tries < 200 && !(await Bun.file(pidFile).exists()); tries++) await Bun.sleep(50);
280
+ const child = Number(await Bun.file(pidFile).text());
281
+ expect(alive(child)).toBe(true);
282
+ parent.kill("SIGKILL");
283
+ await parent.exited;
284
+ expect(await goneWithin(child, 5_000)).toBe(true);
285
+ } finally {
286
+ parent.kill("SIGKILL");
287
+ }
288
+ }, 30_000);
289
+
163
290
  test("reads an env file that writes to stdout as it loads", async () => {
164
291
  const envDir = await writeProfile(
165
292
  'console.info("loading the edge env");\nprocess.stdout.write("{ not json");\nexport const env = { hostname: "edge" };\n',
@@ -1,6 +1,8 @@
1
1
  import { existsSync, realpathSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { Logger, toError } from "akanjs/common";
4
+ import { EnvProfile } from "akanjs/server/lifecycle/envProfile";
5
+ import { ServerEnvEvaluationError } from "./serverEnvEvaluationError";
4
6
 
5
7
  export interface ServerEnvProfileProps {
6
8
  envDir: string;
@@ -16,10 +18,27 @@ export interface ServerEnvSource {
16
18
  export interface LibEnvSource extends ServerEnvSource {
17
19
  profileFile: boolean;
18
20
  stripped: string[];
21
+ /** The defaults `contents` exports when the lib has no profile file: the lib's own with each secret left out. */
22
+ value?: unknown;
19
23
  }
20
24
 
21
25
  type EnvLoad = (envFile: string) => Promise<ServerEnvSource>;
22
26
 
27
+ export interface EnvEvaluation {
28
+ environment?: string;
29
+ loads?: RegExp;
30
+ timeoutMs?: number;
31
+ //* What the child's process env holds beside PATH, HOME and the environment's selector.
32
+ variables?: { readonly [name: string]: string };
33
+ }
34
+
35
+ export interface EnvEvaluated {
36
+ value: unknown;
37
+ lossy: string[];
38
+ //* The names the env file and its imports asked the process env for, set or not.
39
+ reads: string[];
40
+ }
41
+
23
42
  interface Stripped {
24
43
  value: unknown;
25
44
  stripped: string[];
@@ -31,13 +50,15 @@ interface EnvFold<T> {
31
50
  node(value: object, children: (readonly [string, T])[]): T;
32
51
  }
33
52
 
34
- type EvaluatedMessage = { load: string } | { env: string; lossy: string[] } | { failure: string };
53
+ type EvaluatedMessage = { load: string } | { env: string; lossy: string[]; reads: string[] } | { failure: string };
35
54
 
36
55
  //* A server env profile is bundled in place of the environment's own file, for a server that runs where its bundle
37
56
  //* can be read: the computers a desktop app is installed on. So it may hold no secret.
38
57
  export class ServerEnvProfile {
39
- static readonly namePattern = /^[a-z][a-zA-Z0-9-]*$/;
58
+ static readonly namePattern = EnvProfile.namePattern;
40
59
  static readonly envFilePattern = /[\\/]env[\\/]env\.server\.[A-Za-z0-9-]+\.ts$/;
60
+ static readonly envModulePattern = /[\\/]env[\\/]env\.server(?:\.[A-Za-z0-9-]+)?\.ts$/;
61
+ static readonly evaluationTimeoutMs = 60_000;
41
62
 
42
63
  static fileName(environment: string, profile: string) {
43
64
  return `env.server.${environment}.${profile}.ts`;
@@ -65,7 +86,7 @@ export class ServerEnvProfile {
65
86
  return !!url && ServerEnvProfile.#carriesCredential(url);
66
87
  }
67
88
 
68
- static #isSecret(value: string, underSecret: boolean) {
89
+ static isSecret(value: string, underSecret: boolean) {
69
90
  return (underSecret && !!value.trim()) || ServerEnvProfile.#isCredentialUrl(value);
70
91
  }
71
92
 
@@ -92,7 +113,7 @@ export class ServerEnvProfile {
92
113
  static strip(value: unknown): Stripped {
93
114
  return ServerEnvProfile.#fold<Stripped>(value, {
94
115
  text: (text, at, underSecret) =>
95
- ServerEnvProfile.#isSecret(text, underSecret)
116
+ ServerEnvProfile.isSecret(text, underSecret)
96
117
  ? { value: undefined, stripped: [at] }
97
118
  : { value: text, stripped: [] },
98
119
  other: (other) => ({ value: other, stripped: [] }),
@@ -152,26 +173,60 @@ export class ServerEnvProfile {
152
173
  return value.length >= 16 && !/^https?:\/\//.test(value) && !/^[a-z]+(?:[._-][a-z]+)*$/.test(value);
153
174
  }
154
175
 
155
- static secretPaths(value: unknown): string[] {
176
+ static secretPaths(value: unknown, underSecret = false): string[] {
156
177
  return ServerEnvProfile.#fold(
157
178
  value,
158
- ServerEnvProfile.#collect((text, at, underSecret) => (ServerEnvProfile.#isSecret(text, underSecret) ? [at] : [])),
179
+ ServerEnvProfile.#collect((text, at, held) => (ServerEnvProfile.isSecret(text, held) ? [at] : [])),
180
+ "",
181
+ underSecret,
159
182
  );
160
183
  }
161
184
 
185
+ //? A URL's password is looked for on its own too: code that holds it holds it without the URL around it.
186
+ static movedTexts(value: unknown, underSecret: boolean): string[] {
187
+ const texts = ServerEnvProfile.#fold(
188
+ value,
189
+ ServerEnvProfile.#collect((text, _at, held) =>
190
+ ServerEnvProfile.isSecret(text, held) ? [text, ServerEnvProfile.#url(text)?.password ?? ""] : [],
191
+ ),
192
+ "",
193
+ underSecret,
194
+ );
195
+ return [...new Set(texts)].filter((text) => text !== "");
196
+ }
197
+
162
198
  //* Evaluated in a child with no app env, so `process.env.X ?? "fallback"` reads as the fallback the bundle carries.
163
199
  //* The result comes back over IPC, as an import may write to stdout; `load` answers for each env file it reaches.
164
- static async evaluate(file: string, cwd: string, load?: EnvLoad): Promise<unknown> {
165
- return (await ServerEnvProfile.#evaluated(file, cwd, load)).value;
200
+ static async evaluate(file: string, cwd: string, load?: EnvLoad, evaluation?: EnvEvaluation): Promise<unknown> {
201
+ return (await ServerEnvProfile.#evaluated(file, cwd, load, evaluation)).value;
166
202
  }
167
203
 
168
- //? Bun prints a failing module's source line with its error, so stderr is never read: the child sends the error's
169
- //? name and place, and its message without JSC's `(evaluating '…')` or any string literal of the files at fault.
170
- static async #evaluated(file: string, cwd: string, load?: EnvLoad): Promise<{ value: unknown; lossy: string[] }> {
171
- const pattern = (regex: RegExp, flags = "") => `new RegExp(${JSON.stringify(regex.source)}, "${flags}")`;
172
- const literal = /(["'`])((?:\\[\s\S]|(?!\1)[^\\])*)\1/;
204
+ static async evaluateReads(file: string, cwd: string, load: EnvLoad, evaluation: EnvEvaluation) {
205
+ return await ServerEnvProfile.#evaluated(file, cwd, load, evaluation, true);
206
+ }
207
+
208
+ //? Bun prints a failing module's source line with its error, so stderr is never read. The child sends the error's
209
+ //? class and place and never its message, which can quote a value of any file the env file imports.
210
+ static async #evaluated(
211
+ file: string,
212
+ cwd: string,
213
+ load?: EnvLoad,
214
+ {
215
+ environment,
216
+ loads = ServerEnvProfile.envFilePattern,
217
+ timeoutMs = ServerEnvProfile.evaluationTimeoutMs,
218
+ variables,
219
+ }: EnvEvaluation = {},
220
+ notesReads = false,
221
+ ): Promise<EnvEvaluated> {
173
222
  const frame = /^\s*at (?:[^(]*\()?(.+):(\d+):(\d+)\)?\s*$/;
174
223
  const script = [
224
+ //? An import may leave a timer, a server or a socket open, which would keep this process alive past its answer
225
+ //? and past a parent that died: it exits when its answer is sent, when the parent's channel closes, and at a
226
+ //? deadline of its own.
227
+ 'process.on("disconnect", () => process.exit(1));',
228
+ "setTimeout(() => process.exit(1), Number(process.env.AKAN_PROFILE_ENV_DEADLINE)).unref();",
229
+ "const finish = (message, code) => process.send(message, undefined, undefined, () => process.exit(code));",
175
230
  "const waiting = new Map();",
176
231
  'process.on("message", ({ load, error, loader, contents }) => {',
177
232
  " const reply = waiting.get(load);",
@@ -190,23 +245,30 @@ export class ServerEnvProfile {
190
245
  " }));",
191
246
  " },",
192
247
  " });",
193
- `const literal = ${pattern(literal, "g")};`,
194
- `const interpolation = ${pattern(/\$\{[^}]*\}/)};`,
195
- `const frameOf = ${pattern(frame)};`,
196
- `const evaluating = ${pattern(/\s*\(evaluating '[\s\S]*'\)\s*$/)};`,
197
- "const literalsOf = async (file) =>",
198
- ' [...(await Bun.file(file).text().catch(() => "")).matchAll(literal)].flatMap((match) => match[2].split(interpolation));',
199
- "const describe = async (error) => {",
248
+ "const reads = new Set();",
249
+ 'const note = (key) => typeof key === "string" && reads.add(key);',
250
+ "const noting = { get: (target, key, receiver) => (note(key), Reflect.get(target, key, receiver)), has: (target, key) => (note(key), Reflect.has(target, key)) };",
251
+ //? `Bun.env` and `import.meta.env` stay the object `process.env` was, which a proxy put in its place does not
252
+ //? see: a name that object lacks is noted through its prototype, and a name it holds through the proxy alone.
253
+ "if (process.env.AKAN_PROFILE_ENV_READS) {",
254
+ " Object.setPrototypeOf(process.env, new Proxy(Object.prototype, noting));",
255
+ " process.env = new Proxy(process.env, noting);",
256
+ "}",
257
+ `const frameOf = new RegExp(${JSON.stringify(frame.source)});`,
258
+ 'const { existsSync } = require("node:fs");',
259
+ //? The stack opens with the message, whose own lines could read as a frame: only lines after it are looked at,
260
+ //? and only one that names a file on disk.
261
+ "const describe = (error) => {",
200
262
  " const first = Array.isArray(error?.errors) && error.errors.length ? error.errors[0] : error;",
201
- ' const frame = String(first?.stack ?? "").split("\\n").map((line) => frameOf.exec(line)).find(Boolean);',
202
- " const at = first?.position?.file ? [first.position.file, first.position.line, first.position.column] : frame ? frame.slice(1, 4) : [];",
203
- " const files = [process.env.AKAN_PROFILE_ENV_FILE, at[0]].filter(Boolean);",
204
- " const literals = (await Promise.all(files.map(literalsOf))).flat().filter((part) => part.length >= 4);",
205
- ' let message = String(first?.message ?? first).replace(evaluating, "");',
206
- " for (const part of literals.sort((a, b) => b.length - a.length))",
207
- ' message = message.split(part).join("[redacted]");',
208
- ' const name = typeof first?.name === "string" && /^[A-Za-z]+$/.test(first.name) ? first.name : "Error";',
209
- ' return name + ": " + message.slice(0, 200) + (at.length ? " (at " + at.join(":") + ")" : "");',
263
+ ' const stack = String(first?.stack ?? "");',
264
+ ' const message = String(first?.message ?? "");',
265
+ " const frames = message && stack.includes(message) ? stack.slice(stack.indexOf(message) + message.length) : stack;",
266
+ ' const frame = frames.split("\\n").map((line) => frameOf.exec(line)).find((found) => found && existsSync(found[1]));',
267
+ " const at = first?.position?.file ? [first.position.file, first.position.line] : frame ? frame.slice(1, 3) : [];",
268
+ //? `error.name` is a property any code can set to a value, so the class is read from the constructor.
269
+ ' const named = first === null || first === undefined ? "" : String(Object.getPrototypeOf(first)?.constructor?.name ?? "");',
270
+ ' const name = first instanceof Error && /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(named) ? named : "Error";',
271
+ ' return name + (at.length ? " at " + at.join(":") : ", which gave no location");',
210
272
  "};",
211
273
  "try {",
212
274
  " const { env } = await import(process.env.AKAN_PROFILE_ENV_FILE);",
@@ -220,13 +282,12 @@ export class ServerEnvProfile {
220
282
  " };",
221
283
  ' walk(env, "");',
222
284
  ' const plain = (_, value) => (typeof value === "function" || typeof value === "symbol" ? undefined : typeof value === "bigint" ? String(value) : value);',
223
- ' process.send({ env: JSON.stringify(env ?? null, plain) ?? "null", lossy }, undefined, undefined, () => process.disconnect());',
285
+ ' finish({ env: JSON.stringify(env ?? null, plain) ?? "null", lossy, reads: [...reads] }, 0);',
224
286
  "} catch (error) {",
225
- " process.exitCode = 1;",
226
- " process.send({ failure: await describe(error) }, undefined, undefined, () => process.disconnect());",
287
+ " finish({ failure: describe(error) }, 1);",
227
288
  "}",
228
289
  ].join("\n");
229
- let sent: { env: string; lossy: string[] } | undefined;
290
+ let sent: { env: string; lossy: string[]; reads: string[] } | undefined;
230
291
  let failure: string | undefined;
231
292
  let loadError: unknown;
232
293
  const child = Bun.spawn([process.execPath, "--eval", script], {
@@ -234,8 +295,12 @@ export class ServerEnvProfile {
234
295
  env: {
235
296
  PATH: process.env.PATH ?? "",
236
297
  HOME: process.env.HOME ?? "",
298
+ ...variables,
237
299
  AKAN_PROFILE_ENV_FILE: file,
238
- ...(load ? { AKAN_PROFILE_ENV_LOAD: ServerEnvProfile.envFilePattern.source } : {}),
300
+ AKAN_PROFILE_ENV_DEADLINE: String(timeoutMs + 5_000),
301
+ ...(load ? { AKAN_PROFILE_ENV_LOAD: loads.source } : {}),
302
+ ...(notesReads ? { AKAN_PROFILE_ENV_READS: "1" } : {}),
303
+ ...(environment ? { AKAN_PUBLIC_ENV: environment } : {}),
239
304
  },
240
305
  stdout: "ignore",
241
306
  stderr: "ignore",
@@ -264,14 +329,29 @@ export class ServerEnvProfile {
264
329
  .catch(() => undefined);
265
330
  },
266
331
  });
267
- const exitCode = await child.exited;
268
- if (exitCode !== 0 || !sent) {
269
- if (loadError) throw loadError;
270
- throw new Error(
271
- `${path.basename(file)} could not be evaluated to check it for secrets: ${failure ?? `its process exited with code ${exitCode} and sent nothing`}`,
332
+ let timedOut = false;
333
+ const kill = () => child.kill("SIGKILL");
334
+ const timer = setTimeout(() => {
335
+ timedOut = true;
336
+ kill();
337
+ }, timeoutMs);
338
+ process.on("exit", kill);
339
+ const exitCode = await child.exited.finally(() => {
340
+ clearTimeout(timer);
341
+ process.off("exit", kill);
342
+ });
343
+ if (sent && !timedOut && exitCode === 0)
344
+ return { value: JSON.parse(sent.env) as unknown, lossy: sent.lossy, reads: sent.reads };
345
+ if (loadError) throw loadError;
346
+ if (timedOut)
347
+ throw new ServerEnvEvaluationError(
348
+ "timedOut",
349
+ `${file} was not evaluated within ${timeoutMs / 1000}s, so its process was stopped: the file, or one it imports, waits on something as it loads that does not end (a server it starts, a connection it opens, a loop).`,
272
350
  );
273
- }
274
- return { value: JSON.parse(sent.env) as unknown, lossy: sent.lossy };
351
+ throw new ServerEnvEvaluationError(
352
+ failure ? "threw" : "exited",
353
+ `${path.basename(file)} could not be evaluated to check it for secrets: ${failure ?? `its process exited with code ${exitCode} and sent nothing`}`,
354
+ );
275
355
  }
276
356
 
277
357
  //? A profile is served under the path of the file it replaces, so its import of that file would import itself.
@@ -330,15 +410,25 @@ export class ServerEnvProfile {
330
410
  throw new Error(
331
411
  `${file} holds ${evaluated.lossy.join(", ")}, which a "${profile}" build cannot carry: it bundles a lib env's defaults as JSON, which keeps no function, Map, Set, Date or class instance. Give the lib ${path.basename(profileFile)}.`,
332
412
  );
333
- const { value, stripped } = ServerEnvProfile.strip(evaluated.value);
413
+ const { value = {}, stripped } = ServerEnvProfile.strip(evaluated.value);
334
414
  return {
335
415
  loader: "js",
336
- contents: `export const env = ${JSON.stringify(value ?? {})};\n`,
416
+ contents: `export const env = ${JSON.stringify(value)};\n`,
337
417
  profileFile: false,
338
418
  stripped,
419
+ value,
339
420
  };
340
421
  }
341
422
 
423
+ static leftOutNotice(profile: string, workspaceRoot: string, leftOut: ReadonlyMap<string, string[]>) {
424
+ const files = [...leftOut.keys()].sort();
425
+ if (!files.length) return null;
426
+ const named = files.map(
427
+ (file) => `${path.relative(workspaceRoot, file).replaceAll("\\", "/")} (${leftOut.get(file)?.join(", ")})`,
428
+ );
429
+ return `The "${profile}" build leaves out the secret-named defaults of ${files.length} lib env file${files.length === 1 ? "" : "s"}: ${named.join(", ")}. A lib's ${path.basename(ServerEnvProfile.profileFileOf(files[0], profile))} says what this profile runs with.`;
430
+ }
431
+
342
432
  static async #underProfile(
343
433
  envFile: string,
344
434
  profile: string,