@akanjs/devkit 3.3.0-rc.7 → 3.3.0-rc.71

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 (360) hide show
  1. package/DEV_RUNTIME_KNOBS.md +1 -1
  2. package/README.ko.md +10 -3
  3. package/README.md +10 -4
  4. package/akanApp/akanApp.host.test.ts +4 -2
  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 +358 -21
  13. package/akanConfig/akanConfig.ts +113 -272
  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 +250 -0
  20. package/akanConfig/index.ts +3 -0
  21. package/akanConfig/nativeFileSettings.ts +33 -0
  22. package/akanConfig/nativeKeys.ts +52 -0
  23. package/akanConfig/types.ts +4 -0
  24. package/app/appBin.test.ts +63 -0
  25. package/app/appBin.ts +50 -0
  26. package/app/applicationBuildReporter.test.ts +51 -1
  27. package/app/applicationBuildReporter.ts +6 -1
  28. package/app/applicationBuildRunner.test.ts +427 -5
  29. package/app/applicationBuildRunner.ts +232 -37
  30. package/app/clientServerBoundary.test.ts +115 -0
  31. package/app/clientServerBoundary.ts +89 -0
  32. package/app/dictionarySizes.test.ts +40 -0
  33. package/app/dictionarySizes.ts +95 -0
  34. package/app/routeFilesReport.test.ts +59 -0
  35. package/app/routeFilesReport.ts +46 -0
  36. package/app/routeJsBudget.ts +18 -4
  37. package/artifact/implicitRootLayout.test.ts +19 -0
  38. package/artifact/implicitRootLayout.ts +16 -2
  39. package/artifact/implicitRootLayoutRender.test.tsx +4 -1
  40. package/artifact/storeBootstrap.test.ts +28 -0
  41. package/artifact/storeBootstrap.ts +64 -8
  42. package/biome.base.json +7 -5
  43. package/codeAgent/index.ts +1 -34
  44. package/codeAgent/skills/akan-agent/SKILL.md +8 -1
  45. package/codeAgent/skills/akan-code/SKILL.md +38 -3
  46. package/codeAgent/skills/akan-debug/SKILL.md +8 -3
  47. package/codeAgent/skills/akan-deps/SKILL.md +10 -3
  48. package/codeAgent/skills/akan-err/SKILL.md +13 -8
  49. package/codeAgent/skills/akan-mcp/SKILL.md +1 -1
  50. package/codeAgent/skills/akan-module/SKILL.md +2 -2
  51. package/codeAgent/skills/akan-page/SKILL.md +65 -30
  52. package/codeAgent/skills/akan-query/SKILL.md +13 -20
  53. package/codeAgent/skills/akan-runtime/SKILL.md +21 -1
  54. package/codeAgent/skills/akan-service/SKILL.md +21 -20
  55. package/codeAgent/skills/akan-transport/SKILL.md +5 -14
  56. package/codeAgent/skills/akan-ui/SKILL.md +16 -21
  57. package/codeAgent/skills/akan-validate/SKILL.md +8 -2
  58. package/commandDecorators/command.ts +28 -12
  59. package/commandDecorators/commandBuilder.ts +8 -1
  60. package/commandDecorators/commandDecorators.test.ts +70 -3
  61. package/commandDecorators/helpFormatter.ts +14 -12
  62. package/context/akanContext.ts +2 -0
  63. package/csrE2e/devHmrLatency.e2e.test.ts +1 -1
  64. package/csrE2e/ssrRegistry.e2e.test.ts +108 -22
  65. package/docs/apiReference.test.ts +25 -0
  66. package/docs/apiReference.ts +38 -5
  67. package/docs/declarationReader.ts +30 -0
  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 +1690 -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 +686 -13
  80. package/frontendBuild/clientBuildTypes.ts +26 -0
  81. package/frontendBuild/clientEntriesBundler.ts +49 -1
  82. package/frontendBuild/clientEntryDiscovery.test.ts +308 -1
  83. package/frontendBuild/clientEntryDiscovery.ts +136 -14
  84. package/frontendBuild/clientEntryGroups.test.ts +77 -0
  85. package/frontendBuild/clientEntryGroups.ts +61 -0
  86. package/frontendBuild/csrDevArtifactWriter.ts +2 -2
  87. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  88. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  89. package/frontendBuild/csrDevPatcher.test.ts +4 -5
  90. package/frontendBuild/csrDevPatcher.ts +37 -11
  91. package/frontendBuild/csrDevTypes.ts +9 -0
  92. package/frontendBuild/devBarrelImports.test.ts +154 -0
  93. package/frontendBuild/devBarrelImports.ts +83 -23
  94. package/frontendBuild/devChangePlanner.ts +0 -1
  95. package/frontendBuild/devRegistryBundler.ts +4 -2
  96. package/frontendBuild/devRouteRuntime.test.ts +492 -0
  97. package/frontendBuild/devRouteRuntime.ts +167 -0
  98. package/frontendBuild/dictionaryAssetBuilder.test.ts +408 -0
  99. package/frontendBuild/dictionaryAssetBuilder.ts +185 -17
  100. package/frontendBuild/dictionaryConstants.ts +136 -0
  101. package/frontendBuild/dictionaryOwnParts.ts +88 -0
  102. package/frontendBuild/dictionaryPackState.ts +131 -0
  103. package/frontendBuild/dictionaryPacking.test.ts +207 -0
  104. package/frontendBuild/dictionaryPacking.ts +160 -0
  105. package/frontendBuild/dictionaryRoutes.test.ts +251 -0
  106. package/frontendBuild/dictionaryRoutes.ts +227 -0
  107. package/frontendBuild/frontendBuild.test.ts +5 -3
  108. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  109. package/frontendBuild/pagesBundleBuilder.ts +78 -2
  110. package/frontendBuild/precompressArtifacts.test.ts +22 -0
  111. package/frontendBuild/precompressArtifacts.ts +34 -8
  112. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  113. package/frontendBuild/renderedEntries.ts +144 -0
  114. package/frontendBuild/routeClientBuilder.ts +407 -43
  115. package/frontendBuild/routeHandoffs.test.ts +155 -0
  116. package/frontendBuild/routeHandoffs.ts +117 -0
  117. package/frontendBuild/routeModulePreloads.test.ts +32 -0
  118. package/frontendBuild/routeModulePreloads.ts +20 -11
  119. package/frontendBuild/routeRuntimeCheck.test.ts +280 -0
  120. package/frontendBuild/routeRuntimeCheck.ts +248 -0
  121. package/frontendBuild/routeRuntimePays.test.ts +143 -0
  122. package/frontendBuild/routeRuntimePays.ts +117 -0
  123. package/frontendBuild/ssrBaseArtifactBuilder.ts +30 -35
  124. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  125. package/frontendBuild/ssrDevBundler.ts +66 -11
  126. package/frontendBuild/vendorFileImports.test.ts +254 -0
  127. package/frontendBuild/vendorFileImports.ts +163 -0
  128. package/frontendBuild/vendorNarrowing.test.ts +47 -3
  129. package/frontendBuild/vendorNarrowing.ts +38 -2
  130. package/frontendBuild/vendorSpecifiers.ts +2 -0
  131. package/guideline/agentAssets.ts +1 -1
  132. package/incrementalBuilder/buildBatch.proc.ts +35 -9
  133. package/incrementalBuilder/buildBatchProtocol.ts +2 -1
  134. package/incrementalBuilder/builderBoot.ts +5 -5
  135. package/incrementalBuilder/builderGraphPayloads.ts +4 -4
  136. package/incrementalBuilder/builderLanes.ts +2 -2
  137. package/incrementalBuilder/builderWatch.ts +19 -9
  138. package/incrementalBuilder/csrRegistry.ts +4 -4
  139. package/incrementalBuilder/incrementalBuilder.proc.test.ts +159 -0
  140. package/incrementalBuilder/incrementalBuilder.proc.ts +38 -10
  141. package/incrementalBuilder/pendingMetadata.test.ts +27 -0
  142. package/incrementalBuilder/pendingMetadata.ts +19 -0
  143. package/incrementalBuilder/ssrRegistry.ts +6 -6
  144. package/index.ts +1 -1
  145. package/integration/devResourceProbe.ts +14 -0
  146. package/integration/devStability.integration.test.ts +46 -21
  147. package/integration/renderAdmissionSoak.test.ts +99 -0
  148. package/integration/renderAdmissionSoak.ts +615 -0
  149. package/integration/ssrMemoryProbe.ts +5 -0
  150. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  151. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  152. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  153. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  154. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  155. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  156. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  157. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  158. package/lint/biomeBase.test.ts +50 -3
  159. package/lint/biomeBase.ts +1 -1
  160. package/lint/biomeCheck.test.ts +162 -0
  161. package/lint/biomeCheck.ts +131 -0
  162. package/lint/linter.test.ts +16 -11
  163. package/lint/no-arbitrary-color.grit +5 -0
  164. package/lint/no-conditional-st-hook.grit +5 -1
  165. package/lint/no-daisyui-legacy-class.grit +8 -0
  166. package/lint/no-document-cookie.grit +3 -0
  167. package/lint/no-inline-color.grit +10 -2
  168. package/lint/no-oversized-list-limit.grit +2 -0
  169. package/lint/no-raw-palette-class.grit +7 -0
  170. package/lint/no-unpublished-form-setter.grit +2 -0
  171. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  172. package/lint/no-web-storage.grit +3 -0
  173. package/lint/withheldEnvFile.ts +17 -0
  174. package/mobile/desktopBin.ts +2 -2
  175. package/mobile/desktopServerStage.test.ts +18 -3
  176. package/mobile/desktopServerStage.ts +7 -2
  177. package/mobile/nativeApp.test.ts +13 -5
  178. package/mobile/nativeApp.ts +9 -4
  179. package/mobile/nativeConfig.test.ts +96 -1
  180. package/mobile/nativeConfig.ts +46 -12
  181. package/mobile/nativePublicEnv.ts +1 -1
  182. package/mobile/serverBundleSecrets.ts +43 -0
  183. package/package.json +22 -178
  184. package/packageExports.test.ts +39 -24
  185. package/preview/PreviewView.ts +25 -3
  186. package/quality/dictionaryKeys.test.ts +356 -0
  187. package/quality/dictionaryKeys.ts +488 -0
  188. package/quality/objectImportReport.test.ts +36 -0
  189. package/quality/objectImportReport.ts +105 -0
  190. package/quality/qualityScanner.ts +1 -1
  191. package/quality/routeRuntimeReport.test.ts +91 -0
  192. package/quality/routeRuntimeReport.ts +121 -0
  193. package/quality/runtimeConstantFacts.ts +71 -0
  194. package/quality/runtimeConstantGraph.ts +123 -0
  195. package/quality/runtimeConstantReads.ts +116 -0
  196. package/quality/runtimeImports.test.ts +190 -0
  197. package/quality/runtimeImports.ts +233 -0
  198. package/quality/runtimeKeyNames.ts +46 -0
  199. package/quality/runtimeLexicalScope.ts +132 -0
  200. package/quality/runtimeMarkerReach.test.ts +84 -0
  201. package/quality/runtimeMarkerReach.ts +255 -0
  202. package/quality/runtimeModuleFacts.ts +290 -0
  203. package/quality/runtimeNameTable.test.ts +172 -0
  204. package/quality/runtimeNameTable.ts +477 -0
  205. package/quality/runtimeScopeReport.test.ts +123 -0
  206. package/quality/runtimeScopeReport.ts +167 -0
  207. package/quality/runtimeSliceKey.ts +269 -0
  208. package/quality/runtimeSyntax.ts +133 -0
  209. package/quality/runtimeTable.fixture.ts +189 -0
  210. package/quality/runtimeUse.test.ts +737 -0
  211. package/quality/runtimeUse.ts +696 -0
  212. package/quality/runtimeUseReadable.test.ts +393 -0
  213. package/quality/ssrScanner.test.ts +13 -0
  214. package/quality/ssrScanner.ts +1 -1
  215. package/quality/translatorBindings.ts +187 -0
  216. package/test/fakeTerminal.ts +45 -0
  217. package/test/secretEnvFixture.ts +134 -0
  218. package/test/testHelpers.ts +11 -0
  219. package/transforms/barrelAnalyzer.ts +26 -4
  220. package/transforms/barrelImportsPlugin.ts +121 -32
  221. package/transforms/exportReach.test.ts +162 -0
  222. package/transforms/exportReach.ts +308 -0
  223. package/transforms/frameworkObjects.fixture.tsx +58 -0
  224. package/transforms/frameworkObjects.test.ts +54 -0
  225. package/transforms/modelReference.test.ts +196 -0
  226. package/transforms/modelReference.ts +39 -0
  227. package/transforms/moduleParts.test.ts +225 -0
  228. package/transforms/moduleParts.ts +418 -0
  229. package/transforms/objectImportEdits.ts +150 -0
  230. package/transforms/objectMemberImports.test.ts +633 -0
  231. package/transforms/objectMemberImports.ts +571 -0
  232. package/transforms/objectMemberLookup.ts +150 -0
  233. package/transforms/objectModule.test.ts +307 -0
  234. package/transforms/objectModule.ts +482 -0
  235. package/transforms/objectModuleAnalyzer.ts +104 -0
  236. package/transforms/partImports.test.ts +76 -0
  237. package/transforms/partImports.ts +110 -0
  238. package/transforms/partModules.test.ts +187 -0
  239. package/transforms/partModules.ts +90 -0
  240. package/transforms/partPurity.ts +124 -0
  241. package/transforms/reactIconImports.test.ts +231 -0
  242. package/transforms/reactIconImports.ts +325 -0
  243. package/transforms/routeConstants.ts +122 -0
  244. package/transforms/routeRuntime.test.ts +835 -0
  245. package/transforms/routeRuntime.ts +703 -0
  246. package/transforms/routeRuntimeEdits.ts +92 -0
  247. package/transforms/routeRuntimeGraph.ts +66 -0
  248. package/transforms/routeRuntimePlan.ts +244 -0
  249. package/transforms/secretEnvDeclaration.test.ts +211 -0
  250. package/transforms/secretEnvDeclaration.ts +219 -0
  251. package/transforms/secretEnvFile.test.ts +117 -0
  252. package/transforms/secretEnvFile.ts +113 -0
  253. package/transforms/secretEnvName.test.ts +54 -0
  254. package/transforms/secretEnvName.ts +29 -0
  255. package/transforms/secretEnvSource.test.ts +152 -0
  256. package/transforms/secretEnvSource.ts +197 -0
  257. package/transforms/serverEnvEvaluationError.ts +11 -0
  258. package/transforms/serverEnvPlugin.test.ts +118 -1
  259. package/transforms/serverEnvPlugin.ts +95 -2
  260. package/transforms/serverEnvProfile.test.ts +129 -2
  261. package/transforms/serverEnvProfile.ts +133 -43
  262. package/transforms/serverEnvSecrets.test.ts +268 -0
  263. package/transforms/signalDescriptors.test.ts +280 -0
  264. package/transforms/signalDescriptors.ts +227 -0
  265. package/transforms/thisFreeExports.ts +87 -0
  266. package/transforms/transforms.test.ts +180 -3
  267. package/transforms/tsconfigPackageResolver.test.ts +1 -0
  268. package/tunnel/createTunnel.test.ts +29 -8
  269. package/tunnel/createTunnel.ts +22 -11
  270. package/tunnel/ssh2Module.test.ts +37 -0
  271. package/tunnel/ssh2Module.ts +28 -0
  272. package/tunnel/sshTunnel.ts +4 -2
  273. package/typecheck/projectTypecheck.test.ts +32 -1
  274. package/typecheck/projectTypecheck.ts +3 -3
  275. package/typecheck/typeChecker.test.ts +49 -0
  276. package/typecheck/typeChecker.ts +9 -7
  277. package/typecheck/withheldDiagnostics.ts +41 -0
  278. package/util/devInstallCommand.ts +7 -0
  279. package/util/fileEditor.ts +1 -0
  280. package/util/jsonFormatter.test.ts +13 -9
  281. package/util/selectModel.ts +1 -0
  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/getRelatedCnsts.ts +7 -0
  290. package/workspace/mainCheckout.test.ts +55 -0
  291. package/workspace/mainCheckout.ts +38 -0
  292. package/workspace/scanInfo.test.ts +39 -0
  293. package/workspace/scanInfo.ts +55 -6
  294. package/workspace/slicePlanner.ts +2 -1
  295. package/workspace/workspaceLayout.test.ts +22 -1
  296. package/workspace/workspaceLayout.ts +3 -3
  297. package/CHANGELOG.md +0 -2718
  298. package/codeAgent/agent/AkanCodeCompaction.ts +0 -49
  299. package/codeAgent/agent/AkanCodeServices.ts +0 -122
  300. package/codeAgent/agent/AkanContextFiles.ts +0 -94
  301. package/codeAgent/agent/CodeAgent.ts +0 -606
  302. package/codeAgent/agent/CodeAgentAsks.ts +0 -66
  303. package/codeAgent/agent/CodeAgentEventMapper.ts +0 -225
  304. package/codeAgent/agent/CodeAgentGate.ts +0 -239
  305. package/codeAgent/agent/CodeAgentProxy.ts +0 -83
  306. package/codeAgent/agent/CodeAgentRpcHost.ts +0 -109
  307. package/codeAgent/agent/CodeAgentRpcListener.ts +0 -195
  308. package/codeAgent/agent/CodeAgentStreamPrinter.ts +0 -86
  309. package/codeAgent/agent/CodeAgentSuspended.ts +0 -85
  310. package/codeAgent/agent/CodeAgentUi.ts +0 -47
  311. package/codeAgent/agent/CodeMailbox.ts +0 -148
  312. package/codeAgent/agent/CodeSessionFork.ts +0 -56
  313. package/codeAgent/agent/CodeSessionIndex.ts +0 -78
  314. package/codeAgent/agent/SubagentPool.ts +0 -219
  315. package/codeAgent/agent/WorkspaceTrust.ts +0 -200
  316. package/codeAgent/agent/akanCodeCompaction.test.ts +0 -36
  317. package/codeAgent/agent/akanCodeModel.ts +0 -47
  318. package/codeAgent/agent/akanCodeServices.test.ts +0 -54
  319. package/codeAgent/agent/akanContextFiles.test.ts +0 -116
  320. package/codeAgent/agent/akanSystemPrompt.ts +0 -50
  321. package/codeAgent/agent/codeAgent.test.ts +0 -275
  322. package/codeAgent/agent/codeAgentContract.test.ts +0 -643
  323. package/codeAgent/agent/codeAgentHosts.ts +0 -30
  324. package/codeAgent/agent/codeAgentProxy.test.ts +0 -126
  325. package/codeAgent/agent/codeAgentRpcListener.test.ts +0 -215
  326. package/codeAgent/agent/codeAgentSuspended.test.ts +0 -47
  327. package/codeAgent/agent/codeMailbox.test.ts +0 -76
  328. package/codeAgent/agent/codeSessionFork.test.ts +0 -58
  329. package/codeAgent/agent/codeSessionIndex.test.ts +0 -77
  330. package/codeAgent/agent/consoleToStderr.ts +0 -8
  331. package/codeAgent/agent/jsonLines.ts +0 -29
  332. package/codeAgent/agent/stringArg.ts +0 -5
  333. package/codeAgent/feedback/DevLogFeedback.ts +0 -82
  334. package/codeAgent/feedback/PreviewFeedback.ts +0 -46
  335. package/codeAgent/feedback/TurnFeedback.ts +0 -98
  336. package/codeAgent/feedback/VerifyFeedback.ts +0 -39
  337. package/codeAgent/tools/AkanCli.ts +0 -51
  338. package/codeAgent/tools/AkanCodePlugins.ts +0 -142
  339. package/codeAgent/tools/AkanEditScope.ts +0 -53
  340. package/codeAgent/tools/AkanEnvKeys.ts +0 -50
  341. package/codeAgent/tools/AkanToolPack.ts +0 -86
  342. package/codeAgent/tools/AkanVerifier.ts +0 -30
  343. package/codeAgent/tools/AskToolPack.ts +0 -99
  344. package/codeAgent/tools/DeepSeekWeb.ts +0 -127
  345. package/codeAgent/tools/MailToolPack.ts +0 -76
  346. package/codeAgent/tools/McpClient.ts +0 -209
  347. package/codeAgent/tools/McpOAuth.ts +0 -233
  348. package/codeAgent/tools/McpOAuthLoopback.ts +0 -64
  349. package/codeAgent/tools/McpServerConfig.ts +0 -131
  350. package/codeAgent/tools/McpSignIn.ts +0 -158
  351. package/codeAgent/tools/McpTokenStore.ts +0 -128
  352. package/codeAgent/tools/McpToolPack.ts +0 -206
  353. package/codeAgent/tools/SessionToolPack.ts +0 -91
  354. package/codeAgent/tools/WebToolPack.ts +0 -315
  355. package/codeAgent/tools/akanCodePlugins.test.ts +0 -954
  356. package/codeAgent/tools/askToolPack.test.ts +0 -116
  357. package/codeAgent/tools/deepSeekWeb.test.ts +0 -113
  358. package/codeAgent/tools/mcpOAuth.test.ts +0 -648
  359. package/codeAgent/tools/mcpServerConfig.test.ts +0 -341
  360. package/piDependencyPins.test.ts +0 -45
@@ -0,0 +1,268 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import path from "node:path";
3
+ import { SecretEnv } from "akanjs/server/lifecycle/secretEnv";
4
+ import { ServerBundleSecrets } from "../mobile/serverBundleSecrets";
5
+ import {
6
+ computedSecretKeys,
7
+ computedSecrets,
8
+ holdsSentinel,
9
+ secretEnvFixtureNames,
10
+ secretEnvPlain,
11
+ secretEnvSentinels,
12
+ twinSecretEnv,
13
+ twinSecrets,
14
+ writeComputedSecretFixture,
15
+ writeSecretEnvFixture,
16
+ } from "../test/secretEnvFixture";
17
+ import { tempDirs, writeText } from "../test/testHelpers";
18
+ import { SecretEnvDeclaration } from "./secretEnvDeclaration";
19
+ import { createServerEnvPlugin } from "./serverEnvPlugin";
20
+ import { ServerEnvProfile } from "./serverEnvProfile";
21
+
22
+ const makeTempRoot = tempDirs("akan-devkit-server-env-secrets-");
23
+ const environments = ["local", "main"];
24
+ const secretEnvModule = Bun.resolveSync("akanjs/server/lifecycle/secretEnv", import.meta.dir);
25
+
26
+ interface Built {
27
+ root: string;
28
+ appDir: string;
29
+ envDir: string;
30
+ outDir: string;
31
+ file: string;
32
+ text: string;
33
+ }
34
+
35
+ const build = async (root: string, secrets?: "read", { mainExtra = "", overSwitch = false } = {}): Promise<Built> => {
36
+ const { appDir, envDir } = await writeSecretEnvFixture(root, { mainExtra });
37
+ if (overSwitch)
38
+ await writeText(path.join(envDir, "env.server.ts"), await Bun.file(path.join(envDir, "env.server.main.ts")).text());
39
+ const entry = path.join(appDir, "server.ts");
40
+ await writeText(
41
+ entry,
42
+ [
43
+ `import { SecretEnv } from ${JSON.stringify(secretEnvModule)};`,
44
+ 'import { env } from "./env/env.server";',
45
+ "SecretEnv.check({ warn: (message) => console.error(message) });",
46
+ "console.info(JSON.stringify(env));",
47
+ "",
48
+ ].join("\n"),
49
+ );
50
+ const outDir = path.join(root, "dist/apps/demo");
51
+ const result = await Bun.build({
52
+ entrypoints: [entry],
53
+ outdir: outDir,
54
+ target: "bun",
55
+ plugins: [createServerEnvPlugin({ envDir, environment: "main", environments, secrets })],
56
+ });
57
+ const output = result.outputs.find((artifact) => artifact.kind === "entry-point");
58
+ if (!output) throw new Error("no entry output");
59
+ return { root, appDir, envDir, outDir, file: output.path, text: await output.text() };
60
+ };
61
+
62
+ const declare = async ({ envDir }: Built) => {
63
+ const { variables } = await SecretEnvDeclaration.of(envDir, "main");
64
+ return {
65
+ list: SecretEnv.format(variables),
66
+ values: Object.fromEntries(variables.map((each) => [each.name, each.value])),
67
+ };
68
+ };
69
+
70
+ const boot = (file: string, env: { [name: string]: string }) => {
71
+ const proc = Bun.spawnSync([process.execPath, file], {
72
+ env: { PATH: process.env.PATH ?? "", AKAN_PUBLIC_ENV: "main", ...env },
73
+ });
74
+ const stdout = proc.stdout.toString();
75
+ return {
76
+ exitCode: proc.exitCode,
77
+ env: stdout ? (JSON.parse(stdout) as { [key: string]: unknown }) : null,
78
+ warnings: proc.stderr.toString().split("\n").filter(Boolean),
79
+ };
80
+ };
81
+
82
+ const evaluated = ({ envDir, appDir }: Built) =>
83
+ ServerEnvProfile.evaluate(path.join(envDir, "env.server.ts"), appDir, undefined, { environment: "main" });
84
+
85
+ describe("createServerEnvPlugin for an image", () => {
86
+ test("the built server holds no secret of the workspace's env files, a lib's defaults included, and every plain value", async () => {
87
+ const built = await build(await makeTempRoot(), "read");
88
+ expect(holdsSentinel(built.text)).toBe(false);
89
+ for (const plain of Object.values(secretEnvPlain)) expect(built.text).toContain(plain);
90
+ expect(built.text).toContain("noreply@example.test");
91
+ expect(await new ServerBundleSecrets(built.root, built.appDir).assertClean(built.outDir)).toEqual([]);
92
+ });
93
+
94
+ test("started with the variables its env file maps to, it runs on the env that file evaluates to, and warns of nothing", async () => {
95
+ const built = await build(await makeTempRoot(), "read");
96
+ const { list, values } = await declare(built);
97
+ const booted = boot(built.file, { AKAN_ENV_NAMES: list, ...values });
98
+ expect(booted.exitCode).toBe(0);
99
+ expect(booted.warnings).toEqual([]);
100
+ expect(booted.env).toEqual((await evaluated(built)) as { [key: string]: unknown });
101
+ expect(booted.env).toMatchObject({
102
+ security: { jwtSecret: secretEnvSentinels.jwt },
103
+ mailer: { auth: { pass: secretEnvSentinels.libPass } },
104
+ discord: { tokens: secretEnvSentinels.bots },
105
+ pushNoti: { firebase: { private_key: secretEnvSentinels.pem } },
106
+ });
107
+ });
108
+
109
+ test("the developer's own variable still outranks the one the build reads, and stands in for it at boot", async () => {
110
+ const built = await build(await makeTempRoot(), "read");
111
+ const { list, values } = await declare(built);
112
+ expect(list).toContain(",POSTGRES_URL|DATABASE_URL");
113
+ const own = { DATABASE_URL: "postgres://own.example.test/app" };
114
+ const booted = boot(built.file, { AKAN_ENV_NAMES: list, ...values, ...own });
115
+ expect(booted.env).toMatchObject({ database: { postgres: { url: "postgres://own.example.test/app" } } });
116
+ const { POSTGRES_URL: _url, ...set } = values;
117
+ const instead = boot(built.file, { AKAN_ENV_NAMES: list, ...set, ...own });
118
+ expect({ exitCode: instead.exitCode, warnings: instead.warnings }).toEqual({ exitCode: 0, warnings: [] });
119
+ expect(instead.env).toMatchObject({ database: { postgres: { url: "postgres://own.example.test/app" } } });
120
+ });
121
+
122
+ test("started without its variables, it exits non-zero, naming each one and no value", async () => {
123
+ const built = await build(await makeTempRoot(), "read");
124
+ const { list, values } = await declare(built);
125
+ const { MAILER__AUTH__PASS: _pass, DISCORD__TOKENS: _tokens, ...set } = values;
126
+ const booted = boot(built.file, { AKAN_ENV_NAMES: list, ...set });
127
+ expect(booted.exitCode).not.toBe(0);
128
+ expect(booted.env).toBeNull();
129
+ expect(booted.warnings.join("\n")).toContain(
130
+ "2 secret env values this server reads from its process env are not set, so it does not start: MAILER__AUTH__PASS, DISCORD__TOKENS. Its build left the values out of the image. Set them in the deployment's environment; `akan secret-env <app> --env main` lists every name and writes the values from the env file.",
131
+ );
132
+ expect(holdsSentinel(booted.warnings.join("\n"))).toBe(false);
133
+ });
134
+
135
+ test("after a key is renamed in the env file, a deployment still setting the old variable is told the new name", async () => {
136
+ const before = await build(await makeTempRoot(), "read", {
137
+ mainExtra: '\n llm: { apiKey: "sentinel-llm-1c95" },',
138
+ });
139
+ const old = await declare(before);
140
+ expect(old.values.LLM__API_KEY).toBe("sentinel-llm-1c95");
141
+ const renamed = await build(await makeTempRoot(), "read", {
142
+ mainExtra: '\n llm: { accessKey: "sentinel-llm-1c95" },',
143
+ });
144
+ const { list } = await declare(renamed);
145
+ const booted = boot(renamed.file, { AKAN_ENV_NAMES: list, ...old.values });
146
+ expect(booted.exitCode).not.toBe(0);
147
+ expect(booted.warnings.join("\n")).toContain(
148
+ "1 secret env value this server reads from its process env is not set, so it does not start: LLM__ACCESS_KEY.",
149
+ );
150
+ expect(holdsSentinel(booted.warnings.join("\n"))).toBe(false);
151
+ });
152
+
153
+ test("the env file a pipeline copies over the switch is read the same way", async () => {
154
+ const built = await build(await makeTempRoot(), "read", { overSwitch: true });
155
+ expect(holdsSentinel(built.text)).toBe(false);
156
+ const { list, values } = await declare(built);
157
+ expect(Object.keys(values)).toEqual(secretEnvFixtureNames);
158
+ const booted = boot(built.file, { AKAN_ENV_NAMES: list, ...values });
159
+ expect(booted.warnings).toEqual([]);
160
+ expect(booted.env).toEqual((await evaluated(built)) as { [key: string]: unknown });
161
+ });
162
+
163
+ test("a secret the env file imports or computes stays in the built server, and the declaration names its key whatever the value's length", async () => {
164
+ const root = await makeTempRoot();
165
+ const { appDir, envDir } = await writeComputedSecretFixture(root);
166
+ const entry = path.join(appDir, "server.ts");
167
+ await writeText(entry, 'import { env } from "./env/env.server";\nconsole.info(JSON.stringify(env));\n');
168
+ const result = await Bun.build({
169
+ entrypoints: [entry],
170
+ outdir: path.join(root, "dist/apps/demo"),
171
+ target: "bun",
172
+ plugins: [createServerEnvPlugin({ envDir, environment: "main", environments, secrets: "read" })],
173
+ });
174
+ const text = (await result.outputs.find((artifact) => artifact.kind === "entry-point")?.text()) ?? "";
175
+ expect(text).toContain(computedSecrets.password);
176
+ expect(text).toContain(computedSecrets.passphrase);
177
+ expect(text).toContain(computedSecrets.user);
178
+ expect(text).not.toContain(secretEnvSentinels.jwt);
179
+ const declared = await SecretEnvDeclaration.of(envDir, "main");
180
+ expect(declared.unmoved).toEqual(computedSecretKeys);
181
+ expect(declared.variables.map(({ name }) => name)).toEqual(secretEnvFixtureNames);
182
+ });
183
+
184
+ test("a secret string a plain key holds as well stays in the built server: a long mixed one stops the image check by both keys, a short one is a warning, and neither names the value", async () => {
185
+ const built = await build(await makeTempRoot(), "read", { mainExtra: twinSecretEnv });
186
+ for (const value of Object.values(twinSecrets)) expect(built.text).toContain(value);
187
+ const { moved } = await SecretEnvDeclaration.of(built.envDir, "main");
188
+ expect(moved.filter(({ twins }) => twins.length).map(({ path: at, name, twins }) => ({ at, name, twins }))).toEqual(
189
+ [
190
+ { at: "audit.password", name: "AUDIT__PASSWORD", twins: ["audit.label"] },
191
+ { at: "cache.password", name: "CACHE__PASSWORD", twins: ["cache.name"] },
192
+ { at: "door.secret", name: "DOOR__SECRET", twins: ["door.hint"] },
193
+ ],
194
+ );
195
+ const secrets = new ServerBundleSecrets(built.root, built.appDir);
196
+ const failure = await secrets.assertImageClean(built.outDir, moved).then(
197
+ () => "",
198
+ (error: Error) => error.message,
199
+ );
200
+ expect(failure).toStartWith(
201
+ "The build holds secret values the server reads from its process env, so it stops here:\n server.js holds the value of audit.password (AUDIT__PASSWORD), which the env's audit.label holds as well\nThe build left each out",
202
+ );
203
+ expect(holdsSentinel(failure)).toBe(false);
204
+ const note = await secrets.assertImageClean(
205
+ built.outDir,
206
+ moved.filter(({ path: at }) => at !== "audit.password"),
207
+ );
208
+ expect(note).toBe(
209
+ [
210
+ "2 secret values the server reads from its process env are also in what this build wrote, short or plain enough to be there for another reason, so the build goes on:",
211
+ " cache.password (CACHE__PASSWORD): server.js; the env's cache.name holds the same string",
212
+ " door.secret (DOOR__SECRET): the env's door.hint holds the same string",
213
+ "Where another key of the env or the app's code holds a secret's own string, the image holds it too: change one of the two.",
214
+ ].join("\n"),
215
+ );
216
+
217
+ const clean = await build(await makeTempRoot(), "read");
218
+ const declared = await SecretEnvDeclaration.of(clean.envDir, "main");
219
+ expect(declared.moved.map(({ name }) => name)).toEqual([
220
+ "JWT_SECRET",
221
+ "SECURITY__SSO__GOOGLE__CLIENT_SECRET",
222
+ "MAILER__AUTH__PASS",
223
+ "OBJECT_STORAGE__ENDPOINT",
224
+ "OBJECT_STORAGE__ENDPOINT",
225
+ "DISCORD__TOKENS",
226
+ "DISCORD__TOKENS",
227
+ "DISCORD__WEBHOOK",
228
+ "PUSH_NOTI__FIREBASE__PRIVATE_KEY",
229
+ "MESSAGE__API_SECRET",
230
+ "MESSAGE__SENDER_PASSWORD",
231
+ "POSTGRES_URL",
232
+ "POSTGRES_URL",
233
+ ]);
234
+ expect(await new ServerBundleSecrets(clean.root, clean.appDir).assertImageClean(clean.outDir, declared.moved)).toBe(
235
+ null,
236
+ );
237
+ });
238
+
239
+ test("a secret the env file reads from the process env itself stays that read in the built server, which holds no value the build's shell gave it", async () => {
240
+ const shell = process.env.ZQ_API_KEY;
241
+ process.env.ZQ_API_KEY = "shell-api-key-1d20";
242
+ try {
243
+ const built = await build(await makeTempRoot(), "read", {
244
+ mainExtra: '\n own: { apiKey: process.env.ZQ_API_KEY, hosts: process.env.ZQ_API_KEY!.split("-") },',
245
+ });
246
+ expect(built.text).toContain("apiKey: process.env.ZQ_API_KEY");
247
+ expect(built.text).not.toContain("shell-api-key-1d20");
248
+ const { list, values } = await declare(built);
249
+ expect(list).not.toContain("OWN__");
250
+ const booted = boot(built.file, { AKAN_ENV_NAMES: list, ...values, ZQ_API_KEY: "deployed-api-key" });
251
+ expect(booted.warnings).toEqual([]);
252
+ expect(booted.env?.own).toEqual({ apiKey: "deployed-api-key", hosts: ["deployed", "api", "key"] });
253
+ } finally {
254
+ if (shell === undefined) delete process.env.ZQ_API_KEY;
255
+ else process.env.ZQ_API_KEY = shell;
256
+ }
257
+ });
258
+
259
+ test("without the setting, as for the server a desktop app carries, the env files are bundled as written", async () => {
260
+ const built = await build(await makeTempRoot());
261
+ expect(built.text).toContain(secretEnvSentinels.jwt);
262
+ expect(built.text).toContain(secretEnvSentinels.libPass);
263
+ expect(built.text).not.toContain("SecretEnv.read(");
264
+ const booted = boot(built.file, {});
265
+ expect(booted.warnings).toEqual([]);
266
+ expect(booted.env).toEqual((await evaluated(built)) as { [key: string]: unknown });
267
+ });
268
+ });
@@ -0,0 +1,280 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { realpath } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { tempDirs, writeText } from "../test/testHelpers";
5
+ import { SignalDescriptors } from "./signalDescriptors";
6
+
7
+ const makeTempRoot = tempDirs("akan-devkit-signal-descriptors-");
8
+
9
+ const sigSource = `import { appendFileSync } from "node:fs";
10
+ import path from "node:path";
11
+
12
+ appendFileSync(path.join(import.meta.dir, "reads.txt"), "read\\n");
13
+ const serialized = {
14
+ trolley: { endpoint: { pingAt: { type: "query", args: [], returns: { refName: "String" } } } },
15
+ crate: { endpoint: { countOf: { type: "query", args: [], returns: { refName: "Int", nullable: true } } } },
16
+ odd: { endpoint: { at: { type: "query", args: [], returns: { refName: "String", nullable: undefined } } } },
17
+ };
18
+ export const fetch = { ownSerializedSignal: serialized };
19
+ export const getSerializedSignalOf = (name) => (name === "base" ? {} : { [name]: serialized[name] });
20
+ `;
21
+
22
+ const pieceOf = (name: string) => `import { FetchClient } from "akanjs/fetch";
23
+ import * as cnst from "../cnst";
24
+ import { fetch, sig } from "../usePage";
25
+ import { getSerializedSignalOf } from "../sig" with { type: "macro" };
26
+ import type * as signal from "../sig";
27
+ Object.assign(sig, FetchClient.build<typeof signal>(cnst, getSerializedSignalOf("${name}"), { base: fetch }).sig);
28
+ `;
29
+
30
+ const writeScope = async (sig = sigSource) => {
31
+ const root = await realpath(await makeTempRoot());
32
+ await writeText(path.join(root, "apps/shop/lib/sig.ts"), sig);
33
+ const pieceDir = path.join(root, "apps/shop/lib/__client");
34
+ return {
35
+ root,
36
+ pieceDir,
37
+ readsOf: () =>
38
+ Bun.file(path.join(root, "apps/shop/lib/reads.txt"))
39
+ .text()
40
+ .catch(() => ""),
41
+ };
42
+ };
43
+
44
+ const writeHangingScope = async () => {
45
+ const scope = await writeScope();
46
+ const pidFile = path.join(scope.root, "reader.pid");
47
+ await writeText(
48
+ path.join(scope.root, "apps/shop/lib/sig.ts"),
49
+ `await Bun.write(${JSON.stringify(pidFile)}, String(process.pid));\nsetInterval(() => undefined, 1_000);\nawait new Promise(() => undefined);\n${sigSource}`,
50
+ );
51
+ return { ...scope, pidFile };
52
+ };
53
+
54
+ const alive = (pid: number) => {
55
+ try {
56
+ process.kill(pid, 0);
57
+ return true;
58
+ } catch {
59
+ return false;
60
+ }
61
+ };
62
+
63
+ const goneWithin = async (pid: number, ms: number) => {
64
+ for (const started = Date.now(); Date.now() - started < ms; await Bun.sleep(50)) if (!alive(pid)) return true;
65
+ return !alive(pid);
66
+ };
67
+
68
+ describe("SignalDescriptors", () => {
69
+ test("answers each piece with its own descriptors as a literal in place of the macro, reading the signal once", async () => {
70
+ const { root, pieceDir, readsOf } = await writeScope();
71
+ const descriptors = new SignalDescriptors(root, ["apps/shop"]);
72
+ const [trolley, crate, base] = await Promise.all(
73
+ ["trolley", "crate", "base"].map((name) =>
74
+ descriptors.inline(pieceOf(name), path.join(pieceDir, `${name === "base" ? "_base" : name}.fetch.ts`)),
75
+ ),
76
+ );
77
+
78
+ expect(trolley).toBe(
79
+ pieceOf("trolley")
80
+ .replace('import { getSerializedSignalOf } from "../sig" with { type: "macro" };', "")
81
+ .replace(
82
+ 'getSerializedSignalOf("trolley")',
83
+ '{"trolley":{"endpoint":{"pingAt":{"type":"query","args":[],"returns":{"refName":"String"}}}}}',
84
+ ),
85
+ );
86
+ expect(crate).toContain('{"crate":{"endpoint":{"countOf":');
87
+ expect(base).toContain("FetchClient.build<typeof signal>(cnst, {}, { base: fetch })");
88
+ expect([trolley, crate, base].some((source) => source?.includes('with { type: "macro" }'))).toBe(false);
89
+ expect(await readsOf()).toBe("read\n");
90
+ });
91
+
92
+ test("leaves the macro to a file it cannot answer exactly: not a piece, two calls, a name the signal lacks, or a value JSON cannot carry", async () => {
93
+ const { root, pieceDir } = await writeScope();
94
+ const descriptors = new SignalDescriptors(root, ["apps/shop"]);
95
+ const twoCalls = pieceOf("trolley").replace(
96
+ 'getSerializedSignalOf("trolley")',
97
+ 'getSerializedSignalOf("trolley"), getSerializedSignalOf("crate")',
98
+ );
99
+
100
+ expect(await descriptors.inline(pieceOf("trolley"), path.join(root, "apps/shop/lib/sigOf.ts"))).toBeNull();
101
+ expect(await descriptors.inline(twoCalls, path.join(pieceDir, "trolley.fetch.ts"))).toBeNull();
102
+ expect(await descriptors.inline(pieceOf("absent"), path.join(pieceDir, "absent.fetch.ts"))).toBeNull();
103
+ expect(await descriptors.inline(pieceOf("odd"), path.join(pieceDir, "odd.fetch.ts"))).toBeNull();
104
+ for (const name of ["valueOf", "__proto__", "constructor"])
105
+ expect(await descriptors.inline(pieceOf(name), path.join(pieceDir, `${name}.fetch.ts`))).toBeNull();
106
+ });
107
+
108
+ test("says which scope's signals it could not read, leaves only their pieces to the macro and answers the rest", async () => {
109
+ const { root, pieceDir } = await writeScope();
110
+ await writeText(path.join(root, "libs/kit/lib/sig.ts"), 'throw new Error("the signal broke");\n');
111
+ const said: string[] = [];
112
+ const descriptors = new SignalDescriptors(root, ["libs/kit", "apps/shop"], {
113
+ onUnread: (reason) => said.push(reason),
114
+ });
115
+
116
+ expect(
117
+ await descriptors.inline(pieceOf("crate"), path.join(root, "libs/kit/lib/__client/crate.fetch.ts")),
118
+ ).toBeNull();
119
+ expect(await descriptors.inline(pieceOf("trolley"), path.join(pieceDir, "trolley.fetch.ts"))).toContain(
120
+ '{"trolley":{"endpoint":',
121
+ );
122
+ expect(said).toEqual(["the signals of libs/kit could not be read (the signal broke)"]);
123
+ });
124
+
125
+ test("stops a signal that does not finish loading within its time, names its scope once and leaves no process behind", async () => {
126
+ const { root, pieceDir, pidFile } = await writeHangingScope();
127
+ const said: string[] = [];
128
+ const descriptors = new SignalDescriptors(root, ["apps/shop"], {
129
+ onUnread: (reason) => said.push(reason),
130
+ timeoutMs: 500,
131
+ });
132
+
133
+ const inlined = await Promise.all(
134
+ ["trolley", "crate"].map((name) => descriptors.inline(pieceOf(name), path.join(pieceDir, `${name}.fetch.ts`))),
135
+ );
136
+
137
+ expect(inlined).toEqual([null, null]);
138
+ expect(said).toEqual([
139
+ "the signals of apps/shop could not be read (they did not load within 0.5s, so the process reading them was stopped)",
140
+ ]);
141
+ expect(await goneWithin(Number(await Bun.file(pidFile).text()), 3_000)).toBe(true);
142
+ });
143
+
144
+ for (const ending of ["exits", "is killed"] as const)
145
+ test(`the process reading the signals ends when the build that started it ${ending}`, async () => {
146
+ const { root, pieceDir, pidFile } = await writeHangingScope();
147
+ const build = path.join(root, "build.ts");
148
+ await writeText(
149
+ build,
150
+ [
151
+ `import { SignalDescriptors } from ${JSON.stringify(path.join(import.meta.dir, "signalDescriptors.ts"))};`,
152
+ `void new SignalDescriptors(${JSON.stringify(root)}, ["apps/shop"]).inline(${JSON.stringify(pieceOf("trolley"))}, ${JSON.stringify(path.join(pieceDir, "trolley.fetch.ts"))});`,
153
+ `while (!(await Bun.file(${JSON.stringify(pidFile)}).exists())) await Bun.sleep(50);`,
154
+ ending === "exits" ? "process.exit(0);" : "",
155
+ "",
156
+ ].join("\n"),
157
+ );
158
+ const parent = Bun.spawn([process.execPath, build], { cwd: root, stdout: "ignore", stderr: "ignore" });
159
+ try {
160
+ for (let tries = 0; tries < 200 && !(await Bun.file(pidFile).exists()); tries++) await Bun.sleep(50);
161
+ const reader = Number(await Bun.file(pidFile).text());
162
+ if (ending === "is killed") {
163
+ expect(alive(reader)).toBe(true);
164
+ parent.kill("SIGKILL");
165
+ }
166
+ await parent.exited;
167
+ expect(await goneWithin(reader, 5_000)).toBe(true);
168
+ } finally {
169
+ parent.kill("SIGKILL");
170
+ }
171
+ }, 30_000);
172
+
173
+ test("reads the signals in the build's own environment and its define, never a .env file the build did not load", async () => {
174
+ const { root, pieceDir } = await writeScope(
175
+ sigSource.replace(
176
+ 'refName: "String" }',
177
+ 'refName: "String", mode: process.env.NODE_ENV, sentinel: process.env.AKAN_SIGNAL_SENTINEL ?? "none" }',
178
+ ),
179
+ );
180
+ for (const file of [".env.production", ".env.production.local"])
181
+ await writeText(path.join(root, file), "AKAN_SIGNAL_SENTINEL=from-an-env-file\n");
182
+ const descriptors = new SignalDescriptors(root, ["apps/shop"]);
183
+ descriptors.plugin.setup({
184
+ config: { define: { "process.env.NODE_ENV": '"production"' } },
185
+ onLoad: () => undefined,
186
+ } as never);
187
+
188
+ const trolley = await descriptors.inline(pieceOf("trolley"), path.join(pieceDir, "trolley.fetch.ts"));
189
+
190
+ expect(trolley).toContain('"mode":"production","sentinel":"none"');
191
+ expect(trolley).not.toContain("from-an-env-file");
192
+ });
193
+
194
+ describe("a scope's whole runtime file on a page that also loads pieces", () => {
195
+ const wholeSource = `import { FetchClient } from "akanjs/fetch";
196
+ import * as cnst from "./cnst";
197
+ import { fetch as pageFetch, sig as pageSig } from "./usePage";
198
+ import { getSerializedSignal } from "./sig" with { type: "macro" };
199
+ Object.assign(pageSig, FetchClient.build(cnst, getSerializedSignal(), { base: pageFetch }).sig);
200
+ `;
201
+ const plainSig = sigSource.replace("\n odd: {", "\n spare: {").replace(", nullable: undefined }", " }");
202
+ const writePieces = async (pieceDir: string, names: string[]) =>
203
+ Promise.all(
204
+ names.map(async (name) => {
205
+ const file = path.join(pieceDir, `${name}.fetch.ts`);
206
+ await writeText(file, pieceOf(name));
207
+ return file;
208
+ }),
209
+ );
210
+
211
+ test("leaves out the descriptors of the pieces it is told, imports each piece by a name it uses, and keeps the rest", async () => {
212
+ const { root, pieceDir } = await writeScope(plainSig);
213
+ const [trolley] = await writePieces(pieceDir, ["trolley"]);
214
+ const descriptors = new SignalDescriptors(root, ["apps/shop"]);
215
+
216
+ const whole = await descriptors.withoutPieces(wholeSource, path.join(root, "apps/shop/lib/useClient.ts"), [
217
+ trolley ?? "",
218
+ ]);
219
+
220
+ expect(whole).toContain(`import { loaded as __akanPiece0 } from ${JSON.stringify(trolley)};`);
221
+ expect(whole).toContain("__akanPiecesFirst(__akanPiece0);");
222
+ expect(whole).toContain('FetchClient.build(cnst, {"crate":');
223
+ expect(whole).toContain('"spare":');
224
+ expect(whole).not.toContain("pingAt");
225
+ expect(whole).not.toContain('type: "macro"');
226
+ });
227
+
228
+ test("keeps a signal named `base` that the scope takes from its base, unless the base piece holds it", async () => {
229
+ const query = (name: string) =>
230
+ `{ endpoint: { ${name}: { type: "query", args: [], returns: { refName: "String" } } } }`;
231
+ const libSig = `const serialized = {
232
+ base: ${query("pingBase")},
233
+ agent: ${query("askAgent")},
234
+ trolley: ${query("pingAt")},
235
+ crate: ${query("countOf")},
236
+ };
237
+ export const fetch = { ownSerializedSignal: serialized };
238
+ export const getSerializedSignalOf = (name) =>
239
+ name === "base" ? { base: serialized.base, agent: serialized.agent } : { [name]: serialized[name] };
240
+ `;
241
+ const { root, pieceDir } = await writeScope(libSig);
242
+ const [trolley] = await writePieces(pieceDir, ["trolley"]);
243
+ const basePiece = path.join(pieceDir, "_base.fetch.ts");
244
+ await writeText(basePiece, pieceOf("base"));
245
+ const file = path.join(root, "apps/shop/lib/useClient.ts");
246
+ const occurrencesOf = (source: string | null, text: string) => (source ?? "").split(text).length - 1;
247
+
248
+ const beside = await new SignalDescriptors(root, ["apps/shop"]).withoutPieces(wholeSource, file, [trolley ?? ""]);
249
+ expect(occurrencesOf(beside, "pingBase")).toBe(1);
250
+ expect(occurrencesOf(beside, "askAgent")).toBe(1);
251
+ expect(occurrencesOf(beside, "countOf")).toBe(1);
252
+ expect(occurrencesOf(beside, "pingAt")).toBe(0);
253
+
254
+ const taken = await new SignalDescriptors(root, ["apps/shop"]).withoutPieces(wholeSource, file, [
255
+ basePiece,
256
+ trolley ?? "",
257
+ ]);
258
+ expect(occurrencesOf(taken, "pingBase")).toBe(0);
259
+ expect(occurrencesOf(taken, "askAgent")).toBe(0);
260
+ expect(occurrencesOf(taken, "countOf")).toBe(1);
261
+ });
262
+
263
+ test("keeps its macro and every descriptor where a name has no literal, or a piece names none", async () => {
264
+ const { root, pieceDir } = await writeScope();
265
+ const [trolley] = await writePieces(pieceDir, ["trolley"]);
266
+ const file = path.join(root, "apps/shop/lib/useClient.ts");
267
+ expect(
268
+ await new SignalDescriptors(root, ["apps/shop"]).withoutPieces(wholeSource, file, [trolley ?? ""]),
269
+ ).toBeNull();
270
+
271
+ const plain = await writeScope(plainSig);
272
+ const unnamed = path.join(plain.pieceDir, "_base.fetch.ts");
273
+ await writeText(unnamed, "export const loaded = {};\n");
274
+ const plainFile = path.join(plain.root, "apps/shop/lib/useClient.ts");
275
+ expect(
276
+ await new SignalDescriptors(plain.root, ["apps/shop"]).withoutPieces(wholeSource, plainFile, [unnamed]),
277
+ ).toBeNull();
278
+ });
279
+ });
280
+ });