@akanjs/devkit 3.3.0-rc.5 → 3.3.0-rc.50

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 (261) hide show
  1. package/CHANGELOG.md +650 -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 +70 -10
  9. package/akanConfig/akanConfig.ts +57 -206
  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 +39 -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 +49 -0
  19. package/app/applicationBuildReporter.ts +5 -0
  20. package/app/applicationBuildRunner.test.ts +275 -0
  21. package/app/applicationBuildRunner.ts +149 -12
  22. package/app/dictionarySizes.ts +91 -0
  23. package/app/routeFilesReport.test.ts +59 -0
  24. package/app/routeFilesReport.ts +46 -0
  25. package/app/routeJsBudget.ts +18 -4
  26. package/artifact/implicitRootLayout.test.ts +19 -0
  27. package/artifact/implicitRootLayout.ts +16 -2
  28. package/artifact/implicitRootLayoutRender.test.tsx +4 -1
  29. package/artifact/storeBootstrap.test.ts +28 -0
  30. package/artifact/storeBootstrap.ts +64 -8
  31. package/biome.base.json +6 -2
  32. package/codeAgent/agent/CodeAgent.ts +36 -16
  33. package/codeAgent/agent/CodeAgentAllowed.ts +35 -0
  34. package/codeAgent/agent/CodeAgentCommandLine.ts +372 -0
  35. package/codeAgent/agent/CodeAgentGate.ts +23 -4
  36. package/codeAgent/agent/CodeAgentRpcHost.ts +1 -1
  37. package/codeAgent/agent/codeAgent.test.ts +62 -0
  38. package/codeAgent/agent/codeAgentCommandLine.test.ts +212 -0
  39. package/codeAgent/agent/codeAgentContract.test.ts +117 -5
  40. package/codeAgent/skills/akan-agent/SKILL.md +8 -1
  41. package/codeAgent/skills/akan-code/SKILL.md +38 -3
  42. package/codeAgent/skills/akan-deps/SKILL.md +3 -2
  43. package/codeAgent/skills/akan-err/SKILL.md +13 -8
  44. package/codeAgent/skills/akan-mcp/SKILL.md +1 -1
  45. package/codeAgent/skills/akan-module/SKILL.md +2 -2
  46. package/codeAgent/skills/akan-page/SKILL.md +34 -26
  47. package/codeAgent/skills/akan-query/SKILL.md +13 -20
  48. package/codeAgent/skills/akan-runtime/SKILL.md +20 -0
  49. package/codeAgent/skills/akan-service/SKILL.md +10 -11
  50. package/codeAgent/skills/akan-transport/SKILL.md +5 -14
  51. package/codeAgent/skills/akan-ui/SKILL.md +2 -5
  52. package/context/akanContext.ts +2 -0
  53. package/csrE2e/devHmrLatency.e2e.test.ts +1 -1
  54. package/docs/apiReference.test.ts +9 -0
  55. package/docs/apiReference.ts +14 -0
  56. package/executors/appExecutor.ts +3 -1
  57. package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
  58. package/executors/clientRuntimeKeys.fixture.json +393 -0
  59. package/executors/clientRuntimeKeys.test.ts +1690 -0
  60. package/executors/executor.ts +12 -4
  61. package/executors/executors.test.ts +2 -0
  62. package/executors/sysExecutor.ts +70 -4
  63. package/executors/workspaceExecutor.ts +7 -4
  64. package/frontendBuild/allRoutesBuilder.ts +99 -7
  65. package/frontendBuild/autoImportSync.ts +3 -2
  66. package/frontendBuild/buildRouteClient.test.ts +686 -13
  67. package/frontendBuild/clientBuildTypes.ts +26 -0
  68. package/frontendBuild/clientEntriesBundler.ts +49 -1
  69. package/frontendBuild/clientEntryDiscovery.test.ts +308 -1
  70. package/frontendBuild/clientEntryDiscovery.ts +136 -14
  71. package/frontendBuild/clientEntryGroups.test.ts +77 -0
  72. package/frontendBuild/clientEntryGroups.ts +61 -0
  73. package/frontendBuild/csrDevArtifactWriter.ts +2 -2
  74. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  75. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  76. package/frontendBuild/csrDevPatcher.test.ts +1 -1
  77. package/frontendBuild/csrDevPatcher.ts +33 -7
  78. package/frontendBuild/csrDevTypes.ts +9 -0
  79. package/frontendBuild/devBarrelImports.test.ts +154 -0
  80. package/frontendBuild/devBarrelImports.ts +83 -23
  81. package/frontendBuild/devRegistryBundler.ts +4 -2
  82. package/frontendBuild/devRouteRuntime.test.ts +492 -0
  83. package/frontendBuild/devRouteRuntime.ts +167 -0
  84. package/frontendBuild/dictionaryAssetBuilder.test.ts +329 -0
  85. package/frontendBuild/dictionaryAssetBuilder.ts +165 -16
  86. package/frontendBuild/dictionaryConstants.ts +136 -0
  87. package/frontendBuild/dictionaryPacking.test.ts +142 -0
  88. package/frontendBuild/dictionaryPacking.ts +135 -0
  89. package/frontendBuild/dictionaryRoutes.test.ts +251 -0
  90. package/frontendBuild/dictionaryRoutes.ts +227 -0
  91. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  92. package/frontendBuild/pagesBundleBuilder.ts +81 -3
  93. package/frontendBuild/precompressArtifacts.test.ts +22 -0
  94. package/frontendBuild/precompressArtifacts.ts +22 -8
  95. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  96. package/frontendBuild/renderedEntries.ts +144 -0
  97. package/frontendBuild/routeClientBuilder.ts +407 -43
  98. package/frontendBuild/routeHandoffs.test.ts +155 -0
  99. package/frontendBuild/routeHandoffs.ts +117 -0
  100. package/frontendBuild/routeModulePreloads.test.ts +32 -0
  101. package/frontendBuild/routeModulePreloads.ts +20 -11
  102. package/frontendBuild/routeRuntimeCheck.test.ts +280 -0
  103. package/frontendBuild/routeRuntimeCheck.ts +248 -0
  104. package/frontendBuild/routeRuntimePays.test.ts +143 -0
  105. package/frontendBuild/routeRuntimePays.ts +117 -0
  106. package/frontendBuild/rscServerRendererGuard.test.ts +60 -0
  107. package/frontendBuild/rscServerRendererGuard.ts +68 -0
  108. package/frontendBuild/ssrBaseArtifactBuilder.ts +24 -34
  109. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  110. package/frontendBuild/ssrDevBundler.ts +66 -11
  111. package/frontendBuild/vendorFileImports.test.ts +254 -0
  112. package/frontendBuild/vendorFileImports.ts +163 -0
  113. package/frontendBuild/vendorNarrowing.ts +28 -0
  114. package/frontendBuild/vendorSpecifiers.ts +2 -0
  115. package/incrementalBuilder/buildBatch.proc.ts +9 -9
  116. package/incrementalBuilder/buildBatchProtocol.ts +1 -1
  117. package/incrementalBuilder/builderBoot.ts +5 -5
  118. package/incrementalBuilder/builderGraphPayloads.ts +4 -4
  119. package/incrementalBuilder/builderLanes.ts +2 -2
  120. package/incrementalBuilder/builderWatch.ts +8 -8
  121. package/incrementalBuilder/csrRegistry.ts +4 -4
  122. package/incrementalBuilder/incrementalBuilder.proc.test.ts +79 -0
  123. package/incrementalBuilder/incrementalBuilder.proc.ts +27 -8
  124. package/incrementalBuilder/ssrRegistry.ts +6 -6
  125. package/index.ts +1 -1
  126. package/integration/renderAdmissionSoak.test.ts +99 -0
  127. package/integration/renderAdmissionSoak.ts +609 -0
  128. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  129. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  130. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  131. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  132. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  133. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  134. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  135. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  136. package/lint/biomeBase.test.ts +21 -2
  137. package/lint/biomeBase.ts +1 -1
  138. package/lint/biomeCheck.test.ts +162 -0
  139. package/lint/biomeCheck.ts +131 -0
  140. package/lint/linter.test.ts +16 -11
  141. package/lint/no-arbitrary-color.grit +5 -0
  142. package/lint/no-conditional-st-hook.grit +5 -1
  143. package/lint/no-daisyui-legacy-class.grit +8 -0
  144. package/lint/no-document-cookie.grit +3 -0
  145. package/lint/no-inline-color.grit +10 -2
  146. package/lint/no-oversized-list-limit.grit +2 -0
  147. package/lint/no-raw-palette-class.grit +7 -0
  148. package/lint/no-unpublished-form-setter.grit +2 -0
  149. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  150. package/lint/no-web-storage.grit +3 -0
  151. package/lint/withheldEnvFile.ts +17 -0
  152. package/mobile/desktopBin.ts +2 -2
  153. package/mobile/desktopServerStage.test.ts +9 -2
  154. package/mobile/desktopServerStage.ts +1 -0
  155. package/mobile/nativeApp.test.ts +7 -5
  156. package/mobile/nativeApp.ts +2 -2
  157. package/mobile/nativeConfig.test.ts +96 -1
  158. package/mobile/nativeConfig.ts +46 -12
  159. package/mobile/nativePublicEnv.ts +1 -1
  160. package/mobile/serverBundleSecrets.ts +43 -0
  161. package/package.json +15 -169
  162. package/packageExports.test.ts +38 -24
  163. package/quality/dictionaryKeys.test.ts +356 -0
  164. package/quality/dictionaryKeys.ts +488 -0
  165. package/quality/objectImportReport.test.ts +36 -0
  166. package/quality/objectImportReport.ts +105 -0
  167. package/quality/qualityScanner.ts +1 -1
  168. package/quality/routeRuntimeReport.test.ts +91 -0
  169. package/quality/routeRuntimeReport.ts +121 -0
  170. package/quality/runtimeConstantFacts.ts +71 -0
  171. package/quality/runtimeConstantGraph.ts +123 -0
  172. package/quality/runtimeConstantReads.ts +116 -0
  173. package/quality/runtimeImports.test.ts +190 -0
  174. package/quality/runtimeImports.ts +233 -0
  175. package/quality/runtimeKeyNames.ts +46 -0
  176. package/quality/runtimeLexicalScope.ts +132 -0
  177. package/quality/runtimeMarkerReach.test.ts +84 -0
  178. package/quality/runtimeMarkerReach.ts +255 -0
  179. package/quality/runtimeModuleFacts.ts +290 -0
  180. package/quality/runtimeNameTable.test.ts +172 -0
  181. package/quality/runtimeNameTable.ts +477 -0
  182. package/quality/runtimeScopeReport.test.ts +123 -0
  183. package/quality/runtimeScopeReport.ts +167 -0
  184. package/quality/runtimeSliceKey.ts +269 -0
  185. package/quality/runtimeSyntax.ts +133 -0
  186. package/quality/runtimeTable.fixture.ts +189 -0
  187. package/quality/runtimeUse.test.ts +737 -0
  188. package/quality/runtimeUse.ts +696 -0
  189. package/quality/runtimeUseReadable.test.ts +393 -0
  190. package/quality/ssrScanner.test.ts +13 -0
  191. package/quality/ssrScanner.ts +1 -1
  192. package/quality/translatorBindings.ts +187 -0
  193. package/test/secretEnvFixture.ts +134 -0
  194. package/test/testHelpers.ts +11 -0
  195. package/transforms/barrelAnalyzer.ts +26 -4
  196. package/transforms/barrelImportsPlugin.ts +121 -32
  197. package/transforms/exportReach.test.ts +162 -0
  198. package/transforms/exportReach.ts +308 -0
  199. package/transforms/frameworkObjects.fixture.tsx +58 -0
  200. package/transforms/frameworkObjects.test.ts +54 -0
  201. package/transforms/modelReference.test.ts +196 -0
  202. package/transforms/modelReference.ts +39 -0
  203. package/transforms/moduleParts.test.ts +225 -0
  204. package/transforms/moduleParts.ts +418 -0
  205. package/transforms/objectImportEdits.ts +150 -0
  206. package/transforms/objectMemberImports.test.ts +633 -0
  207. package/transforms/objectMemberImports.ts +571 -0
  208. package/transforms/objectMemberLookup.ts +150 -0
  209. package/transforms/objectModule.test.ts +307 -0
  210. package/transforms/objectModule.ts +482 -0
  211. package/transforms/objectModuleAnalyzer.ts +104 -0
  212. package/transforms/partImports.test.ts +76 -0
  213. package/transforms/partImports.ts +110 -0
  214. package/transforms/partModules.test.ts +187 -0
  215. package/transforms/partModules.ts +90 -0
  216. package/transforms/partPurity.ts +124 -0
  217. package/transforms/reactIconImports.test.ts +231 -0
  218. package/transforms/reactIconImports.ts +325 -0
  219. package/transforms/routeConstants.ts +122 -0
  220. package/transforms/routeRuntime.test.ts +835 -0
  221. package/transforms/routeRuntime.ts +703 -0
  222. package/transforms/routeRuntimeEdits.ts +92 -0
  223. package/transforms/routeRuntimeGraph.ts +66 -0
  224. package/transforms/routeRuntimePlan.ts +244 -0
  225. package/transforms/secretEnvDeclaration.test.ts +208 -0
  226. package/transforms/secretEnvDeclaration.ts +213 -0
  227. package/transforms/secretEnvFile.test.ts +117 -0
  228. package/transforms/secretEnvFile.ts +113 -0
  229. package/transforms/secretEnvName.test.ts +54 -0
  230. package/transforms/secretEnvName.ts +29 -0
  231. package/transforms/secretEnvSource.test.ts +148 -0
  232. package/transforms/secretEnvSource.ts +166 -0
  233. package/transforms/serverEnvEvaluationError.ts +11 -0
  234. package/transforms/serverEnvPlugin.test.ts +2 -1
  235. package/transforms/serverEnvPlugin.ts +13 -0
  236. package/transforms/serverEnvProfile.test.ts +115 -2
  237. package/transforms/serverEnvProfile.ts +117 -40
  238. package/transforms/serverEnvSecrets.test.ts +292 -0
  239. package/transforms/signalDescriptors.test.ts +280 -0
  240. package/transforms/signalDescriptors.ts +227 -0
  241. package/transforms/thisFreeExports.ts +87 -0
  242. package/transforms/transforms.test.ts +180 -3
  243. package/transforms/tsconfigPackageResolver.test.ts +1 -0
  244. package/tunnel/createTunnel.test.ts +29 -8
  245. package/tunnel/createTunnel.ts +18 -11
  246. package/typecheck/projectTypecheck.test.ts +29 -0
  247. package/typecheck/typeChecker.test.ts +49 -0
  248. package/typecheck/typeChecker.ts +9 -7
  249. package/typecheck/withheldDiagnostics.ts +41 -0
  250. package/util/fileEditor.ts +1 -0
  251. package/util/selectModel.ts +1 -0
  252. package/workflow/executor.ts +6 -2
  253. package/workflow/index.ts +1 -0
  254. package/workflow/plan.ts +36 -7
  255. package/workflow/types.ts +1 -1
  256. package/workflow/uiTarget.ts +50 -0
  257. package/workspace/getRelatedCnsts.ts +7 -0
  258. package/workspace/scanInfo.test.ts +39 -0
  259. package/workspace/scanInfo.ts +48 -5
  260. package/workspace/slicePlanner.ts +1 -1
  261. package/workspace/workspaceLayout.ts +1 -0
@@ -40,10 +40,12 @@ export class SsrBaseArtifactBuilder {
40
40
  #started = Date.now();
41
41
  #serverEnv: BunPlugin | undefined;
42
42
  #vendorExports: Partial<Record<VendorSpecifier, readonly string[]>>;
43
+ #dictionaryRoutes?: ReadonlyMap<string, readonly string[]>;
43
44
 
44
45
  /**
45
46
  * `serverEnv`: the build's server env plugin, so the route bundle carries the env files the backend does and no more.
46
47
  * `vendorExports`: the only names a vendor entry exports, for a build whose every client module is already bundled.
48
+ * `dictionaryRoutes`: the dictionary groups each route can show, for a build that cuts the page dictionary by route.
47
49
  */
48
50
  constructor(
49
51
  app: App,
@@ -51,12 +53,18 @@ export class SsrBaseArtifactBuilder {
51
53
  {
52
54
  serverEnv,
53
55
  vendorExports = {},
54
- }: { serverEnv?: BunPlugin; vendorExports?: Partial<Record<VendorSpecifier, readonly string[]>> } = {},
56
+ dictionaryRoutes,
57
+ }: {
58
+ serverEnv?: BunPlugin;
59
+ vendorExports?: Partial<Record<VendorSpecifier, readonly string[]>>;
60
+ dictionaryRoutes?: ReadonlyMap<string, readonly string[]>;
61
+ } = {},
55
62
  ) {
56
63
  this.#app = app;
57
64
  this.#command = command;
58
65
  this.#serverEnv = serverEnv;
59
66
  this.#vendorExports = vendorExports;
67
+ this.#dictionaryRoutes = dictionaryRoutes;
60
68
  this.#artifactDir = `${command === "build" ? app.dist.cwdPath : app.cwdPath}/.akan/artifact`;
61
69
  this.#absArtifactDir = path.resolve(this.#artifactDir);
62
70
  }
@@ -80,7 +88,7 @@ export class SsrBaseArtifactBuilder {
80
88
  };
81
89
  const { rscClientUrl, rscRuntimeClientManifest, rscRuntimeSsrManifest, vendorMap, runtimeChunks } = await timed(
82
90
  "runtime",
83
- () => this.#buildRuntimeClientEntries(),
91
+ () => this.buildRuntimeClientEntries(),
84
92
  );
85
93
  const pageEntries = await timed("routes", async () => {
86
94
  const pageKeys = await this.#app.getPageKeys();
@@ -88,8 +96,16 @@ export class SsrBaseArtifactBuilder {
88
96
  return await resolveSsrPageEntriesForApp(this.#app, pageKeys);
89
97
  });
90
98
  const { cssCompiler, optimizedFonts, cssAssets } = await timed("styles", () => this.#buildStyleAssets());
91
- const dictAssets = await timed("dictionary", () =>
92
- new DictionaryAssetBuilder(this.#app, this.#absArtifactDir).build(akanConfig.i18n),
99
+ const {
100
+ assets: dictAssets,
101
+ routes: dictRoutes,
102
+ groups: dictGroups,
103
+ } = await timed("dictionary", () =>
104
+ new DictionaryAssetBuilder(this.#app, this.#absArtifactDir).buildAll(akanConfig.i18n, {
105
+ splitApi: true,
106
+ routes: this.#dictionaryRoutes,
107
+ everyGroupAlone: this.#command === "start",
108
+ }),
93
109
  );
94
110
  const pagesBundle = await timed("pages", () =>
95
111
  new PagesBundleBuilder(this.#app, this.#command, pageEntries, this.#serverEnv).build(),
@@ -113,6 +129,8 @@ export class SsrBaseArtifactBuilder {
113
129
  vendorMap,
114
130
  cssAssets,
115
131
  dictAssets,
132
+ ...(dictRoutes ? { dictRoutes } : {}),
133
+ ...(dictGroups ? { dictGroups } : {}),
116
134
  pagesBundlePath:
117
135
  this.#command === "build"
118
136
  ? path.relative(this.#absArtifactDir, pagesBundle.bundlePath)
@@ -152,13 +170,13 @@ export class SsrBaseArtifactBuilder {
152
170
  await rename(`${artifactPath}.tmp`, artifactPath);
153
171
  }
154
172
 
155
- async #buildRuntimeClientEntries(): Promise<
173
+ async buildRuntimeClientEntries(): Promise<
156
174
  Pick<BaseBuildArtifact, "rscClientUrl" | "rscRuntimeClientManifest" | "rscRuntimeSsrManifest"> & {
157
175
  vendorMap: Record<VendorSpecifier, string>;
158
176
  runtimeChunks: RuntimeChunks;
159
177
  }
160
178
  > {
161
- const akanServerPath = await this.#resolveAkanServerPath();
179
+ const akanServerPath = await VendorNarrowing.akanServerPath(this.#app.workspace.workspaceRoot);
162
180
  const rscClientEntry = path.resolve(akanServerPath, "rscClient.tsx");
163
181
  const rscSegmentOutletEntry = path.resolve(akanServerPath, "rscSegmentOutlet.tsx");
164
182
  const vendorEntries = VendorNarrowing.entriesIn(akanServerPath);
@@ -222,34 +240,6 @@ export class SsrBaseArtifactBuilder {
222
240
  return moduleMap;
223
241
  }
224
242
 
225
- async #resolveAkanServerPath() {
226
- const candidates: string[] = [];
227
- try {
228
- candidates.push(path.dirname(Bun.resolveSync("akanjs/server", this.#app.workspace.workspaceRoot)));
229
- } catch {
230
- // Source workspaces and bundled CLI execution have different resolution roots; try explicit candidates below.
231
- }
232
- candidates.push(
233
- path.join(this.#app.workspace.workspaceRoot, "pkgs/akanjs/server"),
234
- path.join(this.#app.workspace.workspaceRoot, "node_modules/akanjs/server"),
235
- );
236
- try {
237
- candidates.push(path.dirname(Bun.resolveSync("akanjs/server", path.dirname(Bun.main))));
238
- } catch {
239
- // Published CLI installs may hoist dependencies differently; explicit Bun.main candidates cover that.
240
- }
241
- candidates.push(
242
- path.join(path.dirname(Bun.main), "node_modules/akanjs/server"),
243
- path.join(path.dirname(Bun.main), "../../akanjs/server"),
244
- path.resolve(import.meta.dir, "../../server"),
245
- path.resolve(import.meta.dir, "../server"),
246
- );
247
- for (const candidate of candidates) {
248
- if (await Bun.file(path.join(candidate, "rscClient.tsx")).exists()) return candidate;
249
- }
250
- throw new Error(`[base-artifact] failed to locate akanjs/server; looked in: ${candidates.join(", ")}`);
251
- }
252
-
253
243
  async #buildStyleAssets(): Promise<{
254
244
  cssCompiler: CssCompiler;
255
245
  optimizedFonts: Awaited<ReturnType<FontOptimizer["optimize"]>>;
@@ -1,6 +1,9 @@
1
- import { describe, expect, test } from "bun:test";
1
+ import { describe, expect, spyOn, test } from "bun:test";
2
2
  import path from "node:path";
3
+ import { StoreBootstrap } from "../artifact/storeBootstrap";
3
4
  import { tempDirs, writeText as write } from "../test/testHelpers";
5
+ import { ModelReference } from "../transforms/modelReference";
6
+ import { RouteRuntime } from "../transforms/routeRuntime";
4
7
  import { SsrDevBundler } from "./ssrDevBundler";
5
8
 
6
9
  const makeTempRoot = tempDirs("akan-ssr-dev-bundler-");
@@ -24,3 +27,149 @@ describe("SsrDevBundler bootstrap", () => {
24
27
  expect(await bootstrapOf(await makeTempRoot())).toBe("export {};\n");
25
28
  });
26
29
  });
30
+
31
+ describe("SsrDevBundler loading per module", () => {
32
+ const appOf = (root: string, warnings: string[] = []) =>
33
+ ({
34
+ name: "demo",
35
+ cwdPath: path.join(root, "apps/demo"),
36
+ workspace: { workspaceRoot: root },
37
+ basePaths: new Set<string>(),
38
+ getConfig: async () => ({ optimizeImports: [], barrelImports: [], basePaths: new Set<string>() }),
39
+ getPublicEnv: () => ({}),
40
+ logger: { warn: (message: string) => warnings.push(message) },
41
+ }) as never;
42
+ const writeLib = async (root: string, files: string[]) => {
43
+ for (const file of files) await write(path.join(root, "apps/demo/lib", file), "export {};\n");
44
+ };
45
+
46
+ const pageFiles = [
47
+ "st.ts",
48
+ "useClient.ts",
49
+ `${StoreBootstrap.pageRuntime}.ts`,
50
+ `${StoreBootstrap.baseDescriptors}.ts`,
51
+ ...StoreBootstrap.assembled.map((file) => `${file}.ts`),
52
+ `${ModelReference.registry}.ts`,
53
+ ];
54
+
55
+ const writeFrameworkBase = async (root: string) => {
56
+ const akanjsRoot = path.dirname(Bun.resolveSync("akanjs/package.json", import.meta.dir));
57
+ for (const file of ["package.json", "store/baseSt.ts", "signal/base.signal.ts", "signal/agent.signal.ts"])
58
+ await write(path.join(root, "node_modules/akanjs", file), await Bun.file(path.join(akanjsRoot, file)).text());
59
+ };
60
+
61
+ test("boots the page runtime with the framework's own descriptors and answers the model runtime marker with the app's assembled pieces", async () => {
62
+ const root = await makeTempRoot();
63
+ await writeLib(root, pageFiles);
64
+ await writeFrameworkBase(root);
65
+ const warnings: string[] = [];
66
+ const bundler = new SsrDevBundler(appOf(root, warnings));
67
+ const context = await bundler.context();
68
+ const { files } = await bundler.writeEntries(context);
69
+
70
+ expect(warnings).toEqual([]);
71
+
72
+ const bootstrap = await Bun.file(files[SsrDevBundler.bootstrapKey] ?? "").text();
73
+ expect(bootstrap).toStartWith(
74
+ `import "@apps/demo/lib/${StoreBootstrap.pageRuntime}";\nimport "@apps/demo/lib/${StoreBootstrap.baseDescriptors}";\n`,
75
+ );
76
+ expect(bootstrap).toEndWith('import "./storeOwners";\n');
77
+ const owners = path.join(path.dirname(files[SsrDevBundler.bootstrapKey] ?? ""), "storeOwners.ts");
78
+ expect(await Bun.file(owners).text()).toContain('[Symbol.for("akanjs.store.owners")] = {"use":');
79
+ expect(context.routeRuntime).toBeDefined();
80
+ const [useClient, st] = StoreBootstrap.assembled.map((piece) =>
81
+ JSON.stringify(path.join(root, "apps/demo/lib", `${piece}.ts`).split(path.sep).join("/")),
82
+ );
83
+ const constants = JSON.stringify(path.join(root, "apps/demo/lib/cnst.ts").split(path.sep).join("/"));
84
+ expect(context.modelRuntime).toBe(
85
+ [
86
+ 'import { loadedAfter as __akanLoadedAfter } from "akanjs/base";',
87
+ `import * as __akanLoaded0 from ${constants};`,
88
+ `import { sig as __akanLoaded1 } from ${useClient};`,
89
+ `import { st as __akanLoaded2 } from ${st};`,
90
+ "__akanLoadedAfter(__akanLoaded0, __akanLoaded1, __akanLoaded2);",
91
+ "",
92
+ ].join("\n"),
93
+ );
94
+ await Bun.file(path.join(root, "apps/demo/lib", pageFiles.at(-1) ?? "")).delete();
95
+ const whole = await new SsrDevBundler(appOf(root)).context();
96
+ expect(context.configKey).not.toBe(whole.configKey);
97
+ expect(whole.routeRuntime).toBeUndefined();
98
+ expect(whole.modelRuntime).toBeUndefined();
99
+ });
100
+
101
+ for (const missing of pageFiles.slice(2))
102
+ test(`keeps the whole runtime when the app was not synced to lib/${missing} yet`, async () => {
103
+ const root = await makeTempRoot();
104
+ await writeLib(
105
+ root,
106
+ pageFiles.filter((file) => file !== missing),
107
+ );
108
+ const bundler = new SsrDevBundler(appOf(root));
109
+ const context = await bundler.context();
110
+ const { files } = await bundler.writeEntries(context);
111
+
112
+ expect(context.modelRuntime).toBeUndefined();
113
+ expect(await Bun.file(files[SsrDevBundler.bootstrapKey] ?? "").text()).toBe(
114
+ 'import "@apps/demo/lib/useClient";\nimport "@apps/demo/lib/st";\n',
115
+ );
116
+ });
117
+
118
+ test("says once, not on every save, that an app missing its runtime files loads the whole runtime", async () => {
119
+ const root = await makeTempRoot();
120
+ await writeLib(root, pageFiles.slice(0, -1));
121
+ await writeFrameworkBase(root);
122
+ const warnings: string[] = [];
123
+ const bundler = new SsrDevBundler(appOf(root, warnings));
124
+
125
+ await bundler.context();
126
+ await bundler.context();
127
+ expect(warnings).toHaveLength(1);
128
+ expect(warnings[0]).toBe(
129
+ "[client-runtime] the per-module runtime files of demo or a lib it mounts are missing, so every page of the development server loads the whole client runtime, not only what it uses. Run `akan sync demo`.",
130
+ );
131
+
132
+ await writeLib(root, pageFiles.slice(-1));
133
+ expect((await bundler.context()).routeRuntime).toBeDefined();
134
+ await Bun.file(path.join(root, "apps/demo/lib", pageFiles.at(-1) ?? "")).delete();
135
+ await bundler.context();
136
+ expect(warnings).toHaveLength(2);
137
+ });
138
+
139
+ test("loads per module again once a lib the app mounts is synced, with no change to the app's own files", async () => {
140
+ const root = await makeTempRoot();
141
+ await writeLib(root, pageFiles);
142
+ await write(path.join(root, "apps/demo/lib/st.ts"), 'export { st as shared } from "@libs/shared/client";\n');
143
+ await writeFrameworkBase(root);
144
+ const warnings: string[] = [];
145
+ const bundler = new SsrDevBundler(appOf(root, warnings));
146
+
147
+ expect((await bundler.context()).routeRuntime).toBeUndefined();
148
+ expect(warnings).toEqual([expect.stringContaining("runtime files of demo or a lib it mounts are missing")]);
149
+
150
+ await write(path.join(root, "libs/shared/lib/st.ts"), "export const st = {};\n");
151
+ expect((await bundler.context()).routeRuntime?.scopes).toEqual(["libs/shared", "apps/demo"]);
152
+ expect(warnings).toHaveLength(1);
153
+ });
154
+
155
+ test("says what failed when the modules cannot be read, and loads per module again once they can", async () => {
156
+ const root = await makeTempRoot();
157
+ await writeLib(root, pageFiles);
158
+ await writeFrameworkBase(root);
159
+ const warnings: string[] = [];
160
+ const bundler = new SsrDevBundler(appOf(root, warnings));
161
+ const read = spyOn(RouteRuntime, "read").mockRejectedValue(new Error("memo.store.ts is unreadable"));
162
+ try {
163
+ expect((await bundler.context()).routeRuntime).toBeUndefined();
164
+ await bundler.context();
165
+ } finally {
166
+ read.mockRestore();
167
+ }
168
+
169
+ expect(warnings).toEqual([
170
+ expect.stringContaining("the modules of demo or a lib it mounts could not be read (memo.store.ts is unreadable)"),
171
+ ]);
172
+ expect(warnings[0]).toContain("Fix that, then run `akan sync demo`.");
173
+ expect((await bundler.context()).routeRuntime).toBeDefined();
174
+ });
175
+ });
@@ -5,14 +5,14 @@ import { resolveSsrPageEntriesForApp } from "../artifact/implicitRootLayout";
5
5
  import { computeRouteSeedIndex } from "../artifact/routeSeedIndex";
6
6
  import { StoreBootstrap } from "../artifact/storeBootstrap";
7
7
  import type { App } from "../commandDecorators";
8
- import { workspaceBarrels } from "../transforms/barrelImportsPlugin";
9
8
  import { bundleDefine } from "./bundleDefine";
10
9
  import type { ClientEntryDiscovery } from "./clientBuildTypes";
11
10
  import { GraphClientEntryDiscovery } from "./clientEntryDiscovery";
12
11
  import { CsrDevPaths } from "./csrDevPaths";
13
12
  import type { CsrDevContext } from "./csrDevTypes";
14
13
  import { DevRegistryBundler } from "./devRegistryBundler";
15
- import { VENDOR_SPECIFIERS } from "./vendorSpecifiers";
14
+ import { DevRouteRuntime } from "./devRouteRuntime";
15
+ import { VendorFileImports } from "./vendorFileImports";
16
16
 
17
17
  //* Dev-only client code of SSR pages as a module registry, under `.akan/artifact/ssr-dev`. Its roots are a bootstrap
18
18
  //* (the app's client runtime) and every `"use client"` entry; React and the akanjs vendor facets stay the import map's,
@@ -23,6 +23,8 @@ export class SsrDevBundler extends DevRegistryBundler {
23
23
  readonly reloadsOnEntryChange = false;
24
24
  #discovery: ClientEntryDiscovery | null = null;
25
25
  readonly #sharedDiscovery: (() => ClientEntryDiscovery) | null;
26
+ #route: { inputs: string; runtime: DevRouteRuntime } | null = null;
27
+ #wholeWarned: string | null = null;
26
28
 
27
29
  /** `discovery` is the resident builder's, which it keeps current with every save; a worker discovers afresh. */
28
30
  constructor(app: App, { discovery }: { discovery?: () => ClientEntryDiscovery } = {}) {
@@ -34,7 +36,16 @@ export class SsrDevBundler extends DevRegistryBundler {
34
36
  const akanConfig = await this.app.getConfig();
35
37
  const define = bundleDefine(this.app, "start", "ssr");
36
38
  const optimizeImports = [...akanConfig.optimizeImports];
37
- const barrelImports = workspaceBarrels(akanConfig.barrelImports);
39
+ const externals = await VendorFileImports.specifiersIn(this.app.workspace.workspaceRoot);
40
+ //? The framework barrels narrow as in a route build: `akanjs/ui` whole names every model runtime marker, which
41
+ //? would load every module's store on every page.
42
+ const barrelImports = [...new Set(akanConfig.barrelImports)].filter(
43
+ (barrel) => barrel && !(externals as readonly string[]).includes(barrel),
44
+ );
45
+ const route = await this.#routeRuntime();
46
+ const routeRuntime = typeof route === "string" ? null : route;
47
+ this.#warnWhole(typeof route === "string" ? route : null);
48
+ const modelRuntime = routeRuntime?.wholeSource;
38
49
  const configKey = Bun.hash(
39
50
  JSON.stringify([
40
51
  "ssr",
@@ -42,8 +53,9 @@ export class SsrDevBundler extends DevRegistryBundler {
42
53
  Bun.version,
43
54
  define,
44
55
  optimizeImports,
45
- VENDOR_SPECIFIERS,
56
+ externals,
46
57
  barrelImports,
58
+ ...(modelRuntime === undefined ? [] : [modelRuntime]),
47
59
  ]),
48
60
  ).toString(36);
49
61
  return {
@@ -54,27 +66,70 @@ export class SsrDevBundler extends DevRegistryBundler {
54
66
  optimizeImports,
55
67
  configKey,
56
68
  refreshFile: null,
57
- externals: VENDOR_SPECIFIERS,
69
+ externals,
58
70
  barrelImports,
71
+ ...(routeRuntime ? { modelRuntime, routeRuntime } : {}),
59
72
  };
60
73
  }
61
74
 
62
- //? The client runtime of an SSR page inlines no dictionary (`useClient.ts` reads one only when rendering csr), so
75
+ //? A runtime that could not be read is never kept: syncing a lib it mounts changes none of the app's own inputs.
76
+ async #routeRuntime(): Promise<DevRouteRuntime | string> {
77
+ const { name } = this.app;
78
+ const whole = (why: string, first = "Run") =>
79
+ `[client-runtime] ${why}, so every page of the development server loads the whole client runtime, not only what it uses. ${first} \`akan sync ${name}\`.`;
80
+ const missing = whole(`the per-module runtime files of ${name} or a lib it mounts are missing`);
81
+ if ((await StoreBootstrap.scopeOf(this.app)) !== "page") return missing;
82
+ const root = this.app.workspace.workspaceRoot;
83
+ const scope = `apps/${name}`;
84
+ const scopes = this.#route?.runtime.scopes ?? [scope];
85
+ const inputs = DevRouteRuntime.inputsOf(root, scopes);
86
+ if (this.#route?.inputs === inputs) return this.#route.runtime;
87
+ this.#route = null;
88
+ try {
89
+ const runtime = await DevRouteRuntime.read(root, scope);
90
+ if (!runtime) return missing;
91
+ const moved = JSON.stringify(runtime.scopes) !== JSON.stringify(scopes);
92
+ this.#route = { inputs: moved ? DevRouteRuntime.inputsOf(root, runtime.scopes) : inputs, runtime };
93
+ return runtime;
94
+ } catch (error) {
95
+ const reason = error instanceof Error ? error.message : String(error);
96
+ return whole(`the modules of ${name} or a lib it mounts could not be read (${reason})`, "Fix that, then run");
97
+ }
98
+ }
99
+
100
+ #warnWhole(warning: string | null) {
101
+ if (warning && warning !== this.#wholeWarned) this.app.logger.warn(warning);
102
+ this.#wholeWarned = warning;
103
+ }
104
+
105
+ //? The client runtime of an SSR page inlines no dictionary (`lib/usePage.ts` reads one only when rendering csr), so
63
106
  //? a dictionary save is none of this registry's business.
64
107
  override isMetadataFile(file: string): boolean {
65
108
  return super.isMetadataFile(file) && !file.endsWith(".dictionary.ts") && path.basename(file) !== "dict.ts";
66
109
  }
67
110
 
68
111
  // Run first in the tab, before any client module the payload names: the store registry must exist by then.
69
- async writeEntries(): Promise<{ files: Record<string, string>; changed: string[] }> {
112
+ async writeEntries(context?: CsrDevContext): Promise<{ files: Record<string, string>; changed: string[] }> {
70
113
  await mkdir(this.entryDir, { recursive: true });
71
- const file = path.join(this.entryDir, "bootstrap.ts");
72
114
  const hasStore = await Bun.file(path.join(this.app.cwdPath, "lib", "st.ts")).exists();
73
- const source = hasStore ? StoreBootstrap.source(this.app.name) : "export {};\n";
115
+ const scope = context?.modelRuntime === undefined ? "whole" : "page";
116
+ const owners = hasStore ? context?.routeRuntime?.ownersSource() : undefined;
117
+ const { ownersModule } = DevRouteRuntime;
118
+ const bootstrap = hasStore
119
+ ? `${StoreBootstrap.source(this.app.name, scope)}${owners ? `import "./${ownersModule}";\n` : ""}`
120
+ : "export {};\n";
121
+ const entryFile = await SsrDevBundler.#writeIfChanged(path.join(this.entryDir, "bootstrap.ts"), bootstrap);
122
+ const ownersFile = owners
123
+ ? await SsrDevBundler.#writeIfChanged(path.join(this.entryDir, `${ownersModule}.ts`), owners)
124
+ : null;
125
+ const changed = [entryFile, ownersFile].flatMap((written) => (written?.changed ? [written.file] : []));
126
+ return { files: { [SsrDevBundler.bootstrapKey]: entryFile.file }, changed };
127
+ }
128
+
129
+ static async #writeIfChanged(file: string, source: string): Promise<{ file: string; changed: boolean }> {
74
130
  const unchanged = (await Bun.file(file).exists()) && (await Bun.file(file).text()) === source;
75
131
  if (!unchanged) await Bun.write(file, source);
76
- const entryFile = CsrDevPaths.realpath(file);
77
- return { files: { [SsrDevBundler.bootstrapKey]: entryFile }, changed: unchanged ? [] : [entryFile] };
132
+ return { file: CsrDevPaths.realpath(file), changed: !unchanged };
78
133
  }
79
134
 
80
135
  /** Every `"use client"` entry the app's routes reach, the ones a route build names in its manifest. */