@akanjs/devkit 3.3.0-rc.4 → 3.3.0-rc.41

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 (252) hide show
  1. package/CHANGELOG.md +628 -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 +133 -6
  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 -4
  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 +31 -20
  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 +2 -5
  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/docs/apiReference.test.ts +9 -0
  54. package/docs/apiReference.ts +14 -0
  55. package/executors/appExecutor.ts +3 -1
  56. package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
  57. package/executors/clientRuntimeKeys.fixture.json +393 -0
  58. package/executors/clientRuntimeKeys.test.ts +1690 -0
  59. package/executors/executors.test.ts +2 -0
  60. package/executors/sysExecutor.ts +70 -4
  61. package/executors/workspaceExecutor.ts +7 -4
  62. package/frontendBuild/allRoutesBuilder.ts +88 -7
  63. package/frontendBuild/autoImportSync.ts +3 -2
  64. package/frontendBuild/buildRouteClient.test.ts +666 -12
  65. package/frontendBuild/clientBuildTypes.ts +26 -0
  66. package/frontendBuild/clientEntriesBundler.ts +49 -1
  67. package/frontendBuild/clientEntryDiscovery.test.ts +308 -1
  68. package/frontendBuild/clientEntryDiscovery.ts +135 -13
  69. package/frontendBuild/clientEntryGroups.test.ts +77 -0
  70. package/frontendBuild/clientEntryGroups.ts +61 -0
  71. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  72. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  73. package/frontendBuild/csrDevPatcher.ts +33 -7
  74. package/frontendBuild/csrDevTypes.ts +9 -0
  75. package/frontendBuild/devBarrelImports.test.ts +154 -0
  76. package/frontendBuild/devBarrelImports.ts +83 -23
  77. package/frontendBuild/devRegistryBundler.ts +4 -2
  78. package/frontendBuild/devRouteRuntime.test.ts +492 -0
  79. package/frontendBuild/devRouteRuntime.ts +167 -0
  80. package/frontendBuild/dictionaryAssetBuilder.test.ts +324 -0
  81. package/frontendBuild/dictionaryAssetBuilder.ts +165 -16
  82. package/frontendBuild/dictionaryConstants.ts +136 -0
  83. package/frontendBuild/dictionaryPacking.test.ts +142 -0
  84. package/frontendBuild/dictionaryPacking.ts +135 -0
  85. package/frontendBuild/dictionaryRoutes.test.ts +251 -0
  86. package/frontendBuild/dictionaryRoutes.ts +227 -0
  87. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  88. package/frontendBuild/pagesBundleBuilder.ts +81 -3
  89. package/frontendBuild/precompressArtifacts.test.ts +22 -0
  90. package/frontendBuild/precompressArtifacts.ts +22 -8
  91. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  92. package/frontendBuild/renderedEntries.ts +144 -0
  93. package/frontendBuild/routeClientBuilder.ts +405 -43
  94. package/frontendBuild/routeHandoffs.test.ts +155 -0
  95. package/frontendBuild/routeHandoffs.ts +117 -0
  96. package/frontendBuild/routeModulePreloads.test.ts +32 -0
  97. package/frontendBuild/routeModulePreloads.ts +20 -11
  98. package/frontendBuild/routeRuntimeCheck.test.ts +280 -0
  99. package/frontendBuild/routeRuntimeCheck.ts +248 -0
  100. package/frontendBuild/routeRuntimePays.test.ts +143 -0
  101. package/frontendBuild/routeRuntimePays.ts +117 -0
  102. package/frontendBuild/rscServerRendererGuard.test.ts +60 -0
  103. package/frontendBuild/rscServerRendererGuard.ts +68 -0
  104. package/frontendBuild/ssrBaseArtifactBuilder.ts +24 -34
  105. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  106. package/frontendBuild/ssrDevBundler.ts +66 -11
  107. package/frontendBuild/vendorFileImports.test.ts +254 -0
  108. package/frontendBuild/vendorFileImports.ts +163 -0
  109. package/frontendBuild/vendorNarrowing.ts +28 -0
  110. package/frontendBuild/vendorSpecifiers.ts +2 -0
  111. package/incrementalBuilder/buildBatch.proc.ts +9 -9
  112. package/incrementalBuilder/buildBatchProtocol.ts +1 -1
  113. package/incrementalBuilder/builderBoot.ts +5 -5
  114. package/incrementalBuilder/builderGraphPayloads.ts +4 -4
  115. package/incrementalBuilder/builderLanes.ts +2 -2
  116. package/incrementalBuilder/builderWatch.ts +8 -8
  117. package/incrementalBuilder/csrRegistry.ts +4 -4
  118. package/incrementalBuilder/incrementalBuilder.proc.test.ts +79 -0
  119. package/incrementalBuilder/incrementalBuilder.proc.ts +27 -8
  120. package/incrementalBuilder/ssrRegistry.ts +6 -6
  121. package/index.ts +1 -1
  122. package/integration/renderAdmissionSoak.test.ts +99 -0
  123. package/integration/renderAdmissionSoak.ts +609 -0
  124. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  125. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  126. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  127. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  128. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  129. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  130. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  131. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  132. package/lint/biomeBase.test.ts +23 -3
  133. package/lint/biomeCheck.test.ts +145 -0
  134. package/lint/biomeCheck.ts +131 -0
  135. package/lint/no-arbitrary-color.grit +5 -0
  136. package/lint/no-conditional-st-hook.grit +5 -1
  137. package/lint/no-daisyui-legacy-class.grit +8 -0
  138. package/lint/no-document-cookie.grit +3 -0
  139. package/lint/no-inline-color.grit +10 -2
  140. package/lint/no-oversized-list-limit.grit +2 -0
  141. package/lint/no-raw-palette-class.grit +7 -0
  142. package/lint/no-unpublished-form-setter.grit +2 -0
  143. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  144. package/lint/no-web-storage.grit +3 -0
  145. package/lint/withheldEnvFile.ts +17 -0
  146. package/mobile/desktopBin.ts +2 -2
  147. package/mobile/desktopServerStage.ts +1 -0
  148. package/mobile/nativeApp.test.ts +7 -5
  149. package/mobile/nativeApp.ts +2 -2
  150. package/mobile/nativeConfig.test.ts +96 -1
  151. package/mobile/nativeConfig.ts +46 -12
  152. package/mobile/serverBundleSecrets.ts +43 -0
  153. package/package.json +15 -169
  154. package/packageExports.test.ts +38 -24
  155. package/quality/dictionaryKeys.test.ts +356 -0
  156. package/quality/dictionaryKeys.ts +488 -0
  157. package/quality/objectImportReport.test.ts +36 -0
  158. package/quality/objectImportReport.ts +105 -0
  159. package/quality/qualityScanner.ts +1 -1
  160. package/quality/routeRuntimeReport.test.ts +91 -0
  161. package/quality/routeRuntimeReport.ts +121 -0
  162. package/quality/runtimeConstantFacts.ts +71 -0
  163. package/quality/runtimeConstantGraph.ts +123 -0
  164. package/quality/runtimeConstantReads.ts +116 -0
  165. package/quality/runtimeImports.test.ts +190 -0
  166. package/quality/runtimeImports.ts +233 -0
  167. package/quality/runtimeKeyNames.ts +46 -0
  168. package/quality/runtimeLexicalScope.ts +132 -0
  169. package/quality/runtimeMarkerReach.test.ts +84 -0
  170. package/quality/runtimeMarkerReach.ts +255 -0
  171. package/quality/runtimeModuleFacts.ts +290 -0
  172. package/quality/runtimeNameTable.test.ts +172 -0
  173. package/quality/runtimeNameTable.ts +477 -0
  174. package/quality/runtimeScopeReport.test.ts +123 -0
  175. package/quality/runtimeScopeReport.ts +167 -0
  176. package/quality/runtimeSliceKey.ts +269 -0
  177. package/quality/runtimeSyntax.ts +133 -0
  178. package/quality/runtimeTable.fixture.ts +189 -0
  179. package/quality/runtimeUse.test.ts +737 -0
  180. package/quality/runtimeUse.ts +696 -0
  181. package/quality/runtimeUseReadable.test.ts +393 -0
  182. package/quality/ssrScanner.test.ts +13 -0
  183. package/quality/ssrScanner.ts +1 -1
  184. package/quality/translatorBindings.ts +187 -0
  185. package/test/secretEnvFixture.ts +134 -0
  186. package/test/testHelpers.ts +11 -0
  187. package/transforms/barrelAnalyzer.ts +26 -4
  188. package/transforms/barrelImportsPlugin.ts +121 -32
  189. package/transforms/exportReach.test.ts +162 -0
  190. package/transforms/exportReach.ts +308 -0
  191. package/transforms/frameworkObjects.fixture.tsx +58 -0
  192. package/transforms/frameworkObjects.test.ts +54 -0
  193. package/transforms/modelReference.test.ts +196 -0
  194. package/transforms/modelReference.ts +39 -0
  195. package/transforms/moduleParts.test.ts +225 -0
  196. package/transforms/moduleParts.ts +418 -0
  197. package/transforms/objectImportEdits.ts +150 -0
  198. package/transforms/objectMemberImports.test.ts +629 -0
  199. package/transforms/objectMemberImports.ts +571 -0
  200. package/transforms/objectMemberLookup.ts +150 -0
  201. package/transforms/objectModule.test.ts +307 -0
  202. package/transforms/objectModule.ts +482 -0
  203. package/transforms/objectModuleAnalyzer.ts +104 -0
  204. package/transforms/partImports.test.ts +76 -0
  205. package/transforms/partImports.ts +110 -0
  206. package/transforms/partModules.test.ts +187 -0
  207. package/transforms/partModules.ts +90 -0
  208. package/transforms/partPurity.ts +124 -0
  209. package/transforms/reactIconImports.test.ts +231 -0
  210. package/transforms/reactIconImports.ts +325 -0
  211. package/transforms/routeConstants.ts +122 -0
  212. package/transforms/routeRuntime.test.ts +835 -0
  213. package/transforms/routeRuntime.ts +703 -0
  214. package/transforms/routeRuntimeEdits.ts +92 -0
  215. package/transforms/routeRuntimeGraph.ts +66 -0
  216. package/transforms/routeRuntimePlan.ts +244 -0
  217. package/transforms/secretEnvDeclaration.test.ts +208 -0
  218. package/transforms/secretEnvDeclaration.ts +213 -0
  219. package/transforms/secretEnvFile.test.ts +117 -0
  220. package/transforms/secretEnvFile.ts +113 -0
  221. package/transforms/secretEnvName.test.ts +54 -0
  222. package/transforms/secretEnvName.ts +29 -0
  223. package/transforms/secretEnvSource.test.ts +148 -0
  224. package/transforms/secretEnvSource.ts +166 -0
  225. package/transforms/serverEnvEvaluationError.ts +11 -0
  226. package/transforms/serverEnvPlugin.test.ts +2 -1
  227. package/transforms/serverEnvPlugin.ts +13 -0
  228. package/transforms/serverEnvProfile.test.ts +115 -2
  229. package/transforms/serverEnvProfile.ts +117 -40
  230. package/transforms/serverEnvSecrets.test.ts +292 -0
  231. package/transforms/signalDescriptors.test.ts +280 -0
  232. package/transforms/signalDescriptors.ts +227 -0
  233. package/transforms/thisFreeExports.ts +87 -0
  234. package/transforms/transforms.test.ts +180 -3
  235. package/transforms/tsconfigPackageResolver.test.ts +1 -0
  236. package/tunnel/createTunnel.test.ts +29 -8
  237. package/tunnel/createTunnel.ts +18 -11
  238. package/typecheck/projectTypecheck.test.ts +29 -0
  239. package/typecheck/typeChecker.test.ts +49 -0
  240. package/typecheck/typeChecker.ts +9 -7
  241. package/typecheck/withheldDiagnostics.ts +41 -0
  242. package/util/fileEditor.ts +1 -0
  243. package/util/selectModel.ts +1 -0
  244. package/workflow/executor.ts +6 -2
  245. package/workflow/index.ts +1 -0
  246. package/workflow/plan.ts +36 -7
  247. package/workflow/types.ts +1 -1
  248. package/workflow/uiTarget.ts +50 -0
  249. package/workspace/getRelatedCnsts.ts +7 -0
  250. package/workspace/scanInfo.test.ts +39 -0
  251. package/workspace/scanInfo.ts +48 -5
  252. package/workspace/workspaceLayout.ts +1 -0
@@ -1,17 +1,27 @@
1
- import { mkdir } from "node:fs/promises";
1
+ import { mkdir, rm } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import type { BaseBuildArtifact, ClientManifest, ClientManifestEntry, SsrManifest } from "akanjs/server";
4
4
  import { SSR_DEV_CHUNK, SSR_DEV_ID_PREFIX } from "akanjs/server/hmr/csrDevManifest";
5
- import { StoreBootstrap } from "../artifact/storeBootstrap";
5
+ import { type ClientRuntimeScope, StoreBootstrap } from "../artifact/storeBootstrap";
6
6
  import type { App } from "../commandDecorators";
7
+ import { type RouteRuntimeBuildReport, RouteRuntimeReport } from "../quality/routeRuntimeReport";
7
8
  import { createBarrelImportsPlugin } from "../transforms/barrelImportsPlugin";
9
+ import { ModuleParts } from "../transforms/moduleParts";
8
10
  import { loaderFor } from "../transforms/moduleSyntax";
11
+ import { PartModules } from "../transforms/partModules";
12
+ import { ReactIconImports } from "../transforms/reactIconImports";
13
+ import { RouteRuntime } from "../transforms/routeRuntime";
14
+ import type { RouteRuntimeBundle } from "../transforms/routeRuntimeGraph";
9
15
  import { scanUseClientExports, toClientReferencePath } from "../transforms/rscUseClientTransform";
10
- import type { ClientBundleTarget, ClientEntryDiscovery } from "./clientBuildTypes";
16
+ import { SignalDescriptors } from "../transforms/signalDescriptors";
17
+ import type { AskedExports, ClientBundleTarget, ClientEntryDiscovery, ClientModuleImport } from "./clientBuildTypes";
11
18
  import { ClientEntriesBundler } from "./clientEntriesBundler";
12
19
  import { GraphClientEntryDiscovery } from "./clientEntryDiscovery";
20
+ import { ClientEntryGroups, type ClientEntryPart, type GroupedExport } from "./clientEntryGroups";
13
21
  import { CsrDevPaths } from "./csrDevPaths";
14
- import { VENDOR_SPECIFIERS } from "./vendorSpecifiers";
22
+ import { RouteRuntimeCheck } from "./routeRuntimeCheck";
23
+ import { type RoutePaysVerdict, RouteRuntimePays } from "./routeRuntimePays";
24
+ import { VendorFileImports } from "./vendorFileImports";
15
25
 
16
26
  const SSR_CLIENT_ALIAS_EXTERNALS = [
17
27
  "react",
@@ -36,6 +46,12 @@ export interface BuildRouteClientOptions {
36
46
  entries?: string[];
37
47
  /** Defaults to `registry` under `start`: the browser loads each entry from the SSR dev registry, so only `client-ssr` builds. */
38
48
  browser?: "chunks" | "registry";
49
+ /** The entries each route loads: an entry only whole-runtime routes hold keeps the whole runtime too. */
50
+ entriesByRoute?: ReadonlyMap<string, readonly string[]>;
51
+ /** The entries each route loads first, which its size is measured over. Defaults to `entriesByRoute`. */
52
+ sizedEntriesByRoute?: ReadonlyMap<string, readonly string[]>;
53
+ /** The exports each route asks of an entry it loads first; an entry left out, or null, is asked for all of them. */
54
+ askedByRoute?: ReadonlyMap<string, AskedExports>;
39
55
  }
40
56
 
41
57
  export interface BuildRouteClientResult {
@@ -49,13 +65,38 @@ export interface BuildRouteClientResult {
49
65
  registryEntries?: string[];
50
66
  /** Chunks mode: the importmap specifiers each browser chunk imports statically. */
51
67
  externalsByChunkUrl?: Record<string, string[]>;
68
+ /** The imports of every module the browser loads, or in registry mode of the SSR bundle standing in for it. */
69
+ clientGraph?: ReadonlyMap<string, readonly ClientModuleImport[]>;
52
70
  }
53
71
 
54
72
  interface BootstrapEntries {
55
73
  buildEntries: string[];
56
74
  originalByBuildEntry: Map<string, string>;
75
+ //? Only for an entry built as several: the export names each of its build entries holds.
76
+ namesByBuildEntry?: Map<string, readonly string[]>;
77
+ //? Only for a build entry holding several entries: each name it exports, with the entry and the name behind it.
78
+ membersByBuildEntry?: Map<string, ReadonlyMap<string, GroupedExport>>;
57
79
  }
58
80
 
81
+ interface WrappedPart extends ClientEntryPart {
82
+ file: string;
83
+ split: boolean;
84
+ }
85
+
86
+ interface NarrowedBuild {
87
+ entries: BootstrapEntries;
88
+ kept: ReadonlySet<string>;
89
+ bundle: Awaited<ReturnType<ClientEntriesBundler["bundle"]>>;
90
+ runtime: RouteRuntime;
91
+ report?: RouteRuntimeBuildReport;
92
+ }
93
+
94
+ type BundleOf = (runtime: RouteRuntime, kept: ReadonlySet<string>, outputSubdir?: string) => Promise<NarrowedBuild>;
95
+
96
+ const referenceSubdir = "client-whole";
97
+ //? Each trial bundles the whole app again, and the entries left to try shrink slowly where pages share most of them.
98
+ const measuredTrials = 6;
99
+
59
100
  export class RouteClientBuilder {
60
101
  #app: App;
61
102
  #seeds: string[];
@@ -65,6 +106,10 @@ export class RouteClientBuilder {
65
106
  #discovery?: ClientEntryDiscovery;
66
107
  #entries?: string[];
67
108
  #browser: "chunks" | "registry";
109
+ #entriesByRoute?: ReadonlyMap<string, readonly string[]>;
110
+ #sizedEntriesByRoute?: ReadonlyMap<string, readonly string[]>;
111
+ #askedByRoute?: ReadonlyMap<string, AskedExports>;
112
+ readonly #parts = new Map<string, ModuleParts | null>();
68
113
 
69
114
  constructor(options: BuildRouteClientOptions) {
70
115
  this.#app = options.app;
@@ -75,6 +120,9 @@ export class RouteClientBuilder {
75
120
  this.#discovery = options.discovery;
76
121
  this.#entries = options.entries;
77
122
  this.#browser = options.browser ?? (this.#command === "start" ? "registry" : "chunks");
123
+ this.#entriesByRoute = options.entriesByRoute;
124
+ this.#sizedEntriesByRoute = options.sizedEntriesByRoute;
125
+ this.#askedByRoute = options.askedByRoute;
78
126
  }
79
127
 
80
128
  async build(): Promise<BuildRouteClientResult> {
@@ -84,12 +132,34 @@ export class RouteClientBuilder {
84
132
  ? [...new Set([...discovered, ...(await (await this.#getDiscovery()).discover(this.#graphSeeds))])].sort()
85
133
  : discovered.filter((e) => !this.#knownEntries.has(e));
86
134
 
87
- const bootstrapEntries = await this.#createBootstrapEntries(entries);
88
135
  //? Registry mode builds no browser bundle: the SSR bundle has the same entries, exports and imports to read.
89
136
  const registry = this.#browser === "registry" ? new CsrDevPaths(this.#app.workspace.workspaceRoot) : null;
90
- const browserBundle = registry ? null : await this.#buildBrowserBundle(bootstrapEntries);
91
- const ssrBundle = await this.#buildSsrBundle(bootstrapEntries);
137
+ const routeRuntime = registry ? null : await this.#readRouteRuntime();
138
+ if (!registry && !routeRuntime) await rm(path.join(this.#app.cwdPath, RouteRuntimeReport.file), { force: true });
139
+ const ssrEntries = await this.#createBootstrapEntries(entries, "whole");
140
+ //? First: its entries all load the whole runtime, so its graph says which of them a per-route build may narrow.
141
+ const ssrBundle = await this.#buildSsrBundle(ssrEntries);
142
+ const narrowed = routeRuntime
143
+ ? await this.#buildNarrowed(entries, ssrEntries, routeRuntime, {
144
+ importsByModule: ssrBundle.graph.importsByModule,
145
+ entries: entries.map((entry) => path.resolve(entry)),
146
+ entriesByRoute: this.#entriesByRoute,
147
+ })
148
+ : null;
149
+ const trusted = narrowed && this.#check(narrowed) ? narrowed : null;
150
+ const browserEntries = registry ? null : (trusted?.entries ?? ssrEntries);
151
+ const browserBundle =
152
+ trusted?.bundle ?? (browserEntries ? await this.#buildBrowserBundle(browserEntries, null) : null);
153
+ if (trusted?.report) await this.#say(trusted.report);
154
+ if (narrowed && !trusted && browserBundle) {
155
+ await rm(path.join(this.#app.cwdPath, RouteRuntimeReport.file), { force: true });
156
+ await RouteClientBuilder.#removeChunks(narrowed.bundle, browserBundle);
157
+ }
92
158
  const referenceBundle = browserBundle ?? ssrBundle;
159
+ const bootstrapEntries = browserEntries ?? ssrEntries;
160
+ const ssrEntryByOriginal = new Map(
161
+ [...ssrEntries.originalByBuildEntry].map(([buildEntry, originalEntry]) => [originalEntry, buildEntry]),
162
+ );
93
163
 
94
164
  const acceptedEntries = new Set(entries);
95
165
  const routeEntries = new Set(discovered);
@@ -103,6 +173,7 @@ export class RouteClientBuilder {
103
173
  bootstrapEntries.originalByBuildEntry,
104
174
  referenceBundle.clientReferenceIdByAbsPath,
105
175
  this.#app.workspace.workspaceRoot,
176
+ bootstrapEntries.membersByBuildEntry,
106
177
  );
107
178
  if (!manifestEntry) continue;
108
179
  if (!acceptedEntries.has(manifestEntry.originalEntry)) continue;
@@ -111,21 +182,29 @@ export class RouteClientBuilder {
111
182
  : bundleRow;
112
183
  manifestDelta[manifestEntry.key] = row;
113
184
 
114
- const ssrOutput = ssrBundle.entryOutputAbsByAbsPath.get(manifestEntry.buildEntry);
185
+ const ssrOutput = ssrBundle.entryOutputAbsByAbsPath.get(
186
+ ssrEntryByOriginal.get(manifestEntry.originalEntry) ?? manifestEntry.buildEntry,
187
+ );
115
188
  if (!ssrOutput) continue;
116
189
 
117
190
  ssrModuleMap[row.id] ??= {};
118
- ssrModuleMap[row.id][row.name] = { id: ssrOutput, chunks: [ssrOutput, ssrOutput], name: row.name, async: true };
191
+ const { name } = manifestEntry;
192
+ ssrModuleMap[row.id][row.name] = { id: ssrOutput, chunks: [ssrOutput, ssrOutput], name, async: true };
119
193
  }
120
194
  for (const entry of bootstrapEntries.buildEntries) {
121
195
  const buildEntry = path.resolve(entry);
122
- const originalEntry = path.resolve(bootstrapEntries.originalByBuildEntry.get(buildEntry) ?? buildEntry);
123
- if (!acceptedEntries.has(originalEntry)) continue;
124
- const deps = new Set<string>([originalEntry]);
125
- for (const dep of referenceBundle.entryDepsByAbsPath.get(buildEntry) ?? []) deps.add(path.resolve(dep));
126
- const sortedDeps = [...deps].sort();
127
- clientDepsByEntry[originalEntry] = sortedDeps;
128
- if (routeEntries.has(originalEntry)) for (const dep of sortedDeps) clientDeps.add(dep);
196
+ const grouped = bootstrapEntries.membersByBuildEntry?.get(buildEntry);
197
+ const originalEntries = grouped
198
+ ? new Set([...grouped.values()].map((member) => member.entry))
199
+ : [path.resolve(bootstrapEntries.originalByBuildEntry.get(buildEntry) ?? buildEntry)];
200
+ for (const originalEntry of originalEntries) {
201
+ if (!acceptedEntries.has(originalEntry)) continue;
202
+ const deps = new Set<string>(clientDepsByEntry[originalEntry] ?? [originalEntry]);
203
+ for (const dep of referenceBundle.entryDepsByAbsPath.get(buildEntry) ?? []) deps.add(path.resolve(dep));
204
+ const sortedDeps = [...deps].sort();
205
+ clientDepsByEntry[originalEntry] = sortedDeps;
206
+ if (routeEntries.has(originalEntry)) for (const dep of sortedDeps) clientDeps.add(dep);
207
+ }
129
208
  }
130
209
 
131
210
  return {
@@ -137,6 +216,7 @@ export class RouteClientBuilder {
137
216
  clientDepsByEntry,
138
217
  ...(registry ? { registryEntries: [...acceptedEntries].sort() } : {}),
139
218
  ...(browserBundle ? { externalsByChunkUrl: Object.fromEntries(browserBundle.externalsByChunkUrl) } : {}),
219
+ clientGraph: referenceBundle.graph.importsByModule,
140
220
  };
141
221
  }
142
222
 
@@ -165,23 +245,244 @@ export class RouteClientBuilder {
165
245
  };
166
246
  }
167
247
 
168
- async #buildBrowserBundle(bootstrapEntries: BootstrapEntries) {
248
+ async #readRouteRuntime(): Promise<RouteRuntime | null> {
249
+ const { name } = this.#app;
250
+ const whole = (why: string, first = "Run") => {
251
+ this.#app.logger.warn(
252
+ `[client-runtime] ${why}, so every page of this build loads the whole client runtime, not only what it uses. ${first} \`akan sync ${name}\` and build again.`,
253
+ );
254
+ return null;
255
+ };
256
+ const missing = `the per-module runtime files of ${name} or a lib it mounts are missing`;
257
+ if ((await StoreBootstrap.scopeOf(this.#app)) !== "page") return whole(missing);
258
+ try {
259
+ return (await RouteRuntime.read(this.#app.workspace.workspaceRoot, `apps/${name}`)) ?? whole(missing);
260
+ } catch (error) {
261
+ const reason = error instanceof Error ? error.message : String(error);
262
+ return whole(`the modules of ${name} or a lib it mounts could not be read (${reason})`, "Fix that, then run");
263
+ }
264
+ }
265
+
266
+ async #buildNarrowed(
267
+ entries: string[],
268
+ whole: BootstrapEntries,
269
+ runtime: RouteRuntime,
270
+ planned: RouteRuntimeBundle,
271
+ ): Promise<NarrowedBuild> {
272
+ const bundleOf: BundleOf = async (routeRuntime, kept, outputSubdir) => {
273
+ const started = Date.now();
274
+ const browserEntries = await this.#createBootstrapEntries(entries, "page", { kept, whole });
275
+ const bundle = await this.#buildBrowserBundle(browserEntries, routeRuntime, outputSubdir);
276
+ this.#app.verbose(`[client-runtime] bundled ${outputSubdir ?? "client"} (${Date.now() - started}ms)`);
277
+ return { entries: browserEntries, kept, bundle, runtime: routeRuntime };
278
+ };
279
+ const first = await bundleOf(runtime, runtime.plan(planned));
280
+ const routes = this.#entriesByRoute;
281
+ if (!routes || !runtime.decided) return first;
282
+ const perModuleIn = ({ kept }: NarrowedBuild) =>
283
+ [...routes].filter(([, held]) => !held.some((entry) => kept.has(entry))).map(([route]) => route);
284
+ const analysed = perModuleIn(first);
285
+ const { built, refused } =
286
+ analysed.length > 0
287
+ ? await this.#keptWhereNotSmaller(first, routes, planned, bundleOf)
288
+ : { built: first, refused: [] };
289
+ const perModule = perModuleIn(built);
290
+ return {
291
+ ...built,
292
+ report: {
293
+ app: this.#app.name,
294
+ routes: routes.size,
295
+ perModule,
296
+ notSmaller: analysed.filter((route) => !perModule.includes(route)),
297
+ refused,
298
+ causes: built.runtime.decided?.causes() ?? [],
299
+ },
300
+ };
301
+ }
302
+
303
+ async #say(report: RouteRuntimeBuildReport) {
304
+ await RouteRuntimeReport.write(this.#app.cwdPath, report);
305
+ this.#app.log(`[client-runtime] ${RouteRuntimeReport.summary(report)}`);
306
+ for (const route of report.notSmaller) this.#app.verbose(`[client-runtime] not smaller per module: ${route}`);
307
+ for (const route of report.refused ?? [])
308
+ this.#app.verbose(`[client-runtime] larger with the whole runtime here: ${route}`);
309
+ for (const route of report.perModule) this.#app.verbose(`[client-runtime] per module: ${route}`);
310
+ }
311
+
312
+ static async #removeChunks(replaced: NarrowedBuild["bundle"], served: NarrowedBuild["bundle"]) {
313
+ for (const chunk of replaced.graph.importsByChunk.keys())
314
+ if (!served.graph.importsByChunk.has(chunk)) await rm(chunk, { force: true });
315
+ }
316
+
317
+ //? A pass either keeps entries or refuses some for good, and neither set ever loses one, so the passes end.
318
+ async #keptWhereNotSmaller(
319
+ first: NarrowedBuild,
320
+ routes: ReadonlyMap<string, readonly string[]>,
321
+ planned: RouteRuntimeBundle,
322
+ bundleOf: BundleOf,
323
+ ): Promise<{ built: NarrowedBuild; refused: string[] }> {
324
+ const pays = new RouteRuntimePays();
325
+ const sizesOf = (build: NarrowedBuild) => pays.sizesOf(build.bundle, this.#sizedBuildEntries(build.entries));
326
+ //? A keep is never taken back, so a build that did not pay is replaced from a runtime read again.
327
+ const bundleWith = async (verdicts: readonly RoutePaysVerdict[], last: NarrowedBuild | null, subdir?: string) => {
328
+ const runtime = await this.#readRouteRuntime();
329
+ if (!runtime) return null;
330
+ let kept = runtime.plan(planned);
331
+ for (const { entry, ...measured } of verdicts) kept = runtime.keep([entry], { rule: "not-smaller", ...measured });
332
+ const build = await bundleOf(runtime, subdir ? runtime.keepAll() : kept, subdir);
333
+ if (last) await RouteClientBuilder.#removeChunks(last.bundle, build.bundle);
334
+ return build;
335
+ };
336
+ const reference = await bundleWith([], null, referenceSubdir);
337
+ if (!reference) return { built: first, refused: [] };
338
+ const wholeSizes = await sizesOf(reference);
339
+ await rm(path.join(this.#artifactDir, referenceSubdir), { recursive: true, force: true });
340
+ let current = { build: first, sizes: await sizesOf(first), verdicts: [] as RoutePaysVerdict[] };
341
+ let onDisk = first;
342
+ const refused = new Set<string>();
343
+ const refusedRoutes = new Set<string>();
344
+ for (let trial = 0; trial < measuredTrials; trial++) {
345
+ const verdicts = RouteRuntimePays.decide({
346
+ entriesByRoute: routes,
347
+ isKept: (entry) => current.build.kept.has(entry),
348
+ isRefused: (entry) => refused.has(entry),
349
+ whole: wholeSizes,
350
+ measured: current.sizes,
351
+ });
352
+ if (verdicts.length === 0) break;
353
+ const tried = await bundleWith([...current.verdicts, ...verdicts], onDisk);
354
+ if (!tried) break;
355
+ onDisk = tried;
356
+ const sizes = await sizesOf(tried);
357
+ const larger = RouteRuntimePays.larger({
358
+ entriesByRoute: routes,
359
+ wasKept: (entry) => current.build.kept.has(entry),
360
+ isKept: (entry) => tried.kept.has(entry),
361
+ before: current.sizes,
362
+ after: sizes,
363
+ });
364
+ if (larger.length === 0) {
365
+ current = { build: tried, sizes, verdicts: [...current.verdicts, ...verdicts] };
366
+ continue;
367
+ }
368
+ for (const route of larger) {
369
+ refusedRoutes.add(route);
370
+ for (const entry of routes.get(route) ?? []) refused.add(entry);
371
+ }
372
+ if (!verdicts.some(({ entry }) => refused.has(entry))) for (const { entry } of verdicts) refused.add(entry);
373
+ }
374
+ const built = onDisk === current.build ? onDisk : ((await bundleWith(current.verdicts, onDisk)) ?? onDisk);
375
+ return { built, refused: [...refusedRoutes] };
376
+ }
377
+
378
+ get #artifactDir() {
379
+ return path.join(this.#command === "build" ? this.#app.dist.cwdPath : this.#app.cwdPath, ".akan/artifact");
380
+ }
381
+
382
+ #sizedBuildEntries(entries: BootstrapEntries): Map<string, string[]> {
383
+ const buildEntriesOf = RouteClientBuilder.#buildEntriesOf(entries);
384
+ return new Map(
385
+ [...(this.#sizedEntriesByRoute ?? this.#entriesByRoute ?? [])].map(([route, held]) => {
386
+ const asked = this.#askedByRoute?.get(route);
387
+ return [route, held.flatMap((entry) => buildEntriesOf(entry, asked?.get(path.resolve(entry))))];
388
+ }),
389
+ );
390
+ }
391
+
392
+ //? An entry built as several answers with the ones holding a name asked, and with all of them asked for none.
393
+ static #buildEntriesOf({ originalByBuildEntry, namesByBuildEntry, membersByBuildEntry }: BootstrapEntries) {
394
+ const built = new Map<string, { buildEntry: string; names?: readonly string[] }[]>();
395
+ for (const [buildEntry, original] of originalByBuildEntry)
396
+ built.getOrInsert(original, []).push({ buildEntry, names: namesByBuildEntry?.get(buildEntry) });
397
+ for (const [buildEntry, exports] of membersByBuildEntry ?? [])
398
+ for (const [original, held] of Map.groupBy(exports.values(), (member) => member.entry))
399
+ built.getOrInsert(original, []).push({ buildEntry, names: held.map((member) => member.name) });
400
+ return (entry: string, asked?: readonly string[] | null): string[] => {
401
+ const held = built.get(path.resolve(entry));
402
+ if (!held) return [path.resolve(entry)];
403
+ return held
404
+ .filter(({ names }) => !asked || !names || names.some((name) => asked.includes(name)))
405
+ .map(({ buildEntry }) => buildEntry);
406
+ };
407
+ }
408
+
409
+ #check({ entries, kept, bundle, runtime: routeRuntime }: NarrowedBuild): boolean {
410
+ const { workspaceRoot } = this.#app.workspace;
411
+ const buildEntriesOf = RouteClientBuilder.#buildEntriesOf(entries);
412
+ const grouped = [...(entries.membersByBuildEntry ?? [])].flatMap(([buildEntry, exports]) => {
413
+ const [first] = exports.values();
414
+ return first ? [[buildEntry, first.entry] as const] : [];
415
+ });
416
+ const check = new RouteRuntimeCheck(workspaceRoot, bundle.graph, {
417
+ entries: new Map([...[...entries.originalByBuildEntry].filter(([, entry]) => !kept.has(entry)), ...grouped]),
418
+ wholeReaders: routeRuntime.wholeReaders,
419
+ wholeConstantReaders: routeRuntime.wholeConstantReaders,
420
+ routes: new Map(
421
+ [...(this.#entriesByRoute ?? [])].map(([route, held]) => [
422
+ route,
423
+ held.flatMap((entry) => buildEntriesOf(entry)),
424
+ ]),
425
+ ),
426
+ });
427
+ const { refusal, repeated } = check;
428
+ if (refusal) {
429
+ this.#app.logger.warn(refusal);
430
+ return false;
431
+ }
432
+ if (repeated.length === 0) return true;
433
+ const more = repeated.length - RouteRuntimeCheck.shown;
434
+ this.#app.logger.warn(
435
+ [
436
+ `[client-runtime] a page keeping the whole runtime loads a piece of what that runtime already holds:`,
437
+ ...repeated.slice(0, RouteRuntimeCheck.shown).map((line) => ` - ${line}`),
438
+ ...(more > 0 ? [` - and ${more} more`] : []),
439
+ ].join("\n"),
440
+ );
441
+ return true;
442
+ }
443
+
444
+ async #buildBrowserBundle(
445
+ bootstrapEntries: BootstrapEntries,
446
+ routeRuntime: RouteRuntime | null,
447
+ outputSubdir?: string,
448
+ ) {
169
449
  const reactFastRefresh = process.env.AKAN_REACT_FAST_REFRESH !== "0";
450
+ const icons = ReactIconImports.forApp(this.#app);
451
+ const vendorFiles = await VendorFileImports.of(this.#app.workspace.workspaceRoot);
170
452
  return new ClientEntriesBundler({
171
453
  app: this.#app,
172
454
  entries: bootstrapEntries.buildEntries,
173
455
  plugins: [
456
+ icons.plugin,
457
+ ...(routeRuntime ? [this.#signalDescriptors(routeRuntime)] : []),
458
+ vendorFiles.plugin(),
174
459
  await createBarrelImportsPlugin(this.#app, {
175
- pipeAfter: reactFastRefresh ? RouteClientBuilder.normalizeNamedDefaultFunctionForFastRefresh : undefined,
176
- external: VENDOR_SPECIFIERS,
460
+ pipeAfter: icons.pipe(
461
+ reactFastRefresh ? RouteClientBuilder.normalizeNamedDefaultFunctionForFastRefresh : undefined,
462
+ ),
463
+ external: vendorFiles.specifiers,
464
+ routeRuntime,
465
+ ...(this.#command === "build" ? { parts: this.#parts } : {}),
177
466
  }),
178
467
  ],
179
- external: VENDOR_SPECIFIERS,
468
+ external: vendorFiles.specifiers,
180
469
  command: this.#command,
181
470
  reactFastRefresh,
471
+ ...(outputSubdir ? { outputSubdir } : {}),
182
472
  }).bundle();
183
473
  }
184
474
 
475
+ #signalDescriptors(routeRuntime: RouteRuntime) {
476
+ const scopes = routeRuntime.table.layers.map(({ scope }) => scope);
477
+ return new SignalDescriptors(this.#app.workspace.workspaceRoot, scopes, {
478
+ onUnread: (reason) =>
479
+ this.#app.logger.warn(
480
+ `[client-runtime] ${reason}, so each of their pieces reads its signal again: a slower build of the same pages. Run \`akan sync ${this.#app.name}\` if their generated files are from an earlier release.`,
481
+ ),
482
+ takenFromPieces: (absPath) => routeRuntime.takenFromPieces(absPath),
483
+ }).plugin;
484
+ }
485
+
185
486
  async #buildSsrBundle(bootstrapEntries: BootstrapEntries) {
186
487
  return new ClientEntriesBundler({
187
488
  app: this.#app,
@@ -193,40 +494,95 @@ export class RouteClientBuilder {
193
494
  }).bundle();
194
495
  }
195
496
 
196
- async #createBootstrapEntries(entries: string[]): Promise<BootstrapEntries> {
497
+ //? `narrowed.kept`: an entry keeping the whole runtime is the same file a build of every page on it bundles.
498
+ async #createBootstrapEntries(
499
+ entries: string[],
500
+ scope: ClientRuntimeScope,
501
+ narrowed?: { kept: ReadonlySet<string>; whole: BootstrapEntries },
502
+ ): Promise<BootstrapEntries> {
197
503
  if (!(await Bun.file(path.join(this.#app.cwdPath, "lib", "st.ts")).exists())) {
198
504
  return { buildEntries: entries, originalByBuildEntry: new Map() };
199
505
  }
506
+ const wholeByOriginal = new Map(
507
+ [...(narrowed?.whole.originalByBuildEntry ?? [])].map(([buildEntry, original]) => [original, buildEntry]),
508
+ );
200
509
 
201
- const outdir = path.join(this.#app.cwdPath, ".akan", "generated", "client-entry-bootstrap");
510
+ const dirName = scope === "page" ? "client-entry-bootstrap-route" : "client-entry-bootstrap";
511
+ const outdir = path.join(this.#app.cwdPath, ".akan", "generated", dirName);
202
512
  await mkdir(outdir, { recursive: true });
203
513
 
204
514
  const originalByBuildEntry = new Map<string, string>();
205
- const buildEntries = await Promise.all(
206
- entries.map(async (entry) => {
515
+ const namesByBuildEntry = new Map<string, readonly string[]>();
516
+ const membersByBuildEntry = new Map<string, ReadonlyMap<string, GroupedExport>>();
517
+ const { workspaceRoot } = this.#app.workspace;
518
+ const byExport = scope === "page" && this.#command === "build";
519
+ const read = await Promise.all(
520
+ entries.map(async (entry): Promise<{ whole?: string; parts: WrappedPart[] }> => {
207
521
  const absEntry = path.resolve(entry);
522
+ const whole = narrowed?.kept.has(absEntry) ? wholeByOriginal.get(absEntry) : undefined;
523
+ if (whole) {
524
+ originalByBuildEntry.set(whole, absEntry);
525
+ return { whole, parts: [] };
526
+ }
208
527
  const hash = Bun.hash(`${this.#app.name}\n${absEntry}`).toString(36);
209
528
  const base = path.basename(absEntry).replace(/[^A-Za-z0-9._-]/g, "_");
210
- const wrapperEntry = path.join(outdir, `${base}-${hash}.tsx`);
211
- const exportNames = await this.#scanExportNames(absEntry);
212
- await Bun.write(
213
- wrapperEntry,
214
- RouteClientBuilder.createStoreBootstrapEntrySource({
215
- appName: this.#app.name,
216
- originalEntry: absEntry,
217
- exportNames,
218
- }),
219
- );
220
- originalByBuildEntry.set(path.resolve(wrapperEntry), absEntry);
221
- return wrapperEntry;
529
+ const source = await Bun.file(absEntry).text();
530
+ const exportNames = scanUseClientExports(source, absEntry, workspaceRoot);
531
+ const groups =
532
+ byExport && PartModules.splits(workspaceRoot, absEntry)
533
+ ? RouteClientBuilder.#exportGroups(source, absEntry, exportNames)
534
+ : [exportNames];
535
+ const parts = groups.map((names, index) => ({
536
+ entry: absEntry,
537
+ names,
538
+ file: path.join(outdir, `${base}-${hash}${groups.length > 1 ? `-${index}` : ""}.tsx`),
539
+ split: groups.length > 1,
540
+ }));
541
+ return { parts };
222
542
  }),
223
543
  );
224
-
225
- return { buildEntries, originalByBuildEntry };
544
+ const parts = read.flatMap((entry) => entry.parts);
545
+ const routes = byExport ? (this.#sizedEntriesByRoute ?? this.#entriesByRoute) : undefined;
546
+ const planned = routes
547
+ ? ClientEntryGroups.plan(parts, ClientEntryGroups.loadedBy(routes, this.#askedByRoute))
548
+ : parts.map((part) => [part]);
549
+ const wrappers = await Promise.all(
550
+ planned.map(async (group) => {
551
+ const [only] = group;
552
+ if (group.length === 1 && only) {
553
+ await Bun.write(
554
+ only.file,
555
+ RouteClientBuilder.createStoreBootstrapEntrySource({
556
+ appName: this.#app.name,
557
+ originalEntry: only.entry,
558
+ exportNames: [...only.names],
559
+ scope,
560
+ }),
561
+ );
562
+ originalByBuildEntry.set(path.resolve(only.file), only.entry);
563
+ if (only.split) namesByBuildEntry.set(path.resolve(only.file), only.names);
564
+ return only.file;
565
+ }
566
+ const exports = ClientEntryGroups.exportsOf(group);
567
+ const held = [...exports.values()].map(({ entry, name }) => `${entry}#${name}`).join("\n");
568
+ const file = path.join(outdir, `group-${Bun.hash(`${this.#app.name}\n${held}`).toString(36)}.tsx`);
569
+ await Bun.write(file, ClientEntryGroups.source(this.#app.name, exports, scope));
570
+ membersByBuildEntry.set(path.resolve(file), exports);
571
+ return file;
572
+ }),
573
+ );
574
+ const kept = read.flatMap(({ whole }) => (whole ? [whole] : []));
575
+ return { buildEntries: [...kept, ...wrappers], originalByBuildEntry, namesByBuildEntry, membersByBuildEntry };
226
576
  }
227
577
 
228
- async #scanExportNames(absEntry: string): Promise<string[]> {
229
- return scanUseClientExports(await Bun.file(absEntry).text(), absEntry, this.#app.workspace.workspaceRoot);
578
+ //? Names one part of the file holds share a build entry. The parts are read from the file as written, and a bundle
579
+ //? may place a name elsewhere after its rewrites: then a build entry only loads more than the names it holds need.
580
+ static #exportGroups(source: string, absEntry: string, names: string[]): string[][] {
581
+ const parts = names.length > 0 ? ModuleParts.read(source, absEntry) : null;
582
+ if (!parts) return [names];
583
+ const groups = new Map<string, string[]>();
584
+ for (const name of names) groups.getOrInsert(parts.partOf(name) ?? "", []).push(name);
585
+ return [...groups.values()];
230
586
  }
231
587
 
232
588
  static normalizeNamedDefaultFunctionForFastRefresh(
@@ -317,11 +673,12 @@ export class RouteClientBuilder {
317
673
  appName: string;
318
674
  originalEntry: string;
319
675
  exportNames: string[];
676
+ scope?: ClientRuntimeScope;
320
677
  }): string {
321
678
  const originalEntry = JSON.stringify(path.resolve(args.originalEntry));
322
679
  const namedExports = args.exportNames.filter((name) => name !== "default");
323
680
  const lines = [
324
- ...StoreBootstrap.importLines(args.appName),
681
+ ...StoreBootstrap.importLines(args.appName, args.scope),
325
682
  ...(namedExports.length > 0 ? [`export { ${namedExports.join(", ")} } from ${originalEntry};`] : []),
326
683
  ];
327
684
  if (args.exportNames.includes("default")) lines.push(`export { default } from ${originalEntry};`);
@@ -333,15 +690,20 @@ export class RouteClientBuilder {
333
690
  originalByBuildEntry: Map<string, string>,
334
691
  clientReferenceIdByBuildEntry: Map<string, string> = new Map(),
335
692
  workspaceRoot = process.cwd(),
693
+ membersByBuildEntry?: ReadonlyMap<string, ReadonlyMap<string, GroupedExport>>,
336
694
  ): { buildEntry: string; originalEntry: string; name: string; key: string } | null {
337
695
  const hashIdx = manifestKey.lastIndexOf("#");
338
696
  if (hashIdx < 0) return null;
339
697
  const buildReferenceId = manifestKey.slice(0, hashIdx);
340
- const name = manifestKey.slice(hashIdx + 1);
698
+ const builtName = manifestKey.slice(hashIdx + 1);
341
699
  const buildEntry =
342
700
  [...clientReferenceIdByBuildEntry.entries()].find(([, referenceId]) => referenceId === buildReferenceId)?.[0] ??
343
701
  buildReferenceId;
344
- const originalEntry = originalByBuildEntry.get(buildEntry) ?? buildEntry;
702
+ const grouped = membersByBuildEntry?.get(buildEntry);
703
+ const member = grouped?.get(builtName);
704
+ if (grouped && !member) return null;
705
+ const name = member?.name ?? builtName;
706
+ const originalEntry = member?.entry ?? originalByBuildEntry.get(buildEntry) ?? buildEntry;
345
707
  const originalReferenceId = toClientReferencePath(originalEntry, workspaceRoot);
346
708
  return { buildEntry, originalEntry, name, key: `${originalReferenceId}#${name}` };
347
709
  }