@akanjs/devkit 3.3.0-rc.3 → 3.3.0-rc.30

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 (229) hide show
  1. package/CHANGELOG.md +547 -0
  2. package/DEV_RUNTIME_KNOBS.md +1 -1
  3. package/README.ko.md +3 -2
  4. package/README.md +3 -3
  5. package/akanApp/akanApp.host.test.ts +1 -1
  6. package/akanApp/akanApp.host.ts +11 -0
  7. package/akanConfig/akanBin.ts +4 -0
  8. package/akanConfig/akanConfig.test.ts +66 -7
  9. package/akanConfig/akanConfig.ts +53 -204
  10. package/akanConfig/akanWorkers.test.ts +39 -0
  11. package/akanConfig/akanWorkers.ts +32 -0
  12. package/akanConfig/desktopServerConfig.ts +96 -0
  13. package/akanConfig/dockerImage.ts +37 -0
  14. package/akanConfig/nativeKeys.ts +52 -0
  15. package/akanConfig/types.ts +1 -0
  16. package/app/appBin.test.ts +63 -0
  17. package/app/appBin.ts +50 -0
  18. package/app/applicationBuildReporter.test.ts +32 -0
  19. package/app/applicationBuildReporter.ts +4 -0
  20. package/app/applicationBuildRunner.test.ts +275 -0
  21. package/app/applicationBuildRunner.ts +126 -5
  22. package/app/dictionarySizes.ts +94 -0
  23. package/artifact/implicitRootLayout.test.ts +19 -0
  24. package/artifact/implicitRootLayout.ts +16 -2
  25. package/artifact/implicitRootLayoutRender.test.tsx +4 -1
  26. package/artifact/storeBootstrap.test.ts +28 -0
  27. package/artifact/storeBootstrap.ts +60 -8
  28. package/biome.base.json +5 -1
  29. package/codeAgent/agent/CodeAgent.ts +36 -16
  30. package/codeAgent/agent/CodeAgentAllowed.ts +35 -0
  31. package/codeAgent/agent/CodeAgentCommandLine.ts +372 -0
  32. package/codeAgent/agent/CodeAgentGate.ts +23 -4
  33. package/codeAgent/agent/CodeAgentRpcHost.ts +1 -1
  34. package/codeAgent/agent/codeAgent.test.ts +62 -0
  35. package/codeAgent/agent/codeAgentCommandLine.test.ts +212 -0
  36. package/codeAgent/agent/codeAgentContract.test.ts +117 -5
  37. package/codeAgent/skills/akan-agent/SKILL.md +8 -1
  38. package/codeAgent/skills/akan-code/SKILL.md +38 -3
  39. package/codeAgent/skills/akan-deps/SKILL.md +3 -2
  40. package/codeAgent/skills/akan-err/SKILL.md +13 -8
  41. package/codeAgent/skills/akan-mcp/SKILL.md +1 -1
  42. package/codeAgent/skills/akan-module/SKILL.md +2 -2
  43. package/codeAgent/skills/akan-page/SKILL.md +4 -14
  44. package/codeAgent/skills/akan-query/SKILL.md +13 -20
  45. package/codeAgent/skills/akan-runtime/SKILL.md +20 -0
  46. package/codeAgent/skills/akan-service/SKILL.md +2 -5
  47. package/codeAgent/skills/akan-transport/SKILL.md +5 -14
  48. package/codeAgent/skills/akan-ui/SKILL.md +2 -5
  49. package/context/akanContext.ts +2 -0
  50. package/docs/apiReference.test.ts +9 -0
  51. package/docs/apiReference.ts +14 -0
  52. package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
  53. package/executors/clientRuntimeKeys.fixture.json +393 -0
  54. package/executors/clientRuntimeKeys.test.ts +1591 -0
  55. package/executors/executors.test.ts +2 -0
  56. package/executors/sysExecutor.ts +66 -3
  57. package/executors/workspaceExecutor.ts +7 -4
  58. package/frontendBuild/allRoutesBuilder.ts +72 -3
  59. package/frontendBuild/autoImportSync.ts +3 -2
  60. package/frontendBuild/buildRouteClient.test.ts +515 -12
  61. package/frontendBuild/clientBuildTypes.ts +15 -0
  62. package/frontendBuild/clientEntriesBundler.ts +38 -0
  63. package/frontendBuild/clientEntryDiscovery.test.ts +95 -1
  64. package/frontendBuild/clientEntryDiscovery.ts +88 -7
  65. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  66. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  67. package/frontendBuild/csrDevPatcher.ts +33 -7
  68. package/frontendBuild/csrDevTypes.ts +9 -0
  69. package/frontendBuild/devBarrelImports.test.ts +100 -0
  70. package/frontendBuild/devBarrelImports.ts +82 -23
  71. package/frontendBuild/devRegistryBundler.ts +4 -2
  72. package/frontendBuild/devRouteRuntime.test.ts +492 -0
  73. package/frontendBuild/devRouteRuntime.ts +167 -0
  74. package/frontendBuild/dictionaryAssetBuilder.test.ts +316 -0
  75. package/frontendBuild/dictionaryAssetBuilder.ts +152 -16
  76. package/frontendBuild/dictionaryConstants.ts +82 -0
  77. package/frontendBuild/dictionaryPacking.test.ts +84 -0
  78. package/frontendBuild/dictionaryPacking.ts +92 -0
  79. package/frontendBuild/dictionaryRoutes.test.ts +186 -0
  80. package/frontendBuild/dictionaryRoutes.ts +225 -0
  81. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  82. package/frontendBuild/pagesBundleBuilder.ts +81 -3
  83. package/frontendBuild/precompressArtifacts.ts +7 -0
  84. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  85. package/frontendBuild/routeClientBuilder.ts +288 -15
  86. package/frontendBuild/routeHandoffs.test.ts +145 -0
  87. package/frontendBuild/routeHandoffs.ts +115 -0
  88. package/frontendBuild/routeRuntimeCheck.test.ts +257 -0
  89. package/frontendBuild/routeRuntimeCheck.ts +241 -0
  90. package/frontendBuild/routeRuntimePays.test.ts +137 -0
  91. package/frontendBuild/routeRuntimePays.ts +117 -0
  92. package/frontendBuild/rscServerRendererGuard.test.ts +60 -0
  93. package/frontendBuild/rscServerRendererGuard.ts +68 -0
  94. package/frontendBuild/ssrBaseArtifactBuilder.ts +24 -34
  95. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  96. package/frontendBuild/ssrDevBundler.ts +66 -11
  97. package/frontendBuild/vendorFileImports.test.ts +254 -0
  98. package/frontendBuild/vendorFileImports.ts +163 -0
  99. package/frontendBuild/vendorNarrowing.ts +28 -0
  100. package/frontendBuild/vendorSpecifiers.ts +2 -0
  101. package/incrementalBuilder/buildBatch.proc.ts +9 -9
  102. package/incrementalBuilder/buildBatchProtocol.ts +1 -1
  103. package/incrementalBuilder/builderBoot.ts +5 -5
  104. package/incrementalBuilder/builderGraphPayloads.ts +4 -4
  105. package/incrementalBuilder/builderLanes.ts +2 -2
  106. package/incrementalBuilder/builderWatch.ts +8 -8
  107. package/incrementalBuilder/csrRegistry.ts +4 -4
  108. package/incrementalBuilder/incrementalBuilder.proc.test.ts +79 -0
  109. package/incrementalBuilder/incrementalBuilder.proc.ts +27 -8
  110. package/incrementalBuilder/ssrRegistry.ts +6 -6
  111. package/index.ts +1 -1
  112. package/integration/renderAdmissionSoak.test.ts +99 -0
  113. package/integration/renderAdmissionSoak.ts +609 -0
  114. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  115. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  116. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  117. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  118. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  119. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  120. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  121. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  122. package/lint/biomeCheck.test.ts +145 -0
  123. package/lint/biomeCheck.ts +131 -0
  124. package/lint/no-arbitrary-color.grit +5 -0
  125. package/lint/no-conditional-st-hook.grit +5 -1
  126. package/lint/no-daisyui-legacy-class.grit +8 -0
  127. package/lint/no-document-cookie.grit +3 -0
  128. package/lint/no-inline-color.grit +10 -2
  129. package/lint/no-oversized-list-limit.grit +2 -0
  130. package/lint/no-raw-palette-class.grit +7 -0
  131. package/lint/no-unpublished-form-setter.grit +2 -0
  132. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  133. package/lint/no-web-storage.grit +3 -0
  134. package/lint/withheldEnvFile.ts +17 -0
  135. package/mobile/desktopBin.ts +2 -2
  136. package/mobile/desktopServerStage.ts +1 -0
  137. package/mobile/nativeApp.test.ts +7 -5
  138. package/mobile/nativeApp.ts +2 -2
  139. package/mobile/nativeConfig.test.ts +96 -1
  140. package/mobile/nativeConfig.ts +46 -12
  141. package/mobile/serverBundleSecrets.ts +43 -0
  142. package/package.json +15 -169
  143. package/packageExports.test.ts +38 -24
  144. package/quality/dictionaryKeys.test.ts +173 -0
  145. package/quality/dictionaryKeys.ts +415 -0
  146. package/quality/objectImportReport.test.ts +36 -0
  147. package/quality/objectImportReport.ts +102 -0
  148. package/quality/qualityScanner.ts +1 -1
  149. package/quality/routeRuntimeReport.test.ts +91 -0
  150. package/quality/routeRuntimeReport.ts +121 -0
  151. package/quality/runtimeConstantFacts.ts +71 -0
  152. package/quality/runtimeConstantGraph.ts +123 -0
  153. package/quality/runtimeConstantReads.ts +116 -0
  154. package/quality/runtimeImports.test.ts +190 -0
  155. package/quality/runtimeImports.ts +233 -0
  156. package/quality/runtimeKeyNames.ts +46 -0
  157. package/quality/runtimeLexicalScope.ts +132 -0
  158. package/quality/runtimeMarkerReach.test.ts +84 -0
  159. package/quality/runtimeMarkerReach.ts +255 -0
  160. package/quality/runtimeModuleFacts.ts +290 -0
  161. package/quality/runtimeNameTable.test.ts +172 -0
  162. package/quality/runtimeNameTable.ts +477 -0
  163. package/quality/runtimeScopeReport.test.ts +123 -0
  164. package/quality/runtimeScopeReport.ts +167 -0
  165. package/quality/runtimeSliceKey.ts +269 -0
  166. package/quality/runtimeSyntax.ts +133 -0
  167. package/quality/runtimeTable.fixture.ts +189 -0
  168. package/quality/runtimeUse.test.ts +737 -0
  169. package/quality/runtimeUse.ts +696 -0
  170. package/quality/runtimeUseReadable.test.ts +393 -0
  171. package/quality/ssrScanner.test.ts +13 -0
  172. package/quality/ssrScanner.ts +1 -1
  173. package/test/secretEnvFixture.ts +134 -0
  174. package/test/testHelpers.ts +11 -0
  175. package/transforms/barrelAnalyzer.ts +26 -4
  176. package/transforms/barrelImportsPlugin.ts +82 -14
  177. package/transforms/frameworkObjects.fixture.tsx +58 -0
  178. package/transforms/frameworkObjects.test.ts +54 -0
  179. package/transforms/modelReference.test.ts +196 -0
  180. package/transforms/modelReference.ts +39 -0
  181. package/transforms/objectImportEdits.ts +150 -0
  182. package/transforms/objectMemberImports.test.ts +347 -0
  183. package/transforms/objectMemberImports.ts +537 -0
  184. package/transforms/objectModule.test.ts +237 -0
  185. package/transforms/objectModule.ts +458 -0
  186. package/transforms/objectModuleAnalyzer.ts +104 -0
  187. package/transforms/reactIconImports.test.ts +231 -0
  188. package/transforms/reactIconImports.ts +325 -0
  189. package/transforms/routeConstants.ts +122 -0
  190. package/transforms/routeRuntime.test.ts +835 -0
  191. package/transforms/routeRuntime.ts +703 -0
  192. package/transforms/routeRuntimeEdits.ts +92 -0
  193. package/transforms/routeRuntimeGraph.ts +66 -0
  194. package/transforms/routeRuntimePlan.ts +244 -0
  195. package/transforms/secretEnvDeclaration.test.ts +208 -0
  196. package/transforms/secretEnvDeclaration.ts +213 -0
  197. package/transforms/secretEnvFile.test.ts +117 -0
  198. package/transforms/secretEnvFile.ts +113 -0
  199. package/transforms/secretEnvName.test.ts +54 -0
  200. package/transforms/secretEnvName.ts +29 -0
  201. package/transforms/secretEnvSource.test.ts +148 -0
  202. package/transforms/secretEnvSource.ts +166 -0
  203. package/transforms/serverEnvEvaluationError.ts +11 -0
  204. package/transforms/serverEnvPlugin.test.ts +2 -1
  205. package/transforms/serverEnvPlugin.ts +13 -0
  206. package/transforms/serverEnvProfile.test.ts +115 -2
  207. package/transforms/serverEnvProfile.ts +117 -40
  208. package/transforms/serverEnvSecrets.test.ts +292 -0
  209. package/transforms/signalDescriptors.test.ts +280 -0
  210. package/transforms/signalDescriptors.ts +227 -0
  211. package/transforms/thisFreeExports.ts +87 -0
  212. package/transforms/transforms.test.ts +180 -3
  213. package/transforms/tsconfigPackageResolver.test.ts +1 -0
  214. package/tunnel/createTunnel.test.ts +29 -8
  215. package/tunnel/createTunnel.ts +18 -11
  216. package/typecheck/projectTypecheck.test.ts +29 -0
  217. package/typecheck/typeChecker.test.ts +49 -0
  218. package/typecheck/typeChecker.ts +9 -7
  219. package/typecheck/withheldDiagnostics.ts +41 -0
  220. package/util/fileEditor.ts +1 -0
  221. package/util/selectModel.ts +1 -0
  222. package/workflow/executor.ts +6 -2
  223. package/workflow/index.ts +1 -0
  224. package/workflow/plan.ts +36 -7
  225. package/workflow/types.ts +1 -1
  226. package/workflow/uiTarget.ts +50 -0
  227. package/workspace/getRelatedCnsts.ts +7 -0
  228. package/workspace/scanInfo.ts +1 -1
  229. package/workspace/workspaceLayout.ts +1 -0
@@ -0,0 +1,393 @@
1
+ import { beforeAll, describe, expect, test } from "bun:test";
2
+ import type { RuntimeNameEntry, RuntimeNameTable } from "./runtimeNameTable";
3
+ import { runtimeFixtureTables } from "./runtimeTable.fixture";
4
+ import { RuntimeUse, type RuntimeUseVerdict } from "./runtimeUse";
5
+
6
+ let demo: RuntimeNameTable;
7
+ let kit: RuntimeNameTable;
8
+
9
+ beforeAll(async () => {
10
+ ({ demo, kit } = await runtimeFixtureTables());
11
+ });
12
+
13
+ const head = 'import { fetch, st } from "@apps/demo/client";\n';
14
+ const sliceHead = `import { capitalize } from "akanjs/common";\nimport type { SliceMeta } from "akanjs/fetch";\n${head}`;
15
+ const memo = ["apps/demo/memo store"];
16
+ const memoAndNote = ["apps/demo/memo store", "apps/demo/note store"];
17
+
18
+ const summaryOf = (verdict: RuntimeUseVerdict) =>
19
+ verdict.resolvable
20
+ ? verdict.owners.map(({ scope, module, needs }) => `${scope}/${module} ${needs}`)
21
+ : `${verdict.reason}: ${verdict.text}`;
22
+
23
+ const analyze = (text: string, fileName = "apps/demo/ui/Card.tsx", table: RuntimeNameTable = demo) =>
24
+ summaryOf(RuntimeUse.analyze({ fileName, text }, table));
25
+
26
+ const storeOf = (body: string, lead = "") =>
27
+ analyze(
28
+ `import { store } from "akanjs/store";\nimport { sig } from "../useClient";\n${lead}\nexport class MemoStore extends store(sig.memo, () => ({ draft: "" })) {\n${body}\n}\n`,
29
+ "apps/demo/lib/memo/memo.store.ts",
30
+ );
31
+
32
+ describe("RuntimeUse.analyze, names read through a cast", () => {
33
+ test("reads a name written after a cast as it reads it with no cast", () => {
34
+ const loose = "{ [key: string]: () => unknown }";
35
+ expect([
36
+ analyze(`${head}export const a = () => (st.use as unknown as ${loose}).draft();\n`),
37
+ analyze(`${head}const use = st.use as ${loose};\nexport const a = () => use.draft();\n`),
38
+ analyze(`${head}export const a = () => {\n const { draft } = st.get() as unknown as { draft: string };\n};\n`),
39
+ analyze(`${head}export const a = () => (st.do satisfies object).clearDraft();\n`),
40
+ analyze(`${head}export const a = () => st.do!.clearDraft();\n`),
41
+ analyze(`${head}export const a = () => (<any>st.do).clearDraft();\n`, "apps/demo/webkit/clear.ts"),
42
+ analyze(`${head}export const a = () => (st.get() as any).pinned;\n`),
43
+ ]).toEqual([memo, memo, memo, memo, memo, memo, ["apps/demo/note store"]]);
44
+ expect(
45
+ analyze(`${head}export const a = () => (fetch as unknown as { memoNote: () => void }).memoNote();\n`),
46
+ ).toEqual(["apps/demo/memo descriptor"]);
47
+ });
48
+
49
+ test("reads the framework's fetch cast to the app's as the app's, and a store's state read taken off it once", () => {
50
+ expect(
51
+ analyze(
52
+ 'import { fetch as runtimeFetch } from "akanjs/client";\nimport type { fetch } from "@apps/demo/client";\nconst live = runtimeFetch as unknown as typeof fetch;\nexport const a = () => live.memoNote();\n',
53
+ ),
54
+ ).toEqual(["apps/demo/memo descriptor"]);
55
+ expect(
56
+ analyze(
57
+ `${head}const get = st.get as unknown as <T>() => { [key: string]: T };\nexport const a = () => get<string>().draft;\n`,
58
+ ),
59
+ ).toEqual(memo);
60
+ expect(analyze(`${head}const get = st.get;\nexport const a = (run: (get: unknown) => void) => run(get);\n`)).toBe(
61
+ "passed-on: get",
62
+ );
63
+ });
64
+
65
+ test("keeps the whole runtime for every read a cast does not make visible", () => {
66
+ expect([
67
+ analyze(`${head}export const a = (name: string) => (st.use as any)[name]();\n`),
68
+ analyze(`${head}export const a = () => (fetch as unknown as { notThere: () => void }).notThere();\n`),
69
+ analyze(`${head}export const a = () => ({ ...(st.do as object) });\n`),
70
+ analyze(`${head}export const a = (run: (all: unknown) => void) => run(st.do as any);\n`),
71
+ analyze(`${head}export const a = () => (st as any).everything;\n`),
72
+ analyze(`${head}export const a = () => (st.get() as any).nothing;\n`),
73
+ ]).toEqual([
74
+ "computed-access: (st.use as any)[name]",
75
+ "unknown-name: (fetch as unknown as { notThere: () => void }).notThere",
76
+ "passed-on: (st.do as object)",
77
+ "passed-on: st.do as any",
78
+ "unknown-name: (st as any).everything",
79
+ "unknown-name: (st.get() as any).nothing",
80
+ ]);
81
+ });
82
+ });
83
+
84
+ describe("RuntimeUse.analyze, a key asserted as a name", () => {
85
+ test("reads a computed key asserted as a name, directly or through a const, as that name", () => {
86
+ expect([
87
+ analyze(`${head}export const a = (key: string) => st.use[key as "draft"]();\n`),
88
+ analyze(`${head}export const a = (key: string) => st.use[<"draft">key]();\n`, "apps/demo/webkit/draft.ts"),
89
+ analyze(
90
+ `${head}export const a = (name: string) => {\n const key = name.replace("x", "draft") as "draft";\n return st.get()[key];\n};\n`,
91
+ ),
92
+ analyze(`${head}const key = "draft";\nexport const a = () => st.use[key]();\n`),
93
+ analyze(`${head}export const a = (key: string) => st.slice[key as "memoInBoard"].use.memoList();\n`),
94
+ ]).toEqual([memo, memo, memo, memo, memo]);
95
+ expect(analyze(`${head}export const a = (key: string) => st.use[key as "draft" | "pinned"]();\n`)).toEqual(
96
+ memoAndNote,
97
+ );
98
+ });
99
+
100
+ test("reads an asserted key of a destructuring, a state write and a pick in a store", () => {
101
+ const key = ' const key = slice.replace("x", "pinned") as "pinned";\n';
102
+ expect([
103
+ storeOf(` show(slice: string) {\n${key} const { [key]: value } = this.get();\n return value;\n }`),
104
+ storeOf(` show(slice: string) {\n${key} this.set({ [key]: true });\n }`),
105
+ storeOf(` show(slice: string) {\n${key} return this.pick(key);\n }`),
106
+ ]).toEqual([memoAndNote, memoAndNote, memoAndNote]);
107
+ });
108
+
109
+ test("keeps the whole runtime for a spread written through a cast `this`, which is not the store's own typed `set`", () => {
110
+ const mergeOf = (write: string) => storeOf(` merge(patch: { draft: string }) {\n ${write};\n }`);
111
+ expect([
112
+ mergeOf("this.set({ ...patch })"),
113
+ mergeOf("(this as any).set({ ...patch })"),
114
+ mergeOf("(this as unknown as { set(p: object): void }).set({ ...patch })"),
115
+ mergeOf("(this as any)['set']({ ...patch })"),
116
+ ]).toEqual([
117
+ ["apps/demo/memo store"],
118
+ "computed-access: patch",
119
+ "computed-access: patch",
120
+ "computed-access: patch",
121
+ ]);
122
+ });
123
+
124
+ test("reports an asserted name the runtime does not have, and keeps the whole runtime for a key nothing asserts", () => {
125
+ expect([
126
+ analyze(`${head}export const a = (key: string) => st.use[key as "nothing"]();\n`),
127
+ analyze(`${head}export const a = (key: string) => st.use[key as string]();\n`),
128
+ analyze(
129
+ `${head}export const a = (key: string) => {\n let name = key as "draft";\n return st.use[name]();\n};\n`,
130
+ ),
131
+ analyze(`${head}export const a = (key: string) => st[key as "do" | "use"];\n`),
132
+ storeOf(" show(key: string) {\n const { [key]: value } = this.get();\n return value;\n }"),
133
+ storeOf(" show(key: string) {\n this.set({ [key]: true });\n }"),
134
+ ]).toEqual([
135
+ 'unknown-name: st.use[key as "nothing"]',
136
+ "computed-access: st.use[key as string]",
137
+ "computed-access: st.use[name]",
138
+ 'computed-access: st[key as "do" | "use"]',
139
+ "hidden-by-destructuring: [key]: value",
140
+ "computed-access: [key]: true",
141
+ ]);
142
+ });
143
+ });
144
+
145
+ describe("RuntimeUse.analyze, a name built from a slice the function is handed", () => {
146
+ const props = "interface Props {\n className?: string;\n slice: SliceMeta;\n}\n";
147
+
148
+ test("reads a name built from the sliceName or refName of a slice parameter, loading nothing the slice brought", () => {
149
+ expect([
150
+ analyze(
151
+ `${sliceHead}${props}export const Search = ({ slice }: Props) => {\n const { sliceName } = slice;\n const use = st.use as unknown as { [key: string]: () => unknown };\n return () => use[\`queryArgsOf\${capitalize(sliceName)}\`]();\n};\n`,
152
+ ),
153
+ analyze(
154
+ `${sliceHead}export const More = ({ slice }: { slice?: SliceMeta }) => {\n const SliceName = capitalize(slice.sliceName);\n return (st.do as any)["loadMoreOf" + SliceName]();\n};\n`,
155
+ ),
156
+ analyze(`${sliceHead}export const sliceOf = (slice: SliceMeta | null) => st.slice[slice.sliceName];\n`),
157
+ analyze(
158
+ `${sliceHead}type Handed = SliceMeta & { title: string };\nexport const uploadOf = (slice: Handed) => (fetch as any)[\`add\${capitalize(slice.refName)}Files\`];\n`,
159
+ ),
160
+ ]).toEqual([[], [], [], []]);
161
+ expect(
162
+ analyze(
163
+ `import { capitalize } from "akanjs/common";\nimport type { SliceMeta } from "akanjs/fetch";\nimport { fetch } from "@libs/kit/client";\nexport const uploadOf = (slice: SliceMeta) => (fetch as any)[\`add\${capitalize(slice.sliceName)}Files\`];\n`,
164
+ "libs/kit/ui/upload.ts",
165
+ kit,
166
+ ),
167
+ ).toEqual([]);
168
+ });
169
+
170
+ test("keeps the whole runtime where the name's parts are not one handed slice's", () => {
171
+ const built = `st.use[\`queryArgsOf\${capitalize(sliceName)}\`]`;
172
+ const read = ` return ${built}();\n};\n`;
173
+ expect([
174
+ analyze(`${sliceHead}export const a = (sliceName: string) => {\n${read}`),
175
+ analyze(
176
+ `${sliceHead}export const a = (slice: { sliceName: string }) => {\n const { sliceName } = slice;\n${read}`,
177
+ ),
178
+ analyze(
179
+ `import { capitalize } from "akanjs/common";\nimport type { SliceMeta } from "./slice";\n${head}export const a = (slice: SliceMeta) => {\n const { sliceName } = slice;\n${read}`,
180
+ ),
181
+ analyze(
182
+ `import type { SliceMeta } from "akanjs/fetch";\n${head}const capitalize = (text: string) => text;\nexport const a = (slice: SliceMeta) => {\n const { sliceName } = slice;\n${read}`,
183
+ ),
184
+ analyze(
185
+ `${sliceHead}export const a = (slice: SliceMeta) => {\n const { sliceName = "memoInBoard" } = slice;\n${read}`,
186
+ ),
187
+ analyze(`${sliceHead}export const a = (slice: SliceMeta) => {\n let { sliceName } = slice;\n${read}`),
188
+ analyze(
189
+ `${sliceHead}export const a = (one: SliceMeta, other: SliceMeta) => st.use[\`\${one.refName}ListIn\${other.sliceName}\`]();\n`,
190
+ ),
191
+ analyze(
192
+ `${sliceHead}export const a = (slice: SliceMeta) => st.use[\`nothingOf\${capitalize(slice.sliceName)}\`]();\n`,
193
+ ),
194
+ analyze(`${sliceHead}export const a = (slice: SliceMeta) => st[slice.refName];\n`),
195
+ ]).toEqual([
196
+ `computed-access: ${built}`,
197
+ `computed-access: ${built}`,
198
+ `computed-access: ${built}`,
199
+ `computed-access: ${built}`,
200
+ `computed-access: ${built}`,
201
+ `computed-access: ${built}`,
202
+ `computed-access: st.use[\`\${one.refName}ListIn\${other.sliceName}\`]`,
203
+ `computed-access: st.use[\`nothingOf\${capitalize(slice.sliceName)}\`]`,
204
+ "computed-access: st[slice.refName]",
205
+ ]);
206
+ });
207
+
208
+ test("keeps the whole runtime where the slice parameter is reassigned or defaulted", () => {
209
+ const built = `st.use[\`queryArgsOf\${capitalize(slice.sliceName)}\`]`;
210
+ const read = `${built}()`;
211
+ const inFunction = (parameters: string, before: string) =>
212
+ analyze(`${sliceHead}export const a = (${parameters}) => {\n${before} return ${read};\n};\n`);
213
+ expect([
214
+ inFunction("slice: SliceMeta, other: any", " slice = other;\n"),
215
+ inFunction("slice: SliceMeta, other: any", " ({ slice } = other);\n"),
216
+ inFunction("slice: SliceMeta, other: any", " [slice] = other;\n"),
217
+ inFunction("slice: SliceMeta, other: any", " (slice as any) = other;\n"),
218
+ inFunction("slice: SliceMeta", " for (slice of []) break;\n"),
219
+ inFunction("slice: SliceMeta", " slice ||= slice;\n"),
220
+ inFunction("slice = (undefined as unknown) as SliceMeta", ""),
221
+ inFunction("{ slice }: { slice: SliceMeta }, other: any", " slice = other;\n"),
222
+ inFunction("{ slice = other as SliceMeta }: { slice?: SliceMeta }, other: any", ""),
223
+ inFunction("{ slice }: { slice: SliceMeta } = { slice: {} as SliceMeta }", ""),
224
+ inFunction("slice: SliceMeta", " const other = { slice };\n"),
225
+ ]).toEqual([...Array.from({ length: 10 }, () => `computed-access: ${built}`), []]);
226
+ });
227
+
228
+ test("loads a module the slice's own arrival does not, for every slice the name may stand for", () => {
229
+ const entry = (scope: string, module: string): RuntimeNameEntry => ({
230
+ owners: [{ scope, module }],
231
+ definedBy: [{ scope, module }],
232
+ base: null,
233
+ needs: "store",
234
+ uses: [],
235
+ });
236
+ const names: Record<string, RuntimeNameEntry> = {
237
+ "fetch.slice/postInFeed": entry("libs/base", "post"),
238
+ "st.slice/postInFeed": entry("apps/blog", "post"),
239
+ "st.use/post": entry("apps/blog", "post"),
240
+ "st.use/queryArgsOfPostInFeed": entry("apps/blog", "post"),
241
+ "fetch.slice/tagInFeed": entry("libs/base", "tag"),
242
+ "st.use/tag": entry("libs/base", "tag"),
243
+ "st.use/queryArgsOfTagInFeed": entry("libs/base", "tag"),
244
+ };
245
+ const blog = {
246
+ scope: "apps/blog",
247
+ layers: [{ scope: "libs/base" }, { scope: "apps/blog" }],
248
+ lookup: (family: string, key: string) => names[`${family}/${key}`] ?? null,
249
+ keysOf: (family: string) =>
250
+ Object.keys(names).flatMap((name) => (name.startsWith(`${family}/`) ? [name.slice(family.length + 1)] : [])),
251
+ } as unknown as RuntimeNameTable;
252
+ expect(
253
+ analyze(
254
+ `import { capitalize } from "akanjs/common";\nimport type { SliceMeta } from "akanjs/fetch";\nimport { st } from "@apps/blog/client";\nexport const a = (slice: SliceMeta) => st.use[\`queryArgsOf\${capitalize(slice.sliceName)}\`]();\n`,
255
+ "apps/blog/ui/Search.tsx",
256
+ blog,
257
+ ),
258
+ ).toEqual(["apps/blog/post store"]);
259
+ });
260
+
261
+ test("loads nothing for a copy of a handed slice's names, and keeps the whole runtime for any other copy", () => {
262
+ const type = 'import type { SliceMeta } from "akanjs/fetch";\n';
263
+ const copy = "{ refName: slice.refName, sliceName: slice.sliceName, argLength: 0 }";
264
+ expect([
265
+ analyze(`${type}export const copy = (slice: SliceMeta) => (${copy});\n`),
266
+ analyze(
267
+ `${type}export const copy = (slice: SliceMeta) => {\n const { refName, sliceName } = slice;\n return { refName, sliceName, argLength: 0 };\n};\n`,
268
+ ),
269
+ analyze(
270
+ `${type}export const copy = (slice: SliceMeta, other: SliceMeta) => {\n slice = other;\n return ${copy};\n};\n`,
271
+ ),
272
+ analyze(
273
+ `${type}export const copy = (slice: SliceMeta) => ({ refName: slice.refName, sliceName: slice.refName, argLength: 0 });\n`,
274
+ ),
275
+ analyze(`${type}export const copy = (slice: { refName: string; sliceName: string }) => (${copy});\n`),
276
+ ]).toEqual([
277
+ [],
278
+ [],
279
+ "computed-access: sliceName: slice.sliceName",
280
+ "computed-access: sliceName: slice.refName",
281
+ "computed-access: sliceName: slice.sliceName",
282
+ ]);
283
+ });
284
+
285
+ test("reads a slice written out by hand as naming its model, and keeps the whole runtime where its name is not written", () => {
286
+ expect([
287
+ analyze('export const slice = { refName: "memo", sliceName: "memoInBoard", argLength: 0 };\n'),
288
+ analyze(
289
+ "export const sliceOf = (refName: string, sliceName: string) => ({ refName, sliceName, argLength: 0 });\n",
290
+ ),
291
+ analyze('export const slice = { refName: "memo", sliceName: "nothing", argLength: 0 };\n'),
292
+ analyze('export const names = { sliceName: "memoInBoard" };\n'),
293
+ ]).toEqual([memo, "computed-access: sliceName", 'unknown-name: sliceName: "nothing"', []]);
294
+ });
295
+ });
296
+
297
+ describe("RuntimeUse.analyze, state handed to a function of the same file", () => {
298
+ test("reads the names a function of the file reads from the state it is handed", () => {
299
+ expect([
300
+ storeOf(
301
+ " static announce({ draft, pinned }: { draft: string; pinned: boolean }) {\n return [draft, pinned];\n }\n show() {\n return MemoStore.announce(this.get());\n }",
302
+ ),
303
+ analyze(
304
+ `${head}const labelOf = (state: { draft: string }) => state.draft;\nexport const a = () => labelOf(st.get());\n`,
305
+ ),
306
+ analyze(
307
+ `${head}export const a = () => labelOf(1, st.get() as never);\nfunction labelOf(this: void, count: number, state: { draft: string }) {\n return state.draft.repeat(count);\n}\n`,
308
+ ),
309
+ analyze(
310
+ `${head}const inner = ({ pinned }: { pinned: boolean }) => pinned;\nconst outer = (state: { draft: string }) => [state.draft, inner(state as never)];\nexport const a = () => outer(st.get());\n`,
311
+ ),
312
+ ]).toEqual([memoAndNote, memo, memo, memoAndNote]);
313
+ });
314
+
315
+ test("keeps the whole runtime where the function hands the state on, picks a name at run time or is not the file's", () => {
316
+ expect([
317
+ analyze(
318
+ `${head}const labelOf = (state: object, run: (all: object) => void) => run(state);\nexport const a = () => labelOf(st.get(), () => {});\n`,
319
+ ),
320
+ analyze(
321
+ `${head}const labelOf = (state: Record<string, string>, key: string) => state[key];\nexport const a = () => labelOf(st.get(), "draft");\n`,
322
+ ),
323
+ analyze(`${head}const labelOf = (...states: object[]) => states;\nexport const a = () => labelOf(st.get());\n`),
324
+ analyze(
325
+ `${head}function labelOf(state: object) {\n return arguments[0];\n}\nexport const a = () => labelOf(st.get());\n`,
326
+ ),
327
+ analyze(`${head}import { labelOf } from "./label";\nexport const a = () => labelOf(st.get());\n`),
328
+ analyze(
329
+ `${head}let labelOf = (state: { draft: string }) => state.draft;\nexport const a = () => labelOf(st.get());\n`,
330
+ ),
331
+ analyze(
332
+ `${head}const labelOf = (state: { draft: string }) => state.draft;\nexport const a = () => labelOf(st.do);\n`,
333
+ ),
334
+ storeOf(
335
+ " label(state: { draft: string }) {\n return state.draft;\n }\n show() {\n return this.label(this.get());\n }",
336
+ ),
337
+ ]).toEqual([
338
+ "passed-on: state",
339
+ "computed-access: state[key]",
340
+ "passed-on: st.get()",
341
+ "passed-on: st.get()",
342
+ "passed-on: st.get()",
343
+ "passed-on: st.get()",
344
+ "passed-on: st.do",
345
+ "passed-on: this.get()",
346
+ ]);
347
+ });
348
+ });
349
+
350
+ describe("RuntimeUse.analyze, the agent entry of the framework store", () => {
351
+ test("reads the screen and cursor exports as no runtime, and the ones holding the root store as the whole runtime", () => {
352
+ expect([
353
+ analyze(
354
+ 'import { ScreenSettle, ScreenTarget } from "akanjs/store/agent";\nexport const a = [ScreenSettle, ScreenTarget];\n',
355
+ ),
356
+ analyze('import { AgentBridge } from "akanjs/store/agent";\nexport const a = AgentBridge;\n'),
357
+ analyze('import * as agent from "akanjs/store/agent";\nexport const a = agent;\n'),
358
+ analyze('import { ScreenSettle } from "akanjs/store/agent/ScreenSettle";\nexport const a = ScreenSettle;\n'),
359
+ ]).toEqual([
360
+ [],
361
+ "whole-runtime-import: AgentBridge",
362
+ "whole-runtime-import: agent",
363
+ "whole-runtime-import: ScreenSettle",
364
+ ]);
365
+ });
366
+ });
367
+
368
+ describe("RuntimeUse.analyze, the note of a read that keeps the whole runtime", () => {
369
+ test("ends with what to write instead, where there is a usual answer", () => {
370
+ const answerOf = (text: string) => {
371
+ const verdict = RuntimeUse.analyze({ fileName: "apps/demo/ui/Card.tsx", text }, demo);
372
+ return verdict.resolvable ? null : (verdict.message.split("; ")[1] ?? null);
373
+ };
374
+ const assertKey = 'assert the key as the name it stands for (`key as "name"`)';
375
+ expect([
376
+ answerOf(`${head}export const a = (name: string) => st.use[name]();\n`),
377
+ answerOf(`${head}export const a = (name: string) => fetch[name]();\n`),
378
+ answerOf(`${head}export const a = (sliceName: string) => st.slice[sliceName];\n`),
379
+ answerOf(`${head}export const a = (run: (all: unknown) => void) => run(fetch);\n`),
380
+ answerOf(`${head}export const a = (run: (all: unknown) => void) => run(st.get());\n`),
381
+ answerOf(`${head}export const a = (key: string) => {\n const { [key]: value } = st.get();\n};\n`),
382
+ answerOf(`${head}export const a = () => st.use.nothing();\n`),
383
+ ]).toEqual([
384
+ assertKey,
385
+ `name the endpoint, or ${assertKey}`,
386
+ `take the slice as a \`SliceMeta\` parameter, or ${assertKey}`,
387
+ "name the endpoint here and pass that",
388
+ "read the names here",
389
+ assertKey,
390
+ null,
391
+ ]);
392
+ });
393
+ });
@@ -35,6 +35,19 @@ describe("akan.ssr.unnecessary-use-client", () => {
35
35
  expect(scanOne(UI, `"use client";\n${body}\n`)).not.toContain("akan.ssr.unnecessary-use-client");
36
36
  });
37
37
 
38
+ test("a module's Zone, Template or Util carries the directive by role, in a service module too", () => {
39
+ const plain = `"use client";\nexport const Main = () => <div />;\n`;
40
+ for (const file of [
41
+ "apps/demo/lib/task/Task.Zone.tsx",
42
+ "apps/demo/lib/task/Task.Template.tsx",
43
+ "apps/demo/lib/_camera/Camera.Zone.tsx",
44
+ "libs/shared/lib/_camera/Camera.Util.tsx",
45
+ ])
46
+ expect(scanOne(file, plain)).not.toContain("akan.ssr.unnecessary-use-client");
47
+ for (const file of ["apps/demo/lib/task/Task.View.tsx", "apps/demo/lib/__scalar/geo/Geo.Template.tsx"])
48
+ expect(scanOne(file, plain)).toContain("akan.ssr.unnecessary-use-client");
49
+ });
50
+
38
51
  test("a third-party import is a reason the AST cannot rule out", () => {
39
52
  expect(scanOne(UI, `"use client";\nimport Chart from "recharts";\nexport const Thing = () => <div />;\n`)).toEqual(
40
53
  [],
@@ -354,7 +354,7 @@ export class SsrScanner {
354
354
  // Zone/Template/Util carry the directive by file role, and `index_.tsx` is the declared lazy() boundary.
355
355
  #isConventionClientFile(file: string) {
356
356
  if (file.endsWith("/index_.tsx")) return true;
357
- return /\.(Zone|Template|Util)\.tsx$/.test(file) && this.#getModuleDir(file) !== null;
357
+ return /\/lib\/_?[^_/][^/]*\/.*\.(Zone|Template|Util)\.tsx$/.test(file);
358
358
  }
359
359
 
360
360
  #isBalancedFile(file: string) {
@@ -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[]>[] = [];
@@ -18,14 +18,18 @@ export interface PackageEntry {
18
18
  entryFile: string;
19
19
  /** Absolute base directory for subpath computation, typically `dirname(entryFile)`. */
20
20
  pkgDir: string;
21
- /** Emit concrete file paths, for package exports that do not support extensionless deep imports. */
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,8 +218,12 @@ 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;
214
- if (pkg.preserveFilePath) return `${pkg.pkgName}/${rel.split(path.sep).join("/")}`;
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
+ }
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);
217
229
  // `xxx/index` collapses to `xxx`: callers import `@pkg/xxx`, never `@pkg/xxx/index`.
@@ -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);