@akanjs/devkit 3.3.0-rc.25 → 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
@@ -0,0 +1,415 @@
1
+ import ts from "typescript";
2
+ import { RuntimeLexicalScope } from "./runtimeLexicalScope";
3
+
4
+ export interface DictionaryKeyUnread {
5
+ line: number;
6
+ why: string;
7
+ }
8
+
9
+ export interface DictionaryKeyRead {
10
+ //? The first segment of every string the file holds, and every string that is one name: a superset of its groups.
11
+ names: string[];
12
+ //? PascalCase names, which a constant table turns into the groups of the enums, scalars and models they name.
13
+ classNames: string[];
14
+ //? One-name strings handed to a component as a prop (`modelName="memo"`): what a server module tells client UI.
15
+ propNames: string[];
16
+ api: boolean;
17
+ unread: DictionaryKeyUnread[];
18
+ //? A framework surface that shows the texts of whichever module its data names, not of the modules a page loads.
19
+ anyModule: string | null;
20
+ }
21
+
22
+ const leadName = /^([A-Za-z_$][\w$]*)(?:\.|$)/;
23
+ const className = /^[A-Z][A-Za-z0-9]*$/;
24
+ const apiKey = /\.signal\.[^.\s]*\.(?:desc|arg)\b/;
25
+ const anyModuleSurfaces = new Set(["Signal", "Constant"]);
26
+ const frameworkUi = /^akanjs\/ui(?:\/(Signal|Constant)(?:\/|$)|$)/;
27
+ const oneName = /^[A-Za-z_$][\w$]*$/;
28
+ //? `Data.Dashboard` labels its columns `summary.<column>` unless it is handed another `summaryRefName`.
29
+ const impliedNames = new Map([["Dashboard", "summary"]]);
30
+ const tableMethods = new Set(["map", "forEach", "filter", "flatMap", "find", "findLast", "some", "every"]);
31
+ const subsetMethods = new Set(["filter", "slice", "sort", "toSorted", "reverse", "toReversed", "concat", "at"]);
32
+ const objectReaders = new Set(["keys", "values", "entries"]);
33
+ const memberCalls = new Set(["field", "enum", "trans"]);
34
+ const translatorChain = new Set(["_", "rich"]);
35
+ const groupHead = /^[A-Za-z_$][\w$]*\./;
36
+ const maxDepth = 16;
37
+
38
+ const strip = (node: ts.Expression): ts.Expression =>
39
+ ts.isParenthesizedExpression(node) ||
40
+ ts.isAsExpression(node) ||
41
+ ts.isSatisfiesExpression(node) ||
42
+ ts.isNonNullExpression(node) ||
43
+ ts.isTypeAssertionExpression(node)
44
+ ? strip(node.expression)
45
+ : node;
46
+
47
+ //* Which dictionary groups a client file can show: the keys it hands `l`, `l._`, `l.rich` or `translate` must come from
48
+ //* strings written in the file (a literal, a template with a literal group, a table or a typed union it holds).
49
+ export class DictionaryKeys {
50
+ readonly #sourceFile: ts.SourceFile;
51
+ readonly #scope = new RuntimeLexicalScope();
52
+ readonly #translators = new Set(["l"]);
53
+ readonly #names = new Set<string>();
54
+ readonly #classNames = new Set<string>();
55
+ readonly #propNames = new Set<string>();
56
+ readonly #unread: DictionaryKeyUnread[] = [];
57
+ #api = false;
58
+ #anyModule: string | null = null;
59
+
60
+ private constructor(sourceFile: ts.SourceFile) {
61
+ this.#sourceFile = sourceFile;
62
+ }
63
+
64
+ static read(text: string, fileName: string): DictionaryKeyRead {
65
+ const kind = fileName.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
66
+ const sourceFile = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true, kind);
67
+ return new DictionaryKeys(sourceFile).#read();
68
+ }
69
+
70
+ #read(): DictionaryKeyRead {
71
+ this.#collectAliases(this.#sourceFile);
72
+ this.#visit(this.#sourceFile);
73
+ return {
74
+ names: [...this.#names].sort(),
75
+ classNames: [...this.#classNames].sort(),
76
+ propNames: [...this.#propNames].sort(),
77
+ api: this.#api,
78
+ unread: this.#unread,
79
+ anyModule: this.#anyModule,
80
+ };
81
+ }
82
+
83
+ #collectAliases(node: ts.Node) {
84
+ if (ts.isBindingElement(node) && node.propertyName && ts.isIdentifier(node.name)) {
85
+ const property = node.propertyName;
86
+ if (ts.isIdentifier(property) && property.text === "l") this.#translators.add(node.name.text);
87
+ }
88
+ ts.forEachChild(node, (child) => this.#collectAliases(child));
89
+ }
90
+
91
+ #visit(node: ts.Node) {
92
+ if (ts.isExpression(node) && this.#isTranslator(node) && this.#isReference(node)) this.#checkTranslatorUse(node);
93
+ if (ts.isImportDeclaration(node)) this.#readImport(node);
94
+ else if (ts.isStringLiteralLike(node)) this.#addText(node.text, node.text);
95
+ else if (ts.isTemplateExpression(node))
96
+ this.#addText(node.head.text, [node.head.text, ...node.templateSpans.map((span) => span.literal.text)].join("*"));
97
+ else if (ts.isTemplateLiteralTypeNode(node))
98
+ this.#addText(node.head.text, [node.head.text, ...node.templateSpans.map((span) => span.literal.text)].join("*"));
99
+ else if (ts.isIdentifier(node) && className.test(node.text)) this.#classNames.add(node.text);
100
+ else if (ts.isCallExpression(node)) this.#readCall(node);
101
+ else if (ts.isJsxAttribute(node) && node.initializer && ts.isStringLiteral(node.initializer)) {
102
+ if (oneName.test(node.initializer.text)) this.#propNames.add(node.initializer.text);
103
+ }
104
+ const implied = ts.isPropertyAccessExpression(node) ? impliedNames.get(node.name.text) : undefined;
105
+ if (implied) {
106
+ this.#names.add(implied);
107
+ this.#propNames.add(implied);
108
+ }
109
+ ts.forEachChild(node, (child) => this.#visit(child));
110
+ }
111
+
112
+ #addText(lead: string, pattern: string) {
113
+ const name = lead.match(leadName)?.[1];
114
+ if (name) this.#names.add(name);
115
+ if (apiKey.test(pattern)) this.#api = true;
116
+ }
117
+
118
+ #readImport(node: ts.ImportDeclaration) {
119
+ if (!ts.isStringLiteral(node.moduleSpecifier) || node.importClause?.isTypeOnly) return;
120
+ const specifier = node.moduleSpecifier.text;
121
+ const [matched, surface] = specifier.match(frameworkUi) ?? [];
122
+ if (!matched) return;
123
+ const bindings = node.importClause?.namedBindings;
124
+ const named =
125
+ bindings && ts.isNamedImports(bindings)
126
+ ? bindings.elements
127
+ .filter((element) => !element.isTypeOnly)
128
+ .map((element) => (element.propertyName ?? element.name).text)
129
+ : [];
130
+ const shown = surface ?? named.find((name) => anyModuleSurfaces.has(name));
131
+ if (shown) this.#anyModule ??= `${shown} from ${specifier} shows the texts of any module its data names`;
132
+ }
133
+
134
+ #readCall(call: ts.CallExpression) {
135
+ const key = this.#keyOf(call);
136
+ if (!key || this.#follows(key, 0)) return;
137
+ this.#fail(key, this.#whyOf(strip(key)));
138
+ }
139
+
140
+ #isReference(node: ts.Expression): boolean {
141
+ const { parent } = node;
142
+ if (ts.isShorthandPropertyAssignment(parent)) return true;
143
+ if ((parent as { name?: ts.Node }).name === node) return false;
144
+ if (ts.isBindingElement(parent) || ts.isImportSpecifier(parent) || ts.isExportSpecifier(parent))
145
+ return parent.propertyName !== node;
146
+ return !ts.isTypeQueryNode(parent) && !ts.isQualifiedName(parent);
147
+ }
148
+
149
+ #checkTranslatorUse(node: ts.Expression) {
150
+ const outerOf = (inner: ts.Node): ts.Node => {
151
+ let outer = inner;
152
+ while (
153
+ ts.isParenthesizedExpression(outer.parent) ||
154
+ ts.isAsExpression(outer.parent) ||
155
+ ts.isSatisfiesExpression(outer.parent) ||
156
+ ts.isNonNullExpression(outer.parent) ||
157
+ ts.isTypeAssertionExpression(outer.parent)
158
+ )
159
+ outer = outer.parent;
160
+ return outer;
161
+ };
162
+ const outer = outerOf(node);
163
+ const { parent } = outer;
164
+ if (ts.isCallExpression(parent) && parent.expression === outer) return;
165
+ if (ts.isPropertyAccessExpression(parent) && parent.expression === outer) {
166
+ if (translatorChain.has(parent.name.text)) return;
167
+ const access = outerOf(parent);
168
+ if (
169
+ memberCalls.has(parent.name.text) &&
170
+ ts.isCallExpression(access.parent) &&
171
+ access.parent.expression === access
172
+ )
173
+ return;
174
+ }
175
+ this.#fail(
176
+ node,
177
+ ts.isCallExpression(parent)
178
+ ? "passes the translator on"
179
+ : "is used other than as a call, which no key can be read from",
180
+ );
181
+ }
182
+
183
+ #isTranslator(node: ts.Expression): boolean {
184
+ if (ts.isIdentifier(node)) return this.#translators.has(node.text);
185
+ if (!ts.isPropertyAccessExpression(node)) return false;
186
+ const name = node.name.text;
187
+ if (name === "l") return true;
188
+ return (name === "_" || name === "rich") && this.#isTranslator(strip(node.expression));
189
+ }
190
+
191
+ #keyOf(call: ts.CallExpression): ts.Expression | undefined {
192
+ const callee = strip(call.expression);
193
+ if (this.#isTranslator(callee)) return call.arguments[0];
194
+ const name = ts.isIdentifier(callee)
195
+ ? callee.text
196
+ : ts.isPropertyAccessExpression(callee)
197
+ ? callee.name.text
198
+ : null;
199
+ if (name === "translate" || name === "translateByLocale")
200
+ return call.arguments.length > 1 ? call.arguments[1] : undefined;
201
+ return undefined;
202
+ }
203
+
204
+ #fail(node: ts.Node, why: string) {
205
+ const { line } = this.#sourceFile.getLineAndCharacterOfPosition(node.getStart(this.#sourceFile));
206
+ const text = node.getText(this.#sourceFile).replace(/\s+/g, " ");
207
+ this.#unread.push({ line: line + 1, why: `${text.length > 60 ? `${text.slice(0, 57)}...` : text} ${why}` });
208
+ }
209
+
210
+ #whyOf(node: ts.Expression): string {
211
+ if (ts.isCallExpression(node)) return "is a call's result";
212
+ if (ts.isIdentifier(node)) {
213
+ const declared = this.#scope.resolve(node)?.parent;
214
+ if (!declared) return "is not declared in this file";
215
+ if (ts.isImportSpecifier(declared) || ts.isImportClause(declared) || ts.isNamespaceImport(declared))
216
+ return "is imported from another file";
217
+ if (ts.isParameter(this.#rootOf(declared) ?? declared)) return "is a parameter or prop whose type names no key";
218
+ return "is a variable this file does not hold as a written key";
219
+ }
220
+ if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node))
221
+ return "is read from data at run time";
222
+ return "is built from data at run time";
223
+ }
224
+
225
+ #rootOf(node: ts.Node): ts.Node | null {
226
+ let at: ts.Node = node;
227
+ while (ts.isBindingElement(at) || ts.isObjectBindingPattern(at) || ts.isArrayBindingPattern(at)) at = at.parent;
228
+ return at === node ? null : at;
229
+ }
230
+
231
+ #follows(expression: ts.Expression, depth: number): boolean {
232
+ if (depth > maxDepth) return false;
233
+ const next = (inner: ts.Expression) => this.#follows(inner, depth + 1);
234
+ const node = strip(expression);
235
+ if (ts.isStringLiteralLike(node)) return true;
236
+ if (ts.isTemplateExpression(node)) {
237
+ if (node.head.text.includes(".")) return true;
238
+ const [first] = node.templateSpans;
239
+ return !node.head.text && !!first && first.literal.text.startsWith(".") && next(first.expression);
240
+ }
241
+ if (ts.isConditionalExpression(node)) return next(node.whenTrue) && next(node.whenFalse);
242
+ if (ts.isBinaryExpression(node)) {
243
+ const operator = node.operatorToken.kind;
244
+ if (operator === ts.SyntaxKind.QuestionQuestionToken || operator === ts.SyntaxKind.BarBarToken)
245
+ return next(node.left) && next(node.right);
246
+ if (operator === ts.SyntaxKind.AmpersandAmpersandToken) return next(node.right);
247
+ if (operator !== ts.SyntaxKind.PlusToken) return false;
248
+ const left = strip(node.left);
249
+ const right = strip(node.right);
250
+ if (ts.isStringLiteralLike(left)) return left.text.includes(".");
251
+ return next(left) && ts.isStringLiteralLike(right) && right.text.startsWith(".");
252
+ }
253
+ if (ts.isIdentifier(node)) return this.#bindingFollows(node, depth + 1, false);
254
+ if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node))
255
+ return this.#isTable(node.expression, depth + 1);
256
+ return false;
257
+ }
258
+
259
+ //? With `names`, the property names are the keys: each one is added to the groups, and a name that is not written fails.
260
+ #isTable(expression: ts.Expression, depth: number, names = false): boolean {
261
+ if (depth > maxDepth) return false;
262
+ const node = strip(expression);
263
+ const value = (inner: ts.Expression) => this.#isValue(inner, depth + 1);
264
+ if (ts.isArrayLiteralExpression(node))
265
+ return node.elements.every((element) =>
266
+ ts.isSpreadElement(element) ? this.#isTable(element.expression, depth + 1, names) : value(element),
267
+ );
268
+ if (ts.isObjectLiteralExpression(node))
269
+ return node.properties.every((property) => {
270
+ if (names && !this.#addPropertyName(property)) return false;
271
+ if (ts.isPropertyAssignment(property)) return value(property.initializer);
272
+ if (ts.isShorthandPropertyAssignment(property)) return value(property.name);
273
+ if (ts.isSpreadAssignment(property)) return this.#isTable(property.expression, depth + 1, names);
274
+ return ts.isMethodDeclaration(property);
275
+ });
276
+ if (ts.isIdentifier(node)) return this.#bindingFollows(node, depth + 1, true, names);
277
+ if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node))
278
+ return !names && this.#isTable(node.expression, depth + 1);
279
+ if (!ts.isCallExpression(node)) return false;
280
+ const callee = strip(node.expression);
281
+ if (!ts.isPropertyAccessExpression(callee)) return false;
282
+ const method = callee.name.text;
283
+ if (ts.isIdentifier(callee.expression) && callee.expression.text === "Object" && objectReaders.has(method))
284
+ return !!node.arguments[0] && this.#isTable(node.arguments[0], depth + 1, method !== "values");
285
+ if (!subsetMethods.has(method)) return false;
286
+ const own = this.#isTable(callee.expression, depth + 1, names);
287
+ return own && (method !== "concat" || node.arguments.every((argument) => this.#isTable(argument, depth + 1)));
288
+ }
289
+
290
+ #addPropertyName(property: ts.ObjectLiteralElementLike): boolean {
291
+ if (ts.isSpreadAssignment(property)) return true;
292
+ const { name } = property;
293
+ if (ts.isComputedPropertyName(name)) {
294
+ const inner = strip(name.expression);
295
+ if (!ts.isStringLiteralLike(inner) && !ts.isNumericLiteral(inner)) return false;
296
+ this.#addText(inner.text, inner.text);
297
+ return true;
298
+ }
299
+ if (ts.isPrivateIdentifier(name)) return false;
300
+ this.#addText(name.text, name.text);
301
+ return true;
302
+ }
303
+
304
+ //? A value in a table is either text the file writes or something no key is made from (a number, an icon, a handler).
305
+ #isValue(expression: ts.Expression, depth: number): boolean {
306
+ const node = strip(expression);
307
+ if (
308
+ ts.isNumericLiteral(node) ||
309
+ node.kind === ts.SyntaxKind.TrueKeyword ||
310
+ node.kind === ts.SyntaxKind.FalseKeyword ||
311
+ node.kind === ts.SyntaxKind.NullKeyword ||
312
+ ts.isArrowFunction(node) ||
313
+ ts.isFunctionExpression(node) ||
314
+ ts.isJsxElement(node) ||
315
+ ts.isJsxSelfClosingElement(node) ||
316
+ ts.isJsxFragment(node) ||
317
+ (ts.isIdentifier(node) && (node.text === "undefined" || className.test(node.text)))
318
+ )
319
+ return true;
320
+ return this.#follows(node, depth) || this.#isTable(node, depth);
321
+ }
322
+
323
+ #bindingFollows(identifier: ts.Identifier, depth: number, asTable: boolean, names = false): boolean {
324
+ const declared = this.#scope.resolve(identifier);
325
+ if (!declared) return false;
326
+ const declaration = declared.parent;
327
+ const root = this.#rootOf(declaration) ?? declaration;
328
+ if (ts.isParameter(root)) return !names && this.#parameterFollows(root, declaration, depth, asTable);
329
+ if (!ts.isVariableDeclaration(root)) return false;
330
+ const list = root.parent;
331
+ if (ts.isVariableDeclarationList(list) && ts.isForInStatement(list.parent))
332
+ return !asTable && !names && root === declaration && this.#isTable(list.parent.expression, depth + 1, true);
333
+ if (ts.isVariableDeclarationList(list) && ts.isForOfStatement(list.parent))
334
+ return !names && this.#isTable(list.parent.expression, depth + 1);
335
+ if (!ts.isVariableDeclarationList(list) || !(list.flags & ts.NodeFlags.Const) || !root.initializer) return false;
336
+ if (root !== declaration) return !names && this.#isTable(root.initializer, depth + 1);
337
+ return asTable ? this.#isTable(root.initializer, depth + 1, names) : this.#follows(root.initializer, depth + 1);
338
+ }
339
+
340
+ #parameterFollows(parameter: ts.ParameterDeclaration, declaration: ts.Node, depth: number, asTable: boolean) {
341
+ if (parameter.type) {
342
+ const property = ts.isBindingElement(declaration) ? (declaration.propertyName ?? declaration.name) : null;
343
+ if (!property) return this.#typeFollows(parameter.type, depth + 1, asTable);
344
+ const member = ts.isIdentifier(property) ? this.#memberType(parameter.type, property.text, depth) : null;
345
+ return !!member && this.#typeFollows(member, depth + 1, asTable);
346
+ }
347
+ const callback = parameter.parent;
348
+ const call = callback.parent;
349
+ if (!(ts.isArrowFunction(callback) || ts.isFunctionExpression(callback)) || !ts.isCallExpression(call))
350
+ return false;
351
+ const callee = strip(call.expression);
352
+ return (
353
+ ts.isPropertyAccessExpression(callee) &&
354
+ tableMethods.has(callee.name.text) &&
355
+ callback.parameters[0] === parameter &&
356
+ this.#isTable(callee.expression, depth + 1)
357
+ );
358
+ }
359
+
360
+ #memberType(type: ts.TypeNode, name: string, depth: number): ts.TypeNode | null {
361
+ if (depth > maxDepth) return null;
362
+ if (ts.isTypeLiteralNode(type))
363
+ for (const member of type.members)
364
+ if (ts.isPropertySignature(member) && member.name.getText(this.#sourceFile) === name)
365
+ return member.type ?? null;
366
+ if (ts.isIntersectionTypeNode(type)) {
367
+ for (const part of type.types) {
368
+ const found = this.#memberType(part, name, depth + 1);
369
+ if (found) return found;
370
+ }
371
+ return null;
372
+ }
373
+ if (!ts.isTypeReferenceNode(type) || !ts.isIdentifier(type.typeName)) return null;
374
+ const declared = this.#typeDeclaration(type.typeName.text);
375
+ if (declared && ts.isTypeAliasDeclaration(declared)) return this.#memberType(declared.type, name, depth + 1);
376
+ if (!declared || !ts.isInterfaceDeclaration(declared)) return null;
377
+ for (const member of declared.members)
378
+ if (ts.isPropertySignature(member) && member.name.getText(this.#sourceFile) === name) return member.type ?? null;
379
+ return null;
380
+ }
381
+
382
+ #typeFollows(type: ts.TypeNode, depth: number, asTable: boolean): boolean {
383
+ if (depth > maxDepth) return false;
384
+ const next = (inner: ts.TypeNode) => this.#typeFollows(inner, depth + 1, asTable);
385
+ if (ts.isParenthesizedTypeNode(type)) return next(type.type);
386
+ if (ts.isUnionTypeNode(type)) return type.types.every(next);
387
+ if (ts.isLiteralTypeNode(type)) return true;
388
+ if (type.kind === ts.SyntaxKind.UndefinedKeyword || type.kind === ts.SyntaxKind.NullKeyword) return true;
389
+ if (ts.isTemplateLiteralTypeNode(type)) return groupHead.test(type.head.text);
390
+ if (ts.isArrayTypeNode(type)) return asTable && next(type.elementType);
391
+ if (ts.isTypeOperatorNode(type) && type.operator === ts.SyntaxKind.ReadonlyKeyword) return next(type.type);
392
+ if (ts.isTypeOperatorNode(type) && type.operator === ts.SyntaxKind.KeyOfKeyword)
393
+ return ts.isTypeQueryNode(type.type) && this.#queryIsTable(type.type, depth, true);
394
+ if (ts.isIndexedAccessTypeNode(type)) {
395
+ let object = type.objectType;
396
+ while (ts.isParenthesizedTypeNode(object)) object = object.type;
397
+ return ts.isTypeQueryNode(object) && this.#queryIsTable(object, depth, false);
398
+ }
399
+ if (!ts.isTypeReferenceNode(type) || !ts.isIdentifier(type.typeName)) return false;
400
+ const declared = this.#typeDeclaration(type.typeName.text);
401
+ return !!declared && ts.isTypeAliasDeclaration(declared) && next(declared.type);
402
+ }
403
+
404
+ #queryIsTable(query: ts.TypeQueryNode, depth: number, names: boolean): boolean {
405
+ const name = query.exprName;
406
+ return ts.isIdentifier(name) && this.#isTable(name, depth + 1, names);
407
+ }
408
+
409
+ #typeDeclaration(name: string): ts.TypeAliasDeclaration | ts.InterfaceDeclaration | undefined {
410
+ return this.#sourceFile.statements.find(
411
+ (statement): statement is ts.TypeAliasDeclaration | ts.InterfaceDeclaration =>
412
+ (ts.isTypeAliasDeclaration(statement) || ts.isInterfaceDeclaration(statement)) && statement.name.text === name,
413
+ );
414
+ }
415
+ }
@@ -0,0 +1,36 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { ObjectImportReport } from "./objectImportReport";
3
+
4
+ describe("ObjectImportReport.format", () => {
5
+ test("prints one line per scope with its reasons by count, and where the files are listed", () => {
6
+ const kept = {
7
+ file: "apps/demo/page/_index.tsx",
8
+ line: 3,
9
+ object: "Scroll",
10
+ objectFile: "libs/util/ui/Scroll/index.tsx",
11
+ };
12
+
13
+ expect(
14
+ ObjectImportReport.format({
15
+ scopes: [
16
+ {
17
+ scope: "apps/demo",
18
+ app: "demo",
19
+ narrowed: 12,
20
+ kept: 4,
21
+ reasons: { call: 1, "rendered-or-called": 2, "passed-on": 1 },
22
+ },
23
+ { scope: "libs/util", app: "demo", narrowed: 3, kept: 0, reasons: {} },
24
+ ],
25
+ kept: [{ ...kept, reason: "rendered-or-called" }],
26
+ }),
27
+ ).toBe(
28
+ [
29
+ "apps/demo: 12 object imports load only the members they name, 4 load the whole object (rendered-or-called 2, call 1, passed-on 1)",
30
+ "libs/util: 3 object imports load only the members they name, 0 load the whole object",
31
+ "--format json lists each import that loads the whole object, with its file and line",
32
+ ].join("\n"),
33
+ );
34
+ expect(ObjectImportReport.format({ scopes: [], kept: [] })).toBe("");
35
+ });
36
+ });
@@ -0,0 +1,102 @@
1
+ import path from "node:path";
2
+ import { AppExecutor } from "../executors/appExecutor";
3
+ import type { WorkspaceExecutor } from "../executors/workspaceExecutor";
4
+ import { BarrelAnalyzer } from "../transforms/barrelAnalyzer";
5
+ import { createTsconfigPackageResolver, rewriteBarrelImports } from "../transforms/barrelImportsPlugin";
6
+ import { type ObjectKeepReason, ObjectMemberImports } from "../transforms/objectMemberImports";
7
+ import { RuntimeScopeReport } from "./runtimeScopeReport";
8
+ import { WorkspaceSourceFiles } from "./workspaceSourceFiles";
9
+
10
+ export interface ObjectImportScope {
11
+ scope: string;
12
+ app: string;
13
+ narrowed: number;
14
+ kept: number;
15
+ reasons: Partial<Record<ObjectKeepReason, number>>;
16
+ }
17
+
18
+ export interface ObjectImportKeptEntry {
19
+ file: string;
20
+ line: number;
21
+ object: string;
22
+ objectFile: string;
23
+ reason: ObjectKeepReason;
24
+ }
25
+
26
+ export interface ObjectImportResult {
27
+ scopes: ObjectImportScope[];
28
+ kept: ObjectImportKeptEntry[];
29
+ }
30
+
31
+ interface ScopeReader {
32
+ barrels: string[];
33
+ analyzer: BarrelAnalyzer;
34
+ objects: ObjectMemberImports;
35
+ }
36
+
37
+ const MACRO_ATTR_RE = /with\s*\{\s*type\s*:\s*["']macro["']\s*\}/;
38
+
39
+ //* What a build does with each object import (`Memo.Zone.View`, `Field.Text`) in apps and libs: narrowed to the
40
+ //* members it names, or kept whole and why. A lib is read as the first app reads it.
41
+ export class ObjectImportReport {
42
+ static async scan(workspace: WorkspaceExecutor): Promise<ObjectImportResult> {
43
+ const apps = (await workspace.getApps()).sort();
44
+ const result: ObjectImportResult = { scopes: [], kept: [] };
45
+ const [firstApp] = apps;
46
+ if (firstApp === undefined) return result;
47
+ const readers = new Map<string, ScopeReader>();
48
+ const readerOf = async (app: string) => {
49
+ const cached = readers.get(app);
50
+ if (cached) return cached;
51
+ const executor = AppExecutor.from(workspace, app);
52
+ const resolvePackage = await createTsconfigPackageResolver(executor);
53
+ const reader: ScopeReader = {
54
+ barrels: (await executor.getConfig()).barrelImports,
55
+ analyzer: new BarrelAnalyzer({ resolvePackage, packageRoot: workspace.workspaceRoot }),
56
+ objects: new ObjectMemberImports({ resolve: ObjectMemberImports.resolverOf(resolvePackage) }),
57
+ };
58
+ readers.set(app, reader);
59
+ return reader;
60
+ };
61
+ const sources = new WorkspaceSourceFiles(workspace.workspaceRoot);
62
+ const scopes = new Map<string, ObjectImportScope>();
63
+ for (const file of await sources.collect()) {
64
+ const [, kind, name] = file.match(/^(apps|libs)\/([^/]+)\//) ?? [];
65
+ if (!kind || !name || !RuntimeScopeReport.isRuntimeSource(file)) continue;
66
+ const app = kind === "apps" ? name : firstApp;
67
+ if (!apps.includes(app)) continue;
68
+ const { content, absolutePath } = await sources.read(file);
69
+ if (MACRO_ATTR_RE.test(content)) continue;
70
+ const reader = await readerOf(app);
71
+ const rewritten = await rewriteBarrelImports(content, reader.barrels, reader.analyzer, {
72
+ keepLines: true,
73
+ reexports: true,
74
+ });
75
+ const rewrite = await reader.objects.rewrite(rewritten ?? content, absolutePath);
76
+ if (!rewrite || rewrite.narrowed.length + rewrite.kept.length === 0) continue;
77
+ const scope = `${kind}/${name}`;
78
+ const summary = scopes.get(scope) ?? { scope, app, narrowed: 0, kept: 0, reasons: {} };
79
+ scopes.set(scope, summary);
80
+ summary.narrowed += rewrite.narrowed.length;
81
+ for (const kept of rewrite.kept) {
82
+ summary.kept++;
83
+ summary.reasons[kept.reason] = (summary.reasons[kept.reason] ?? 0) + 1;
84
+ const objectFile = path.relative(workspace.workspaceRoot, kept.file).split(path.sep).join("/");
85
+ result.kept.push({ file, line: kept.line, object: kept.object, objectFile, reason: kept.reason });
86
+ }
87
+ }
88
+ result.scopes = [...scopes.values()];
89
+ return result;
90
+ }
91
+
92
+ static format({ scopes, kept }: ObjectImportResult) {
93
+ const lines = scopes.map(({ scope, narrowed, kept: whole, reasons }) => {
94
+ const counts = Object.entries(reasons)
95
+ .sort(([a, x = 0], [b, y = 0]) => y - x || (a < b ? -1 : 1))
96
+ .map(([reason, count]) => `${reason} ${count}`);
97
+ return `${scope}: ${narrowed} object imports load only the members they name, ${whole} load the whole object${counts.length ? ` (${counts.join(", ")})` : ""}`;
98
+ });
99
+ if (kept.length) lines.push("--format json lists each import that loads the whole object, with its file and line");
100
+ return lines.join("\n");
101
+ }
102
+ }
@@ -98,7 +98,7 @@ const SUGGESTED_RULES = [
98
98
  "Warn earlier on very long Akan files: 500 lines for services, 800 lines for Template/Zone files, and 1000 lines for Util files.",
99
99
  "Global declarations, Window augmentation, and prototype mutation should stay in explicitly approved low-level integration files.",
100
100
  "Keep app root folders small and conventional: application code belongs under common, env, lib, page, plugin, private, public, script, srvkit, ui, or webkit.",
101
- "Keep apps/*/lib and libs/*/lib root files limited to generated support facets such as cnst.ts, db.ts, dict.ts, sig.ts, srv.ts, st.ts, useClient.ts, and useServer.ts.",
101
+ "Keep apps/*/lib and libs/*/lib root files limited to generated support facets such as cnst.ts, db.ts, dict.ts, sig.ts, srv.ts, st.ts, useClient.ts, usePage.ts, and useServer.ts.",
102
102
  "Use domain module folders consistently: lib/<model> for database modules, lib/_<service> for service modules, and lib/__scalar/<scalar> for scalar modules.",
103
103
  "Keep module UI filenames predictable: database modules use <Model>.Template/Unit/Util/View/Zone.tsx, service modules use <Service>.Util/Zone.tsx, and scalar modules use <Scalar>.Template/Unit.tsx.",
104
104
  "Hand a form control its store setter by reference so the field publishes an agent tool; put normalization in the control's transform prop and a multi-write in a _postSet<Field> hook on the store.",
@@ -0,0 +1,91 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import path from "node:path";
3
+ import { tempDirs, writeText } from "../test/testHelpers";
4
+ import { type RouteRuntimeBuildReport, RouteRuntimeReport } from "./routeRuntimeReport";
5
+
6
+ const makeTempRoot = tempDirs("akan-devkit-route-runtime-report-");
7
+
8
+ const report: RouteRuntimeBuildReport = {
9
+ app: "demo",
10
+ routes: 12,
11
+ perModule: ["/memo"],
12
+ notSmaller: ["/board", "/board/:id"],
13
+ refused: ["/tally"],
14
+ causes: [
15
+ {
16
+ rule: "reader",
17
+ file: "apps/demo/ui/Pick.tsx",
18
+ line: 7,
19
+ message: "`st.use[name]`: the name is picked at run time",
20
+ entries: ["apps/demo/ui/Pick.tsx", "apps/demo/ui/Frame.tsx"],
21
+ routes: ["/a", "/b", "/c", "/d", "/e", "/f", "/g", "/h", "/i"],
22
+ chains: [["apps/demo/ui/Frame.tsx", "apps/demo/ui/Pick.tsx"]],
23
+ },
24
+ {
25
+ rule: "not-smaller",
26
+ message: "/board is 950 B loading per module and 900 B with the whole runtime",
27
+ entries: ["apps/demo/ui/Board.tsx"],
28
+ routes: ["/board", "/board/:id"],
29
+ chains: [],
30
+ },
31
+ { rule: "unheld", message: "no page loading per module holds it", entries: ["a", "b"], routes: [], chains: [] },
32
+ ],
33
+ };
34
+
35
+ describe("what a build decided for each route, as akan quality runtime prints it", () => {
36
+ test("the build's one line counts the routes per module, the ones measured no smaller, and the ones kept for a named reason", () => {
37
+ expect(RouteRuntimeReport.summary(report)).toBe(
38
+ "1 route loads per module, 2 keep the whole runtime because per module would not be smaller, 9 keep it for a reason `akan quality runtime` names",
39
+ );
40
+ expect(RouteRuntimeReport.summary({ ...report, routes: 3 })).toBe(
41
+ "1 route loads per module, 2 keep the whole runtime because per module would not be smaller",
42
+ );
43
+ });
44
+
45
+ test("every reason names its file and line or its rule, the entries and routes it holds, and how the file is reached", () => {
46
+ expect(RouteRuntimeReport.format([report]).split("\n")).toEqual([
47
+ "Last build of apps/demo: 1 route loads per module, 2 keep the whole runtime because per module would not be smaller, 9 keep it for a reason `akan quality runtime` names.",
48
+ " per module: /memo",
49
+ " [reader] apps/demo/ui/Pick.tsx:7 `st.use[name]`: the name is picked at run time",
50
+ " 2 entries on 9 routes: /a, /b, /c, /d, /e, /f, and 3 more",
51
+ " reached as apps/demo/ui/Frame.tsx → apps/demo/ui/Pick.tsx",
52
+ " [not-smaller] /board is 950 B loading per module and 900 B with the whole runtime",
53
+ " 1 entry on 2 routes: /board, /board/:id",
54
+ " [unheld] no page loading per module holds it",
55
+ " 2 entries on 0 routes",
56
+ " 1 route measured no smaller per module than where every page keeps the whole runtime, and larger still keeping it here, so it loads per module: /tally",
57
+ ]);
58
+ const many = { ...report, perModule: ["/a", "/b", "/c", "/d", "/e", "/f", "/g", "/h"], causes: [], refused: [] };
59
+ expect(RouteRuntimeReport.format([many]).split("\n")[1]).toBe(" per module: /a, /b, /c, /d, /e, /f, and 2 more");
60
+ expect(RouteRuntimeReport.format([])).toBe("");
61
+ });
62
+
63
+ test("a build's report is read back from every app that has one, a file that is not a report left out", async () => {
64
+ const root = await makeTempRoot();
65
+ await RouteRuntimeReport.write(path.join(root, "apps/demo"), report);
66
+ await writeText(path.join(root, "apps/other", RouteRuntimeReport.file), "{}\n");
67
+ expect(await RouteRuntimeReport.read(root)).toEqual([report]);
68
+ });
69
+
70
+ test("a route that loads every text of the page dictionary is listed under the file and line that cost it", async () => {
71
+ const root = await makeTempRoot();
72
+ const appDir = path.join(root, "apps/demo");
73
+ const dictionary = [
74
+ { file: "apps/demo/ui/Label.tsx", line: 4, why: "`l(key)`: the key is picked at run time", routes: ["/a", "/b"] },
75
+ { file: "apps/demo/ui/Pick.tsx", why: "needs every module's client runtime", routes: ["/c"] },
76
+ ];
77
+ await RouteRuntimeReport.addDictionary(appDir, dictionary);
78
+ expect(await RouteRuntimeReport.read(root)).toEqual([]);
79
+
80
+ await RouteRuntimeReport.write(appDir, { ...report, causes: [], refused: [] });
81
+ await RouteRuntimeReport.addDictionary(appDir, dictionary);
82
+ const reports = await RouteRuntimeReport.read(root);
83
+ expect(reports[0]?.dictionary).toEqual(dictionary);
84
+ expect(RouteRuntimeReport.format(reports).split("\n").slice(2)).toEqual([
85
+ " [dictionary] apps/demo/ui/Label.tsx:4 `l(key)`: the key is picked at run time",
86
+ " 2 routes load every text of the page dictionary: /a, /b",
87
+ " [dictionary] apps/demo/ui/Pick.tsx needs every module's client runtime",
88
+ " 1 route loads every text of the page dictionary: /c",
89
+ ]);
90
+ });
91
+ });