@akanjs/devkit 3.3.0-rc.6 → 3.3.0-rc.61

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 (278) hide show
  1. package/DEV_RUNTIME_KNOBS.md +1 -1
  2. package/README.ko.md +8 -2
  3. package/README.md +8 -3
  4. package/akanApp/akanApp.host.test.ts +4 -2
  5. package/akanApp/akanApp.host.ts +11 -0
  6. package/akanConfig/akanBin.ts +4 -0
  7. package/akanConfig/akanConfig.test.ts +280 -19
  8. package/akanConfig/akanConfig.ts +96 -270
  9. package/akanConfig/akanWorkers.test.ts +73 -0
  10. package/akanConfig/akanWorkers.ts +61 -0
  11. package/akanConfig/desktopServerConfig.ts +96 -0
  12. package/akanConfig/dockerImage.ts +216 -0
  13. package/akanConfig/index.ts +2 -0
  14. package/akanConfig/nativeFileSettings.ts +33 -0
  15. package/akanConfig/nativeKeys.ts +52 -0
  16. package/akanConfig/types.ts +2 -0
  17. package/app/appBin.test.ts +63 -0
  18. package/app/appBin.ts +50 -0
  19. package/app/applicationBuildReporter.test.ts +51 -1
  20. package/app/applicationBuildReporter.ts +6 -1
  21. package/app/applicationBuildRunner.test.ts +358 -5
  22. package/app/applicationBuildRunner.ts +204 -30
  23. package/app/dictionarySizes.test.ts +40 -0
  24. package/app/dictionarySizes.ts +95 -0
  25. package/app/routeFilesReport.test.ts +59 -0
  26. package/app/routeFilesReport.ts +46 -0
  27. package/app/routeJsBudget.ts +18 -4
  28. package/artifact/implicitRootLayout.test.ts +19 -0
  29. package/artifact/implicitRootLayout.ts +16 -2
  30. package/artifact/implicitRootLayoutRender.test.tsx +4 -1
  31. package/artifact/storeBootstrap.test.ts +28 -0
  32. package/artifact/storeBootstrap.ts +64 -8
  33. package/biome.base.json +7 -5
  34. package/codeAgent/agent/CodeAgent.ts +36 -16
  35. package/codeAgent/agent/CodeAgentAllowed.ts +35 -0
  36. package/codeAgent/agent/CodeAgentCommandLine.ts +372 -0
  37. package/codeAgent/agent/CodeAgentGate.ts +23 -4
  38. package/codeAgent/agent/CodeAgentRpcHost.ts +1 -1
  39. package/codeAgent/agent/codeAgent.test.ts +62 -0
  40. package/codeAgent/agent/codeAgentCommandLine.test.ts +212 -0
  41. package/codeAgent/agent/codeAgentContract.test.ts +117 -5
  42. package/codeAgent/skills/akan-agent/SKILL.md +8 -1
  43. package/codeAgent/skills/akan-code/SKILL.md +38 -3
  44. package/codeAgent/skills/akan-debug/SKILL.md +1 -1
  45. package/codeAgent/skills/akan-deps/SKILL.md +3 -2
  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 +52 -28
  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 +10 -11
  53. package/codeAgent/skills/akan-transport/SKILL.md +5 -14
  54. package/codeAgent/skills/akan-ui/SKILL.md +16 -21
  55. package/commandDecorators/command.ts +28 -12
  56. package/commandDecorators/commandBuilder.ts +8 -1
  57. package/commandDecorators/commandDecorators.test.ts +70 -3
  58. package/commandDecorators/helpFormatter.ts +14 -12
  59. package/context/akanContext.ts +2 -0
  60. package/csrE2e/devHmrLatency.e2e.test.ts +1 -1
  61. package/docs/apiReference.test.ts +19 -0
  62. package/docs/apiReference.ts +28 -5
  63. package/executors/appExecutor.ts +26 -12
  64. package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
  65. package/executors/clientRuntimeKeys.fixture.json +393 -0
  66. package/executors/clientRuntimeKeys.test.ts +1690 -0
  67. package/executors/executor.ts +14 -6
  68. package/executors/executors.test.ts +140 -1
  69. package/executors/sysExecutor.ts +112 -8
  70. package/executors/workspaceExecutor.ts +7 -4
  71. package/frontendBuild/allRoutesBuilder.ts +99 -7
  72. package/frontendBuild/autoImportSync.ts +3 -2
  73. package/frontendBuild/buildRouteClient.test.ts +686 -13
  74. package/frontendBuild/clientBuildTypes.ts +26 -0
  75. package/frontendBuild/clientEntriesBundler.ts +49 -1
  76. package/frontendBuild/clientEntryDiscovery.test.ts +308 -1
  77. package/frontendBuild/clientEntryDiscovery.ts +136 -14
  78. package/frontendBuild/clientEntryGroups.test.ts +77 -0
  79. package/frontendBuild/clientEntryGroups.ts +61 -0
  80. package/frontendBuild/csrDevArtifactWriter.ts +2 -2
  81. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  82. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  83. package/frontendBuild/csrDevPatcher.test.ts +1 -1
  84. package/frontendBuild/csrDevPatcher.ts +33 -7
  85. package/frontendBuild/csrDevTypes.ts +9 -0
  86. package/frontendBuild/devBarrelImports.test.ts +154 -0
  87. package/frontendBuild/devBarrelImports.ts +83 -23
  88. package/frontendBuild/devRegistryBundler.ts +4 -2
  89. package/frontendBuild/devRouteRuntime.test.ts +492 -0
  90. package/frontendBuild/devRouteRuntime.ts +167 -0
  91. package/frontendBuild/dictionaryAssetBuilder.test.ts +408 -0
  92. package/frontendBuild/dictionaryAssetBuilder.ts +185 -17
  93. package/frontendBuild/dictionaryConstants.ts +136 -0
  94. package/frontendBuild/dictionaryOwnParts.ts +88 -0
  95. package/frontendBuild/dictionaryPackState.ts +131 -0
  96. package/frontendBuild/dictionaryPacking.test.ts +207 -0
  97. package/frontendBuild/dictionaryPacking.ts +160 -0
  98. package/frontendBuild/dictionaryRoutes.test.ts +251 -0
  99. package/frontendBuild/dictionaryRoutes.ts +227 -0
  100. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  101. package/frontendBuild/pagesBundleBuilder.ts +78 -2
  102. package/frontendBuild/precompressArtifacts.test.ts +22 -0
  103. package/frontendBuild/precompressArtifacts.ts +34 -8
  104. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  105. package/frontendBuild/renderedEntries.ts +144 -0
  106. package/frontendBuild/routeClientBuilder.ts +407 -43
  107. package/frontendBuild/routeHandoffs.test.ts +155 -0
  108. package/frontendBuild/routeHandoffs.ts +117 -0
  109. package/frontendBuild/routeModulePreloads.test.ts +32 -0
  110. package/frontendBuild/routeModulePreloads.ts +20 -11
  111. package/frontendBuild/routeRuntimeCheck.test.ts +280 -0
  112. package/frontendBuild/routeRuntimeCheck.ts +248 -0
  113. package/frontendBuild/routeRuntimePays.test.ts +143 -0
  114. package/frontendBuild/routeRuntimePays.ts +117 -0
  115. package/frontendBuild/ssrBaseArtifactBuilder.ts +24 -34
  116. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  117. package/frontendBuild/ssrDevBundler.ts +66 -11
  118. package/frontendBuild/vendorFileImports.test.ts +254 -0
  119. package/frontendBuild/vendorFileImports.ts +163 -0
  120. package/frontendBuild/vendorNarrowing.ts +28 -0
  121. package/frontendBuild/vendorSpecifiers.ts +2 -0
  122. package/incrementalBuilder/buildBatch.proc.ts +9 -9
  123. package/incrementalBuilder/buildBatchProtocol.ts +1 -1
  124. package/incrementalBuilder/builderBoot.ts +5 -5
  125. package/incrementalBuilder/builderGraphPayloads.ts +4 -4
  126. package/incrementalBuilder/builderLanes.ts +2 -2
  127. package/incrementalBuilder/builderWatch.ts +8 -8
  128. package/incrementalBuilder/csrRegistry.ts +4 -4
  129. package/incrementalBuilder/incrementalBuilder.proc.test.ts +79 -0
  130. package/incrementalBuilder/incrementalBuilder.proc.ts +27 -8
  131. package/incrementalBuilder/ssrRegistry.ts +6 -6
  132. package/index.ts +1 -1
  133. package/integration/renderAdmissionSoak.test.ts +99 -0
  134. package/integration/renderAdmissionSoak.ts +609 -0
  135. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  136. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  137. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  138. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  139. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  140. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  141. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  142. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  143. package/lint/biomeBase.test.ts +50 -3
  144. package/lint/biomeBase.ts +1 -1
  145. package/lint/biomeCheck.test.ts +162 -0
  146. package/lint/biomeCheck.ts +131 -0
  147. package/lint/linter.test.ts +16 -11
  148. package/lint/no-arbitrary-color.grit +5 -0
  149. package/lint/no-conditional-st-hook.grit +5 -1
  150. package/lint/no-daisyui-legacy-class.grit +8 -0
  151. package/lint/no-document-cookie.grit +3 -0
  152. package/lint/no-inline-color.grit +10 -2
  153. package/lint/no-oversized-list-limit.grit +2 -0
  154. package/lint/no-raw-palette-class.grit +7 -0
  155. package/lint/no-unpublished-form-setter.grit +2 -0
  156. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  157. package/lint/no-web-storage.grit +3 -0
  158. package/lint/withheldEnvFile.ts +17 -0
  159. package/mobile/desktopBin.ts +2 -2
  160. package/mobile/desktopServerStage.test.ts +18 -3
  161. package/mobile/desktopServerStage.ts +7 -2
  162. package/mobile/nativeApp.test.ts +7 -5
  163. package/mobile/nativeApp.ts +2 -2
  164. package/mobile/nativeConfig.test.ts +96 -1
  165. package/mobile/nativeConfig.ts +46 -12
  166. package/mobile/nativePublicEnv.ts +1 -1
  167. package/mobile/serverBundleSecrets.ts +43 -0
  168. package/package.json +20 -171
  169. package/packageExports.test.ts +38 -24
  170. package/quality/dictionaryKeys.test.ts +356 -0
  171. package/quality/dictionaryKeys.ts +488 -0
  172. package/quality/objectImportReport.test.ts +36 -0
  173. package/quality/objectImportReport.ts +105 -0
  174. package/quality/qualityScanner.ts +1 -1
  175. package/quality/routeRuntimeReport.test.ts +91 -0
  176. package/quality/routeRuntimeReport.ts +121 -0
  177. package/quality/runtimeConstantFacts.ts +71 -0
  178. package/quality/runtimeConstantGraph.ts +123 -0
  179. package/quality/runtimeConstantReads.ts +116 -0
  180. package/quality/runtimeImports.test.ts +190 -0
  181. package/quality/runtimeImports.ts +233 -0
  182. package/quality/runtimeKeyNames.ts +46 -0
  183. package/quality/runtimeLexicalScope.ts +132 -0
  184. package/quality/runtimeMarkerReach.test.ts +84 -0
  185. package/quality/runtimeMarkerReach.ts +255 -0
  186. package/quality/runtimeModuleFacts.ts +290 -0
  187. package/quality/runtimeNameTable.test.ts +172 -0
  188. package/quality/runtimeNameTable.ts +477 -0
  189. package/quality/runtimeScopeReport.test.ts +123 -0
  190. package/quality/runtimeScopeReport.ts +167 -0
  191. package/quality/runtimeSliceKey.ts +269 -0
  192. package/quality/runtimeSyntax.ts +133 -0
  193. package/quality/runtimeTable.fixture.ts +189 -0
  194. package/quality/runtimeUse.test.ts +737 -0
  195. package/quality/runtimeUse.ts +696 -0
  196. package/quality/runtimeUseReadable.test.ts +393 -0
  197. package/quality/ssrScanner.test.ts +13 -0
  198. package/quality/ssrScanner.ts +1 -1
  199. package/quality/translatorBindings.ts +187 -0
  200. package/test/secretEnvFixture.ts +134 -0
  201. package/test/testHelpers.ts +11 -0
  202. package/transforms/barrelAnalyzer.ts +26 -4
  203. package/transforms/barrelImportsPlugin.ts +121 -32
  204. package/transforms/exportReach.test.ts +162 -0
  205. package/transforms/exportReach.ts +308 -0
  206. package/transforms/frameworkObjects.fixture.tsx +58 -0
  207. package/transforms/frameworkObjects.test.ts +54 -0
  208. package/transforms/modelReference.test.ts +196 -0
  209. package/transforms/modelReference.ts +39 -0
  210. package/transforms/moduleParts.test.ts +225 -0
  211. package/transforms/moduleParts.ts +418 -0
  212. package/transforms/objectImportEdits.ts +150 -0
  213. package/transforms/objectMemberImports.test.ts +633 -0
  214. package/transforms/objectMemberImports.ts +571 -0
  215. package/transforms/objectMemberLookup.ts +150 -0
  216. package/transforms/objectModule.test.ts +307 -0
  217. package/transforms/objectModule.ts +482 -0
  218. package/transforms/objectModuleAnalyzer.ts +104 -0
  219. package/transforms/partImports.test.ts +76 -0
  220. package/transforms/partImports.ts +110 -0
  221. package/transforms/partModules.test.ts +187 -0
  222. package/transforms/partModules.ts +90 -0
  223. package/transforms/partPurity.ts +124 -0
  224. package/transforms/reactIconImports.test.ts +231 -0
  225. package/transforms/reactIconImports.ts +325 -0
  226. package/transforms/routeConstants.ts +122 -0
  227. package/transforms/routeRuntime.test.ts +835 -0
  228. package/transforms/routeRuntime.ts +703 -0
  229. package/transforms/routeRuntimeEdits.ts +92 -0
  230. package/transforms/routeRuntimeGraph.ts +66 -0
  231. package/transforms/routeRuntimePlan.ts +244 -0
  232. package/transforms/secretEnvDeclaration.test.ts +208 -0
  233. package/transforms/secretEnvDeclaration.ts +213 -0
  234. package/transforms/secretEnvFile.test.ts +117 -0
  235. package/transforms/secretEnvFile.ts +113 -0
  236. package/transforms/secretEnvName.test.ts +54 -0
  237. package/transforms/secretEnvName.ts +29 -0
  238. package/transforms/secretEnvSource.test.ts +148 -0
  239. package/transforms/secretEnvSource.ts +166 -0
  240. package/transforms/serverEnvEvaluationError.ts +11 -0
  241. package/transforms/serverEnvPlugin.test.ts +2 -1
  242. package/transforms/serverEnvPlugin.ts +13 -0
  243. package/transforms/serverEnvProfile.test.ts +129 -2
  244. package/transforms/serverEnvProfile.ts +126 -40
  245. package/transforms/serverEnvSecrets.test.ts +292 -0
  246. package/transforms/signalDescriptors.test.ts +280 -0
  247. package/transforms/signalDescriptors.ts +227 -0
  248. package/transforms/thisFreeExports.ts +87 -0
  249. package/transforms/transforms.test.ts +180 -3
  250. package/transforms/tsconfigPackageResolver.test.ts +1 -0
  251. package/tunnel/createTunnel.test.ts +29 -8
  252. package/tunnel/createTunnel.ts +22 -11
  253. package/tunnel/ssh2Module.test.ts +37 -0
  254. package/tunnel/ssh2Module.ts +32 -0
  255. package/tunnel/sshTunnel.ts +4 -2
  256. package/typecheck/projectTypecheck.test.ts +32 -1
  257. package/typecheck/projectTypecheck.ts +3 -3
  258. package/typecheck/typeChecker.test.ts +49 -0
  259. package/typecheck/typeChecker.ts +9 -7
  260. package/typecheck/withheldDiagnostics.ts +41 -0
  261. package/util/fileEditor.ts +1 -0
  262. package/util/selectModel.ts +1 -0
  263. package/workflow/executor.ts +6 -2
  264. package/workflow/index.ts +1 -0
  265. package/workflow/plan.ts +36 -7
  266. package/workflow/types.ts +1 -1
  267. package/workflow/uiTarget.ts +50 -0
  268. package/workspace/envSeed.test.ts +30 -1
  269. package/workspace/envSeed.ts +30 -1
  270. package/workspace/getRelatedCnsts.ts +7 -0
  271. package/workspace/mainCheckout.test.ts +55 -0
  272. package/workspace/mainCheckout.ts +38 -0
  273. package/workspace/scanInfo.test.ts +39 -0
  274. package/workspace/scanInfo.ts +55 -6
  275. package/workspace/slicePlanner.ts +1 -1
  276. package/workspace/workspaceLayout.test.ts +5 -1
  277. package/workspace/workspaceLayout.ts +3 -0
  278. package/CHANGELOG.md +0 -2717
@@ -0,0 +1,148 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { SecretEnvSource } from "./secretEnvSource";
3
+
4
+ const file = "/workspace/apps/demo/env/env.server.main.ts";
5
+ const read = (contents: string) => SecretEnvSource.rewrite(file, contents, "read");
6
+ const body = (rewritten: string) => rewritten.replace(/^import \{ SecretEnv as __akanSecretEnv \} from "[^"]+"; /, "");
7
+
8
+ describe("SecretEnvSource", () => {
9
+ test("leaves a read of the process env where a secret string was, and every plain value as written", () => {
10
+ const source = [
11
+ 'import type { ModulesOptions } from "../lib/option";',
12
+ "export const env: ModulesOptions = {",
13
+ ' hostname: "app.example.test",',
14
+ " security: {",
15
+ ' jwtSecret: "sentinel-jwt",',
16
+ ' verifies: [["password"], ["email"]],',
17
+ " accessTokenSeconds: 900,",
18
+ ' sso: { google: { clientID: "plain-id", "clientSecret": \'sentinel-google\' } },',
19
+ " },",
20
+ " mailer: { auth: { user: `mailer`, pass: `sentinel-pass` } },",
21
+ ' objectStorage: { endpoint: "https://minio:sentinel-url-pass@storage.example.test", region: "ap-northeast-2" },',
22
+ ' cookieDomain: "",',
23
+ "};",
24
+ "",
25
+ ].join("\n");
26
+ const rewritten = read(source);
27
+ expect(rewritten).toStartWith('import { SecretEnv as __akanSecretEnv } from "');
28
+ expect(rewritten.split("\n").length).toBe(source.split("\n").length);
29
+ expect(body(rewritten)).toBe(
30
+ [
31
+ 'import type { ModulesOptions } from "../lib/option";',
32
+ "export const env: ModulesOptions = {",
33
+ ' hostname: "app.example.test",',
34
+ " security: {",
35
+ ' jwtSecret: __akanSecretEnv.read("JWT_SECRET"),',
36
+ ' verifies: [["password"], ["email"]],',
37
+ " accessTokenSeconds: 900,",
38
+ ' sso: { google: { clientID: "plain-id", "clientSecret": __akanSecretEnv.read("SECURITY__SSO__GOOGLE__CLIENT_SECRET") } },',
39
+ " },",
40
+ ' mailer: { auth: { user: `mailer`, pass: __akanSecretEnv.read("MAILER__AUTH__PASS") } },',
41
+ ' objectStorage: { endpoint: __akanSecretEnv.read("OBJECT_STORAGE__ENDPOINT"), region: "ap-northeast-2" },',
42
+ ' cookieDomain: "",',
43
+ "};",
44
+ "",
45
+ ].join("\n"),
46
+ );
47
+ });
48
+
49
+ test("moves an array holding a secret whole, as one JSON variable, and leaves one it cannot read as a literal", () => {
50
+ const rewritten = body(
51
+ read(
52
+ [
53
+ "const more = [];",
54
+ "export const env = {",
55
+ ' discord: { tokens: ["sentinel-a", "sentinel-b"], rooms: ["general"] },',
56
+ ' accounts: [{ name: "ops", password: "sentinel-ops", retries: -1, active: true, note: null }],',
57
+ ' apiKeys: ["sentinel-c", ...more],',
58
+ "};",
59
+ ].join("\n"),
60
+ ),
61
+ );
62
+ expect(rewritten).toContain('discord: { tokens: __akanSecretEnv.json("DISCORD__TOKENS"), rooms: ["general"] },');
63
+ expect(rewritten).toContain('accounts: __akanSecretEnv.json("ACCOUNTS"),');
64
+ expect(rewritten).toContain('apiKeys: ["sentinel-c", ...more],');
65
+ });
66
+
67
+ test("replaces only the literal beside the developer's own variable, through `as` and `satisfies`", () => {
68
+ const rewritten = body(
69
+ read(
70
+ [
71
+ "export const env = {",
72
+ ' database: { postgres: { url: process.env.DATABASE_URL ?? "postgres://app:sentinel@db.example.test/app" } },',
73
+ ' llm: { apiKey: (process.env.LLM_KEY || "sentinel-llm") as string },',
74
+ "} as const satisfies object;",
75
+ ].join("\n"),
76
+ ),
77
+ );
78
+ expect(rewritten).toContain('url: process.env.DATABASE_URL ?? __akanSecretEnv.read("POSTGRES_URL")');
79
+ expect(rewritten).toContain('apiKey: (process.env.LLM_KEY || __akanSecretEnv.read("LLM__API_KEY")) as string');
80
+ });
81
+
82
+ test("a listing marks the literal with the developer's own variable beside it whole, so a shell that sets that variable lists it too", () => {
83
+ const marked = SecretEnvSource.rewrite(
84
+ file,
85
+ [
86
+ "export const env = {",
87
+ ' database: { postgres: { url: process.env.DATABASE_URL ?? "postgres://app:sentinel@db.example.test/app" } },',
88
+ ' llm: { apiKey: (process.env.LLM_KEY || process.env.OTHER_KEY || "sentinel-llm") as string },',
89
+ "};",
90
+ ].join("\n"),
91
+ "mark",
92
+ );
93
+ expect(marked).toContain(
94
+ 'url: ({ __akanSecretEnv: ["POSTGRES_URL", "string", "postgres://app:sentinel@db.example.test/app"] }) }',
95
+ );
96
+ expect(marked).toContain('apiKey: ({ __akanSecretEnv: ["LLM__API_KEY", "string", "sentinel-llm"] }) }');
97
+ });
98
+
99
+ test("leaves a file alone that holds no secret literal, or whose env is not an object it can read", () => {
100
+ const plain = 'export const env = { hostname: "app.example.test", port: 8080, tokenTtl: 3600 };\n';
101
+ expect(read(plain)).toBe(plain);
102
+ const computed = [
103
+ 'import { secret } from "./elsewhere";',
104
+ "const token = [secret].join();",
105
+ ["export const env = { llm: { apiKey: token, model: `m-$", "{secret}` }, ...secret };"].join(""),
106
+ 'export const other = { password: "sentinel-other" };',
107
+ "",
108
+ ].join("\n");
109
+ expect(read(computed)).toBe(computed);
110
+ const switched = "export const env = envConfigs[currentEnv as keyof typeof envConfigs];\n";
111
+ expect(read(switched)).toBe(switched);
112
+ });
113
+
114
+ test("an --inline-secrets build keeps the literal behind the read, and a listing marks it with its variable", () => {
115
+ const source = 'export const env = { llm: { apiKey: "sentinel-llm" }, discord: { tokens: ["sentinel-a"] } };\n';
116
+ expect(body(SecretEnvSource.rewrite(file, source, "inline"))).toBe(
117
+ 'export const env = { llm: { apiKey: __akanSecretEnv.read("LLM__API_KEY", "sentinel-llm") }, discord: { tokens: __akanSecretEnv.json("DISCORD__TOKENS", ["sentinel-a"]) } };\n',
118
+ );
119
+ expect(SecretEnvSource.rewrite(file, source, "mark")).toBe(
120
+ 'export const env = { llm: { apiKey: ({ __akanSecretEnv: ["LLM__API_KEY", "string", "sentinel-llm"] }) }, discord: { tokens: ({ __akanSecretEnv: ["DISCORD__TOKENS", "json", ["sentinel-a"]] }) } };\n',
121
+ );
122
+ });
123
+
124
+ test("marks a string holding a line break as multi-line", () => {
125
+ const source = 'export const env = { push: { privateKey: "-----BEGIN-----\\nsentinel\\n-----END-----\\n" } };\n';
126
+ expect(SecretEnvSource.rewrite(file, source, "mark")).toContain('["PUSH__PRIVATE_KEY", "multiline", ');
127
+ });
128
+
129
+ test("refuses two keys that would share one variable, and a key whose variable the platform owns, without a value", () => {
130
+ const failure = (contents: string) => {
131
+ try {
132
+ read(contents);
133
+ return "";
134
+ } catch (error) {
135
+ return (error as Error).message;
136
+ }
137
+ };
138
+ expect(failure('export const env = { a: { apiKey: "sentinel-one", api_key: "sentinel-two" } };')).toBe(
139
+ `${file} \`a.apiKey\` and \`a.api_key\` are secrets a build would both read from the environment variable A__API_KEY. Rename one of the keys.`,
140
+ );
141
+ expect(failure('export const env = { pwd: "sentinel-three" };')).toBe(
142
+ `${file} \`pwd\` is a secret a build would read from the environment variable PWD, a variable the platform sets. Rename the key, or write \`process.env.<NAME>\` there yourself, which a build leaves as it is.`,
143
+ );
144
+ expect(failure('export const env = { akan: { token: "sentinel-four" } };')).toContain(
145
+ "AKAN__TOKEN, a name akan and Bun keep for their own settings.",
146
+ );
147
+ });
148
+ });
@@ -0,0 +1,166 @@
1
+ import path from "node:path";
2
+ import { Logger } from "akanjs/common";
3
+ import type { SecretEnvKind } from "akanjs/server/lifecycle/secretEnv";
4
+ import ts from "typescript";
5
+ import { SecretEnvName } from "./secretEnvName";
6
+ import { ServerEnvProfile } from "./serverEnvProfile";
7
+
8
+ //* `inline` keeps the literal as the read's fallback; `mark` wraps it with its variable's name, for a listing.
9
+ export type SecretEnvMode = "read" | "inline" | "mark";
10
+
11
+ interface Edit {
12
+ start: number;
13
+ end: number;
14
+ text: string;
15
+ }
16
+
17
+ //* Reads source text alone, so a secret that is computed, imported or spread stays as written.
18
+ export class SecretEnvSource {
19
+ static readonly markKey = "__akanSecretEnv";
20
+ static readonly #runtime = "akanjs/server/lifecycle/secretEnv";
21
+ static readonly #binding = "__akanSecretEnv";
22
+ static readonly #dynamic = Symbol("dynamic");
23
+
24
+ readonly #file: string;
25
+ readonly #source: ts.SourceFile;
26
+ readonly #mode: SecretEnvMode;
27
+ readonly #edits: Edit[] = [];
28
+ readonly #pathOfName = new Map<string, string>();
29
+
30
+ private constructor(file: string, contents: string, mode: SecretEnvMode) {
31
+ this.#file = file;
32
+ this.#source = ts.createSourceFile(file, contents, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
33
+ this.#mode = mode;
34
+ }
35
+
36
+ static rewrite(file: string, contents: string, mode: SecretEnvMode): string {
37
+ return new SecretEnvSource(file, contents, mode).#rewritten(contents);
38
+ }
39
+
40
+ #rewritten(contents: string) {
41
+ for (const statement of this.#source.statements) {
42
+ if (!ts.isVariableStatement(statement)) continue;
43
+ if (!statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) continue;
44
+ for (const declaration of statement.declarationList.declarations)
45
+ if (ts.isIdentifier(declaration.name) && declaration.name.text === "env" && declaration.initializer)
46
+ this.#visit(declaration.initializer, [], false);
47
+ }
48
+ if (!this.#edits.length) return contents;
49
+ const rewritten = this.#edits
50
+ .toSorted((a, b) => b.start - a.start)
51
+ .reduce((text, edit) => `${text.slice(0, edit.start)}${edit.text}${text.slice(edit.end)}`, contents);
52
+ if (this.#mode === "mark") return rewritten;
53
+ //? On the first line, so every line of the file keeps its number in an error the bundler reports.
54
+ return `import { SecretEnv as ${SecretEnvSource.#binding} } from ${JSON.stringify(this.#runtimePath())}; ${rewritten}`;
55
+ }
56
+
57
+ //? As the env file itself would import it, then as this package does: a lib's env file may have no akanjs beside it.
58
+ #runtimePath() {
59
+ for (const from of [path.dirname(this.#file), import.meta.dir]) {
60
+ try {
61
+ return Bun.resolveSync(SecretEnvSource.#runtime, from);
62
+ } catch {}
63
+ }
64
+ throw new Error(
65
+ `${this.#file} holds secret values, which the build reads from the process env through ${SecretEnvSource.#runtime}, and the installed akanjs has no such module. Install the akanjs of this akan version.`,
66
+ );
67
+ }
68
+
69
+ static #unwrap(node: ts.Expression): ts.Expression {
70
+ return ts.isParenthesizedExpression(node) ||
71
+ ts.isAsExpression(node) ||
72
+ ts.isSatisfiesExpression(node) ||
73
+ ts.isNonNullExpression(node) ||
74
+ ts.isTypeAssertionExpression(node)
75
+ ? SecretEnvSource.#unwrap(node.expression)
76
+ : node;
77
+ }
78
+
79
+ static #keyOf(name: ts.PropertyName): string | null {
80
+ return ts.isIdentifier(name) || ts.isStringLiteralLike(name) || ts.isNumericLiteral(name) ? name.text : null;
81
+ }
82
+
83
+ #visit(expression: ts.Expression, keys: string[], underSecret: boolean, beside?: ts.Expression): void {
84
+ const node = SecretEnvSource.#unwrap(expression);
85
+ if (ts.isObjectLiteralExpression(node)) {
86
+ for (const property of node.properties) {
87
+ const key = ts.isPropertyAssignment(property) ? SecretEnvSource.#keyOf(property.name) : null;
88
+ if (key !== null && ts.isPropertyAssignment(property))
89
+ this.#visit(property.initializer, [...keys, key], underSecret || Logger.isSecretKey(key));
90
+ }
91
+ return;
92
+ }
93
+ if (!keys.length) return;
94
+ //? `process.env.X ?? "literal"`: the developer's own variable keeps its place ahead of the one read here.
95
+ if (ts.isBinaryExpression(node)) {
96
+ const { kind } = node.operatorToken;
97
+ if (kind === ts.SyntaxKind.QuestionQuestionToken || kind === ts.SyntaxKind.BarBarToken)
98
+ this.#visit(node.right, keys, underSecret, beside ?? expression);
99
+ return;
100
+ }
101
+ if (ts.isStringLiteralLike(node)) {
102
+ if (ServerEnvProfile.isSecret(node.text, underSecret))
103
+ this.#replace(node, keys, node.text.includes("\n") ? "multiline" : "string", beside);
104
+ return;
105
+ }
106
+ if (!ts.isArrayLiteralExpression(node)) return;
107
+ const value = SecretEnvSource.#literal(node);
108
+ if (value !== SecretEnvSource.#dynamic && ServerEnvProfile.secretPaths(value, underSecret).length)
109
+ this.#replace(node, keys, "json", beside);
110
+ }
111
+
112
+ static #literal(expression: ts.Expression): unknown {
113
+ const node = SecretEnvSource.#unwrap(expression);
114
+ if (ts.isStringLiteralLike(node)) return node.text;
115
+ if (ts.isNumericLiteral(node)) return Number(node.text);
116
+ if (node.kind === ts.SyntaxKind.TrueKeyword) return true;
117
+ if (node.kind === ts.SyntaxKind.FalseKeyword) return false;
118
+ if (node.kind === ts.SyntaxKind.NullKeyword) return null;
119
+ if (ts.isPrefixUnaryExpression(node) && node.operator === ts.SyntaxKind.MinusToken) {
120
+ const operand = SecretEnvSource.#literal(node.operand);
121
+ return typeof operand === "number" ? -operand : SecretEnvSource.#dynamic;
122
+ }
123
+ if (ts.isArrayLiteralExpression(node)) {
124
+ const items = node.elements.map((element) => SecretEnvSource.#literal(element));
125
+ return items.includes(SecretEnvSource.#dynamic) ? SecretEnvSource.#dynamic : items;
126
+ }
127
+ if (!ts.isObjectLiteralExpression(node)) return SecretEnvSource.#dynamic;
128
+ const entries: [string, unknown][] = [];
129
+ for (const property of node.properties) {
130
+ const key = ts.isPropertyAssignment(property) ? SecretEnvSource.#keyOf(property.name) : null;
131
+ if (key === null || !ts.isPropertyAssignment(property)) return SecretEnvSource.#dynamic;
132
+ const value = SecretEnvSource.#literal(property.initializer);
133
+ if (value === SecretEnvSource.#dynamic) return SecretEnvSource.#dynamic;
134
+ entries.push([key, value]);
135
+ }
136
+ return Object.fromEntries(entries);
137
+ }
138
+
139
+ //? A listing marks the whole `process.env.X ?? "literal"`, so it names the variable whether or not a shell sets X.
140
+ #replace(node: ts.Expression, keys: string[], kind: SecretEnvKind, beside?: ts.Expression) {
141
+ const at = keys.join(".");
142
+ const name = SecretEnvName.of(keys);
143
+ const refusal = SecretEnvName.refusal(name);
144
+ if (refusal)
145
+ throw new Error(
146
+ `${this.#file} \`${at}\` is a secret a build would read from the environment variable ${name}, ${refusal}. Rename the key, or write \`process.env.<NAME>\` there yourself, which a build leaves as it is.`,
147
+ );
148
+ const taken = this.#pathOfName.get(name);
149
+ if (taken !== undefined && taken !== at)
150
+ throw new Error(
151
+ `${this.#file} \`${taken}\` and \`${at}\` are secrets a build would both read from the environment variable ${name}. Rename one of the keys.`,
152
+ );
153
+ this.#pathOfName.set(name, at);
154
+ const start = node.getStart(this.#source);
155
+ const written = this.#source.text.slice(start, node.end);
156
+ const read = `${SecretEnvSource.#binding}.${kind === "json" ? "json" : "read"}`;
157
+ const text =
158
+ this.#mode === "mark"
159
+ ? `({ ${SecretEnvSource.markKey}: [${JSON.stringify(name)}, ${JSON.stringify(kind)}, ${written}] })`
160
+ : this.#mode === "inline"
161
+ ? `${read}(${JSON.stringify(name)}, ${written})`
162
+ : `${read}(${JSON.stringify(name)})`;
163
+ const marked = this.#mode === "mark" && beside ? beside : node;
164
+ this.#edits.push({ start: marked.getStart(this.#source), end: marked.end, text });
165
+ }
166
+ }
@@ -0,0 +1,11 @@
1
+ export type ServerEnvEvaluationFailure = "threw" | "exited" | "timedOut";
2
+
3
+ export class ServerEnvEvaluationError extends Error {
4
+ constructor(
5
+ readonly reason: ServerEnvEvaluationFailure,
6
+ message: string,
7
+ ) {
8
+ super(message);
9
+ this.name = "ServerEnvEvaluationError";
10
+ }
11
+ }
@@ -250,7 +250,8 @@ describe("createServerEnvPlugin", () => {
250
250
  });
251
251
  expect(result.success).toBe(false);
252
252
  const printed = result.logs.map((log) => `${log.message}\n${log.position?.lineText ?? ""}`).join("\n");
253
- expect(printed).toContain("ReferenceError: undefinedVar is not defined");
253
+ expect(printed).toMatch(/: ReferenceError at .*libs\/util\/env\/env\.server\.testing\.ts:3\n/);
254
+ expect(printed).not.toContain("undefinedVar");
254
255
  expect(printed).not.toContain("lib-jwt-dummy-0123");
255
256
  });
256
257
 
@@ -1,6 +1,7 @@
1
1
  import { existsSync, realpathSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import type { BunPlugin, OnLoadResult } from "bun";
4
+ import { SecretEnvDeclaration } from "./secretEnvDeclaration";
4
5
  import { ServerEnvProfile } from "./serverEnvProfile";
5
6
 
6
7
  export interface ServerEnvPluginOptions {
@@ -12,6 +13,11 @@ export interface ServerEnvPluginOptions {
12
13
  profile?: string;
13
14
  /** 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
15
  onLibEnv?: (file: string, report: { profileFile: boolean; stripped: string[] }) => void;
16
+ /**
17
+ * Without a profile: `read` bundles each env file, a lib's included, with its secret strings replaced by reads of the
18
+ * process env, and `inline` keeps each string as what its read falls back to. Unset, the files are bundled as written.
19
+ */
20
+ secrets?: "read" | "inline";
15
21
  }
16
22
 
17
23
  const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -24,6 +30,7 @@ export const createServerEnvPlugin = ({
24
30
  environments,
25
31
  profile,
26
32
  onLibEnv,
33
+ secrets,
27
34
  }: ServerEnvPluginOptions): BunPlugin => {
28
35
  const others = [...new Set(environments)].filter((name) => name !== environment);
29
36
  //? Bun hands onLoad the real path, which differs from the given one under a symlink (macOS's /var -> /private/var).
@@ -64,6 +71,12 @@ export const createServerEnvPlugin = ({
64
71
  ].join("\n"),
65
72
  };
66
73
  });
74
+ //? After the stubs, which take the other environments' files first; `env.server.ts` itself is the env file where
75
+ //? a pipeline copies one over the switch.
76
+ if (secrets && !profile)
77
+ build.onLoad({ filter: ServerEnvProfile.envModulePattern }, (args) =>
78
+ SecretEnvDeclaration.source(args.path, secrets),
79
+ );
67
80
  //? Last: the app's own env files above are taken by the handlers before it, which match them first.
68
81
  if (profile)
69
82
  build.onLoad({ filter: ServerEnvProfile.envFilePattern }, async (args) => {
@@ -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',