@akanjs/devkit 3.3.0-rc.25 → 3.3.0-rc.27

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 (145) hide show
  1. package/CHANGELOG.md +300 -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 +145 -0
  67. package/frontendBuild/routeHandoffs.ts +115 -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 +24 -2
  115. package/transforms/barrelImportsPlugin.ts +82 -14
  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 +177 -0
  138. package/transforms/tsconfigPackageResolver.test.ts +1 -0
  139. package/workflow/executor.ts +6 -2
  140. package/workflow/index.ts +1 -0
  141. package/workflow/plan.ts +36 -7
  142. package/workflow/types.ts +1 -1
  143. package/workflow/uiTarget.ts +50 -0
  144. package/workspace/scanInfo.ts +1 -1
  145. package/workspace/workspaceLayout.ts +1 -0
@@ -0,0 +1,145 @@
1
+ import { beforeAll, describe, expect, test } from "bun:test";
2
+ import path from "node:path";
3
+ import { runtimeFixtureTables } from "../quality/runtimeTable.fixture";
4
+ import { tempDirs, writeText as write } from "../test/testHelpers";
5
+ import { RouteRuntime } from "../transforms/routeRuntime";
6
+ import { RouteHandoffs } from "./routeHandoffs";
7
+
8
+ const makeTempRoot = tempDirs("akan-route-handoffs-");
9
+ const models = ["memo", "note", "tag"];
10
+ const client = 'import { fetch } from "@apps/demo/client";\n';
11
+
12
+ let root = "";
13
+ let handoffs: RouteHandoffs;
14
+ const file = (name: string) => path.join(root, name);
15
+ const referenceOf = (model: string) => file(`apps/demo/lib/__client/${model}.ref.ts`);
16
+ const readOf = async (sources: Record<string, string>) => {
17
+ for (const [name, source] of Object.entries(sources)) await write(file(name), source);
18
+ return handoffs.read(Object.keys(sources).map(file));
19
+ };
20
+
21
+ beforeAll(async () => {
22
+ root = await makeTempRoot();
23
+ const { demo } = await runtimeFixtureTables();
24
+ const runtime = new RouteRuntime(root, demo, new Set());
25
+ handoffs = new RouteHandoffs(root, runtime, new Map(models.map((model) => [model, referenceOf(model)])));
26
+ });
27
+
28
+ describe("the models a route's server modules hand to client components", () => {
29
+ test("are those whose init, view, edit or slice a server module names, whichever module of the route names it", async () => {
30
+ const read = await readOf({
31
+ "apps/demo/page/board.tsx": `${client}export const Board = () => fetch.initMemoInBoard();\n`,
32
+ "apps/demo/ui/NoteCard.tsx": `${client}export const card = (id: string) => fetch.viewNote(id);\n`,
33
+ "apps/demo/ui/plain.ts": "export const plain = 1;\n",
34
+ });
35
+
36
+ expect(read).toEqual({ referenceFiles: [referenceOf("memo"), referenceOf("note")], unread: null });
37
+ });
38
+
39
+ test("include a model whose slice is read from `fetch.slice`", async () => {
40
+ const read = await readOf({
41
+ "apps/demo/page/tags.tsx": `${client}export const Tags = () => [fetch.slice.tag, fetch.tagCount()];\n`,
42
+ });
43
+
44
+ expect(read.referenceFiles).toEqual([referenceOf("tag")]);
45
+ });
46
+
47
+ test("leave out a model whose endpoint is only called, since a plain result brings no component a store to read", async () => {
48
+ const read = await readOf({
49
+ "apps/demo/page/count.tsx": `${client}export const Count = async () => [await fetch.memoNote(), await fetch.tagCount()];\n`,
50
+ });
51
+
52
+ expect(read).toEqual({ referenceFiles: [], unread: null });
53
+ });
54
+
55
+ test("do not count every model for a server module that copies the names of a slice it was handed", async () => {
56
+ const read = await readOf({
57
+ "apps/demo/page/board.tsx": `${client}export const Board = () => fetch.initMemoInBoard();\n`,
58
+ "apps/demo/ui/copy.ts":
59
+ 'import type { SliceMeta } from "akanjs/fetch";\nexport const copy = (slice: SliceMeta) => ({ refName: slice.refName, sliceName: slice.sliceName, argLength: 0 });\n',
60
+ });
61
+
62
+ expect(read).toEqual({ referenceFiles: [referenceOf("memo")], unread: null });
63
+ });
64
+
65
+ test("are every model once a server module picks the name at run time, and say which file and line", async () => {
66
+ const read = await readOf({
67
+ "apps/demo/page/board.tsx": `${client}export const Board = () => fetch.initMemoInBoard();\n`,
68
+ "apps/demo/page/any.tsx": `${client}\nexport const Any = (name: string) => (fetch as never)[name];\n`,
69
+ });
70
+
71
+ expect(read.referenceFiles).toEqual(models.map(referenceOf));
72
+ expect(read.unread?.file).toBe("apps/demo/page/any.tsx");
73
+ expect(read.unread?.why).toStartWith("line 3: ");
74
+ });
75
+
76
+ test("are every model once a server module takes `fetch` from the server barrel, where its names are not read", async () => {
77
+ const read = await readOf({
78
+ "apps/demo/page/served.tsx":
79
+ 'import { Memo } from "@apps/demo/client";\nimport { fetch } from "@apps/demo/server";\nexport const Served = (id: string) => [Memo, fetch.viewMemo(id)];\n',
80
+ });
81
+
82
+ expect(read.referenceFiles).toEqual(models.map(referenceOf));
83
+ expect(read.unread).toEqual({
84
+ file: "apps/demo/page/served.tsx",
85
+ why: "line 2: `fetch` comes from the server barrel, where the names read from it are not checked; take it from the client barrel",
86
+ });
87
+ });
88
+
89
+ test("do not count the server barrel's `fetch` where the file hands nothing over, nor a generated file", async () => {
90
+ const read = await readOf({
91
+ "apps/demo/page/ping.tsx":
92
+ 'import { fetch } from "@apps/demo/server";\nexport const ping = () => fetch.memoNote();\n',
93
+ "apps/demo/page/typed.tsx":
94
+ 'import type { fetch } from "@apps/demo/server";\nexport type View = ReturnType<typeof fetch.viewMemo>;\n',
95
+ "apps/demo/server.ts": 'import { fetch } from "./lib/useServer";\nexport const view = fetch.viewMemo;\n',
96
+ "apps/demo/lib/useServer.ts": 'import { fetch } from "./sig";\nexport const view = fetch.viewMemo;\n',
97
+ });
98
+
99
+ expect(read).toEqual({ referenceFiles: [], unread: null });
100
+ });
101
+
102
+ test("do not count a service that calls an endpoint through the server barrel and slices an array of its own", async () => {
103
+ const read = await readOf({
104
+ "apps/demo/lib/memo/memo.service.ts":
105
+ 'import { fetch } from "../useServer";\nexport const scan = async (ips: string[]) => [ips.slice(0, 1), await fetch.memoNote(), { fetch: 1 }.fetch];\n',
106
+ });
107
+
108
+ expect(read).toEqual({ referenceFiles: [], unread: null });
109
+ });
110
+
111
+ test("are every model once the server barrel's `fetch` is indexed, passed on or taken apart", async () => {
112
+ const taken = 'import { fetch } from "@apps/demo/server";\n';
113
+ const unreadOf = async (name: string, body: string) =>
114
+ (await readOf({ [`apps/demo/page/${name}.tsx`]: `${taken}${body}\n` })).unread?.file;
115
+
116
+ expect(
117
+ await unreadOf("indexed", "export const any = (name: string) => [name.slice(1), (fetch as never)[name]];"),
118
+ ).toBe("apps/demo/page/indexed.tsx");
119
+ expect(
120
+ await unreadOf("passed", "export const all = (use: (api: unknown) => void) => [[].slice(), use(fetch)];"),
121
+ ).toBe("apps/demo/page/passed.tsx");
122
+ expect(
123
+ await unreadOf("apart", "const { viewMemo } = fetch;\nexport const view = (id: string) => viewMemo(id);"),
124
+ ).toBe("apps/demo/page/apart.tsx");
125
+ expect(await unreadOf("sliced", "export const tags = () => fetch.slice.tag;")).toBe("apps/demo/page/sliced.tsx");
126
+ });
127
+
128
+ test("name only models with a reference file, so a model the app's sync wrote none for adds nothing", async () => {
129
+ const { demo } = await runtimeFixtureTables();
130
+ const only = new RouteHandoffs(
131
+ root,
132
+ new RouteRuntime(root, demo, new Set()),
133
+ new Map([["memo", referenceOf("memo")]]),
134
+ );
135
+ await write(
136
+ file("apps/demo/page/both.tsx"),
137
+ `${client}export const both = [fetch.initMemoInBoard(), fetch.viewNote("1")];\n`,
138
+ );
139
+
140
+ expect(await only.read([file("apps/demo/page/both.tsx")])).toEqual({
141
+ referenceFiles: [referenceOf("memo")],
142
+ unread: null,
143
+ });
144
+ });
145
+ });
@@ -0,0 +1,115 @@
1
+ import path from "node:path";
2
+ import ts from "typescript";
3
+ import { RuntimeScopeReport } from "../quality/runtimeScopeReport";
4
+ import { RuntimeUse } from "../quality/runtimeUse";
5
+ import type { RouteRuntime } from "../transforms/routeRuntime";
6
+
7
+ export interface RouteHandoffRead {
8
+ referenceFiles: string[];
9
+ unread: { file: string; why: string } | null;
10
+ }
11
+
12
+ interface FileRead {
13
+ models: string[];
14
+ unread: string | null;
15
+ }
16
+
17
+ const capitalize = (name: string) => name.charAt(0).toUpperCase() + name.slice(1);
18
+ const serverFetchSource =
19
+ /^(?:@(?:apps|libs)\/[^/]+\/(?:server|lib\/(?:sig|useServer))|\.{1,2}\/(?:.+\/)?(?:server|sig|useServer))$/;
20
+ const generatedFile = /^(?:apps|libs)\/[^/]+\/(?:(?:server|client)\.ts$|lib\/[^/]+\.ts$|lib\/__client\/)/;
21
+ const handoffName = /\b(?:init|view|edit)[A-Z]|\bget[A-Z]\w*(?:Init|View|Edit)\b|\bslice\b/;
22
+ const handoffMember = /^(?:(?:init|view|edit)[A-Z]|get[A-Z]\w*(?:Init|View|Edit)$|slice$)/;
23
+
24
+ //? Only `fetch.init<Model>`, `view<Model>`, `edit<Model>`, their `get` forms and `fetch.slice` build a handoff object.
25
+ export class RouteHandoffs {
26
+ readonly #workspaceRoot: string;
27
+ readonly #runtime: RouteRuntime;
28
+ readonly #references: Map<string, string>;
29
+ readonly #files = new Map<string, Promise<FileRead>>();
30
+
31
+ constructor(workspaceRoot: string, runtime: RouteRuntime, references: Map<string, string>) {
32
+ this.#workspaceRoot = workspaceRoot;
33
+ this.#runtime = runtime;
34
+ this.#references = references;
35
+ }
36
+
37
+ async read(serverModules: string[]): Promise<RouteHandoffRead> {
38
+ const models = new Set<string>();
39
+ for (const file of serverModules) {
40
+ const read = await this.#fileOf(file);
41
+ if (read.unread)
42
+ return {
43
+ referenceFiles: [...this.#references.values()].sort(),
44
+ unread: { file: path.relative(this.#workspaceRoot, file).split(path.sep).join("/"), why: read.unread },
45
+ };
46
+ for (const model of read.models) models.add(model);
47
+ }
48
+ return { referenceFiles: [...models].flatMap((model) => this.#references.get(model) ?? []).sort(), unread: null };
49
+ }
50
+
51
+ #fileOf(absPath: string): Promise<FileRead> {
52
+ const known = this.#files.get(absPath);
53
+ if (known) return known;
54
+ const read = (async (): Promise<FileRead> => {
55
+ const fileName = this.#runtime.fileNameOf(absPath);
56
+ if (!fileName || generatedFile.test(fileName)) return { models: [], unread: null };
57
+ const text = await Bun.file(absPath).text();
58
+ const serverFetchLine = RouteHandoffs.#serverFetchLineOf(fileName, text);
59
+ if (serverFetchLine)
60
+ return {
61
+ models: [],
62
+ unread: `line ${serverFetchLine}: \`fetch\` comes from the server barrel, where the names read from it are not checked; take it from the client barrel`,
63
+ };
64
+ if (!RuntimeScopeReport.isRuntimeSource(fileName)) return { models: [], unread: null };
65
+ const verdict = RuntimeUse.analyze({ fileName, text }, this.#runtime.table);
66
+ if (!verdict.resolvable) return { models: [], unread: `line ${verdict.line}: ${verdict.message}` };
67
+ const named = verdict.owners.map(({ module }) => module).filter((module) => this.#references.has(module));
68
+ //? Every name of a readable file is written out in it, so a model none of these names can hand nothing over.
69
+ const anySlice = /slice/i.test(text);
70
+ const hands = (module: string) => new RegExp(`(?:init|view|edit|get)${capitalize(module)}`).test(text);
71
+ return { models: named.filter((module) => anySlice || hands(module)), unread: null };
72
+ })();
73
+ this.#files.set(absPath, read);
74
+ return read;
75
+ }
76
+
77
+ //? The server barrel's `fetch` hands the same references over, and the analysis reads only a client barrel's.
78
+ static #serverFetchLineOf(fileName: string, text: string): number | null {
79
+ if (!text.includes("fetch") || !handoffName.test(text)) return null;
80
+ const kind = fileName.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
81
+ const source = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true, kind);
82
+ for (const statement of source.statements) {
83
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) continue;
84
+ const clause = statement.importClause;
85
+ if (!clause || clause.isTypeOnly || !serverFetchSource.test(statement.moduleSpecifier.text)) continue;
86
+ const bindings = clause.namedBindings;
87
+ if (!bindings) continue;
88
+ const line = source.getLineAndCharacterOfPosition(statement.getStart(source)).line + 1;
89
+ if (ts.isNamespaceImport(bindings)) return line;
90
+ const taken = bindings.elements.find((el) => !el.isTypeOnly && (el.propertyName ?? el.name).text === "fetch");
91
+ if (taken && RouteHandoffs.#handsOver(source, taken.name.text)) return line;
92
+ }
93
+ return null;
94
+ }
95
+
96
+ //? Text alone took `ips.slice(0, 1)` in a service that calls an endpoint for a slice handed over, on every route.
97
+ static #handsOver(source: ts.SourceFile, local: string): boolean {
98
+ const visit = (node: ts.Node): boolean => {
99
+ if (ts.isImportDeclaration(node)) return false;
100
+ if (ts.isIdentifier(node) && node.text === local) {
101
+ const { parent } = node;
102
+ const named =
103
+ (ts.isPropertyAccessExpression(parent) && parent.name === node) ||
104
+ ((ts.isPropertyAssignment(parent) || ts.isMethodDeclaration(parent) || ts.isPropertyDeclaration(parent)) &&
105
+ parent.name === node);
106
+ if (named) return false;
107
+ if (ts.isPropertyAccessExpression(parent) && parent.expression === node)
108
+ return handoffMember.test(parent.name.text);
109
+ return true;
110
+ }
111
+ return ts.forEachChild(node, visit) ?? false;
112
+ };
113
+ return visit(source);
114
+ }
115
+ }
@@ -0,0 +1,257 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import type { ClientBundleGraph } from "./clientBuildTypes";
3
+ import { RouteRuntimeCheck } from "./routeRuntimeCheck";
4
+
5
+ const root = "/ws";
6
+ const abs = (file: string) => `${root}/${file}`;
7
+ const fetchPiece = "apps/demo/lib/__client/memo.fetch.ts";
8
+ const storePiece = "apps/demo/lib/__client/memo.st.ts";
9
+ const storeFile = "apps/demo/lib/memo/memo.store.ts";
10
+ const card = "apps/demo/ui/Card.tsx";
11
+
12
+ interface GraphShape {
13
+ imports: Record<string, (string | { lazy: string })[]>;
14
+ chunks?: Record<string, string[]>;
15
+ chunkImports?: Record<string, string[]>;
16
+ }
17
+
18
+ const graphOf = ({ imports, chunks = {}, chunkImports = {} }: GraphShape): ClientBundleGraph => ({
19
+ importsByModule: new Map(
20
+ Object.entries(imports).map(([module, list]) => [
21
+ abs(module),
22
+ list.map((imported) =>
23
+ typeof imported === "string" ? { path: abs(imported), lazy: false } : { path: abs(imported.lazy), lazy: true },
24
+ ),
25
+ ]),
26
+ ),
27
+ chunksByModule: new Map(Object.entries(chunks).map(([module, list]) => [abs(module), list])),
28
+ importsByChunk: new Map(Object.entries(chunkImports)),
29
+ });
30
+
31
+ interface NarrowedShape {
32
+ entries: Record<string, string>;
33
+ wholeReaders?: string[];
34
+ wholeConstantReaders?: string[];
35
+ }
36
+
37
+ const failuresOf = (shape: GraphShape, narrowed?: NarrowedShape) =>
38
+ new RouteRuntimeCheck(
39
+ root,
40
+ graphOf(shape),
41
+ narrowed
42
+ ? {
43
+ entries: new Map(Object.entries(narrowed.entries).map(([build, entry]) => [abs(build), abs(entry)])),
44
+ wholeReaders: new Set((narrowed.wholeReaders ?? []).map(abs)),
45
+ wholeConstantReaders: new Set((narrowed.wholeConstantReaders ?? []).map(abs)),
46
+ }
47
+ : null,
48
+ ).failures;
49
+
50
+ describe("what a build loading per module checks in its own output", () => {
51
+ const storeAndPiece = { [storeFile]: [fetchPiece], [fetchPiece]: [] };
52
+
53
+ test("a module's chunk reaches the chunk of each runtime piece it imports, directly, through another chunk or by holding it", () => {
54
+ const split = { [storeFile]: ["/out/store.js"], [fetchPiece]: ["/out/fetch.js"] };
55
+ expect(failuresOf({ imports: storeAndPiece, chunks: split })).toEqual([
56
+ "apps/demo/lib/memo/memo.store.ts needs apps/demo/lib/__client/memo.fetch.ts loaded first, but its chunk store.js does not import the chunk holding that piece",
57
+ ]);
58
+ const direct = { "/out/store.js": ["/out/fetch.js"] };
59
+ const through = { "/out/store.js": ["/out/shared.js"], "/out/shared.js": ["/out/fetch.js"] };
60
+ expect(failuresOf({ imports: storeAndPiece, chunks: split, chunkImports: direct })).toEqual([]);
61
+ expect(failuresOf({ imports: storeAndPiece, chunks: split, chunkImports: through })).toEqual([]);
62
+ const together = { [storeFile]: ["/out/store.js"], [fetchPiece]: ["/out/store.js"] };
63
+ expect(failuresOf({ imports: storeAndPiece, chunks: together })).toEqual([]);
64
+ });
65
+
66
+ test("every chunk a module is copied into reaches the piece, and a piece asked for with `import()` needs no order", () => {
67
+ const copied = { [storeFile]: ["/out/a.js", "/out/b.js"], [fetchPiece]: ["/out/fetch.js"] };
68
+ const onlyFirst = { "/out/a.js": ["/out/fetch.js"] };
69
+ expect(failuresOf({ imports: storeAndPiece, chunks: copied, chunkImports: onlyFirst })).toHaveLength(1);
70
+ const lazy = { [card]: [{ lazy: storePiece }], [storePiece]: [] };
71
+ const apart = { [card]: ["/out/card.js"], [storePiece]: ["/out/piece.js"] };
72
+ expect(failuresOf({ imports: lazy, chunks: apart })).toEqual([]);
73
+ });
74
+
75
+ test("no store file is imported back by a runtime piece that a file it imports loads", () => {
76
+ const helper = "apps/demo/webkit/relabel.ts";
77
+ const cycle = { [storeFile]: [helper], [helper]: [storePiece], [storePiece]: [storeFile] };
78
+ expect(failuresOf({ imports: cycle })).toEqual([
79
+ "apps/demo/lib/memo/memo.store.ts imports apps/demo/webkit/relabel.ts, which loads apps/demo/lib/__client/memo.st.ts, and that piece imports the store file back before it is defined: move what apps/demo/webkit/relabel.ts reads from the store out of the files a store file imports",
80
+ ]);
81
+ expect(failuresOf({ imports: { ...cycle, [helper]: [] } })).toEqual([]);
82
+ const uiCycle = { [card]: ["apps/demo/ui/Frame.tsx"], "apps/demo/ui/Frame.tsx": [card, storePiece] };
83
+ expect(failuresOf({ imports: { ...uiCycle, [storePiece]: [storeFile], [storeFile]: [] } })).toEqual([]);
84
+ });
85
+
86
+ test("a page built to load only the modules its code names reaches neither a file needing every module nor the runtime of every module", () => {
87
+ const entry = "apps/demo/.akan/generated/client-entry-bootstrap-route/Card.tsx";
88
+ const run = "apps/demo/ui/Run.tsx";
89
+ const whole = "apps/demo/lib/st.ts";
90
+ const entries = { [entry]: card };
91
+ expect(
92
+ failuresOf({ imports: { [entry]: [card], [card]: [run], [run]: [] } }, { entries, wholeReaders: [run] }),
93
+ ).toEqual([
94
+ "apps/demo/ui/Card.tsx was built to load only the modules its code names, but it reaches apps/demo/ui/Run.tsx, which needs every module",
95
+ ]);
96
+ expect(failuresOf({ imports: { [entry]: [card], [card]: [whole], [whole]: [] } }, { entries })).toEqual([
97
+ "apps/demo/ui/Card.tsx was built to load only the modules its code names, but apps/demo/ui/Card.tsx imports apps/demo/lib/st.ts, the runtime of every module",
98
+ ]);
99
+ expect(
100
+ failuresOf(
101
+ { imports: { [entry]: [card], [card]: [{ lazy: run }], [run]: [] } },
102
+ { entries, wholeReaders: [run] },
103
+ ),
104
+ ).toEqual([]);
105
+ expect(failuresOf({ imports: { [entry]: [card], [card]: [] } }, { entries, wholeReaders: [run] })).toEqual([]);
106
+ });
107
+
108
+ test("a registration piece loads before the file reading its model, and no file it loads imports it back", () => {
109
+ const registration = "apps/demo/lib/__client/memo.cnst.ts";
110
+ const constant = "apps/demo/lib/memo/memo.constant.ts";
111
+ const reads = { [card]: [registration], [registration]: [constant], [constant]: [] };
112
+ const apart = { [card]: ["/out/card.js"], [registration]: ["/out/cnst.js"] };
113
+ expect(failuresOf({ imports: reads, chunks: apart })).toEqual([
114
+ "apps/demo/ui/Card.tsx needs apps/demo/lib/__client/memo.cnst.ts loaded first, but its chunk card.js does not import the chunk holding that piece",
115
+ ]);
116
+ expect(failuresOf({ imports: reads, chunks: apart, chunkImports: { "/out/card.js": ["/out/cnst.js"] } })).toEqual(
117
+ [],
118
+ );
119
+ const helper = "apps/demo/common/label.ts";
120
+ const back = { [registration]: [constant], [constant]: [helper], [helper]: [registration] };
121
+ expect(failuresOf({ imports: back })).toEqual([
122
+ "apps/demo/lib/__client/memo.cnst.ts loads files that import it back through apps/demo/common/label.ts, which reads the model before it is registered",
123
+ ]);
124
+ expect(failuresOf({ imports: { ...back, [helper]: [] } })).toEqual([]);
125
+ });
126
+
127
+ test("a registration piece answering from `lib/cnst.ts` needs that file loaded first, wherever its bare re-export lands", () => {
128
+ const answering = "apps/demo/lib/__client/board.cnst.ts";
129
+ const constants = "apps/demo/lib/cnst.ts";
130
+ const imports = { [fetchPiece]: [answering], [answering]: [constants], [constants]: [] };
131
+ const chunks = { [fetchPiece]: ["/out/fetch.js"], [answering]: ["/out/empty.js"], [constants]: ["/out/cnst.js"] };
132
+ const toConstants = { "/out/fetch.js": ["/out/cnst.js"] };
133
+ const answered = { entries: {}, wholeConstantReaders: [answering] };
134
+ expect(failuresOf({ imports, chunks, chunkImports: toConstants }, answered)).toEqual([]);
135
+ expect(failuresOf({ imports, chunks }, answered)).toEqual([
136
+ "apps/demo/lib/__client/memo.fetch.ts needs apps/demo/lib/__client/board.cnst.ts loaded first, but its chunk fetch.js does not import the chunk holding that piece",
137
+ ]);
138
+ expect(failuresOf({ imports, chunks, chunkImports: toConstants }, { entries: {} })).toHaveLength(1);
139
+ expect(failuresOf({ imports, chunks, chunkImports: toConstants })).toHaveLength(1);
140
+ const together = { ...imports, [constants]: [answering] };
141
+ expect(failuresOf({ imports: together }, answered)).toEqual([]);
142
+ expect(failuresOf({ imports: together }, { entries: {} })).toHaveLength(1);
143
+ });
144
+
145
+ test("a page built to load only the modules its code names reaches every constant only through a file `akan quality runtime` names", () => {
146
+ const entry = "apps/demo/.akan/generated/client-entry-bootstrap-route/Card.tsx";
147
+ const entries = { [entry]: card };
148
+ const registration = "apps/demo/lib/__client/board.cnst.ts";
149
+ const constant = "apps/demo/lib/board/board.constant.ts";
150
+ const barrel = "libs/kit/index.ts";
151
+ const libConstants = "libs/kit/lib/cnst.ts";
152
+ const throughBarrel = {
153
+ [entry]: [card],
154
+ [card]: [registration],
155
+ [registration]: [constant],
156
+ [constant]: [barrel],
157
+ [barrel]: [libConstants],
158
+ [libConstants]: [],
159
+ };
160
+ expect(failuresOf({ imports: throughBarrel }, { entries })).toEqual([
161
+ "apps/demo/ui/Card.tsx was built to load only the modules its code names, but libs/kit/index.ts imports libs/kit/lib/cnst.ts, the constants of every model, for no reason `akan quality runtime` names",
162
+ ]);
163
+ expect(failuresOf({ imports: throughBarrel }, { entries, wholeConstantReaders: [constant] })).toEqual([]);
164
+ const own = "apps/demo/lib/cnst.ts";
165
+ const computed = { [entry]: [card], [card]: [own], [own]: [] };
166
+ expect(failuresOf({ imports: computed }, { entries })).toHaveLength(1);
167
+ expect(failuresOf({ imports: computed }, { entries, wholeConstantReaders: [card] })).toEqual([]);
168
+ expect(failuresOf({ imports: { [entry]: [card], [card]: [{ lazy: own }], [own]: [] } }, { entries })).toEqual([]);
169
+ });
170
+
171
+ test("a page a registration piece answering from `lib/cnst.ts` already makes load every constant may reach them through a constant file left as written, and no further than that piece loads", () => {
172
+ const entry = "apps/demo/.akan/generated/client-entry-bootstrap-route/board.ref.tsx";
173
+ const reference = "apps/demo/lib/__client/board.ref.ts";
174
+ const entries = { [entry]: reference };
175
+ const boardStorePiece = "apps/demo/lib/__client/board.st.ts";
176
+ const boardStore = "libs/kit/lib/board/board.store.ts";
177
+ const answering = "libs/kit/lib/__client/board.cnst.ts";
178
+ const constant = "libs/kit/lib/board/board.constant.ts";
179
+ const [kitConstants, appConstants] = ["libs/kit/lib/cnst.ts", "apps/demo/lib/cnst.ts"];
180
+ const [baseBarrel, baseConstants] = ["libs/base/index.ts", "libs/base/lib/cnst.ts"];
181
+ const handedOverByNoRoute = {
182
+ [entry]: [reference],
183
+ [reference]: [boardStorePiece],
184
+ [boardStorePiece]: [boardStore],
185
+ [boardStore]: [answering, constant],
186
+ [answering]: [kitConstants, appConstants],
187
+ [kitConstants]: [constant],
188
+ [constant]: [baseBarrel],
189
+ [baseBarrel]: [baseConstants],
190
+ [appConstants]: [kitConstants, baseBarrel],
191
+ [baseConstants]: [],
192
+ };
193
+ expect(failuresOf({ imports: handedOverByNoRoute }, { entries, wholeConstantReaders: [answering] })).toEqual([]);
194
+ expect(failuresOf({ imports: handedOverByNoRoute }, { entries })).toEqual([
195
+ "apps/demo/lib/__client/board.ref.ts was built to load only the modules its code names, but libs/kit/lib/__client/board.cnst.ts imports libs/kit/lib/cnst.ts, the constants of every model, for no reason `akan quality runtime` names",
196
+ ]);
197
+ const ownScopeOnly = { ...handedOverByNoRoute, [answering]: [kitConstants], [kitConstants]: [] };
198
+ expect(failuresOf({ imports: ownScopeOnly }, { entries, wholeConstantReaders: [answering] })).toEqual([
199
+ "apps/demo/lib/__client/board.ref.ts was built to load only the modules its code names, but libs/base/index.ts imports libs/base/lib/cnst.ts, the constants of every model, for no reason `akan quality runtime` names",
200
+ ]);
201
+ });
202
+
203
+ test("a failing check names the first failures, how many more there are, what the build does instead and that it is a bug to report", () => {
204
+ const stores = Array.from(
205
+ { length: RouteRuntimeCheck.shown + 2 },
206
+ (_, index) => `apps/demo/lib/m${index}/m${index}.store.ts`,
207
+ );
208
+ const imports = { ...Object.fromEntries(stores.map((store) => [store, [fetchPiece]])), [fetchPiece]: [] };
209
+ const chunks = {
210
+ ...Object.fromEntries(stores.map((store) => [store, ["/out/store.js"]])),
211
+ [fetchPiece]: ["/out/fetch.js"],
212
+ };
213
+ const check = new RouteRuntimeCheck(root, graphOf({ imports, chunks }));
214
+ expect(check.refusal).toBe(
215
+ [
216
+ "[client-runtime] loading per module, this build would not load its modules in order:",
217
+ ...stores
218
+ .slice(0, RouteRuntimeCheck.shown)
219
+ .map(
220
+ (store) =>
221
+ ` - ${store} needs ${fetchPiece} loaded first, but its chunk store.js does not import the chunk holding that piece`,
222
+ ),
223
+ " - and 2 more",
224
+ "Every page of this build loads the whole client runtime instead, not only what it uses. This is a bug in akan: report it with the lines above.",
225
+ ].join("\n"),
226
+ );
227
+ expect(new RouteRuntimeCheck(root, graphOf({ imports: storeAndPiece })).refusal).toBeNull();
228
+ });
229
+
230
+ test("a route loading a scope's whole file and a piece of that scope is named, unless one of the two takes its part from the other", () => {
231
+ const whole = "apps/demo/lib/useClient.ts";
232
+ const constants = "apps/demo/lib/cnst.ts";
233
+ const constantPiece = "apps/demo/lib/__client/memo.cnst.ts";
234
+ const kitPiece = "libs/kit/lib/__client/memo.fetch.ts";
235
+ const frame = "apps/demo/ui/Frame.tsx";
236
+ const later = "apps/demo/ui/Later.tsx";
237
+ const repeatedOf = (imports: GraphShape["imports"], routes: Record<string, string[]>) =>
238
+ new RouteRuntimeCheck(root, graphOf({ imports }), {
239
+ entries: new Map(),
240
+ wholeReaders: new Set(),
241
+ routes: new Map(Object.entries(routes).map(([route, entries]) => [route, entries.map(abs)])),
242
+ }).repeated;
243
+ const both = { [frame]: [whole], [card]: [fetchPiece], [whole]: [], [fetchPiece]: [] };
244
+ expect(repeatedOf(both, { "/frame": [frame, card], "/plain": [frame], "/card": [card] })).toEqual([
245
+ `${whole} and ${fetchPiece} both load on 1 route(s), the first /frame: the piece holds again what the file holds`,
246
+ ]);
247
+ expect(repeatedOf({ ...both, [whole]: [fetchPiece] }, { "/frame": [frame, card] })).toEqual([]);
248
+ expect(repeatedOf({ ...both, [fetchPiece]: [whole] }, { "/frame": [frame, card] })).toEqual([]);
249
+ expect(repeatedOf({ ...both, [card]: [kitPiece], [kitPiece]: [] }, { "/frame": [frame, card] })).toEqual([]);
250
+ const asked = { [frame]: [whole, { lazy: later }], [later]: [fetchPiece], [whole]: [], [fetchPiece]: [] };
251
+ expect(repeatedOf(asked, { "/frame": [frame] })).toHaveLength(1);
252
+ const registered = { [frame]: [constants], [card]: [constantPiece], [constants]: [], [constantPiece]: [] };
253
+ expect(repeatedOf(registered, { "/frame": [frame, card] })).toEqual([
254
+ `${constants} and ${constantPiece} both load on 1 route(s), the first /frame: the piece holds again what the file holds`,
255
+ ]);
256
+ });
257
+ });