@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
@@ -0,0 +1,227 @@
1
+ import { readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { StoreBootstrap } from "../artifact/storeBootstrap";
4
+ import type { App } from "../commandDecorators";
5
+ import { type DictionaryKeyRead, DictionaryKeys } from "../quality/dictionaryKeys";
6
+ import { ModelReference } from "../transforms/modelReference";
7
+ import { RouteRuntime } from "../transforms/routeRuntime";
8
+ import type { ClientEntryDiscovery, ClientModuleImport } from "./clientBuildTypes";
9
+ import { DictionaryAssetBuilder } from "./dictionaryAssetBuilder";
10
+ import { DictionaryConstants } from "./dictionaryConstants";
11
+ import { RouteHandoffs } from "./routeHandoffs";
12
+
13
+ export interface DictionaryRouteUnread {
14
+ file: string;
15
+ line?: number;
16
+ why: string;
17
+ }
18
+
19
+ export interface DictionaryRouteRead {
20
+ //? Every group the route's client modules can show, a superset: names no dictionary holds are dropped when packed.
21
+ groups: string[];
22
+ api: boolean;
23
+ //? Set when the route shows a key the build cannot follow: it loads the whole page dictionary.
24
+ whole: DictionaryRouteUnread | null;
25
+ }
26
+
27
+ export interface DictionaryRouteInput {
28
+ entries: readonly string[];
29
+ serverModules?: readonly string[];
30
+ references?: readonly string[];
31
+ }
32
+
33
+ //? Development's graph links the whole runtime, so a file importing it is asked which module pieces it would load.
34
+ export type DictionaryPiecesOf = (absPath: string, source: string) => { perModule: boolean; pieces: string[] } | null;
35
+
36
+ export interface DictionaryRoutesOptions {
37
+ importsByModule: ReadonlyMap<string, readonly ClientModuleImport[]>;
38
+ constants: DictionaryConstants;
39
+ piecesOf?: DictionaryPiecesOf;
40
+ }
41
+
42
+ const scoped = /^(?:apps|libs)\/[^/]+\//;
43
+ const piece = /^((?:apps|libs)\/[^/]+)\/lib\/__client\/([^/_.][^/.]*)\.(st|fetch|ref)(?:\.ts)?$/;
44
+ const wholeRuntime = /^(?:apps|libs)\/[^/]+\/lib\/(?:st|useClient)\.ts$/;
45
+ const noTexts = /\.(?:constant|dictionary|document|service|signal)\.ts$/;
46
+ const generated = /^(?:apps|libs)\/[^/]+\/(?:lib\/[^/]+\.ts$|client\.ts$|server\.ts$|\.akan\/)/;
47
+ //? Every page shows the framework's own texts: buttons, empty states, confirmations, validation messages.
48
+ const frameworkGroups = ["base"];
49
+
50
+ export class DictionaryRoutes {
51
+ readonly #workspaceRoot: string;
52
+ readonly #options: DictionaryRoutesOptions;
53
+ readonly #reads = new Map<string, { source: string; read: DictionaryKeyRead }>();
54
+
55
+ constructor(workspaceRoot: string, options: DictionaryRoutesOptions) {
56
+ this.#workspaceRoot = workspaceRoot;
57
+ this.#options = options;
58
+ }
59
+
60
+ static get frameworkGroups(): readonly string[] {
61
+ return frameworkGroups;
62
+ }
63
+
64
+ static async forApp(
65
+ workspaceRoot: string,
66
+ appScope: string,
67
+ options: Omit<DictionaryRoutesOptions, "constants">,
68
+ runtime?: RouteRuntime | null,
69
+ ): Promise<DictionaryRoutes> {
70
+ const table = runtime === undefined ? await RouteRuntime.read(workspaceRoot, appScope).catch(() => null) : runtime;
71
+ const scopes = table?.table.layers.map(({ scope }) => scope) ?? [appScope];
72
+ const constants = await DictionaryConstants.read(workspaceRoot, [...new Set([appScope, ...scopes])]);
73
+ return new DictionaryRoutes(workspaceRoot, { ...options, constants });
74
+ }
75
+
76
+ //? Development reads a route as it builds, from the SSR bundle standing in for the browser's, whose graph links the
77
+ //? whole runtime; the constants are read again each time, as saving one restarts no builder.
78
+ static async ofBuiltRoute(
79
+ app: App,
80
+ route: {
81
+ seeds: string[];
82
+ entries: readonly string[];
83
+ importsByModule: ReadonlyMap<string, readonly ClientModuleImport[]>;
84
+ discovery: ClientEntryDiscovery;
85
+ },
86
+ ): Promise<string[] | null> {
87
+ const { workspaceRoot } = app.workspace;
88
+ const unbuilt = route.entries.find((entry) => !route.importsByModule.has(path.resolve(entry)));
89
+ if (unbuilt) {
90
+ const fileName = path.relative(workspaceRoot, unbuilt).split(path.sep).join("/");
91
+ app.verbose(`[dictionary] the route loads the whole page dictionary: this builder has not bundled ${fileName}`);
92
+ return null;
93
+ }
94
+ const appScope = `apps/${app.name}`;
95
+ const runtime = await RouteRuntime.read(workspaceRoot, appScope).catch(() => null);
96
+ const piecesOf: DictionaryPiecesOf | undefined = runtime
97
+ ? (absPath, source) => runtime.transform(source, absPath)
98
+ : undefined;
99
+ const reader = await DictionaryRoutes.forApp(
100
+ workspaceRoot,
101
+ appScope,
102
+ { importsByModule: route.importsByModule, ...(piecesOf ? { piecesOf } : {}) },
103
+ runtime,
104
+ );
105
+ const { discovery } = route;
106
+ const serverModules =
107
+ "serverModules" in discovery && typeof discovery.serverModules === "function"
108
+ ? await (discovery.serverModules as (seeds: string[]) => Promise<string[]>)(route.seeds)
109
+ : [];
110
+ const handoffs = await DictionaryRoutes.#handoffsOf(app, runtime);
111
+ const entries = await DictionaryRoutes.handedEntries(route.entries, serverModules, handoffs);
112
+ const read = reader.read({ entries, serverModules });
113
+ if (read.whole)
114
+ app.verbose(`[dictionary] the route loads the whole page dictionary: ${DictionaryRoutes.pinned(read.whole)}`);
115
+ return read.whole ? null : read.groups;
116
+ }
117
+
118
+ //? Development's root layout imports every model's reference; production keeps those a server module hands over.
119
+ static async handedEntries(
120
+ entries: readonly string[],
121
+ serverModules: string[],
122
+ handoffs: RouteHandoffs | null,
123
+ ): Promise<readonly string[]> {
124
+ if (!handoffs) return entries;
125
+ const { referenceFiles } = await handoffs.read(serverModules);
126
+ return [...new Set([...entries.filter((entry) => !ModelReference.isFile(entry)), ...referenceFiles])];
127
+ }
128
+
129
+ static async #handoffsOf(app: App, runtime: RouteRuntime | null): Promise<RouteHandoffs | null> {
130
+ if (!runtime || (await StoreBootstrap.scopeOf(app)) !== "page") return null;
131
+ const { workspaceRoot } = app.workspace;
132
+ return new RouteHandoffs(workspaceRoot, runtime, await ModelReference.filesOf(workspaceRoot, `apps/${app.name}`));
133
+ }
134
+
135
+ static pinned({ file, line, why }: DictionaryRouteUnread): string {
136
+ return `${file}${line ? `:${line}` : ""} ${why}`;
137
+ }
138
+
139
+ read({ entries, serverModules = [], references = [] }: DictionaryRouteInput): DictionaryRouteRead {
140
+ const names = new Set<string>(frameworkGroups);
141
+ const modules = new Set<string>(references);
142
+ const route = { names, modules, api: false as boolean, whole: null as DictionaryRouteUnread | null };
143
+ const queue = entries.map((entry) => path.resolve(entry));
144
+ const visited = new Set<string>();
145
+ for (let file = queue.pop(); file !== undefined && !route.whole; file = queue.pop()) {
146
+ if (visited.has(file)) continue;
147
+ visited.add(file);
148
+ const fileName = this.#fileNameOf(file);
149
+ const pieceOf = fileName.match(piece);
150
+ if (pieceOf?.[2]) modules.add(pieceOf[2]);
151
+ if (wholeRuntime.test(fileName)) {
152
+ if (!this.#options.piecesOf) route.whole = { file: fileName, why: "loads every module's client runtime" };
153
+ continue;
154
+ }
155
+ if (noTexts.test(fileName)) continue;
156
+ if (scoped.test(fileName) && !pieceOf && !generated.test(fileName))
157
+ this.#readClient(file, fileName, route, queue);
158
+ for (const imported of this.#options.importsByModule.get(file) ?? []) queue.push(imported.path);
159
+ }
160
+ for (const file of serverModules) {
161
+ if (route.whole) break;
162
+ const fileName = this.#fileNameOf(file);
163
+ if (!scoped.test(fileName) || noTexts.test(fileName) || generated.test(fileName)) continue;
164
+ const read = this.#readOf(file, fileName)?.read;
165
+ if (read?.anyModule) route.whole = { file: fileName, why: read.anyModule };
166
+ for (const name of read?.propNames ?? []) names.add(name);
167
+ }
168
+ if (route.whole) return { groups: [], api: route.api, whole: route.whole };
169
+ const { constants } = this.#options;
170
+ for (const module of modules) for (const group of constants.reachOf(module)) names.add(group);
171
+ if (route.api) names.add(DictionaryAssetBuilder.apiGroup);
172
+ return { groups: [...names].sort(), api: route.api, whole: null };
173
+ }
174
+
175
+ #readClient(
176
+ file: string,
177
+ fileName: string,
178
+ route: { names: Set<string>; modules: Set<string>; api: boolean; whole: DictionaryRouteUnread | null },
179
+ queue: string[],
180
+ ) {
181
+ const known = this.#readOf(file, fileName);
182
+ if (!known) return;
183
+ const { read, source } = known;
184
+ const [unread] = read.unread;
185
+ if (unread) route.whole = { file: fileName, line: unread.line, why: unread.why };
186
+ else if (read.anyModule) route.whole = { file: fileName, why: read.anyModule };
187
+ for (const name of read.names) route.names.add(name);
188
+ for (const name of read.classNames)
189
+ for (const group of this.#options.constants.groupsOfClass(name)) route.modules.add(group);
190
+ route.api ||= read.api;
191
+ const { piecesOf } = this.#options;
192
+ const readsWhole = (this.#options.importsByModule.get(file) ?? []).some(({ path: imported }) =>
193
+ wholeRuntime.test(this.#fileNameOf(imported)),
194
+ );
195
+ if (!piecesOf || !readsWhole) return;
196
+ const routed = piecesOf(file, source);
197
+ if (routed && !routed.perModule) route.whole = { file: fileName, why: "needs every module's client runtime" };
198
+ for (const loaded of routed?.pieces ?? []) {
199
+ const [, scope, module, role] = loaded.match(piece) ?? [];
200
+ if (!scope || !module) continue;
201
+ route.modules.add(module);
202
+ if (role === "st")
203
+ for (const dir of [module, `_${module}`])
204
+ queue.push(path.join(this.#workspaceRoot, scope, "lib", dir, `${module}.store.ts`));
205
+ }
206
+ }
207
+
208
+ #readOf(file: string, fileName: string) {
209
+ let source: string;
210
+ try {
211
+ source = readFileSync(file, "utf8");
212
+ } catch {
213
+ return null;
214
+ }
215
+ const known = this.#reads.get(file);
216
+ if (known?.source === source) return known;
217
+ const { constants } = this.#options;
218
+ const staticKeys = (className: string, member: string) => constants.staticKeysOf(className, member);
219
+ const next = { source, read: DictionaryKeys.read(source, fileName, staticKeys) };
220
+ this.#reads.set(file, next);
221
+ return next;
222
+ }
223
+
224
+ #fileNameOf(absPath: string) {
225
+ return path.relative(this.#workspaceRoot, absPath).split(path.sep).join("/");
226
+ }
227
+ }
@@ -95,3 +95,87 @@ describe("PagesBundleBuilder.transformServerUseClientFetchSource", () => {
95
95
  }
96
96
  });
97
97
  });
98
+
99
+ describe("PagesBundleBuilder on the generated layout with lib/usePage.ts", () => {
100
+ const emptyBuild = "const fetchProto = FetchClient.build<typeof signal>({}, {});";
101
+ const generatedPage = (fetchProtoLine = emptyBuild) =>
102
+ [
103
+ 'import { makePageProto, registerClientRuntime } from "akanjs/client";',
104
+ 'import { FetchClient } from "akanjs/fetch";',
105
+ 'import { getAllDictionary } from "./dict" with { type: "macro" };',
106
+ 'import type * as dict from "./dict";',
107
+ 'import type * as signal from "./sig";',
108
+ "",
109
+ 'const dictionary = process.env.AKAN_PUBLIC_RENDER_ENV === "csr" ? getAllDictionary() : {};',
110
+ "const pageProto = makePageProto<typeof dict>(dictionary);",
111
+ fetchProtoLine,
112
+ 'export const runtime = registerClientRuntime({ ...pageProto, ...fetchProto }, { scope: "app" });',
113
+ "",
114
+ "export const { msg, Err, usePage, sig, fetch } = runtime;",
115
+ "",
116
+ ].join("\n");
117
+ const generatedUseClientOnPage = (lines: { importLine?: string; signalArg?: string } = {}) =>
118
+ [
119
+ 'import { FetchClient } from "akanjs/fetch";',
120
+ 'import * as cnst from "./cnst";',
121
+ 'import { fetch as pageFetch, sig as pageSig } from "./usePage";',
122
+ lines.importLine ?? macroImport,
123
+ 'import type * as signal from "./sig";',
124
+ "",
125
+ `Object.assign(pageSig, FetchClient.build<typeof signal>(cnst, ${lines.signalArg ?? "getSerializedSignal()"}, { base: pageFetch }).sig);`,
126
+ "",
127
+ "export const fetch = pageFetch;",
128
+ "export const sig = pageSig;",
129
+ 'export { Err, msg, runtime, usePage } from "./usePage";',
130
+ "",
131
+ ].join("\n");
132
+
133
+ test("builds usePage.ts's client onto the live server fetch, so a server render calls what it calls today", () => {
134
+ expect(PagesBundleBuilder.transformServerPageFetchSource(generatedPage())).toBe(
135
+ `${serverImport}\n${generatedPage("const fetchProto = FetchClient.build<typeof signal>({}, {}, { base: serverFetch });")}`,
136
+ );
137
+ });
138
+
139
+ test("applies the server fetch's own signal in useClient.ts instead of the signal macro", () => {
140
+ expect(transform(generatedUseClientOnPage())).toBe(
141
+ generatedUseClientOnPage({ importLine: serverImport, signalArg: "serverFetch.serializedSignal" }),
142
+ );
143
+ });
144
+
145
+ test("leaves a usePage.ts or useClient.ts it does not recognise unchanged", () => {
146
+ const withDescriptors = generatedPage("const fetchProto = FetchClient.build<typeof signal>(cnst, {});");
147
+ expect(PagesBundleBuilder.transformServerPageFetchSource(withDescriptors)).toBe(withDescriptors);
148
+ const commented = generatedPage(`// ${emptyBuild}`);
149
+ expect(PagesBundleBuilder.transformServerPageFetchSource(commented)).toBe(commented);
150
+ const withoutMacroImport = generatedUseClientOnPage({ importLine: 'import { getSerializedSignal } from "./sig";' });
151
+ expect(transform(withoutMacroImport)).toBe(withoutMacroImport);
152
+ });
153
+ });
154
+
155
+ describe("PagesBundleBuilder on a generated lib/__client fetch piece", () => {
156
+ const pieceMacroImport = `import { getSerializedSignalOf } from "../sig" with { type: "macro" };`;
157
+ const generatedPiece = (importLine = pieceMacroImport) =>
158
+ [
159
+ 'import { FetchClient } from "akanjs/fetch";',
160
+ 'import * as cnst from "../cnst";',
161
+ 'import { fetch, sig } from "../usePage";',
162
+ importLine,
163
+ 'import type * as signal from "../sig";',
164
+ "",
165
+ 'Object.assign(sig, FetchClient.build<typeof signal>(cnst, getSerializedSignalOf("memo"), { base: fetch }).sig);',
166
+ "",
167
+ ].join("\n");
168
+
169
+ test("reads the module's descriptors from the live server signal instead of the build-time macro", () => {
170
+ expect(PagesBundleBuilder.transformServerClientPieceSource(generatedPiece())).toBe(
171
+ generatedPiece('import { getSerializedSignalOf } from "../sig";'),
172
+ );
173
+ });
174
+
175
+ test("leaves a piece it does not recognise unchanged", () => {
176
+ const commented = generatedPiece(`// ${pieceMacroImport}`);
177
+ expect(PagesBundleBuilder.transformServerClientPieceSource(commented)).toBe(commented);
178
+ const otherMacro = generatedPiece(`import { getSerializedSignal } from "../sig" with { type: "macro" };`);
179
+ expect(PagesBundleBuilder.transformServerClientPieceSource(otherMacro)).toBe(otherMacro);
180
+ });
181
+ });
@@ -13,6 +13,7 @@ import { createUseClientBundlePlugin } from "../transforms/useClientBundlePlugin
13
13
  import { bundleDefine } from "./bundleDefine";
14
14
  import { CsrDevPaths } from "./csrDevPaths";
15
15
  import { PagesEntrySourceGenerator } from "./pagesEntrySourceGenerator";
16
+ import { RscServerRendererGuard } from "./rscServerRendererGuard";
16
17
  import { ServerGraphFile } from "./serverGraphFile";
17
18
 
18
19
  export interface BuildPagesBundleResult {
@@ -74,7 +75,7 @@ export class PagesBundleBuilder {
74
75
  asset: "assets/[name]-[hash].[ext]",
75
76
  },
76
77
  define: bundleDefine(this.#app, this.#command, "ssr"),
77
- metafile: dev,
78
+ metafile: true,
78
79
  plugins: [
79
80
  //? First: the use-client plugins below load every module, and an env file must be swapped before they do.
80
81
  ...(this.#serverEnv ? [this.#serverEnv] : []),
@@ -96,6 +97,7 @@ export class PagesBundleBuilder {
96
97
  });
97
98
 
98
99
  if (!result.success) throw new AggregateError(result.logs, "[PagesBundleBuilder] Bun.build failed");
100
+ RscServerRendererGuard.assert(result.metafile, workspaceRoot);
99
101
 
100
102
  const entryArtifact = result.outputs.find((a) => a.kind === "entry-point");
101
103
  if (!entryArtifact) throw new Error("[PagesBundleBuilder] Bun.build emitted no entry-point artifact");
@@ -169,9 +171,15 @@ export class PagesBundleBuilder {
169
171
  return {
170
172
  name: "akan-server-use-client-fetch",
171
173
  setup(build) {
172
- build.onLoad({ filter: /[/\\]lib[/\\]useClient\.(ts|tsx|js|jsx)$/ }, async (args) => {
174
+ const filter = /[/\\]lib[/\\](?:useClient|usePage|__client[/\\][^/\\]+\.fetch)\.(ts|tsx|js|jsx)$/;
175
+ build.onLoad({ filter }, async (args) => {
173
176
  const source = await Bun.file(args.path).text();
174
- const transformed = PagesBundleBuilder.transformServerUseClientFetchSource(source);
177
+ const transformed =
178
+ path.basename(path.dirname(args.path)) === "__client"
179
+ ? PagesBundleBuilder.transformServerClientPieceSource(source)
180
+ : path.basename(args.path).startsWith("usePage.")
181
+ ? PagesBundleBuilder.transformServerPageFetchSource(source)
182
+ : PagesBundleBuilder.transformServerUseClientFetchSource(source);
175
183
  if (transformed === source) return undefined;
176
184
  return { contents: transformed, loader: loaderFor(args.path) };
177
185
  });
@@ -198,12 +206,47 @@ export class PagesBundleBuilder {
198
206
  end: fetchProtoEnd.end,
199
207
  text: "const fetchProto = FetchClient.build<typeof signal>(cnst, serverFetch.serializedSignal, { base: serverFetch });",
200
208
  });
209
+ const macroCallAt =
210
+ fetchProtoAt === -1 && importAt !== -1
211
+ ? PagesBundleBuilder.#indexOfTokens(tokens, PagesBundleBuilder.#macroCallTokens)
212
+ : -1;
213
+ if (macroCallAt !== -1)
214
+ edits.push({
215
+ start: tokens[macroCallAt].start,
216
+ end: tokens[macroCallAt + PagesBundleBuilder.#macroCallTokens.length - 1].end,
217
+ text: "serverFetch.serializedSignal",
218
+ });
201
219
  let transformed = source;
202
220
  for (const { start, end, text } of edits.sort((a, b) => b.start - a.start))
203
221
  transformed = transformed.slice(0, start) + text + transformed.slice(end);
204
222
  return transformed;
205
223
  }
206
224
 
225
+ //? A piece reads its descriptors from the live server signal at render time instead of inlining them at build time.
226
+ static transformServerClientPieceSource(source: string): string {
227
+ if (!source.includes(`with { type: "macro" }`)) return source;
228
+ const tokens = PagesBundleBuilder.#tokenize(source);
229
+ const at = PagesBundleBuilder.#indexOfTokens(tokens, PagesBundleBuilder.#pieceMacroImportTokens);
230
+ if (at === -1) return source;
231
+ const end = tokens[at + PagesBundleBuilder.#pieceMacroImportTokens.length - 1].end;
232
+ return `${source.slice(0, tokens[at].start)}import { getSerializedSignalOf } from "../sig";${source.slice(end)}`;
233
+ }
234
+
235
+ static readonly #pieceMacroImportTokens = [
236
+ "import",
237
+ "{",
238
+ "getSerializedSignalOf",
239
+ "}",
240
+ "from",
241
+ '"../sig"',
242
+ "with",
243
+ "{",
244
+ "type",
245
+ ":",
246
+ '"macro"',
247
+ "}",
248
+ ";",
249
+ ] as const;
207
250
  static readonly #macroImportTokens = [
208
251
  "import",
209
252
  "{",
@@ -220,6 +263,41 @@ export class PagesBundleBuilder {
220
263
  ";",
221
264
  ] as const;
222
265
  static readonly #fetchProtoTokens = ["const", "fetchProto", "=", "FetchClient", ".", "build", "<"] as const;
266
+ static readonly #macroCallTokens = ["getSerializedSignal", "(", ")"] as const;
267
+ static readonly #pageFetchProtoTokens = [
268
+ "const",
269
+ "fetchProto",
270
+ "=",
271
+ "FetchClient",
272
+ ".",
273
+ "build",
274
+ "<",
275
+ "typeof",
276
+ "signal",
277
+ ">",
278
+ "(",
279
+ "{",
280
+ "}",
281
+ ",",
282
+ "{",
283
+ "}",
284
+ ")",
285
+ ";",
286
+ ] as const;
287
+
288
+ static transformServerPageFetchSource(source: string): string {
289
+ if (!source.includes("FetchClient.build")) return source;
290
+ const tokens = PagesBundleBuilder.#tokenize(source);
291
+ const at = PagesBundleBuilder.#indexOfTokens(tokens, PagesBundleBuilder.#pageFetchProtoTokens);
292
+ if (at === -1) return source;
293
+ const end = tokens[at + PagesBundleBuilder.#pageFetchProtoTokens.length - 1].end;
294
+ return [
295
+ `import { fetch as serverFetch } from "./sig";\n`,
296
+ source.slice(0, tokens[at].start),
297
+ "const fetchProto = FetchClient.build<typeof signal>({}, {}, { base: serverFetch });",
298
+ source.slice(end),
299
+ ].join("");
300
+ }
223
301
 
224
302
  //? The scanner, not the parser: parsing recurses per nesting level and overflows the stack on a deep `{` run.
225
303
  static #tokenize(source: string): TextSpan[] {
@@ -39,4 +39,26 @@ describe("precompressArtifacts", () => {
39
39
  expect(await readFile(`${chunkPath}.br`)).toEqual(brotliAt(await readFile(chunkPath), 9));
40
40
  expect(await Bun.file(`${dictPath}.gz`).exists()).toBe(true);
41
41
  });
42
+
43
+ test("compresses a chunk under 1 KB too, and writes no sidecar that would be larger than its file", async () => {
44
+ const distPath = await tempRoot();
45
+ const artifactDir = path.join(distPath, ".akan/artifact");
46
+ const stubPath = path.join(artifactDir, "client/stub.js");
47
+ const tinyPath = path.join(artifactDir, "client/tiny.js");
48
+ await mkdir(path.dirname(stubPath), { recursive: true });
49
+ await writeFile(
50
+ stubPath,
51
+ 'import{a as memoStore,b as memoList}from"./chunks/abc.js";export{memoStore,memoList};\n'.repeat(4),
52
+ );
53
+ await writeFile(tinyPath, "x");
54
+ const app = { dist: { cwdPath: distPath }, verbose: () => undefined } as unknown as App;
55
+
56
+ expect((await precompressArtifacts(app)).files).toBe(1);
57
+ const stubBytes = await readFile(stubPath);
58
+ expect(stubBytes.byteLength).toBeLessThan(1024);
59
+ expect(await readFile(`${stubPath}.br`)).toEqual(brotliAt(stubBytes, 9));
60
+ expect((await readFile(`${stubPath}.gz`)).byteLength).toBeLessThan(stubBytes.byteLength);
61
+ expect(await Bun.file(`${tinyPath}.br`).exists()).toBe(false);
62
+ expect(await Bun.file(`${tinyPath}.gz`).exists()).toBe(false);
63
+ });
42
64
  });
@@ -5,7 +5,6 @@ import type { App } from "../commandDecorators";
5
5
  import { FontPruner } from "./fontPruner";
6
6
 
7
7
  const COMPRESSIBLE_EXTS = new Set([".css", ".html", ".js", ".json", ".svg"]);
8
- const MIN_COMPRESS_BYTES = 1024;
9
8
  // Brotli 11 is ~100x slower than gzip: worth it for the one CSS asset per basePath and one dictionary per locale, not
10
9
  // for hundreds of JS chunks.
11
10
  const MAX_BROTLI_QUALITY = 11;
@@ -59,11 +58,17 @@ async function precompressRoot(
59
58
  const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
60
59
  const gz = Bun.gzipSync(buffer, { level: GZIP_LEVEL });
61
60
  const br = brotliCompress(buffer, brotliQuality ?? brotliQualityOf(path.extname(filePath).toLowerCase()));
62
- await Promise.all([Bun.write(`${filePath}.gz`, gz), Bun.write(`${filePath}.br`, br)]);
61
+ //? No 1 KB floor, unlike a response compressed as it is sent: serving a sidecar costs nothing per request.
62
+ const smaller = [
63
+ { ext: ".gz", encoded: gz },
64
+ { ext: ".br", encoded: br },
65
+ ].filter(({ encoded }) => encoded.byteLength < bytes.byteLength);
66
+ if (smaller.length === 0) continue;
67
+ await Promise.all(smaller.map(({ ext, encoded }) => Bun.write(`${filePath}${ext}`, encoded)));
63
68
  result.files += 1;
64
69
  result.inputBytes += bytes.byteLength;
65
- result.outputBytes += gz.byteLength;
66
- result.brotliBytes += br.byteLength;
70
+ result.outputBytes += Math.min(gz.byteLength, bytes.byteLength);
71
+ result.brotliBytes += Math.min(br.byteLength, bytes.byteLength);
67
72
  }
68
73
  }
69
74
 
@@ -73,13 +78,24 @@ export async function servedBrotliBytesOf(artifactDir: string, filePath: string)
73
78
  const bytes = await Bun.file(filePath).bytes();
74
79
  const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
75
80
  const quality = ROOT_BROTLI_QUALITY[root] ?? brotliQualityOf(path.extname(filePath).toLowerCase());
76
- return brotliCompress(buffer, quality).byteLength;
81
+ return Math.min(bytes.byteLength, brotliCompress(buffer, quality).byteLength);
82
+ }
83
+
84
+ export function chunkBrotliBytesOf(bytes: Uint8Array): number {
85
+ const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
86
+ return Math.min(bytes.byteLength, brotliCompress(buffer, brotliQualityOf(".js")).byteLength);
77
87
  }
78
88
 
79
89
  function brotliQualityOf(ext: string): number {
80
90
  return BROTLI_QUALITY_BY_EXT[ext as keyof typeof BROTLI_QUALITY_BY_EXT] ?? DEFAULT_BROTLI_QUALITY;
81
91
  }
82
92
 
93
+ export function dictionaryBrotliBytesOf(source: string): number {
94
+ const bytes = new TextEncoder().encode(source);
95
+ const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
96
+ return brotliCompress(buffer, ROOT_BROTLI_QUALITY.dict ?? MAX_BROTLI_QUALITY).byteLength;
97
+ }
98
+
83
99
  function brotliCompress(buffer: ArrayBuffer, quality: number): Buffer {
84
100
  return zlib.brotliCompressSync(buffer, {
85
101
  params: {
@@ -92,7 +108,5 @@ function brotliCompress(buffer: ArrayBuffer, quality: number): Buffer {
92
108
  async function shouldPrecompress(filePath: string): Promise<boolean> {
93
109
  if (filePath.endsWith(".gz") || filePath.endsWith(".br")) return false;
94
110
  if (!COMPRESSIBLE_EXTS.has(path.extname(filePath).toLowerCase())) return false;
95
- const file = Bun.file(filePath);
96
- if (!(await file.exists())) return false;
97
- return file.size >= MIN_COMPRESS_BYTES;
111
+ return Bun.file(filePath).exists();
98
112
  }
@@ -1,9 +1,9 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
 
4
- //* The sources `lib/useClient.ts` reads through its macros, which no registry graph lists as a dependency. A registry
5
- //* records their stamp, so a builder that loads one built before a signal or dictionary save rebuilds it, whichever
6
- //* process saw that save (a builder restarted for it never finishes the rebuild it started).
4
+ //* The sources `lib/useClient.ts` and `lib/usePage.ts` read through macros, which no registry graph lists as a
5
+ //* dependency. A registry records their stamp, so a builder that loads one built before a signal or dictionary save
6
+ //* rebuilds it, whichever process saw that save (a builder restarted for it never finishes the rebuild it started).
7
7
  export class RegistryMetadataFingerprint {
8
8
  static readonly #sources = new Bun.Glob("**/*.{signal,dictionary}.ts");
9
9
  static readonly #libFiles = ["sig.ts", "dict.ts", "useClient.ts"];