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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (347) hide show
  1. package/DEV_RUNTIME_KNOBS.md +1 -1
  2. package/README.ko.md +7 -1
  3. package/README.md +7 -1
  4. package/akanApp/akanApp.host.test.ts +3 -1
  5. package/akanApp/akanApp.host.ts +26 -2
  6. package/akanApp/akanApp.host.wiring.test.ts +111 -0
  7. package/akanApp/devHostPolicy.ts +5 -0
  8. package/akanApp/devMetadataRestart.ts +93 -0
  9. package/akanApp/devRecycler.test.ts +2 -0
  10. package/akanApp/devRecycler.ts +9 -0
  11. package/akanConfig/akanBin.ts +4 -0
  12. package/akanConfig/akanConfig.test.ts +269 -18
  13. package/akanConfig/akanConfig.ts +104 -210
  14. package/akanConfig/akanPreview.test.ts +28 -0
  15. package/akanConfig/akanPreview.ts +24 -0
  16. package/akanConfig/akanWorkers.test.ts +73 -0
  17. package/akanConfig/akanWorkers.ts +61 -0
  18. package/akanConfig/desktopServerConfig.ts +96 -0
  19. package/akanConfig/dockerImage.ts +212 -0
  20. package/akanConfig/index.ts +3 -0
  21. package/akanConfig/nativeFileSettings.ts +33 -0
  22. package/akanConfig/types.ts +4 -0
  23. package/app/appBin.test.ts +63 -0
  24. package/app/appBin.ts +50 -0
  25. package/app/applicationBuildReporter.test.ts +51 -1
  26. package/app/applicationBuildReporter.ts +6 -1
  27. package/app/applicationBuildRunner.test.ts +358 -5
  28. package/app/applicationBuildRunner.ts +221 -31
  29. package/app/clientServerBoundary.test.ts +115 -0
  30. package/app/clientServerBoundary.ts +89 -0
  31. package/app/dictionarySizes.test.ts +40 -0
  32. package/app/dictionarySizes.ts +95 -0
  33. package/app/routeFilesReport.test.ts +59 -0
  34. package/app/routeFilesReport.ts +46 -0
  35. package/app/routeJsBudget.ts +18 -4
  36. package/artifact/implicitRootLayout.test.ts +19 -0
  37. package/artifact/implicitRootLayout.ts +16 -2
  38. package/artifact/implicitRootLayoutRender.test.tsx +4 -1
  39. package/artifact/storeBootstrap.test.ts +28 -0
  40. package/artifact/storeBootstrap.ts +64 -8
  41. package/biome.base.json +7 -5
  42. package/codeAgent/index.ts +1 -34
  43. package/codeAgent/skills/akan-agent/SKILL.md +2 -2
  44. package/codeAgent/skills/akan-debug/SKILL.md +8 -3
  45. package/codeAgent/skills/akan-deps/SKILL.md +10 -3
  46. package/codeAgent/skills/akan-err/SKILL.md +13 -8
  47. package/codeAgent/skills/akan-mcp/SKILL.md +1 -1
  48. package/codeAgent/skills/akan-module/SKILL.md +2 -2
  49. package/codeAgent/skills/akan-page/SKILL.md +65 -30
  50. package/codeAgent/skills/akan-query/SKILL.md +13 -20
  51. package/codeAgent/skills/akan-runtime/SKILL.md +21 -1
  52. package/codeAgent/skills/akan-service/SKILL.md +21 -20
  53. package/codeAgent/skills/akan-transport/SKILL.md +5 -14
  54. package/codeAgent/skills/akan-ui/SKILL.md +16 -21
  55. package/codeAgent/skills/akan-validate/SKILL.md +8 -2
  56. package/commandDecorators/command.ts +28 -12
  57. package/commandDecorators/commandBuilder.ts +8 -1
  58. package/commandDecorators/commandDecorators.test.ts +70 -3
  59. package/commandDecorators/helpFormatter.ts +14 -12
  60. package/context/akanContext.ts +2 -0
  61. package/csrE2e/devHmrLatency.e2e.test.ts +1 -1
  62. package/csrE2e/ssrRegistry.e2e.test.ts +108 -22
  63. package/docs/apiReference.test.ts +25 -0
  64. package/docs/apiReference.ts +38 -5
  65. package/docs/declarationReader.ts +30 -0
  66. package/executors/appExecutor.ts +26 -12
  67. package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
  68. package/executors/clientRuntimeKeys.fixture.json +393 -0
  69. package/executors/clientRuntimeKeys.test.ts +1690 -0
  70. package/executors/executor.ts +14 -6
  71. package/executors/executors.test.ts +155 -1
  72. package/executors/pkgExecutor.ts +2 -1
  73. package/executors/sysExecutor.ts +112 -8
  74. package/executors/workspaceExecutor.ts +7 -4
  75. package/frontendBuild/allRoutesBuilder.ts +99 -7
  76. package/frontendBuild/autoImportSync.ts +3 -2
  77. package/frontendBuild/buildRouteClient.test.ts +684 -6
  78. package/frontendBuild/clientBuildTypes.ts +26 -0
  79. package/frontendBuild/clientEntriesBundler.ts +49 -1
  80. package/frontendBuild/clientEntryDiscovery.test.ts +308 -1
  81. package/frontendBuild/clientEntryDiscovery.ts +134 -12
  82. package/frontendBuild/clientEntryGroups.test.ts +77 -0
  83. package/frontendBuild/clientEntryGroups.ts +61 -0
  84. package/frontendBuild/csrDevArtifactWriter.ts +2 -2
  85. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  86. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  87. package/frontendBuild/csrDevPatcher.test.ts +4 -5
  88. package/frontendBuild/csrDevPatcher.ts +37 -11
  89. package/frontendBuild/csrDevTypes.ts +9 -0
  90. package/frontendBuild/devBarrelImports.test.ts +124 -0
  91. package/frontendBuild/devBarrelImports.ts +81 -21
  92. package/frontendBuild/devChangePlanner.ts +0 -1
  93. package/frontendBuild/devRegistryBundler.ts +4 -2
  94. package/frontendBuild/devRouteRuntime.test.ts +492 -0
  95. package/frontendBuild/devRouteRuntime.ts +167 -0
  96. package/frontendBuild/dictionaryAssetBuilder.test.ts +408 -0
  97. package/frontendBuild/dictionaryAssetBuilder.ts +185 -17
  98. package/frontendBuild/dictionaryConstants.ts +136 -0
  99. package/frontendBuild/dictionaryOwnParts.ts +88 -0
  100. package/frontendBuild/dictionaryPackState.ts +131 -0
  101. package/frontendBuild/dictionaryPacking.test.ts +207 -0
  102. package/frontendBuild/dictionaryPacking.ts +160 -0
  103. package/frontendBuild/dictionaryRoutes.test.ts +251 -0
  104. package/frontendBuild/dictionaryRoutes.ts +227 -0
  105. package/frontendBuild/frontendBuild.test.ts +5 -3
  106. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  107. package/frontendBuild/pagesBundleBuilder.ts +78 -2
  108. package/frontendBuild/precompressArtifacts.test.ts +22 -0
  109. package/frontendBuild/precompressArtifacts.ts +34 -8
  110. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  111. package/frontendBuild/renderedEntries.ts +144 -0
  112. package/frontendBuild/routeClientBuilder.ts +407 -43
  113. package/frontendBuild/routeHandoffs.test.ts +155 -0
  114. package/frontendBuild/routeHandoffs.ts +117 -0
  115. package/frontendBuild/routeModulePreloads.test.ts +32 -0
  116. package/frontendBuild/routeModulePreloads.ts +20 -11
  117. package/frontendBuild/routeRuntimeCheck.test.ts +280 -0
  118. package/frontendBuild/routeRuntimeCheck.ts +248 -0
  119. package/frontendBuild/routeRuntimePays.test.ts +143 -0
  120. package/frontendBuild/routeRuntimePays.ts +117 -0
  121. package/frontendBuild/ssrBaseArtifactBuilder.ts +30 -35
  122. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  123. package/frontendBuild/ssrDevBundler.ts +66 -11
  124. package/frontendBuild/vendorFileImports.test.ts +254 -0
  125. package/frontendBuild/vendorFileImports.ts +163 -0
  126. package/frontendBuild/vendorNarrowing.test.ts +47 -3
  127. package/frontendBuild/vendorNarrowing.ts +38 -2
  128. package/frontendBuild/vendorSpecifiers.ts +2 -0
  129. package/guideline/agentAssets.ts +1 -1
  130. package/incrementalBuilder/buildBatch.proc.ts +27 -1
  131. package/incrementalBuilder/buildBatchProtocol.ts +1 -0
  132. package/incrementalBuilder/builderWatch.ts +11 -1
  133. package/incrementalBuilder/incrementalBuilder.proc.test.ts +159 -0
  134. package/incrementalBuilder/incrementalBuilder.proc.ts +31 -3
  135. package/incrementalBuilder/pendingMetadata.test.ts +27 -0
  136. package/incrementalBuilder/pendingMetadata.ts +19 -0
  137. package/integration/devStability.integration.test.ts +46 -21
  138. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  139. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  140. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  141. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  142. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  143. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  144. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  145. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  146. package/lint/biomeBase.test.ts +50 -3
  147. package/lint/biomeBase.ts +1 -1
  148. package/lint/biomeCheck.test.ts +162 -0
  149. package/lint/biomeCheck.ts +131 -0
  150. package/lint/linter.test.ts +16 -11
  151. package/lint/no-arbitrary-color.grit +5 -0
  152. package/lint/no-conditional-st-hook.grit +5 -1
  153. package/lint/no-daisyui-legacy-class.grit +8 -0
  154. package/lint/no-document-cookie.grit +3 -0
  155. package/lint/no-inline-color.grit +10 -2
  156. package/lint/no-oversized-list-limit.grit +2 -0
  157. package/lint/no-raw-palette-class.grit +7 -0
  158. package/lint/no-unpublished-form-setter.grit +2 -0
  159. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  160. package/lint/no-web-storage.grit +3 -0
  161. package/lint/withheldEnvFile.ts +17 -0
  162. package/mobile/desktopBin.ts +2 -2
  163. package/mobile/desktopServerStage.test.ts +18 -3
  164. package/mobile/desktopServerStage.ts +7 -2
  165. package/mobile/nativeApp.test.ts +7 -5
  166. package/mobile/nativeApp.ts +2 -2
  167. package/mobile/nativeConfig.test.ts +17 -1
  168. package/mobile/nativeConfig.ts +11 -6
  169. package/mobile/nativePublicEnv.ts +1 -1
  170. package/mobile/serverBundleSecrets.ts +43 -0
  171. package/package.json +11 -12
  172. package/packageExports.test.ts +3 -2
  173. package/preview/PreviewView.ts +25 -3
  174. package/quality/dictionaryKeys.test.ts +356 -0
  175. package/quality/dictionaryKeys.ts +488 -0
  176. package/quality/objectImportReport.test.ts +36 -0
  177. package/quality/objectImportReport.ts +105 -0
  178. package/quality/qualityScanner.ts +1 -1
  179. package/quality/routeRuntimeReport.test.ts +91 -0
  180. package/quality/routeRuntimeReport.ts +121 -0
  181. package/quality/runtimeConstantFacts.ts +71 -0
  182. package/quality/runtimeConstantGraph.ts +123 -0
  183. package/quality/runtimeConstantReads.ts +116 -0
  184. package/quality/runtimeImports.test.ts +190 -0
  185. package/quality/runtimeImports.ts +233 -0
  186. package/quality/runtimeKeyNames.ts +46 -0
  187. package/quality/runtimeLexicalScope.ts +132 -0
  188. package/quality/runtimeMarkerReach.test.ts +84 -0
  189. package/quality/runtimeMarkerReach.ts +255 -0
  190. package/quality/runtimeModuleFacts.ts +290 -0
  191. package/quality/runtimeNameTable.test.ts +172 -0
  192. package/quality/runtimeNameTable.ts +477 -0
  193. package/quality/runtimeScopeReport.test.ts +123 -0
  194. package/quality/runtimeScopeReport.ts +167 -0
  195. package/quality/runtimeSliceKey.ts +269 -0
  196. package/quality/runtimeSyntax.ts +133 -0
  197. package/quality/runtimeTable.fixture.ts +189 -0
  198. package/quality/runtimeUse.test.ts +737 -0
  199. package/quality/runtimeUse.ts +696 -0
  200. package/quality/runtimeUseReadable.test.ts +393 -0
  201. package/quality/ssrScanner.test.ts +13 -0
  202. package/quality/ssrScanner.ts +1 -1
  203. package/quality/translatorBindings.ts +187 -0
  204. package/test/fakeTerminal.ts +45 -0
  205. package/test/secretEnvFixture.ts +134 -0
  206. package/test/testHelpers.ts +11 -0
  207. package/transforms/barrelAnalyzer.ts +24 -2
  208. package/transforms/barrelImportsPlugin.ts +121 -32
  209. package/transforms/exportReach.test.ts +162 -0
  210. package/transforms/exportReach.ts +308 -0
  211. package/transforms/frameworkObjects.fixture.tsx +58 -0
  212. package/transforms/frameworkObjects.test.ts +54 -0
  213. package/transforms/modelReference.test.ts +196 -0
  214. package/transforms/modelReference.ts +39 -0
  215. package/transforms/moduleParts.test.ts +225 -0
  216. package/transforms/moduleParts.ts +418 -0
  217. package/transforms/objectImportEdits.ts +150 -0
  218. package/transforms/objectMemberImports.test.ts +633 -0
  219. package/transforms/objectMemberImports.ts +571 -0
  220. package/transforms/objectMemberLookup.ts +150 -0
  221. package/transforms/objectModule.test.ts +307 -0
  222. package/transforms/objectModule.ts +482 -0
  223. package/transforms/objectModuleAnalyzer.ts +104 -0
  224. package/transforms/partImports.test.ts +76 -0
  225. package/transforms/partImports.ts +110 -0
  226. package/transforms/partModules.test.ts +187 -0
  227. package/transforms/partModules.ts +90 -0
  228. package/transforms/partPurity.ts +124 -0
  229. package/transforms/reactIconImports.test.ts +231 -0
  230. package/transforms/reactIconImports.ts +325 -0
  231. package/transforms/routeConstants.ts +122 -0
  232. package/transforms/routeRuntime.test.ts +835 -0
  233. package/transforms/routeRuntime.ts +703 -0
  234. package/transforms/routeRuntimeEdits.ts +92 -0
  235. package/transforms/routeRuntimeGraph.ts +66 -0
  236. package/transforms/routeRuntimePlan.ts +244 -0
  237. package/transforms/secretEnvDeclaration.test.ts +208 -0
  238. package/transforms/secretEnvDeclaration.ts +213 -0
  239. package/transforms/secretEnvFile.test.ts +117 -0
  240. package/transforms/secretEnvFile.ts +113 -0
  241. package/transforms/secretEnvName.test.ts +54 -0
  242. package/transforms/secretEnvName.ts +29 -0
  243. package/transforms/secretEnvSource.test.ts +148 -0
  244. package/transforms/secretEnvSource.ts +166 -0
  245. package/transforms/serverEnvEvaluationError.ts +11 -0
  246. package/transforms/serverEnvPlugin.test.ts +2 -1
  247. package/transforms/serverEnvPlugin.ts +13 -0
  248. package/transforms/serverEnvProfile.test.ts +129 -2
  249. package/transforms/serverEnvProfile.ts +126 -40
  250. package/transforms/serverEnvSecrets.test.ts +292 -0
  251. package/transforms/signalDescriptors.test.ts +280 -0
  252. package/transforms/signalDescriptors.ts +227 -0
  253. package/transforms/thisFreeExports.ts +87 -0
  254. package/transforms/transforms.test.ts +177 -0
  255. package/transforms/tsconfigPackageResolver.test.ts +1 -0
  256. package/tunnel/createTunnel.ts +5 -1
  257. package/tunnel/ssh2Module.test.ts +37 -0
  258. package/tunnel/ssh2Module.ts +28 -0
  259. package/tunnel/sshTunnel.ts +4 -2
  260. package/typecheck/projectTypecheck.test.ts +32 -1
  261. package/typecheck/projectTypecheck.ts +3 -3
  262. package/typecheck/typeChecker.test.ts +49 -0
  263. package/typecheck/typeChecker.ts +9 -7
  264. package/typecheck/withheldDiagnostics.ts +41 -0
  265. package/util/devInstallCommand.ts +7 -0
  266. package/util/jsonFormatter.test.ts +13 -9
  267. package/workflow/executor.ts +6 -2
  268. package/workflow/index.ts +1 -0
  269. package/workflow/plan.ts +36 -7
  270. package/workflow/types.ts +1 -1
  271. package/workflow/uiTarget.ts +50 -0
  272. package/workspace/envSeed.test.ts +30 -1
  273. package/workspace/envSeed.ts +30 -1
  274. package/workspace/mainCheckout.test.ts +55 -0
  275. package/workspace/mainCheckout.ts +38 -0
  276. package/workspace/scanInfo.test.ts +39 -0
  277. package/workspace/scanInfo.ts +55 -6
  278. package/workspace/slicePlanner.ts +2 -1
  279. package/workspace/workspaceLayout.test.ts +22 -1
  280. package/workspace/workspaceLayout.ts +3 -3
  281. package/CHANGELOG.md +0 -2904
  282. package/codeAgent/agent/AkanCodeCompaction.ts +0 -49
  283. package/codeAgent/agent/AkanCodeServices.ts +0 -122
  284. package/codeAgent/agent/AkanContextFiles.ts +0 -94
  285. package/codeAgent/agent/CodeAgent.ts +0 -626
  286. package/codeAgent/agent/CodeAgentAllowed.ts +0 -35
  287. package/codeAgent/agent/CodeAgentAsks.ts +0 -66
  288. package/codeAgent/agent/CodeAgentCommandLine.ts +0 -372
  289. package/codeAgent/agent/CodeAgentEventMapper.ts +0 -225
  290. package/codeAgent/agent/CodeAgentGate.ts +0 -258
  291. package/codeAgent/agent/CodeAgentProxy.ts +0 -83
  292. package/codeAgent/agent/CodeAgentRpcHost.ts +0 -109
  293. package/codeAgent/agent/CodeAgentRpcListener.ts +0 -195
  294. package/codeAgent/agent/CodeAgentStreamPrinter.ts +0 -86
  295. package/codeAgent/agent/CodeAgentSuspended.ts +0 -85
  296. package/codeAgent/agent/CodeAgentUi.ts +0 -47
  297. package/codeAgent/agent/CodeMailbox.ts +0 -148
  298. package/codeAgent/agent/CodeSessionFork.ts +0 -56
  299. package/codeAgent/agent/CodeSessionIndex.ts +0 -78
  300. package/codeAgent/agent/SubagentPool.ts +0 -219
  301. package/codeAgent/agent/WorkspaceTrust.ts +0 -200
  302. package/codeAgent/agent/akanCodeCompaction.test.ts +0 -36
  303. package/codeAgent/agent/akanCodeModel.ts +0 -47
  304. package/codeAgent/agent/akanCodeServices.test.ts +0 -54
  305. package/codeAgent/agent/akanContextFiles.test.ts +0 -116
  306. package/codeAgent/agent/akanSystemPrompt.ts +0 -50
  307. package/codeAgent/agent/codeAgent.test.ts +0 -337
  308. package/codeAgent/agent/codeAgentCommandLine.test.ts +0 -212
  309. package/codeAgent/agent/codeAgentContract.test.ts +0 -755
  310. package/codeAgent/agent/codeAgentHosts.ts +0 -30
  311. package/codeAgent/agent/codeAgentProxy.test.ts +0 -126
  312. package/codeAgent/agent/codeAgentRpcListener.test.ts +0 -215
  313. package/codeAgent/agent/codeAgentSuspended.test.ts +0 -47
  314. package/codeAgent/agent/codeMailbox.test.ts +0 -76
  315. package/codeAgent/agent/codeSessionFork.test.ts +0 -58
  316. package/codeAgent/agent/codeSessionIndex.test.ts +0 -77
  317. package/codeAgent/agent/consoleToStderr.ts +0 -8
  318. package/codeAgent/agent/jsonLines.ts +0 -29
  319. package/codeAgent/agent/stringArg.ts +0 -5
  320. package/codeAgent/feedback/DevLogFeedback.ts +0 -82
  321. package/codeAgent/feedback/PreviewFeedback.ts +0 -46
  322. package/codeAgent/feedback/TurnFeedback.ts +0 -98
  323. package/codeAgent/feedback/VerifyFeedback.ts +0 -39
  324. package/codeAgent/tools/AkanCli.ts +0 -51
  325. package/codeAgent/tools/AkanCodePlugins.ts +0 -142
  326. package/codeAgent/tools/AkanEditScope.ts +0 -53
  327. package/codeAgent/tools/AkanEnvKeys.ts +0 -50
  328. package/codeAgent/tools/AkanToolPack.ts +0 -86
  329. package/codeAgent/tools/AkanVerifier.ts +0 -30
  330. package/codeAgent/tools/AskToolPack.ts +0 -99
  331. package/codeAgent/tools/DeepSeekWeb.ts +0 -127
  332. package/codeAgent/tools/MailToolPack.ts +0 -76
  333. package/codeAgent/tools/McpClient.ts +0 -209
  334. package/codeAgent/tools/McpOAuth.ts +0 -233
  335. package/codeAgent/tools/McpOAuthLoopback.ts +0 -64
  336. package/codeAgent/tools/McpServerConfig.ts +0 -131
  337. package/codeAgent/tools/McpSignIn.ts +0 -158
  338. package/codeAgent/tools/McpTokenStore.ts +0 -128
  339. package/codeAgent/tools/McpToolPack.ts +0 -206
  340. package/codeAgent/tools/SessionToolPack.ts +0 -91
  341. package/codeAgent/tools/WebToolPack.ts +0 -315
  342. package/codeAgent/tools/akanCodePlugins.test.ts +0 -954
  343. package/codeAgent/tools/askToolPack.test.ts +0 -116
  344. package/codeAgent/tools/deepSeekWeb.test.ts +0 -113
  345. package/codeAgent/tools/mcpOAuth.test.ts +0 -648
  346. package/codeAgent/tools/mcpServerConfig.test.ts +0 -341
  347. package/piDependencyPins.test.ts +0 -45
@@ -0,0 +1,134 @@
1
+ import path from "node:path";
2
+ import { writeText } from "./testHelpers";
3
+
4
+ const environments = ["local", "main"] as const;
5
+
6
+ export const secretEnvSentinels = {
7
+ jwt: "sentinel-jwt-2f0c",
8
+ google: "sentinel-google-91ab",
9
+ bots: ["sentinel-bot-a-44d1", "sentinel-bot-b-55e2"],
10
+ webhook: "https://hooks.example.test/services/sentinel-hook-66f3",
11
+ pem: "-----BEGIN PRIVATE KEY-----\nsentinel-pem-line-one-aa17\nsentinel-pem-line-two-bb28\n-----END PRIVATE KEY-----\n",
12
+ postgres: "postgres://app:sentinel-db-pass-77a4@db.example.test:5432/app",
13
+ storage: "https://minio:sentinel-url-pass-cc39@storage.example.test",
14
+ dollar: ["sentinel-$HOME-", '"quoted"-$', "{USER}-dd40"].join(""),
15
+ apostrophe: "sentinel-it's-$1-ee51",
16
+ libPass: "sentinel-lib-pass-88b5",
17
+ libJwt: "sentinel-lib-jwt-99c6",
18
+ local: "sentinel-local-llm-ff62",
19
+ };
20
+
21
+ export const secretEnvPlain = { hostname: "app.example.test", clientID: "plain-client-id", region: "ap-northeast-2" };
22
+
23
+ const s = secretEnvSentinels;
24
+
25
+ const mainEnv = (extra = "", head = "") => `${head}import { libEnv } from "./env.server.type";
26
+
27
+ export const env = {
28
+ ...libEnv,
29
+ hostname: ${JSON.stringify(secretEnvPlain.hostname)},
30
+ security: {
31
+ jwtSecret: ${JSON.stringify(s.jwt)},
32
+ verifies: [["password"], ["email"]],
33
+ accessTokenSeconds: 900,
34
+ sso: { google: { clientID: ${JSON.stringify(secretEnvPlain.clientID)}, clientSecret: ${JSON.stringify(s.google)} } },
35
+ },
36
+ objectStorage: { region: ${JSON.stringify(secretEnvPlain.region)}, endpoint: ${JSON.stringify(s.storage)} },
37
+ discord: { tokens: ${JSON.stringify(s.bots)}, webhook: ${JSON.stringify(s.webhook)} },
38
+ pushNoti: { firebase: { type: "service_account", private_key: ${JSON.stringify(s.pem)} } },
39
+ message: { apiSecret: ${JSON.stringify(s.dollar)}, senderPassword: ${JSON.stringify(s.apostrophe)} },
40
+ database: { postgres: { url: process.env.DATABASE_URL ?? ${JSON.stringify(s.postgres)} } },${extra}
41
+ } as const;
42
+ `;
43
+
44
+ export interface SecretEnvFixture {
45
+ appDir: string;
46
+ envDir: string;
47
+ libEnvFile: string;
48
+ }
49
+
50
+ export const writeSecretEnvFixture = async (
51
+ root: string,
52
+ { app = "demo", mainExtra = "", mainHead = "" } = {},
53
+ ): Promise<SecretEnvFixture> => {
54
+ const appDir = path.join(root, "apps", app);
55
+ const envDir = path.join(appDir, "env");
56
+ const libEnvFile = path.join(root, "libs/util/env/env.server.testing.ts");
57
+ await writeText(
58
+ path.join(envDir, "env.server.ts"),
59
+ [
60
+ ...environments.map((name) => `import { env as ${name} } from "./env.server.${name}";`),
61
+ `const envConfigs = { ${environments.join(", ")} };`,
62
+ 'const currentEnv = process.env.AKAN_PUBLIC_ENV ?? "local";',
63
+ "export const env = envConfigs[currentEnv as keyof typeof envConfigs];",
64
+ "",
65
+ ].join("\n"),
66
+ );
67
+ await writeText(
68
+ path.join(envDir, "env.server.type.ts"),
69
+ `import { env as utilOption } from ${JSON.stringify(libEnvFile)};\n\nexport const libEnv = { ...utilOption };\n`,
70
+ );
71
+ await writeText(
72
+ libEnvFile,
73
+ `export const env = {\n hostname: null,\n security: { jwtSecret: ${JSON.stringify(s.libJwt)}, verifies: [["password"]] },\n mailer: { address: "noreply@example.test", auth: { user: "mailer", pass: ${JSON.stringify(s.libPass)} } },\n};\n`,
74
+ );
75
+ await writeText(path.join(envDir, "env.server.main.ts"), mainEnv(mainExtra, mainHead));
76
+ await writeText(
77
+ path.join(envDir, "env.server.local.ts"),
78
+ `export const env = { hostname: "localhost", llm: { apiKey: ${JSON.stringify(s.local)} } };\n`,
79
+ );
80
+ return { appDir, envDir, libEnvFile };
81
+ };
82
+
83
+ export const secretEnvFixtureNames = [
84
+ "JWT_SECRET",
85
+ "SECURITY__SSO__GOOGLE__CLIENT_SECRET",
86
+ "MAILER__AUTH__PASS",
87
+ "OBJECT_STORAGE__ENDPOINT",
88
+ "DISCORD__TOKENS",
89
+ "DISCORD__WEBHOOK",
90
+ "PUSH_NOTI__FIREBASE__PRIVATE_KEY",
91
+ "MESSAGE__API_SECRET",
92
+ "MESSAGE__SENDER_PASSWORD",
93
+ "POSTGRES_URL",
94
+ ];
95
+
96
+ export const holdsSentinel = (text: string) => text.includes("sentinel-");
97
+
98
+ //* What no search of a build's files tells from code: a short password, a passphrase of plain words, a value under
99
+ //* eight characters, and a plain-named key under a secret-named one.
100
+ export const computedSecrets = {
101
+ password: "sentinel-12c",
102
+ passphrase: "sentinel-correct-horse-battery-xyzz",
103
+ short: "s9-k2",
104
+ user: "sentinel-user",
105
+ };
106
+
107
+ //* One string under a secret-named key and a plain one: a long mixed one, a short one, and one under eight characters.
108
+ export const twinSecrets = { long: "sentinel-Twin-7d21-Xq", plain: "sentinel-db", short: "s-pin" };
109
+
110
+ export const twinSecretEnv = [
111
+ "",
112
+ ` audit: { password: ${JSON.stringify(twinSecrets.long)}, label: ${JSON.stringify(twinSecrets.long)} },`,
113
+ ` cache: { password: ${JSON.stringify(twinSecrets.plain)}, name: ${JSON.stringify(twinSecrets.plain)} },`,
114
+ ` door: { secret: ${JSON.stringify(twinSecrets.short)}, hint: ${JSON.stringify(twinSecrets.short)} },`,
115
+ ].join("\n");
116
+
117
+ export const computedSecretKeys = ["store.password", "store.passphrase", "otp.secret", "credentials.user"];
118
+
119
+ export const writeComputedSecretFixture = async (root: string, app = "demo"): Promise<SecretEnvFixture> => {
120
+ await writeText(
121
+ path.join(root, "apps", app, "srvkit/keys.ts"),
122
+ `export const keys = ${JSON.stringify({ password: computedSecrets.password, passphrase: computedSecrets.passphrase, user: computedSecrets.user })};\n`,
123
+ );
124
+ return await writeSecretEnvFixture(root, {
125
+ app,
126
+ mainHead: 'import { keys } from "../srvkit/keys";\n',
127
+ mainExtra: [
128
+ "",
129
+ " store: { password: keys.password, passphrase: keys.passphrase },",
130
+ ` otp: { secret: ${JSON.stringify(computedSecrets.short.split("-"))}.join("-") },`,
131
+ " credentials: { user: keys.user },",
132
+ ].join("\n"),
133
+ });
134
+ };
@@ -129,6 +129,17 @@ export const writeJson = async (filePath: string, value: object) => {
129
129
  await writeText(filePath, `${JSON.stringify(value, null, 2)}\n`);
130
130
  };
131
131
 
132
+ export const printedInOwnProcess = async (script: string, cwd: string): Promise<unknown> => {
133
+ const proc = Bun.spawn([process.execPath, "--eval", script], { cwd, stdout: "pipe", stderr: "pipe" });
134
+ const [code, stdout, stderr] = await Promise.all([
135
+ proc.exited,
136
+ new Response(proc.stdout).text(),
137
+ new Response(proc.stderr).text(),
138
+ ]);
139
+ if (code !== 0) throw new Error(`the script exited with code ${code}:\n${stderr}`);
140
+ return JSON.parse(stdout.trim().split("\n").at(-1) ?? "null");
141
+ };
142
+
132
143
  export const heldMtimeIndex = () => {
133
144
  const primes: PromiseWithResolvers<void>[] = [];
134
145
  const scans: PromiseWithResolvers<string[]>[] = [];
@@ -20,12 +20,16 @@ export interface PackageEntry {
20
20
  pkgDir: string;
21
21
  /** Emit absolute file paths: an installed package's exports name its barrels, never the files behind them. */
22
22
  preserveFilePath?: boolean;
23
+ /** The installed package's own folder: its entry may re-export a file beside the entry's folder (`../vendor/x`). */
24
+ rootDir?: string;
23
25
  }
24
26
 
25
27
  export interface BarrelAnalyzerOptions {
26
28
  resolvePackage: (pkgName: string) => Promise<PackageEntry | null>;
27
29
  /** Resolves to an absolute file path on disk. */
28
30
  resolveRelative?: (fromFile: string, relSpec: string) => Promise<string | null>;
31
+ /** Maps a name the barrel entry re-exports from a package to that package, when it resolves the same from here. */
32
+ packageRoot?: string;
29
33
  }
30
34
 
31
35
  // `Transpiler.scan` gives the export names but not their sources; this regex supplies the name↔source mapping.
@@ -145,7 +149,11 @@ export class BarrelAnalyzer {
145
149
  const nsAs = m[2];
146
150
  const namedList = m[3];
147
151
  const spec = m[5] ?? "";
148
- if (!isRelative(spec)) continue;
152
+ if (!isRelative(spec)) {
153
+ if (namedList !== undefined && absFile === pkg.entryFile && this.#isSamePackage(spec, absFile))
154
+ attribute(namedList, spec);
155
+ continue;
156
+ }
149
157
 
150
158
  if (star) {
151
159
  if (!nsAs) starSpecs.push(spec);
@@ -210,7 +218,11 @@ export class BarrelAnalyzer {
210
218
 
211
219
  #subpathFor(pkg: PackageEntry, absFile: string): string | null {
212
220
  const rel = path.relative(pkg.pkgDir, absFile);
213
- if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return null;
221
+ if (!rel || path.isAbsolute(rel)) return null;
222
+ if (rel.startsWith("..")) {
223
+ const inPackage = pkg.preserveFilePath && pkg.rootDir ? path.relative(pkg.rootDir, absFile) : "..";
224
+ if (inPackage.startsWith("..") || path.isAbsolute(inPackage)) return null;
225
+ }
214
226
  if (pkg.preserveFilePath) return absFile.split(path.sep).join("/");
215
227
  const ext = CANDIDATE_EXTS.find((candidate) => rel.endsWith(candidate));
216
228
  const parts = (ext ? rel.slice(0, -ext.length) : rel).split(path.sep);
@@ -220,6 +232,16 @@ export class BarrelAnalyzer {
220
232
  return tail === "" ? pkg.pkgName : `${pkg.pkgName}/${tail}`;
221
233
  }
222
234
 
235
+ #isSamePackage(spec: string, absFile: string): boolean {
236
+ const root = this.#opts.packageRoot;
237
+ if (!root) return false;
238
+ try {
239
+ return Bun.resolveSync(spec, path.dirname(absFile)) === Bun.resolveSync(spec, root);
240
+ } catch {
241
+ return false;
242
+ }
243
+ }
244
+
223
245
  async #resolveRel(fromFile: string, relSpec: string): Promise<string | null> {
224
246
  if (this.#opts.resolveRelative) return this.#opts.resolveRelative(fromFile, relSpec);
225
247
  return defaultResolveRelative(fromFile, relSpec);
@@ -4,7 +4,11 @@ import ts from "typescript";
4
4
  import { StoreBootstrap } from "../artifact/storeBootstrap";
5
5
  import type { App } from "../commandDecorators";
6
6
  import { BarrelAnalyzer, type BarrelExportMap, type PackageEntry } from "./barrelAnalyzer";
7
+ import { ModuleParts } from "./moduleParts";
7
8
  import { loaderFor, type NamedItem } from "./moduleSyntax";
9
+ import { ObjectMemberImports } from "./objectMemberImports";
10
+ import { PartModules, type PartSource } from "./partModules";
11
+ import type { RouteRuntime } from "./routeRuntime";
8
12
 
9
13
  export interface BarrelImportsPluginOptions {
10
14
  /** Absolute paths whose content is returned unchanged (e.g. node_modules). */
@@ -13,53 +17,101 @@ export interface BarrelImportsPluginOptions {
13
17
  pipeAfter?: (source: string, args: { path: string }) => string | Promise<string | null> | null;
14
18
  /** Barrels the bundle leaves external: a rewritten import would inline the modules the import map already serves. */
15
19
  external?: readonly string[];
16
- /** The barrels to rewrite, instead of the app config's `barrelImports`. */
20
+ /** The barrels to rewrite, instead of the app config's `barrelImports`: a CSR bundle's, which narrows no object or package barrel by member. */
17
21
  barrels?: readonly string[];
22
+ /** What `akanjs/ui/modelRuntime` holds instead of its empty source, in a build loading only the page runtime. */
23
+ modelRuntime?: string;
24
+ /** Gives each client module the runtime pieces of the modules it names, in a build loading only the page runtime. */
25
+ routeRuntime?: RouteRuntime | null;
26
+ /** Takes each workspace file apart by export, so a chunk holds the exports asked for; holds the parts read so far. */
27
+ parts?: Map<string, ModuleParts | null>;
18
28
  }
19
29
 
20
30
  export const createBarrelImportsPlugin = async (
21
31
  app: App,
22
- { skipPath = defaultSkipPath, pipeAfter, external = [], barrels: only }: BarrelImportsPluginOptions = {},
32
+ {
33
+ skipPath = defaultSkipPath,
34
+ pipeAfter,
35
+ external = [],
36
+ barrels: only,
37
+ modelRuntime,
38
+ routeRuntime,
39
+ parts,
40
+ }: BarrelImportsPluginOptions = {},
23
41
  ): Promise<BunPlugin> => {
24
42
  const barrels = [...new Set(only ?? (await app.getConfig()).barrelImports)].filter(
25
43
  (barrel) => barrel && !external.includes(barrel),
26
44
  );
45
+ const route = !only;
46
+ const resolvePackage = await createTsconfigPackageResolver(app);
27
47
  const analyzer = new BarrelAnalyzer({
28
- resolvePackage: await createTsconfigPackageResolver(app),
48
+ resolvePackage,
49
+ ...(route ? { packageRoot: app.workspace.workspaceRoot } : {}),
29
50
  });
51
+ const resolve = ObjectMemberImports.resolverOf(resolvePackage);
52
+ const objects = route ? new ObjectMemberImports({ resolve, barrels: { names: barrels, analyzer } }) : null;
53
+
54
+ const read = async (realPath: string): Promise<PartSource | null> => {
55
+ const file = Bun.file(realPath);
56
+ //? A build's `files` entry has no copy on disk: Bun loads it itself.
57
+ if (!(await file.exists())) return null;
58
+ if (modelRuntime !== undefined && StoreBootstrap.modelRuntimeFilter.test(realPath))
59
+ return { source: modelRuntime, settled: true };
60
+ const whole = routeRuntime?.redirectOf(realPath);
61
+ if (whole) return { source: whole, settled: true };
62
+ let source = await file.text();
63
+ if (skipPath(realPath)) return { source, settled: true };
64
+
65
+ // Bun's macro evaluator races when a rewritten module holds `with { type: "macro" }` imports while another
66
+ // macro host evaluates (a macro identifier ends up undefined), so macro hosts keep their barrel imports.
67
+ const macroHost = MACRO_ATTR_RE.test(source);
68
+ if (!macroHost) {
69
+ const routed = routeRuntime?.transform(source, realPath);
70
+ if (routed) source = routed.source;
71
+ const rewritten =
72
+ barrels.length > 0
73
+ ? await rewriteBarrelImports(source, barrels, analyzer, {
74
+ perModule: routed?.perModule,
75
+ reexports: route,
76
+ })
77
+ : null;
78
+ if (rewritten !== null) source = rewritten;
79
+ const narrowed = await objects?.rewrite(source, realPath);
80
+ if (narrowed?.contents) source = narrowed.contents;
81
+ }
82
+
83
+ if (pipeAfter) {
84
+ const piped = await pipeAfter(source, { path: realPath });
85
+ if (piped !== null) source = piped;
86
+ }
87
+
88
+ return { source, settled: macroHost };
89
+ };
90
+ const partModules =
91
+ parts && route
92
+ ? new PartModules({ workspaceRoot: app.workspace.workspaceRoot, resolve, read, cache: parts })
93
+ : null;
30
94
 
31
95
  return {
32
96
  name: "barrel-imports",
33
97
  setup(build) {
98
+ if (partModules) build.onResolve({ filter: ModuleParts.specifier }, ({ path: asked }) => ({ path: asked }));
34
99
  // node_modules/akanjs stays in: framework `"use client"` modules still need RSC stubbing in generated workspaces.
35
100
  // The optional `?v=N` tail matches HMR cache-busted paths; it is stripped before reading.
36
101
  build.onLoad(
37
102
  {
38
103
  filter:
39
- /^(?:(?!.*[\\/]node_modules[\\/]).*|.*[\\/]node_modules[\\/]akanjs[\\/].*)\.(tsx|ts|jsx|js)(\?v=\d+)?$/,
104
+ /^(?:(?!.*[\\/]node_modules[\\/]).*|.*[\\/]node_modules[\\/]akanjs[\\/].*)\.(tsx|ts|jsx|js)(\?v=\d+|\?akan-part=[\w$]+)?$/,
40
105
  },
41
106
  async (args) => {
42
107
  const realPath = args.path.replace(/\?v=\d+$/, "");
43
- const loader = loaderFor(realPath);
44
- const file = Bun.file(realPath);
45
- //? A build's `files` entry has no copy on disk: Bun loads it itself.
46
- if (!(await file.exists())) return undefined;
47
- let source = await file.text();
48
- if (skipPath(realPath)) return { contents: source, loader };
49
-
50
- // Bun's macro evaluator races when a rewritten module holds `with { type: "macro" }` imports while another
51
- // macro host evaluates (a macro identifier ends up undefined), so macro hosts keep their barrel imports.
52
- if (!MACRO_ATTR_RE.test(source) && barrels.length > 0) {
53
- const rewritten = await rewriteBarrelImports(source, barrels, analyzer);
54
- if (rewritten !== null) source = rewritten;
55
- }
56
-
57
- if (pipeAfter) {
58
- const piped = await pipeAfter(source, { path: realPath });
59
- if (piped !== null) source = piped;
108
+ const loader = loaderFor(PartModules.fileOf(realPath));
109
+ if (partModules) {
110
+ const contents = await partModules.load(realPath);
111
+ return contents === null ? undefined : { contents, loader };
60
112
  }
61
-
62
- return { contents: source, loader };
113
+ const loaded = await read(realPath);
114
+ return loaded ? { contents: loaded.source, loader } : undefined;
63
115
  },
64
116
  );
65
117
  },
@@ -169,7 +221,7 @@ const resolveNodePackageExport = async (workspaceRoot: string, specifier: string
169
221
  if (!rel?.startsWith(".")) return null;
170
222
  const entryFile = await resolveFileCandidate(path.resolve(pkgDir, rel));
171
223
  if (!entryFile) return null;
172
- return { pkgName: specifier, entryFile, pkgDir: path.dirname(entryFile), preserveFilePath: true };
224
+ return { pkgName: specifier, entryFile, pkgDir: path.dirname(entryFile), preserveFilePath: true, rootDir: pkgDir };
173
225
  } catch {
174
226
  return null;
175
227
  }
@@ -240,6 +292,10 @@ export interface RewriteBarrelImportsOptions {
240
292
  specifierOf?: (subpath: string) => string;
241
293
  /** Called for each import of a listed barrel with the value names whose rewrite reads its export map. */
242
294
  onImport?: (barrel: string, names: string[]) => void;
295
+ /** The file names its runtime per module, so a client barrel stands for the page runtime alone. */
296
+ perModule?: boolean;
297
+ /** Rewrites `export { a, b as c } from "<barrel>"` as it rewrites an import of the same names. */
298
+ reexports?: boolean;
243
299
  }
244
300
 
245
301
  export const workspaceBarrels = (barrels: readonly string[]): string[] =>
@@ -249,11 +305,17 @@ export const rewriteBarrelImports = async (
249
305
  source: string,
250
306
  barrels: string[],
251
307
  analyzer: BarrelAnalyzer,
252
- { keepLines = false, specifierOf = (subpath: string) => subpath, onImport }: RewriteBarrelImportsOptions = {},
308
+ {
309
+ keepLines = false,
310
+ specifierOf = (subpath: string) => subpath,
311
+ onImport,
312
+ perModule = false,
313
+ reexports = false,
314
+ }: RewriteBarrelImportsOptions = {},
253
315
  ): Promise<string | null> => {
254
316
  // Sound pre-filter before the costly parse: a static import cannot name a specifier absent from the text.
255
317
  if (!barrels.some((barrel) => source.includes(barrel))) return null;
256
- const statements = findImportStatements(source);
318
+ const statements = findImportStatements(source, reexports);
257
319
  if (statements.length === 0) return null;
258
320
 
259
321
  // Walk import statements in reverse so replacements don't shift earlier ranges.
@@ -267,7 +329,7 @@ export const rewriteBarrelImports = async (
267
329
  if (names.length > 0) onImport?.(stmt.specifier, names);
268
330
  const map = await analyzer.analyze(stmt.specifier);
269
331
  if (!map || map.size === 0) continue;
270
- const lines = rewriteSingleStatement(stmt, map, specifierOf);
332
+ const lines = rewriteSingleStatement(stmt, map, specifierOf, perModule);
271
333
  if (lines === null) continue;
272
334
  const replacement = keepLines
273
335
  ? `${lines.join(" ")}${"\n".repeat(source.slice(stmt.start, stmt.end).split("\n").length - 1)}`
@@ -286,13 +348,14 @@ interface ParsedClause {
286
348
  }
287
349
 
288
350
  interface ImportStatement {
351
+ kind: "import" | "export";
289
352
  start: number;
290
353
  end: number;
291
354
  clause: ParsedClause | null;
292
355
  specifier: string;
293
356
  }
294
357
 
295
- const findImportStatements = (source: string): ImportStatement[] => {
358
+ const findImportStatements = (source: string, reexports: boolean): ImportStatement[] => {
296
359
  const statements: ImportStatement[] = [];
297
360
  // `setParentNodes: false` holds only while nothing reads `node.parent` and positions use `getStart(sourceFile)`.
298
361
  const sourceFile = ts.createSourceFile(
@@ -303,11 +366,25 @@ const findImportStatements = (source: string): ImportStatement[] => {
303
366
  ts.ScriptKind.TSX,
304
367
  );
305
368
  for (const statement of sourceFile.statements) {
369
+ if (reexports && ts.isExportDeclaration(statement)) {
370
+ const exportClause = statement.exportClause;
371
+ if (!statement.moduleSpecifier || !ts.isStringLiteral(statement.moduleSpecifier)) continue;
372
+ if (!exportClause || !ts.isNamedExports(exportClause)) continue;
373
+ statements.push({
374
+ kind: "export",
375
+ start: statement.getStart(sourceFile),
376
+ end: statement.end,
377
+ clause: exportClauseOf(statement.isTypeOnly, exportClause),
378
+ specifier: statement.moduleSpecifier.text,
379
+ });
380
+ continue;
381
+ }
306
382
  if (!ts.isImportDeclaration(statement)) continue;
307
383
  if (!ts.isStringLiteral(statement.moduleSpecifier)) continue;
308
384
  const importClause = statement.importClause;
309
385
  if (!importClause) continue;
310
386
  statements.push({
387
+ kind: "import",
311
388
  start: statement.getStart(sourceFile),
312
389
  end: statement.end,
313
390
  clause: clauseOf(importClause),
@@ -317,6 +394,16 @@ const findImportStatements = (source: string): ImportStatement[] => {
317
394
  return statements;
318
395
  };
319
396
 
397
+ const exportClauseOf = (typeOnly: boolean, exportClause: ts.NamedExports): ParsedClause | null => {
398
+ const named: NamedItem[] = [];
399
+ for (const element of exportClause.elements) {
400
+ const imported = element.propertyName ?? element.name;
401
+ if (!ts.isIdentifier(imported) || !ts.isIdentifier(element.name)) return null;
402
+ named.push({ imported: imported.text, local: element.name.text, isType: element.isTypeOnly });
403
+ }
404
+ return { named, typeOnly };
405
+ };
406
+
320
407
  const clauseOf = (importClause: ts.ImportClause): ParsedClause | null => {
321
408
  const parsed: ParsedClause = { typeOnly: importClause.phaseModifier === ts.SyntaxKind.TypeKeyword };
322
409
  if (importClause.name) parsed.defaultImport = importClause.name.text;
@@ -344,6 +431,7 @@ const rewriteSingleStatement = (
344
431
  stmt: ImportStatement,
345
432
  map: BarrelExportMap,
346
433
  specifierOf: (subpath: string) => string,
434
+ perModule: boolean,
347
435
  ): string[] | null => {
348
436
  const { clause } = stmt;
349
437
  if (!clause) return null;
@@ -353,6 +441,7 @@ const rewriteSingleStatement = (
353
441
  if (clause.typeOnly && !clause.defaultImport) return null;
354
442
  if (!clause.named?.length) return null;
355
443
 
444
+ const { kind } = stmt;
356
445
  const remaining: NamedItem[] = [];
357
446
  const rewrites = new Map<string, NamedItem[]>();
358
447
  const namespaceLines: string[] = [];
@@ -367,7 +456,7 @@ const rewriteSingleStatement = (
367
456
  continue;
368
457
  }
369
458
  if (target.namespace) {
370
- namespaceLines.push(`import * as ${item.local} from ${JSON.stringify(specifierOf(target.subpath))};`);
459
+ namespaceLines.push(`${kind} * as ${item.local} from ${JSON.stringify(specifierOf(target.subpath))};`);
371
460
  continue;
372
461
  }
373
462
  const list = rewrites.get(target.subpath) ?? [];
@@ -378,7 +467,7 @@ const rewriteSingleStatement = (
378
467
  if (rewrites.size === 0 && namespaceLines.length === 0) return null;
379
468
 
380
469
  //? An app or lib client barrel's import-time side effects are its client runtime and store, not its module UI.
381
- const lines = (StoreBootstrap.ofClientBarrel(stmt.specifier, map) ?? []).map(
470
+ const lines = (StoreBootstrap.ofClientBarrel(stmt.specifier, map, valueNamesOf(clause), { perModule }) ?? []).map(
382
471
  (specifier) => `import ${JSON.stringify(specifierOf(specifier))};`,
383
472
  );
384
473
 
@@ -386,11 +475,11 @@ const rewriteSingleStatement = (
386
475
  const parts: string[] = [];
387
476
  if (clause.defaultImport) parts.push(clause.defaultImport);
388
477
  if (remaining.length > 0) parts.push(`{ ${remaining.map(serializeNamedItem).join(", ")} }`);
389
- lines.push(`import ${parts.join(", ")} from "${stmt.specifier}";`);
478
+ lines.push(`${kind} ${parts.join(", ")} from "${stmt.specifier}";`);
390
479
  }
391
480
 
392
481
  for (const [subpath, items] of rewrites) {
393
- lines.push(`import { ${items.map(serializeNamedItem).join(", ")} } from ${JSON.stringify(specifierOf(subpath))};`);
482
+ lines.push(`${kind} { ${items.map(serializeNamedItem).join(", ")} } from ${JSON.stringify(specifierOf(subpath))};`);
394
483
  }
395
484
  lines.push(...namespaceLines);
396
485
 
@@ -0,0 +1,162 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { ExportReach } from "./exportReach";
3
+
4
+ const read = (source: string, file = "View.tsx") => ExportReach.read(source, file) as ExportReach;
5
+ const importsOf = (source: string, name: string) => {
6
+ const reached = read(source).of(name);
7
+ return reached.known ? reached.imports : null;
8
+ };
9
+
10
+ const view = `
11
+ import { Remove, Edit } from "./Memo.Util";
12
+ import { Chart } from "./Chart";
13
+ import type { Memo } from "./memo.constant";
14
+ import * as Unit from "./Memo.Unit";
15
+ import { format } from "./format";
16
+
17
+ const Title = ({ memo }: { memo: Memo }) => <h1>{format(memo.title)}</h1>;
18
+
19
+ export const General = ({ memo }: { memo: Memo }) => (
20
+ <div>
21
+ <Title memo={memo} />
22
+ <Remove id={memo.id} />
23
+ </div>
24
+ );
25
+
26
+ export function Stats({ memo }: { memo: Memo }) {
27
+ return <Chart value={memo.count} />;
28
+ }
29
+
30
+ export const Card = ({ memo }: { memo: Memo }) => <Unit.Card memo={memo} />;
31
+ export const All = () => Object.values(Unit);
32
+ export interface Props { memo: Memo }
33
+ `;
34
+
35
+ describe("ExportReach", () => {
36
+ test("reaches, from one export, the imports its declaration reads and those of the declarations it reads", () => {
37
+ expect(importsOf(view, "General")).toEqual([
38
+ { specifier: "./Memo.Util", names: ["Remove"] },
39
+ { specifier: "./format", names: ["format"] },
40
+ ]);
41
+ expect(importsOf(view, "Stats")).toEqual([{ specifier: "./Chart", names: ["Chart"] }]);
42
+ });
43
+
44
+ test("asks a namespace import for the members read from it, and for the whole module once it is handed on", () => {
45
+ expect(importsOf(view, "Card")).toEqual([{ specifier: "./Memo.Unit", names: ["Card"] }]);
46
+ expect(importsOf(view, "All")).toEqual([{ specifier: "./Memo.Unit", names: null }]);
47
+ });
48
+
49
+ test("reaches nothing for a type, and does not follow a name read only in a type", () => {
50
+ expect(importsOf(view, "Props")).toEqual([]);
51
+ expect(
52
+ read(view)
53
+ .whole()
54
+ .map(({ specifier }) => specifier),
55
+ ).not.toContain("./memo.constant");
56
+ });
57
+
58
+ test("answers a name the file does not hold as unknown, with the `export *` targets that may hold it", () => {
59
+ expect(read(view).of("Missing")).toEqual({ known: false, stars: [] });
60
+ expect(read('export * from "./a";\nexport * from "./b";\nexport const X = 1;\n').of("Y")).toEqual({
61
+ known: false,
62
+ stars: ["./a", "./b"],
63
+ });
64
+ });
65
+
66
+ test("follows an export list, a re-export, a namespace re-export and a default export", () => {
67
+ const source = `
68
+ import Base from "./Base";
69
+ import { Row } from "./Row";
70
+ const List = () => <Row />;
71
+ export { List as Rows };
72
+ export { Cell as GridCell, default as Grid } from "./Grid";
73
+ export * as Icons from "./icons";
74
+ export default function Page() { return <Base />; }
75
+ `;
76
+ expect(importsOf(source, "Rows")).toEqual([{ specifier: "./Row", names: ["Row"] }]);
77
+ expect(importsOf(source, "GridCell")).toEqual([{ specifier: "./Grid", names: ["Cell"] }]);
78
+ expect(importsOf(source, "Grid")).toEqual([{ specifier: "./Grid", names: ["default"] }]);
79
+ expect(importsOf(source, "Icons")).toEqual([{ specifier: "./icons", names: null }]);
80
+ expect(importsOf(source, "default")).toEqual([{ specifier: "./Base", names: ["default"] }]);
81
+ });
82
+
83
+ test("reads a member put on a declaration with the declaration, not with every importer", () => {
84
+ const source = `
85
+ import { Header } from "./Header";
86
+ import { Footer } from "./Footer";
87
+ import { Plain } from "./Plain";
88
+ export const Card = () => null;
89
+ Card.Header = Header;
90
+ Object.assign(Card, { Footer });
91
+ export const Other = () => <Plain />;
92
+ `;
93
+ expect(importsOf(source, "Card")).toEqual([
94
+ { specifier: "./Header", names: ["Header"] },
95
+ { specifier: "./Footer", names: ["Footer"] },
96
+ ]);
97
+ expect(importsOf(source, "Other")).toEqual([{ specifier: "./Plain", names: ["Plain"] }]);
98
+ expect(read(source).always()).toEqual([]);
99
+ });
100
+
101
+ test("reaches, for every importer, a bare import and what a statement that is no declaration reads", () => {
102
+ const source = `
103
+ import "./polyfill";
104
+ import { register } from "./registry";
105
+ import { Panel } from "./Panel";
106
+ import { Plain } from "./Plain";
107
+ register("panel", Panel);
108
+ export const Other = () => <Plain />;
109
+ `;
110
+ expect(read(source).always()).toEqual([
111
+ { specifier: "./polyfill", names: null },
112
+ { specifier: "./registry", names: ["register"] },
113
+ { specifier: "./Panel", names: ["Panel"] },
114
+ ]);
115
+ expect(importsOf(source, "Other")).toEqual([{ specifier: "./Plain", names: ["Plain"] }]);
116
+ });
117
+
118
+ test("reaches a module loaded on demand as a whole, from the export whose declaration loads it", () => {
119
+ const source = `
120
+ import { lazy } from "react";
121
+ const Editor = lazy(() => import("./Editor"));
122
+ export const Rich = () => <Editor />;
123
+ export const Plain = () => null;
124
+ `;
125
+ expect(importsOf(source, "Rich")).toEqual([
126
+ { specifier: "./Editor", names: null },
127
+ { specifier: "react", names: ["lazy"] },
128
+ ]);
129
+ expect(importsOf(source, "Plain")).toEqual([]);
130
+ });
131
+
132
+ test("counts a property name as no read of an import of that name, and a shadowed name as one", () => {
133
+ const source = `
134
+ import { Card } from "./Card";
135
+ import { Row } from "./Row";
136
+ export const A = (props: { Card: string }) => [props.Card, { Card: 1 }];
137
+ export const B = (Row: string) => Row;
138
+ `;
139
+ expect(importsOf(source, "A")).toEqual([]);
140
+ expect(importsOf(source, "B")).toEqual([{ specifier: "./Row", names: ["Row"] }]);
141
+ });
142
+
143
+ test("the whole module reaches every import a value of it reads, re-exports and `export *` included", () => {
144
+ const source = `
145
+ import { A } from "./a";
146
+ import type { T } from "./t";
147
+ export { B } from "./b";
148
+ export * from "./c";
149
+ export const X = () => <A />;
150
+ `;
151
+ expect(read(source).whole()).toEqual([
152
+ { specifier: "./a", names: ["A"] },
153
+ { specifier: "./b", names: ["B"] },
154
+ { specifier: "./c", names: null },
155
+ ]);
156
+ });
157
+
158
+ test("does not read a CommonJS module, whose exports are assigned at run time", () => {
159
+ expect(ExportReach.read('const a = require("./a");\nmodule.exports = { a };\n', "legacy.js")).toBeNull();
160
+ expect(ExportReach.read("export const a = 1;\n", "modern.js")).not.toBeNull();
161
+ });
162
+ });