@akanjs/devkit 3.3.0-rc.24 → 3.3.0-rc.26

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 (144) hide show
  1. package/CHANGELOG.md +294 -0
  2. package/akanApp/akanApp.host.ts +11 -0
  3. package/akanConfig/akanBin.ts +4 -0
  4. package/akanConfig/akanConfig.test.ts +11 -0
  5. package/akanConfig/akanConfig.ts +39 -137
  6. package/akanConfig/akanWorkers.test.ts +39 -0
  7. package/akanConfig/akanWorkers.ts +32 -0
  8. package/akanConfig/desktopServerConfig.ts +96 -0
  9. package/akanConfig/dockerImage.ts +20 -0
  10. package/akanConfig/types.ts +1 -0
  11. package/app/appBin.test.ts +63 -0
  12. package/app/appBin.ts +50 -0
  13. package/app/applicationBuildReporter.test.ts +32 -0
  14. package/app/applicationBuildReporter.ts +4 -0
  15. package/app/applicationBuildRunner.test.ts +3 -0
  16. package/app/applicationBuildRunner.ts +40 -4
  17. package/app/dictionarySizes.ts +94 -0
  18. package/artifact/implicitRootLayout.test.ts +19 -0
  19. package/artifact/implicitRootLayout.ts +16 -2
  20. package/artifact/storeBootstrap.test.ts +28 -0
  21. package/artifact/storeBootstrap.ts +60 -8
  22. package/biome.base.json +5 -1
  23. package/codeAgent/skills/akan-agent/SKILL.md +2 -2
  24. package/codeAgent/skills/akan-deps/SKILL.md +3 -2
  25. package/codeAgent/skills/akan-err/SKILL.md +2 -6
  26. package/codeAgent/skills/akan-mcp/SKILL.md +1 -1
  27. package/codeAgent/skills/akan-module/SKILL.md +2 -2
  28. package/codeAgent/skills/akan-query/SKILL.md +13 -20
  29. package/codeAgent/skills/akan-service/SKILL.md +2 -5
  30. package/codeAgent/skills/akan-transport/SKILL.md +5 -14
  31. package/codeAgent/skills/akan-ui/SKILL.md +2 -5
  32. package/context/akanContext.ts +2 -0
  33. package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
  34. package/executors/clientRuntimeKeys.fixture.json +393 -0
  35. package/executors/clientRuntimeKeys.test.ts +1591 -0
  36. package/executors/executors.test.ts +2 -0
  37. package/executors/sysExecutor.ts +66 -3
  38. package/frontendBuild/allRoutesBuilder.ts +72 -3
  39. package/frontendBuild/autoImportSync.ts +3 -2
  40. package/frontendBuild/buildRouteClient.test.ts +513 -5
  41. package/frontendBuild/clientBuildTypes.ts +15 -0
  42. package/frontendBuild/clientEntriesBundler.ts +38 -0
  43. package/frontendBuild/clientEntryDiscovery.test.ts +60 -1
  44. package/frontendBuild/clientEntryDiscovery.ts +72 -4
  45. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  46. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  47. package/frontendBuild/csrDevPatcher.ts +33 -7
  48. package/frontendBuild/csrDevTypes.ts +9 -0
  49. package/frontendBuild/devBarrelImports.test.ts +70 -0
  50. package/frontendBuild/devBarrelImports.ts +80 -21
  51. package/frontendBuild/devRegistryBundler.ts +4 -2
  52. package/frontendBuild/devRouteRuntime.test.ts +492 -0
  53. package/frontendBuild/devRouteRuntime.ts +167 -0
  54. package/frontendBuild/dictionaryAssetBuilder.test.ts +316 -0
  55. package/frontendBuild/dictionaryAssetBuilder.ts +152 -16
  56. package/frontendBuild/dictionaryConstants.ts +82 -0
  57. package/frontendBuild/dictionaryPacking.test.ts +84 -0
  58. package/frontendBuild/dictionaryPacking.ts +92 -0
  59. package/frontendBuild/dictionaryRoutes.test.ts +186 -0
  60. package/frontendBuild/dictionaryRoutes.ts +225 -0
  61. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  62. package/frontendBuild/pagesBundleBuilder.ts +78 -2
  63. package/frontendBuild/precompressArtifacts.ts +7 -0
  64. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  65. package/frontendBuild/routeClientBuilder.ts +288 -15
  66. package/frontendBuild/routeHandoffs.test.ts +119 -0
  67. package/frontendBuild/routeHandoffs.ts +94 -0
  68. package/frontendBuild/routeRuntimeCheck.test.ts +257 -0
  69. package/frontendBuild/routeRuntimeCheck.ts +241 -0
  70. package/frontendBuild/routeRuntimePays.test.ts +137 -0
  71. package/frontendBuild/routeRuntimePays.ts +117 -0
  72. package/frontendBuild/ssrBaseArtifactBuilder.ts +24 -34
  73. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  74. package/frontendBuild/ssrDevBundler.ts +66 -11
  75. package/frontendBuild/vendorFileImports.test.ts +254 -0
  76. package/frontendBuild/vendorFileImports.ts +163 -0
  77. package/frontendBuild/vendorNarrowing.ts +28 -0
  78. package/frontendBuild/vendorSpecifiers.ts +2 -0
  79. package/incrementalBuilder/incrementalBuilder.proc.test.ts +79 -0
  80. package/incrementalBuilder/incrementalBuilder.proc.ts +20 -1
  81. package/mobile/desktopBin.ts +2 -2
  82. package/mobile/desktopServerStage.ts +1 -0
  83. package/package.json +4 -3
  84. package/quality/dictionaryKeys.test.ts +173 -0
  85. package/quality/dictionaryKeys.ts +415 -0
  86. package/quality/objectImportReport.test.ts +36 -0
  87. package/quality/objectImportReport.ts +102 -0
  88. package/quality/qualityScanner.ts +1 -1
  89. package/quality/routeRuntimeReport.test.ts +91 -0
  90. package/quality/routeRuntimeReport.ts +121 -0
  91. package/quality/runtimeConstantFacts.ts +71 -0
  92. package/quality/runtimeConstantGraph.ts +123 -0
  93. package/quality/runtimeConstantReads.ts +116 -0
  94. package/quality/runtimeImports.test.ts +190 -0
  95. package/quality/runtimeImports.ts +233 -0
  96. package/quality/runtimeKeyNames.ts +46 -0
  97. package/quality/runtimeLexicalScope.ts +132 -0
  98. package/quality/runtimeMarkerReach.test.ts +84 -0
  99. package/quality/runtimeMarkerReach.ts +255 -0
  100. package/quality/runtimeModuleFacts.ts +290 -0
  101. package/quality/runtimeNameTable.test.ts +172 -0
  102. package/quality/runtimeNameTable.ts +477 -0
  103. package/quality/runtimeScopeReport.test.ts +123 -0
  104. package/quality/runtimeScopeReport.ts +167 -0
  105. package/quality/runtimeSliceKey.ts +269 -0
  106. package/quality/runtimeSyntax.ts +133 -0
  107. package/quality/runtimeTable.fixture.ts +189 -0
  108. package/quality/runtimeUse.test.ts +737 -0
  109. package/quality/runtimeUse.ts +696 -0
  110. package/quality/runtimeUseReadable.test.ts +393 -0
  111. package/quality/ssrScanner.test.ts +13 -0
  112. package/quality/ssrScanner.ts +1 -1
  113. package/test/testHelpers.ts +11 -0
  114. package/transforms/barrelAnalyzer.ts +17 -1
  115. package/transforms/barrelImportsPlugin.ts +81 -13
  116. package/transforms/frameworkObjects.fixture.tsx +58 -0
  117. package/transforms/frameworkObjects.test.ts +54 -0
  118. package/transforms/modelReference.test.ts +196 -0
  119. package/transforms/modelReference.ts +39 -0
  120. package/transforms/objectImportEdits.ts +150 -0
  121. package/transforms/objectMemberImports.test.ts +347 -0
  122. package/transforms/objectMemberImports.ts +537 -0
  123. package/transforms/objectModule.test.ts +237 -0
  124. package/transforms/objectModule.ts +458 -0
  125. package/transforms/objectModuleAnalyzer.ts +104 -0
  126. package/transforms/reactIconImports.test.ts +231 -0
  127. package/transforms/reactIconImports.ts +325 -0
  128. package/transforms/routeConstants.ts +122 -0
  129. package/transforms/routeRuntime.test.ts +835 -0
  130. package/transforms/routeRuntime.ts +703 -0
  131. package/transforms/routeRuntimeEdits.ts +92 -0
  132. package/transforms/routeRuntimeGraph.ts +66 -0
  133. package/transforms/routeRuntimePlan.ts +244 -0
  134. package/transforms/signalDescriptors.test.ts +280 -0
  135. package/transforms/signalDescriptors.ts +227 -0
  136. package/transforms/thisFreeExports.ts +87 -0
  137. package/transforms/transforms.test.ts +139 -0
  138. package/workflow/executor.ts +6 -2
  139. package/workflow/index.ts +1 -0
  140. package/workflow/plan.ts +36 -7
  141. package/workflow/types.ts +1 -1
  142. package/workflow/uiTarget.ts +50 -0
  143. package/workspace/scanInfo.ts +1 -1
  144. package/workspace/workspaceLayout.ts +1 -0
@@ -1,9 +1,12 @@
1
1
  import path from "node:path";
2
2
  import { toError } from "akanjs/common";
3
+ import { AppWorkerPath } from "akanjs/server/appWorkerPath";
3
4
  import { BUILD_ENV_FILE } from "akanjs/server/lifecycle/buildEnv";
4
5
  import { SecretEnv } from "akanjs/server/lifecycle/secretEnv";
5
6
  import type { BunPlugin } from "bun";
7
+ import { AkanBin } from "../akanConfig/akanBin";
6
8
  import { ProductionLockfile } from "../akanConfig/productionLockfile";
9
+ import type { AkanWorkersConfig } from "../akanConfig/types";
7
10
  import type { App } from "../commandDecorators";
8
11
  import { parseEnvFile, WorkspaceExecutor } from "../executors";
9
12
  import {
@@ -24,6 +27,7 @@ import { ServerEnvProfile } from "../transforms/serverEnvProfile";
24
27
  import { ProjectTypecheck } from "../typecheck/projectTypecheck";
25
28
  import { Spinner } from "../util/spinner";
26
29
  import type { BaseDevEnv, PackageJson } from "../workspace/types";
30
+ import { AppBin } from "./appBin";
27
31
  import type {
28
32
  ApplicationBuildPhaseResult,
29
33
  ApplicationBuildProgressReporter,
@@ -380,7 +384,17 @@ export class ApplicationBuildRunner {
380
384
  const packageJson = akanConfig.getProductionPackageJson();
381
385
  const lockfile = await this.#pruneLockfile(packageJson);
382
386
  const env = { ...akanConfig.getProductionEnv(environment), ...this.#secretEnvList() };
383
- const dockerfile = akanConfig.dockerfileFor(environment, { lockfile: lockfile !== null, env });
387
+ const carried = await new AppBin(this.#app, akanConfig).stageImage(this.#app.dist.cwdPath);
388
+ if (carried.length)
389
+ this.#app.logger.info(
390
+ typeof akanConfig.docker === "string"
391
+ ? `The build carries ${carried.join(", ")} in ${AppBin.dir}/<TARGETARCH>/; apps/${this.#app.name}/akan.config.ts writes its own Dockerfile, which puts that folder on PATH itself (ENV PATH=${AkanBin.imagePath(AppBin.dir)}).`
392
+ : `The image carries ${carried.join(", ")} from bin, first on its PATH.`,
393
+ );
394
+ const dockerfile = akanConfig.dockerfileFor(environment, {
395
+ lockfile: lockfile !== null,
396
+ env: { ...(carried.length ? { PATH: AkanBin.imagePath(AppBin.dir) } : {}), ...env },
397
+ });
384
398
  await Promise.all([
385
399
  this.#app.dist.writeJson("package.json", packageJson),
386
400
  this.#app.dist.writeJson(BUILD_ENV_FILE, env),
@@ -462,7 +476,7 @@ export class ApplicationBuildRunner {
462
476
  }
463
477
 
464
478
  async #buildBackend() {
465
- const { externalLibs, web, baseDevEnv, branches } = await this.#app.getConfig();
479
+ const { externalLibs, web, baseDevEnv, branches, workers } = await this.#app.getConfig();
466
480
  const backendEntryPoints = [`${this.#app.cwdPath}/main.ts`, `${this.#app.cwdPath}/server.ts`];
467
481
  for (const entrypoint of backendEntryPoints) {
468
482
  if (!(await Bun.file(entrypoint).exists())) throw new Error(`Backend entrypoint not found: ${entrypoint}`);
@@ -503,13 +517,34 @@ export class ApplicationBuildRunner {
503
517
  naming: { entry: "console-runtime.[ext]", chunk: "chunk-[hash].[ext]" },
504
518
  });
505
519
  await this.#writeConsoleShim();
506
- const results = [mainResult, serverResult, rscWorkerResult, consoleRuntimeResult];
520
+ const workerResults = await this.#buildWorkers(workers, backendConfig);
521
+ const results = [mainResult, serverResult, rscWorkerResult, consoleRuntimeResult, ...workerResults];
507
522
  return {
508
- entrypoints: backendEntryPoints.length + (rscWorkerResult ? 2 : 1),
523
+ entrypoints: backendEntryPoints.length + (rscWorkerResult ? 2 : 1) + workerResults.length,
509
524
  outputs: results.reduce((sum, result) => sum + (result?.outputs.length ?? 0), 1),
510
525
  };
511
526
  }
512
527
 
528
+ //* Never a chunk of server.js: the process that runs a worker loads nothing of the server, nor the server of it.
529
+ async #buildWorkers(workers: AkanWorkersConfig, backendConfig: Omit<Bun.BuildConfig, "entrypoints">) {
530
+ const results: Bun.BuildOutput[] = [];
531
+ for (const [name, entry] of Object.entries(workers)) {
532
+ if (!(await Bun.file(entry).exists()))
533
+ throw new Error(
534
+ `apps/${this.#app.name}/akan.config.ts: workers.${name} names ${path.relative(this.#app.workspace.workspaceRoot, entry)}, which does not exist.`,
535
+ );
536
+ results.push(
537
+ await this.#buildOrThrow(`worker ${name}`, {
538
+ ...backendConfig,
539
+ outdir: path.join(this.#app.dist.cwdPath, AppWorkerPath.dir),
540
+ entrypoints: [entry],
541
+ naming: { entry: `${name}.[ext]`, chunk: "chunk-[hash].[ext]" },
542
+ }),
543
+ );
544
+ }
545
+ return results;
546
+ }
547
+
513
548
  async #writeConsoleShim() {
514
549
  await Bun.write(
515
550
  path.join(this.#app.dist.cwdPath, "console.js"),
@@ -569,6 +604,7 @@ void run().catch((error) => {
569
604
  const base = await new SsrBaseArtifactBuilder(this.#app, "build", {
570
605
  serverEnv: this.#serverEnvPlugin(baseDevEnv.env, branches),
571
606
  vendorExports,
607
+ dictionaryRoutes: allRoutes.dictionaryRoutes,
572
608
  }).build();
573
609
  this.#modulesByRoute = (await routes.writeModulePreloads(base.runtimeChunks)).modulesByRoute();
574
610
  return { base, allRoutes };
@@ -0,0 +1,94 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import zlib from "node:zlib";
4
+ import type { BaseBuildArtifact, DictAsset } from "akanjs/server";
5
+ import { FontPruner } from "../frontendBuild/fontPruner";
6
+
7
+ export interface DictionaryRouteBytes {
8
+ lightest: number;
9
+ median: number;
10
+ largest: number;
11
+ }
12
+
13
+ export interface DictionarySize {
14
+ lang: string;
15
+ pageBrotliBytes: number;
16
+ apiBrotliBytes?: number;
17
+ //? What a first visit downloads of the dictionary cut by route, over every route.
18
+ routeBrotliBytes?: DictionaryRouteBytes;
19
+ }
20
+
21
+ //? precompressArtifacts writes no `.br` for a smaller file, so it is served, and counted, raw.
22
+ const minCompressedBytes = 1024;
23
+
24
+ export class DictionarySizes {
25
+ static of(artifactDir: string): DictionarySize[] {
26
+ const artifactPath = path.join(artifactDir, "base-artifact.json");
27
+ if (!fs.existsSync(artifactPath)) return [];
28
+ const { dictAssets = {}, dictRoutes } = JSON.parse(fs.readFileSync(artifactPath, "utf8")) as Pick<
29
+ BaseBuildArtifact,
30
+ "dictAssets" | "dictRoutes"
31
+ >;
32
+ const brotliOf = (relPath: string) => DictionarySizes.#brotliBytesOf(path.join(artifactDir, relPath));
33
+ const routeIds = dictRoutes ? DictionarySizes.#routeIdsOf(artifactDir, dictRoutes) : [];
34
+ return Object.entries(dictAssets).map(([lang, asset]) => {
35
+ const api = asset.parts?.api;
36
+ const page = brotliOf(asset.relPath);
37
+ const routes =
38
+ dictRoutes && routeIds.length ? DictionarySizes.#routes(asset, page, routeIds, dictRoutes, brotliOf) : null;
39
+ return {
40
+ lang,
41
+ pageBrotliBytes: page,
42
+ ...(api ? { apiBrotliBytes: brotliOf(api.relPath) } : {}),
43
+ ...(routes ? { routeBrotliBytes: routes } : {}),
44
+ };
45
+ });
46
+ }
47
+
48
+ static format({ lang, pageBrotliBytes, apiBrotliBytes, routeBrotliBytes }: DictionarySize): string {
49
+ const { formatBytes } = FontPruner;
50
+ const api = apiBrotliBytes === undefined ? "" : `, API descriptions ${formatBytes(apiBrotliBytes)} where shown`;
51
+ if (!routeBrotliBytes) return `Dictionary ${lang}: ${formatBytes(pageBrotliBytes)} brotli on every page${api}`;
52
+ const { lightest, median, largest } = routeBrotliBytes;
53
+ const visit = `${formatBytes(lightest)} / ${formatBytes(median)} / ${formatBytes(largest)}`;
54
+ return `Dictionary ${lang}: first visit ${visit} brotli on the lightest / median / largest route (whole ${formatBytes(pageBrotliBytes)})${api}`;
55
+ }
56
+
57
+ //? A route the build could not read loads the whole page file, so it counts at that file's size.
58
+ static #routes(
59
+ asset: DictAsset,
60
+ pageBytes: number,
61
+ routeIds: string[],
62
+ dictRoutes: Record<string, number[]>,
63
+ brotliOf: (relPath: string) => number,
64
+ ): DictionaryRouteBytes | null {
65
+ const files = asset.routeParts?.files;
66
+ if (!files) return null;
67
+ const fileBytes = files.map(({ relPath }) => brotliOf(relPath));
68
+ const sizes = routeIds
69
+ .map((routeId) => {
70
+ const parts = dictRoutes[routeId];
71
+ return parts ? parts.reduce((total, idx) => total + (fileBytes[idx] ?? 0), 0) : pageBytes;
72
+ })
73
+ .sort((a, b) => a - b);
74
+ const at = (idx: number) => sizes[idx] ?? 0;
75
+ return { lightest: at(0), median: at(Math.floor((sizes.length - 1) / 2)), largest: at(sizes.length - 1) };
76
+ }
77
+
78
+ static #routeIdsOf(artifactDir: string, dictRoutes: Record<string, number[]>): string[] {
79
+ const seedIndexPath = path.join(artifactDir, "route-seed-index.json");
80
+ if (!fs.existsSync(seedIndexPath)) return Object.keys(dictRoutes);
81
+ const { entries = [] } = JSON.parse(fs.readFileSync(seedIndexPath, "utf8")) as { entries?: { routeId: string }[] };
82
+ return [...new Set(entries.map(({ routeId }) => routeId))];
83
+ }
84
+
85
+ //? The `.br` sidecar is what a browser gets; a build that stops before the compress phase has none.
86
+ static #brotliBytesOf(file: string): number {
87
+ const sidecar = `${file}.br`;
88
+ if (fs.existsSync(sidecar)) return fs.statSync(sidecar).size;
89
+ const raw = fs.readFileSync(file);
90
+ if (raw.byteLength < minCompressedBytes) return raw.byteLength;
91
+ const params = { [zlib.constants.BROTLI_PARAM_QUALITY]: zlib.constants.BROTLI_MAX_QUALITY };
92
+ return zlib.brotliCompressSync(raw, { params }).byteLength;
93
+ }
94
+ }
@@ -191,6 +191,25 @@ describe("resolveSsrPageEntries", () => {
191
191
  }
192
192
  });
193
193
 
194
+ test("registers the models' client references after the store, only where the per-route runtime asks for them", async () => {
195
+ const appRoot = await makeTempRoot();
196
+ await write(path.join(appRoot, "env", "env.client.ts"), "export const env = {};\n");
197
+ await write(path.join(appRoot, "lib", "st.ts"), "export const st = {};\n");
198
+ await write(path.join(appRoot, "page", "_layout.tsx"), 'export const theme = "dark";\n');
199
+ const pageKeys = ["./_layout.tsx", "./_index.tsx"];
200
+ const sourceOf = async (modelReferences?: boolean) => {
201
+ const entries = await resolveSsrPageEntries({ appCwdPath: appRoot, appName: "demo", pageKeys, modelReferences });
202
+ return Bun.file(entries.find((entry) => entry.key === "./__root_layout.tsx")?.moduleAbsPath ?? "").text();
203
+ };
204
+
205
+ const whole = await sourceOf();
206
+ expect(whole).not.toContain("__client/refs");
207
+ expect(await sourceOf(false)).toBe(whole);
208
+ expect(await sourceOf(true)).toContain(
209
+ 'import "@apps/demo/lib/useClient";\nimport "@apps/demo/lib/st";\nimport "@apps/demo/lib/__client/refs";\n',
210
+ );
211
+ });
212
+
194
213
  test("imports no store bootstrap for an app without a store", async () => {
195
214
  const appRoot = await makeTempRoot();
196
215
  await write(path.join(appRoot, "env", "env.client.ts"), "export const env = {};\n");
@@ -2,6 +2,7 @@ import { readdir, rm } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import type { App } from "../commandDecorators";
4
4
  import { AsyncDefaultExportDetector } from "../transforms/asyncDefaultExportDetector";
5
+ import { ModelReference } from "../transforms/modelReference";
5
6
  import { StoreBootstrap } from "./storeBootstrap";
6
7
 
7
8
  export interface PageEntry {
@@ -161,6 +162,7 @@ async function writeGeneratedRootLayoutFile(opts: {
161
162
  boundary: RootBoundary;
162
163
  rootSourceAbsPath: string | null;
163
164
  includeStoreBootstrap: boolean;
165
+ includeModelReferences: boolean;
164
166
  includeSystemProvider: boolean;
165
167
  }): Promise<string> {
166
168
  await assertEnvClientConvention(opts.appCwdPath, opts.appName);
@@ -173,7 +175,11 @@ async function writeGeneratedRootLayoutFile(opts: {
173
175
  const inheritedSourceAbsPath =
174
176
  opts.rootSourceAbsPath && opts.rootSourceAbsPath !== opts.boundary.sourceAbsPath ? opts.rootSourceAbsPath : null;
175
177
  const inheritedSourceSpecifier = inheritedSourceAbsPath ? importSpecifier(absPath, inheritedSourceAbsPath) : null;
176
- const storeImport = opts.includeStoreBootstrap ? StoreBootstrap.source(opts.appName) : "";
178
+ const referencesImport =
179
+ opts.includeStoreBootstrap && opts.includeModelReferences
180
+ ? `import ${JSON.stringify(ModelReference.registrySpecifier(opts.appName))};\n`
181
+ : "";
182
+ const storeImport = opts.includeStoreBootstrap ? `${StoreBootstrap.source(opts.appName)}${referencesImport}` : "";
177
183
  //? resolveRouteModule reads a rootLayout() chain and the legacy named exports alike.
178
184
  const inheritedLabel = inheritedSourceAbsPath ? posixRelative(opts.appCwdPath, inheritedSourceAbsPath) : "";
179
185
  const inheritedImport = inheritedSourceSpecifier
@@ -302,6 +308,7 @@ export async function resolveSsrPageEntries(opts: {
302
308
  appName: string;
303
309
  pageKeys: string[];
304
310
  basePaths?: Iterable<string>;
311
+ modelReferences?: boolean;
305
312
  }): Promise<PageEntry[]> {
306
313
  const absPageDir = path.resolve(opts.appCwdPath, "page");
307
314
  const hasSt = await Bun.file(path.join(opts.appCwdPath, "lib", "st.ts")).exists();
@@ -340,6 +347,7 @@ export async function resolveSsrPageEntries(opts: {
340
347
  boundary,
341
348
  rootSourceAbsPath,
342
349
  includeStoreBootstrap: hasSt,
350
+ includeModelReferences: !!opts.modelReferences,
343
351
  includeSystemProvider: !hasAncestorRootBoundary(boundary, rootBoundaries),
344
352
  }),
345
353
  seedAbsPaths: [...new Set([boundary.sourceAbsPath, rootSourceAbsPath].filter((absPath) => absPath !== null))],
@@ -362,5 +370,11 @@ export async function resolveSsrPageEntries(opts: {
362
370
 
363
371
  export async function resolveSsrPageEntriesForApp(app: App, pageKeys: string[]): Promise<PageEntry[]> {
364
372
  const config = await app.getConfig();
365
- return resolveSsrPageEntries({ appCwdPath: app.cwdPath, appName: app.name, pageKeys, basePaths: config.basePaths });
373
+ return resolveSsrPageEntries({
374
+ appCwdPath: app.cwdPath,
375
+ appName: app.name,
376
+ pageKeys,
377
+ basePaths: config.basePaths,
378
+ modelReferences: (await StoreBootstrap.scopeOf(app)) === "page",
379
+ });
366
380
  }
@@ -0,0 +1,28 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { rm } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import type { App } from "../commandDecorators";
5
+ import { tempDirs, writeText as write } from "../test/testHelpers";
6
+ import { StoreBootstrap } from "./storeBootstrap";
7
+
8
+ const makeTempRoot = tempDirs("akan-store-bootstrap-");
9
+ const synced = ["st", "usePage", "__client/_base.fetch", "__client/_useClient", "__client/_st", "__client/refs"];
10
+
11
+ const syncedApp = async () => {
12
+ const cwdPath = await makeTempRoot();
13
+ for (const file of synced) await write(path.join(cwdPath, "lib", `${file}.ts`), "export {};\n");
14
+ return { cwdPath } as unknown as App;
15
+ };
16
+
17
+ describe("StoreBootstrap.scopeOf", () => {
18
+ test("is the page runtime for a synced app", async () => {
19
+ expect(await StoreBootstrap.scopeOf(await syncedApp())).toBe("page");
20
+ });
21
+
22
+ test.each(synced)("keeps the whole runtime while lib/%s.ts was not generated yet", async (file) => {
23
+ const app = await syncedApp();
24
+ await rm(path.join(app.cwdPath, "lib", `${file}.ts`));
25
+
26
+ expect(await StoreBootstrap.scopeOf(app)).toBe("whole");
27
+ });
28
+ });
@@ -1,22 +1,74 @@
1
+ import path from "node:path";
2
+ import type { App } from "../commandDecorators";
1
3
  import type { BarrelExportMap } from "../transforms/barrelAnalyzer";
4
+ import { ModelReference } from "../transforms/modelReference";
5
+
6
+ const PAGE_ONLY_NAMES = new Set(["usePage", "msg", "Err"]);
7
+
8
+ export type ClientRuntimeScope = "whole" | "page";
2
9
 
3
10
  //* Not a bare `@apps/<app>/client` import: it names nothing the barrel rewrite can narrow, so every module's UI ships.
4
11
  export class StoreBootstrap {
5
- static importLines(appName: string): string[] {
6
- return StoreBootstrap.#lines([`@apps/${appName}/lib/useClient`, `@apps/${appName}/lib/st`]);
12
+ static readonly pageRuntime = "usePage";
13
+ //? `akanjs/signal`'s own descriptors, which framework UI on any page calls by a static name (`Reconnect`'s `ping`).
14
+ static readonly baseDescriptors = "__client/_base.fetch";
15
+ //? The whole runtime as its per-module pieces: what a page loads beside the pieces it already holds, each once.
16
+ static readonly assembled = ["__client/_useClient", "__client/_st"];
17
+
18
+ //? `akanjs/ui/modelRuntime` is empty on disk: a framework UI file reaching a store key or a fetch handler by a
19
+ //? computed name imports it, and a build whose entries load only the page runtime answers it with the app's.
20
+ static readonly modelRuntimeFilter = /[\\/]akanjs[\\/]ui[\\/]modelRuntime\.[jt]s$/;
21
+
22
+ //? `"page"` only where the page runtime files exist: a workspace not synced since it came keeps the whole runtime.
23
+ static async scopeOf(app: App): Promise<ClientRuntimeScope> {
24
+ const lib = path.join(app.cwdPath, "lib");
25
+ const found = await Promise.all(
26
+ [
27
+ "st",
28
+ StoreBootstrap.pageRuntime,
29
+ StoreBootstrap.baseDescriptors,
30
+ ...StoreBootstrap.assembled,
31
+ ModelReference.registry,
32
+ ].map((file) => Bun.file(path.join(lib, `${file}.ts`)).exists()),
33
+ );
34
+ return found.every(Boolean) ? "page" : "whole";
35
+ }
36
+
37
+ static importLines(appName: string, scope: ClientRuntimeScope = "whole"): string[] {
38
+ return StoreBootstrap.#lines(
39
+ scope === "page"
40
+ ? [StoreBootstrap.pageRuntime, StoreBootstrap.baseDescriptors].map((file) => `@apps/${appName}/lib/${file}`)
41
+ : [`@apps/${appName}/lib/useClient`, `@apps/${appName}/lib/st`],
42
+ );
43
+ }
44
+
45
+ static source(appName: string, scope: ClientRuntimeScope = "whole"): string {
46
+ return `${StoreBootstrap.importLines(appName, scope).join("\n")}\n`;
7
47
  }
8
48
 
9
- static source(appName: string): string {
10
- return `${StoreBootstrap.importLines(appName).join("\n")}\n`;
49
+ //? Absolute paths: the marker sits in `akanjs`, where neither a consumer's node_modules nor this repo's package
50
+ //? tsconfig maps `@apps/*`. Always the app's runtime, never a lib's, so every module's descriptors and stores load.
51
+ static modelRuntimeSource(app: App): string {
52
+ const files = ["useClient.ts", "st.ts"].map((file) => path.join(app.cwdPath, "lib", file));
53
+ return `${StoreBootstrap.#lines(files.map((file) => file.split(path.sep).join("/"))).join("\n")}\n`;
11
54
  }
12
55
 
13
- static ofClientBarrel(specifier: string, exports: BarrelExportMap): string[] | null {
56
+ static ofClientBarrel(
57
+ specifier: string,
58
+ exports: BarrelExportMap,
59
+ names: string[] = [],
60
+ { perModule = false }: { perModule?: boolean } = {},
61
+ ): string[] | null {
14
62
  if (!/^@(?:apps|libs)\/[^/]+\/client$/.test(specifier)) return null;
15
- const runtime = exports.get("usePage");
63
+ const page = exports.get("usePage");
64
+ const descriptors = exports.get("fetch") ?? page;
16
65
  const store = exports.get("st");
17
66
  //? A barrel with only one of the two is not the generated shape, so what else it runs on import is unknown.
18
- if (!runtime || runtime.namespace || !store || store.namespace) return [specifier];
19
- return [...new Set([runtime.subpath, store.subpath])];
67
+ if (!page || page.namespace || !descriptors || descriptors.namespace || !store || store.namespace)
68
+ return [specifier];
69
+ const pageOnly = perModule || (names.length > 0 && names.every((name) => PAGE_ONLY_NAMES.has(name)));
70
+ if (pageOnly && page.subpath !== descriptors.subpath) return [page.subpath];
71
+ return [...new Set([descriptors.subpath, store.subpath])];
20
72
  }
21
73
 
22
74
  static #lines(specifiers: string[]): string[] {
package/biome.base.json CHANGED
@@ -91,6 +91,7 @@
91
91
  "apps/*/lib/srv.ts",
92
92
  "apps/*/lib/st.ts",
93
93
  "apps/*/lib/sig.ts",
94
+ "apps/*/lib/usePage.ts",
94
95
  "apps/*/lib/useClient.ts",
95
96
  "apps/*/lib/useServer.ts",
96
97
  "apps/*/client.ts",
@@ -102,6 +103,7 @@
102
103
  "libs/*/lib/srv.ts",
103
104
  "libs/*/lib/st.ts",
104
105
  "libs/*/lib/sig.ts",
106
+ "libs/*/lib/usePage.ts",
105
107
  "libs/*/lib/useClient.ts",
106
108
  "libs/*/lib/useServer.ts",
107
109
  "libs/*/client.ts",
@@ -109,7 +111,9 @@
109
111
  "libs/*/index.ts",
110
112
  "libs/*/lib/*/index.tsx",
111
113
  "apps/*/lib/__lib/**",
112
- "libs/*/lib/__lib/**"
114
+ "libs/*/lib/__lib/**",
115
+ "apps/*/lib/__client/**",
116
+ "libs/*/lib/__client/**"
113
117
  ],
114
118
  "linter": { "enabled": false },
115
119
  "formatter": { "enabled": false },
@@ -42,8 +42,8 @@ agent nothing, and only the current page's declarations are live.
42
42
  param or a list row's title included, is left out and read with `readState` or `readScreen`, so instructions say
43
43
  "read `searchParams`", never "the query is in the route context". A search param rides inline when a store
44
44
  declares its key with `search()`; of the others at most four short ones do. A zone's `label` and a value
45
- published with `st.expose`, `st.useState` or `useAgentResource` ride whole: publish an id or a count there, never
46
- text a user wrote.
45
+ published with `st.expose`, `st.useState` or `useAgentResource` follow the same rule: free text there is read
46
+ with `readScreen` of the zone or `readState(name)`.
47
47
  - A tool value is capped at 20,000 characters.
48
48
  - Route guidance is `<Agent.Guide instructions="…" />`; model-facing text is English.
49
49
 
@@ -8,8 +8,9 @@ description: "Fix an import, dependency, or barrel problem in an Akan workspace
8
8
  ## Barrels are generated
9
9
 
10
10
  Every `index.ts` under `ui/`, `webkit/`, `srvkit/`, `common/`, `plugin/` and `lib/**` is scanner output, as
11
- are `cnst.ts`, `db.ts`, `dict.ts`, `sig.ts`, `srv.ts`, `st.ts`, `useClient.ts`, `useServer.ts`, `client.ts`
12
- and `server.ts`. Do not hand-edit them and do not rely on their exact contents.
11
+ are `cnst.ts`, `db.ts`, `dict.ts`, `sig.ts`, `srv.ts`, `st.ts`, `useClient.ts`, `usePage.ts`, `useServer.ts`,
12
+ `client.ts`, `server.ts`, `lib/__lib/` and `lib/__client/`. Do not hand-edit them and do not rely on their exact
13
+ contents.
13
14
 
14
15
  **If an import "cannot be found" but the file exists, the barrel is stale** — run `akan sync <app-or-lib>`,
15
16
  or `repair_generated`. A `ui/<Folder>/index.tsx` that builds a namespace is hand-written source; the
@@ -24,12 +24,8 @@ import path at all**, so keep throwing code out of them entirely rather than rea
24
24
 
25
25
  ## Where each error belongs
26
26
 
27
- - a state-machine precondition → `document.ts`
28
- - a cross-document rule → `service.ts`
29
- - request-level policy → a guard in `signal.ts`
30
-
31
- Best-effort code returns a sentinel (`null`, `undefined`, `{}`) instead of throwing. `try/catch` is rare and
32
- always converts an exception into a decision: a guard catches, warns, and returns `false`; an adapter
27
+ Which file throws which error, and the sentinel best-effort code returns instead, are the `server` rule.
28
+ `try/catch` is rare and always converts an exception into a decision: a guard catches, warns, and returns `false`; an adapter
33
29
  catches, logs (`logger.error`), and returns `null`; a UI `try/finally` resets a spinner. A store action never
34
30
  catches — let the framework toast the `Err`, or list it in the store's `static silent` when no screen waits on it
35
31
  and its caller handles the rejection.
@@ -23,7 +23,7 @@ an endpoint with a real guard is published, one with none is refused, and so is
23
23
  - `option.setMcp({ … })` in the app's `lib/option.ts`, never `main.ts`; `AKAN_MCP=false` takes the surface off.
24
24
  - `JWT_SECRET` is required outside `local`.
25
25
  - Every published entry needs a `.desc()`; model-facing text is English.
26
- - Never make a refusal message more helpful. A client branches on the code a failure carries
26
+ - A client branches on the code a failure carries
27
27
  (`_meta["akanjs/failure"]`, or a JSON-RPC error's `data.code`), never on its text.
28
28
 
29
29
  ## Pages for the host
@@ -36,8 +36,8 @@ module. Collection-level helpers go `static` on the full model.
36
36
  - Keep business decisions in constant, document and service; API exposure in signal; client coordination in
37
37
  store; rendering in UI.
38
38
  - Never hand-edit a generated registry file — `cnst.ts`, `db.ts`, `dict.ts`, `option.ts`, `sig.ts`, `srv.ts`,
39
- `st.ts`, `useClient.ts`, `useServer.ts`, and every `index.ts` barrel. They are scanner output; run
40
- `akan sync <app>` or `repair_generated`.
39
+ `st.ts`, `useClient.ts`, `usePage.ts`, `useServer.ts`, the files under `lib/__lib/` and `lib/__client/`, and every
40
+ `index.ts` barrel. They are scanner output; run `akan sync <app>` or `repair_generated`.
41
41
  - Read the module's `<module>.abstract.md` before changing it, and update it when an invariant or workflow
42
42
  changes — not for formatting.
43
43
 
@@ -5,35 +5,28 @@ description: "Write filters, slices and list loading: query descriptors, init pa
5
5
 
6
6
  # Akan queries and slices
7
7
 
8
+ The `module` rule, loaded with every `lib/` file, holds the musts: a slice returns a query, at most 500 rows, soft
9
+ removal and `purge`, the hookless `updateById` / `removeById`, secret projections, the cascade direction and when a
10
+ search slice is safe. This skill adds what it does not say.
11
+
8
12
  ## Filters and slices
9
13
 
10
- - A filter in `<model>.document.ts` declares its args; a slice in `<model>.signal.ts` serves it to stores. A slice
11
- `exec` returns a `query<Filter>(…)` descriptor — never a `list<Filter>` array — and you cannot chain sort or
12
- limit on it.
14
+ - A filter in `<model>.document.ts` declares its args; a slice in `<model>.signal.ts` serves it to stores. The
15
+ `query<Filter>(…)` descriptor a slice returns takes no chained sort or limit.
13
16
  - Page through the store: `initX(…, { sort, page, limit })`, then `st.do.loadMoreOf<Model>()` while
14
17
  `hasMoreOf<Model>`. Never compare `count > page * limit`.
15
- - Never ask for more than 500 rows: the server serves at most 500 per request and drops the rest silently.
16
- A figure over the whole set belongs in an insight or an endpoint.
17
- - The root slice takes a filter name and its args, never a raw query, and its `root:` guard is always `Admin`.
18
+ - The root slice takes a filter name and its args, never a raw query.
18
19
  - No value is `q.empty`, never `q.missing`.
19
- - A projection is bare on the facade (`pickById(id, { secret: true })`) and under `select` on a filter accessor —
20
- the only way to read a `field.secret` value.
21
20
 
22
- ## Writes and removal
21
+ ## Writes
23
22
 
24
- - Removal is soft: reads see live rows unless `{ withRemoved: true }`. The one hard delete is `purge<Filter>` /
25
- `purgeMany`, for data past retention.
26
- - A filter's `remove*` / `update*`, `updateById` and `removeById` run no hooks and no cascade. A model with a
27
- cascade or `_postRemove` removes through `remove<Model>(id)`.
28
- - Load a set once (`load<Model>Many`, one filter query) and create one with `create<Model>Many(rows)` instead of one
29
- call per item in a loop — lint fails a per-item service call an endpoint reaches. `create<Model>Many` runs every
30
- row's `_preCreate` before writing any, so a check there does not see the batch's own rows.
23
+ - A filter's `update*` runs no hooks and no cascade, like its `remove*`.
24
+ - `create<Model>Many(rows)` runs every row's `_preCreate` before writing any, so a check there does not see the
25
+ batch's own rows.
31
26
 
32
- ## Search and cascade
27
+ ## Search
33
28
 
34
29
  - `q.search(text, { prefix: true })` sits in a filter at an AND position, over fields with the `text` role. Blank
35
- input matches nothing — never a passthrough. A search slice only over data safe to enumerate.
36
- - `cascade` names a direction, and the wrong one loses data: `removeRef` on the owner's relation, `removeWith` on
37
- the child's reference to its owner.
30
+ input matches nothing — never a passthrough.
38
31
 
39
32
  Full detail: `get_guideline` with `queryRule`, and `workspaceRecipes` for a worked slice.
@@ -29,11 +29,8 @@ dictionary is a `serviceDictionary`.
29
29
 
30
30
  Inside a service, in preference order: `service<srv.XService>()` for another module's service,
31
31
  `plug(AdapterClass)` for an adapter, `use<T>()` only for an `option.ts`-registered legacy singleton, and
32
- `env(...)` for config. Injection resolves by field name — a field named `<refName>Service` finds the service
33
- registered under `<refName>`, and the `Service` suffix is required.
34
-
35
- An external API or piece of infrastructure is an `adapt()` class in `srvkit/`, injected with `plug`. It
36
- self-registers, so do **not** add it to `lib/option.ts`.
32
+ `env(...)` for config. Injection resolves by field name: a field named `<refName>Service` finds the service
33
+ registered under `<refName>`. The adapter's place and the field-name suffix are the `server` rule.
37
34
 
38
35
  ## Recipe: pages backed by an external HTTP API
39
36
 
@@ -7,21 +7,14 @@ description: "Guard and tune endpoints on the wire: writing a Can<Verb><Model> g
7
7
 
8
8
  ## Guards
9
9
 
10
- - Every custom `query` / `mutation` / `pubsub` / `message` names its own `guards: [...]`; every `slice()` takes an
11
- explicit guard map with `root: Admin`. `Public` belongs on a slice `get:`, and on a mutation only for an act that
12
- must work signed out (sign-up, sign-in, token refresh, an OAuth route), which also declares a `rateLimit`.
10
+ - Which guards each endpoint and slice names, `Public`, `static scope`, `static name`, the acting user and the
11
+ service's second check are the `auth` rule, loaded with every `signal.ts` and `srvkit/` file.
13
12
  - A resource guard is a `Can<Verb><Model>` class in the model library's `srvkit/guards.ts` that fails closed:
14
13
  no resource named, or a load that throws, is `false` (after a `logger.warn`). Admin bypass goes first.
15
- - Every guard declares `static scope`: `"account"` reads only the caller (`SignedIn`, `Admin`, roles), and
16
- `"resource"` needs the call's arguments (every `Can<Verb><Model>`). Keep `static name = "User";` with a comment.
17
- - Guards read `context.get<T>("account")`, serve HTTP and websocket alike, and stay side-effect free. The acting
18
- user comes from `.with(Self)` / `.with(CurrentUserId)` / `.with(Me)`, the address from `.with(Ip)` — never a
19
- client-supplied id. The service re-checks ownership: two independent gates.
20
14
 
21
15
  ## Endpoint options
22
16
 
23
- - `{ timeout: <ms> }` is the deadline on both ends; undeclared, the client quits at 30 s and the handler is not
24
- cancelled.
17
+ - `{ timeout: <ms> }` is the deadline on both ends.
25
18
  - `{ cache }` only on a `query` with no internal argument, capped at one day; `invalidate(endpoint, args?)` drops
26
19
  it early through a plugged `EndpointCacheControl`.
27
20
  - `{ rateLimit: { calls, windowMs?, by? } }` per endpoint, `option.setRateLimit` per app, `plug(RateLimit)` for a
@@ -34,9 +27,7 @@ description: "Guard and tune endpoints on the wire: writing a Can<Verb><Model> g
34
27
 
35
28
  ## Bodies and other servers
36
29
 
37
- - `.body()` / `.param()` take scalars, model refs or `enumOf(...)`; `Int` / `Float`, never `Number`; bytes are
38
- `Binary`, never `Any`; `Upload` only in a `fileUpload: true` mutation.
39
- - Server to server, `fetch.clone({ origin })` opens no socket without `connect: true`, retries through `retry`,
40
- and rethrows a remote `Err` as it is — never wrap or re-key it.
30
+ - `.body()` / `.param()` take scalars, model refs or `enumOf(...)`; the types they refuse are the `server` rule.
31
+ - Server to server, `fetch.clone({ origin })` opens no socket without `connect: true` and retries through `retry`.
41
32
 
42
33
  Full detail: `get_guideline` with `transportRule`, or `mcpRule` for what a guard's scope does to an MCP listing.
@@ -47,11 +47,8 @@ the literal string `"false"`.
47
47
 
48
48
  ## Classes
49
49
 
50
- Never hand-order Tailwind classes; the formatter sorts them and its output is correct. Stay inside the
51
- semantic token vocabulary — `bg-primary`, `text-foreground/70` — because a raw palette class (`bg-blue-500`),
52
- an arbitrary colour (`bg-[#3b82f6]`), a daisyUI legacy class, and a colour literal in `style={{…}}` all
53
- render no CSS and fail lint. Reach for `cn` only for a conditional or to merge an incoming `className`, and
54
- merge the caller last.
50
+ Class order and the colour vocabulary are the `style` rule. Reach for `cn` only for a conditional or to merge an
51
+ incoming `className`, and merge the caller last.
55
52
 
56
53
  ## Forms
57
54
 
@@ -272,8 +272,10 @@ const generatedFiles = [
272
272
  "*/lib/sig.ts",
273
273
  "*/lib/srv.ts",
274
274
  "*/lib/st.ts",
275
+ "*/lib/usePage.ts",
275
276
  "*/lib/useClient.ts",
276
277
  "*/lib/useServer.ts",
278
+ "*/lib/__client/*.ts",
277
279
  "*/lib/**/index.ts",
278
280
  "*/ui/index.ts",
279
281
  "*/webkit/index.ts",