@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
@@ -0,0 +1,696 @@
1
+ import ts from "typescript";
2
+ import { RuntimeConstantReads, type RuntimeConstantUse } from "./runtimeConstantReads";
3
+ import {
4
+ type RuntimeBinding,
5
+ type RuntimeConstantTarget,
6
+ type RuntimeHandle,
7
+ type RuntimeHandleKind,
8
+ RuntimeImports,
9
+ type RuntimeImportTarget,
10
+ type RuntimeImportUse,
11
+ } from "./runtimeImports";
12
+ import { RuntimeKeyNames } from "./runtimeKeyNames";
13
+ import { RuntimeLexicalScope } from "./runtimeLexicalScope";
14
+ import type { RuntimeFamily, RuntimeNameTable, RuntimeNeed, RuntimeOwner } from "./runtimeNameTable";
15
+ import { type RuntimeSlice, RuntimeSliceKey } from "./runtimeSliceKey";
16
+ import {
17
+ climb,
18
+ climbCasts,
19
+ declaredFunction,
20
+ inlineFunction,
21
+ memberName,
22
+ ownArguments,
23
+ type PositionedProblem,
24
+ problemAt,
25
+ returnsOf,
26
+ sortedProblems,
27
+ staticName,
28
+ uncast,
29
+ unwrap,
30
+ } from "./runtimeSyntax";
31
+
32
+ export type { RuntimeConstantName, RuntimeConstantRead, RuntimeConstantUse } from "./runtimeConstantReads";
33
+ export type { RuntimeImportKind, RuntimeImportTarget } from "./runtimeImports";
34
+
35
+ export const runtimeUseReasons = [
36
+ "computed-access",
37
+ "passed-on",
38
+ "re-exported",
39
+ "hidden-by-destructuring",
40
+ "unknown-name",
41
+ "whole-runtime-import",
42
+ ] as const;
43
+ export type RuntimeUseReason = (typeof runtimeUseReasons)[number];
44
+
45
+ export interface RuntimeUseOwner {
46
+ scope: string;
47
+ module: string;
48
+ needs: RuntimeNeed;
49
+ }
50
+
51
+ export interface RuntimeUseProblem {
52
+ reason: RuntimeUseReason;
53
+ line: number;
54
+ column: number;
55
+ text: string;
56
+ message: string;
57
+ }
58
+
59
+ export type RuntimeUseVerdict = (
60
+ | { resolvable: true; owners: RuntimeUseOwner[]; baseStore: boolean; baseDescriptor: boolean; reads: boolean }
61
+ | ({ resolvable: false; problems: RuntimeUseProblem[] } & RuntimeUseProblem)
62
+ ) & { constants: RuntimeConstantUse };
63
+
64
+ export interface RuntimeUseOptions {
65
+ runtimeOf?: (specifier: string, fileName: string) => RuntimeImportTarget | null;
66
+ }
67
+
68
+ type StoreMethod = "get" | "set" | "sel" | "ref" | "sub" | "pick";
69
+
70
+ type Step =
71
+ | { leaf: RuntimeFamily; key: string; next?: RuntimeHandle }
72
+ | { handle: RuntimeHandle }
73
+ | { method: StoreMethod; own?: boolean }
74
+ | { none: true }
75
+ | { unknown: true }
76
+ | { whole: true };
77
+
78
+ const stMethods = new Set(["get", "set", "sel", "ref", "sub"]);
79
+ const agenticMembers = new Set(["tool", "expose", "useState"]);
80
+ const signalData = new Set(["refName", "cnst", "slices", "serializedSignal", "_slice"]);
81
+ //? Fetch client members reaching no endpoint; `handler`, `instance`, `clone` and the descriptor maps do pick a name.
82
+ const fetchClientMembers = new Set([
83
+ "ws",
84
+ "http",
85
+ "origin",
86
+ "jwt",
87
+ "logger",
88
+ "setJwt",
89
+ "setTimeout",
90
+ "connect",
91
+ "connectOnUse",
92
+ "disconnect",
93
+ "configureWs",
94
+ ]);
95
+ const isPlain = (step: Step) => "none" in step || ("leaf" in step && !step.next);
96
+ const isThisParameter = ({ name }: ts.ParameterDeclaration) => ts.isIdentifier(name) && name.text === "this";
97
+ const assertKey = 'assert the key as the name it stands for (`key as "name"`)';
98
+ const nothingRead: RuntimeUseVerdict = {
99
+ resolvable: true,
100
+ owners: [],
101
+ baseStore: false,
102
+ baseDescriptor: false,
103
+ reads: false,
104
+ constants: { reads: [], imports: [], problems: [] },
105
+ };
106
+
107
+ export class RuntimeUse {
108
+ readonly #source: ts.SourceFile;
109
+ readonly #fileName: string;
110
+ readonly #consumer: RuntimeNameTable | null;
111
+ readonly #options: RuntimeUseOptions;
112
+ readonly #storeFile: boolean;
113
+ readonly #lexical = new RuntimeLexicalScope();
114
+ readonly #keys = new RuntimeKeyNames(this.#lexical);
115
+ readonly #slices: RuntimeSliceKey;
116
+ readonly #bindings = new Map<ts.Identifier, RuntimeBinding>();
117
+ readonly #owners = new Map<string, RuntimeUseOwner>();
118
+ readonly #problems: PositionedProblem[] = [];
119
+ readonly #constants: RuntimeConstantReads;
120
+ #baseStore = false;
121
+ #baseDescriptor = false;
122
+ #reads = false;
123
+ #recording: boolean = false;
124
+
125
+ static targetOf(specifier: string, fileName: string) {
126
+ return RuntimeImports.targetOf(specifier, fileName);
127
+ }
128
+
129
+ static analyze(
130
+ input: { fileName: string; text: string; sourceFile?: ts.SourceFile },
131
+ consumer: RuntimeNameTable | null,
132
+ options: RuntimeUseOptions = {},
133
+ ): RuntimeUseVerdict {
134
+ const storeFile = input.fileName.endsWith(".store.ts");
135
+ const runtime = !!options.runtimeOf || storeFile || RuntimeImports.mayUseRuntime(input.text, input.fileName);
136
+ if (!runtime && !RuntimeImports.mayUseConstants(input.text, input.fileName)) return nothingRead;
137
+ const source =
138
+ input.sourceFile ??
139
+ ts.createSourceFile(input.fileName, input.text, ts.ScriptTarget.Latest, true, RuntimeUse.#kindOf(input.fileName));
140
+ const verdict = new RuntimeUse(source, input.fileName, consumer, options, storeFile).#run();
141
+ return runtime ? verdict : { ...nothingRead, constants: verdict.constants };
142
+ }
143
+
144
+ private constructor(
145
+ source: ts.SourceFile,
146
+ fileName: string,
147
+ consumer: RuntimeNameTable | null,
148
+ options: RuntimeUseOptions,
149
+ storeFile: boolean,
150
+ ) {
151
+ this.#source = source;
152
+ this.#fileName = fileName;
153
+ this.#consumer = consumer;
154
+ this.#options = options;
155
+ this.#storeFile = storeFile;
156
+ this.#slices = new RuntimeSliceKey(this.#lexical, source);
157
+ this.#constants = new RuntimeConstantReads(source, fileName, consumer, () => this.#recording);
158
+ }
159
+
160
+ #run(): RuntimeUseVerdict {
161
+ this.#readImports();
162
+ for (let size = -1; size !== this.#bindings.size; ) {
163
+ size = this.#bindings.size;
164
+ this.#visit(this.#source);
165
+ }
166
+ this.#recording = true;
167
+ this.#visit(this.#source);
168
+ const problems = sortedProblems(this.#problems);
169
+ const constants = this.#constants.use;
170
+ const [first] = problems;
171
+ if (first) return { resolvable: false, ...first, problems, constants };
172
+ const owners = [...this.#owners.values()].sort((a, b) =>
173
+ `${a.scope}/${a.module}` < `${b.scope}/${b.module}` ? -1 : 1,
174
+ );
175
+ return {
176
+ resolvable: true,
177
+ owners,
178
+ baseStore: this.#baseStore,
179
+ baseDescriptor: this.#baseDescriptor,
180
+ reads: this.#reads,
181
+ constants,
182
+ };
183
+ }
184
+
185
+ #targetOf(specifier: string) {
186
+ return this.#options.runtimeOf?.(specifier, this.#fileName) ?? RuntimeImports.targetOf(specifier, this.#fileName);
187
+ }
188
+
189
+ #readImports() {
190
+ this.#recording = true;
191
+ for (const statement of this.#source.statements) {
192
+ if (ts.isImportDeclaration(statement)) this.#readImport(statement);
193
+ else if (ts.isExportDeclaration(statement)) this.#readReexport(statement);
194
+ else if (ts.isImportEqualsDeclaration(statement) && !statement.isTypeOnly) {
195
+ const reference = statement.moduleReference;
196
+ const specifier = ts.isExternalModuleReference(reference) ? reference.expression : null;
197
+ if (specifier && ts.isStringLiteralLike(specifier) && this.#targetOf(specifier.text))
198
+ this.#problem("whole-runtime-import", statement, "the import loads the runtime module whole");
199
+ }
200
+ }
201
+ this.#recording = false;
202
+ }
203
+
204
+ #readImport(statement: ts.ImportDeclaration) {
205
+ if (!ts.isStringLiteral(statement.moduleSpecifier)) return;
206
+ if (!statement.importClause?.isTypeOnly) this.#constants.imported(statement.moduleSpecifier.text);
207
+ const constant = RuntimeImports.constantTargetOf(statement.moduleSpecifier.text, this.#fileName);
208
+ if (constant) return this.#readConstantImport(statement, constant);
209
+ const target = this.#targetOf(statement.moduleSpecifier.text);
210
+ const clause = statement.importClause;
211
+ if (!target || (!clause && target.kind.startsWith("framework-"))) return;
212
+ if (!clause?.isTypeOnly && !target.kind.startsWith("framework-") && !this.#loads(target, statement)) return;
213
+ const named = clause?.namedBindings && ts.isNamedImports(clause.namedBindings) ? clause.namedBindings.elements : [];
214
+ const values = clause?.isTypeOnly ? [] : named.filter((element) => !element.isTypeOnly);
215
+ const namespace = clause?.namedBindings && ts.isNamespaceImport(clause.namedBindings) ? clause.namedBindings : null;
216
+ const wholeImport = !clause || (!clause.isTypeOnly && !clause.name && !namespace && !values.length);
217
+ if (wholeImport && !target.kind.startsWith("framework-"))
218
+ return this.#problem("whole-runtime-import", statement, `the import runs ${target.scope}'s client runtime whole`);
219
+ for (const name of clause?.isTypeOnly ? [] : [clause?.name, namespace?.name])
220
+ if (name) this.#use(name, RuntimeImports.namespaceUse(target.kind, name.text));
221
+ for (const element of named) {
222
+ const imported = (element.propertyName ?? element.name).text;
223
+ const typeOnly = !!clause?.isTypeOnly || element.isTypeOnly;
224
+ if (target.kind === "client" && target.scope && imported === "cnst") {
225
+ if (!typeOnly) this.#bindings.set(element.name, { type: "cnst", scope: target.scope });
226
+ } else this.#use(element, RuntimeImports.useOf(target, imported, typeOnly));
227
+ }
228
+ }
229
+
230
+ #readConstantImport(statement: ts.ImportDeclaration, { scope, kind }: RuntimeConstantTarget) {
231
+ const clause = statement.importClause;
232
+ if (clause?.isTypeOnly) return;
233
+ const bindings = clause?.namedBindings;
234
+ if (kind === "cnst" && !clause?.name && bindings && ts.isNamespaceImport(bindings)) {
235
+ this.#bindings.set(bindings.name, { type: "cnst", scope });
236
+ return;
237
+ }
238
+ const named =
239
+ kind === "barrel" && !clause?.name && bindings && ts.isNamedImports(bindings) ? bindings.elements : null;
240
+ if (!named)
241
+ return this.#constants.problem("whole-runtime-import", statement, `the import takes ${scope}'s constants whole`);
242
+ for (const element of named)
243
+ if (!element.isTypeOnly && (element.propertyName ?? element.name).text === "cnst")
244
+ this.#bindings.set(element.name, { type: "cnst", scope });
245
+ }
246
+
247
+ #use(node: ts.ImportSpecifier | ts.Identifier, use: RuntimeImportUse) {
248
+ if (!use) return;
249
+ if ("binding" in use) this.#bindings.set(ts.isIdentifier(node) ? node : node.name, use.binding);
250
+ else this.#problem(use.reason, node, use.why);
251
+ }
252
+
253
+ #loads(target: RuntimeImportTarget, statement: ts.ImportDeclaration) {
254
+ const consumer = this.#consumer;
255
+ const loaded = !!consumer?.layers.some((layer) => layer.scope === target.scope);
256
+ if (!loaded) {
257
+ const why = !target.scope
258
+ ? "this file belongs to no app or lib"
259
+ : consumer
260
+ ? `${consumer.scope} does not load ${target.scope}'s client runtime`
261
+ : "there is no generated client runtime to read names from";
262
+ this.#problem("whole-runtime-import", statement.moduleSpecifier, why);
263
+ }
264
+ return loaded;
265
+ }
266
+
267
+ #readReexport(statement: ts.ExportDeclaration) {
268
+ const specifier = statement.moduleSpecifier;
269
+ if (statement.isTypeOnly || !specifier || !ts.isStringLiteral(specifier)) return;
270
+ this.#constants.imported(specifier.text);
271
+ const target = this.#targetOf(specifier.text);
272
+ if (!target) return;
273
+ const clause = statement.exportClause;
274
+ const why = "other files read the runtime through this one";
275
+ if (!clause || ts.isNamespaceExport(clause)) return this.#problem("re-exported", statement, why);
276
+ for (const element of clause.elements) {
277
+ const imported = (element.propertyName ?? element.name).text;
278
+ if (!element.isTypeOnly && target.kind === "client" && imported === "cnst")
279
+ this.#constants.problem("re-exported", element, why);
280
+ else if (!element.isTypeOnly && RuntimeImports.useOf(target, imported, false))
281
+ this.#problem("re-exported", element, why);
282
+ }
283
+ }
284
+
285
+ #localExport(statement: ts.ExportDeclaration) {
286
+ const clause = statement.exportClause;
287
+ if (statement.isTypeOnly || statement.moduleSpecifier || !clause || !ts.isNamedExports(clause)) return;
288
+ for (const element of clause.elements) {
289
+ const local = element.propertyName ?? element.name;
290
+ const declaration = ts.isIdentifier(local) && !element.isTypeOnly ? this.#lexical.resolve(local) : null;
291
+ const binding = declaration && this.#bindings.get(declaration);
292
+ if (binding?.type === "cnst")
293
+ this.#constants.problem("re-exported", element, "other files read the constants here");
294
+ else if (binding && binding.type !== "storeFactory")
295
+ this.#problem("re-exported", element, "other files read the runtime through this one");
296
+ }
297
+ }
298
+
299
+ #visit(node: ts.Node) {
300
+ if (ts.isExportDeclaration(node)) return this.#localExport(node);
301
+ if (ts.isImportDeclaration(node) || ts.isImportEqualsDeclaration(node)) return;
302
+ if (ts.isHeritageClause(node) && node.token === ts.SyntaxKind.ImplementsKeyword) return;
303
+ if ((ts.isAsExpression(node) || ts.isTypeAssertionExpression(node)) && this.#isRootStoreType(node.type)) {
304
+ const inner = RuntimeUse.#castInner(node.expression);
305
+ if (inner.kind !== ts.SyntaxKind.ThisKeyword) this.#visit(node.expression);
306
+ this.#followRead(node, { kind: "root" });
307
+ return;
308
+ }
309
+ if (ts.isTypeNode(node) && !ts.isExpressionWithTypeArguments(node)) return;
310
+ if (node.kind === ts.SyntaxKind.ThisKeyword || node.kind === ts.SyntaxKind.SuperKeyword)
311
+ this.#storeSelf(node as ts.Expression);
312
+ else if (this.#isLoader(node)) this.#loader(node as ts.Expression);
313
+ else if (ts.isIdentifier(node) && RuntimeLexicalScope.isReference(node)) this.#reference(node);
314
+ else if (ts.isStringLiteralLike(node)) this.#literalArgument(node);
315
+ else if (ts.isObjectLiteralExpression(node)) this.#writtenSlice(node);
316
+ ts.forEachChild(node, (child) => this.#visit(child));
317
+ }
318
+
319
+ #reference(identifier: ts.Identifier) {
320
+ const declaration = this.#lexical.resolve(identifier);
321
+ const binding = declaration && this.#bindings.get(declaration);
322
+ if (!binding || binding.type === "storeFactory" || binding.type === "rootStore") return;
323
+ if (binding.type === "cnst") return this.#constants.follow(identifier, binding.scope);
324
+ if (binding.type === "whole")
325
+ return this.#problem("whole-runtime-import", identifier, `${binding.name} hands out the whole client runtime`);
326
+ this.#followRead(identifier, binding.handle);
327
+ }
328
+
329
+ #followRead(node: ts.Expression, handle: RuntimeHandle) {
330
+ if (this.#recording) this.#reads = true;
331
+ this.#follow(node, handle);
332
+ }
333
+
334
+ #storeSelf(node: ts.Expression) {
335
+ const owner = RuntimeLexicalScope.thisOwnerOf(node);
336
+ if (node.kind === ts.SyntaxKind.SuperKeyword && ts.isCallExpression(node.parent) && node.parent.expression === node)
337
+ return;
338
+ if (owner?.kind === "class" && this.#isStoreClass(owner.node)) {
339
+ if (owner.isStatic)
340
+ return this.#problem("unknown-name", node, "a static member's `this` is the store class, not a module name");
341
+ const members = node.kind === ts.SyntaxKind.ThisKeyword ? RuntimeUse.#membersOf(owner.node) : new Set<string>();
342
+ return this.#followRead(node, { kind: "self", members });
343
+ }
344
+ const [first] = owner?.kind === "function" ? owner.node.parameters : [];
345
+ const typedThis = first && ts.isIdentifier(first.name) && first.name.text === "this" && first.type;
346
+ if (typedThis && this.#isRootStoreType(typedThis)) return this.#followRead(node, { kind: "root" });
347
+ if (this.#storeFile && owner)
348
+ this.#problem(
349
+ "passed-on",
350
+ node,
351
+ "outside a store class member `this` may be the store, and its reads are not followed",
352
+ );
353
+ }
354
+
355
+ #isStoreClass(node: ts.ClassLikeDeclaration) {
356
+ if (this.#storeFile) return true;
357
+ const heritage = node.heritageClauses?.find((clause) => clause.token === ts.SyntaxKind.ExtendsKeyword)?.types[0];
358
+ const base = heritage && unwrap(heritage.expression);
359
+ return !!base && ts.isCallExpression(base) && this.#isStoreFactory(base.expression);
360
+ }
361
+
362
+ #isStoreFactory(expression: ts.Expression) {
363
+ const callee = unwrap(expression);
364
+ const declaration = ts.isIdentifier(callee) ? this.#lexical.resolve(callee) : null;
365
+ return !!declaration && this.#bindings.get(declaration)?.type === "storeFactory";
366
+ }
367
+
368
+ #isRootStoreType(type: ts.TypeNode) {
369
+ if (!ts.isTypeReferenceNode(type) || !ts.isIdentifier(type.typeName) || type.typeArguments) return false;
370
+ const declaration = this.#lexical.resolve(type.typeName);
371
+ return !!declaration && this.#bindings.get(declaration)?.type === "rootStore";
372
+ }
373
+
374
+ #isLoader(node: ts.Node) {
375
+ if (node.kind === ts.SyntaxKind.ImportKeyword) return true;
376
+ const free = (expression: ts.Expression) => ts.isIdentifier(expression) && !this.#lexical.resolve(expression);
377
+ if (ts.isIdentifier(node)) return node.text === "require" && RuntimeLexicalScope.isReference(node) && free(node);
378
+ const member =
379
+ ts.isPropertyAccessExpression(node) ||
380
+ (ts.isElementAccessExpression(node) && ts.isStringLiteralLike(node.argumentExpression));
381
+ if (!member || memberName(node) !== "require") return false;
382
+ return ts.isMetaProperty(node.expression) || free(node.expression);
383
+ }
384
+
385
+ #loader(node: ts.Expression) {
386
+ const { current, parent } = climb(node);
387
+ const called = ts.isCallExpression(parent) && parent.expression === current;
388
+ const [specifier] = called ? parent.arguments : [];
389
+ if (!called) this.#problem("whole-runtime-import", node, "a module loader taken as a value may load any module");
390
+ else if (!specifier || !ts.isStringLiteralLike(specifier))
391
+ this.#problem("whole-runtime-import", parent, "the module it loads is picked at run time");
392
+ else if (this.#targetOf(specifier.text))
393
+ this.#problem("whole-runtime-import", parent, "the import loads the runtime module whole");
394
+ }
395
+
396
+ #literalArgument(literal: ts.StringLiteralLike) {
397
+ const parent = literal.parent;
398
+ if (!(ts.isCallExpression(parent) || ts.isNewExpression(parent)) || !parent.arguments?.includes(literal)) return;
399
+ if (!this.#isLoader(unwrap(parent.expression)) && this.#targetOf(literal.text))
400
+ this.#problem("whole-runtime-import", literal, "the runtime module is handed to code that may load it whole");
401
+ }
402
+
403
+ #follow(node: ts.Expression, reached: RuntimeHandle) {
404
+ const { current, parent } = climbCasts(node);
405
+ const handle = current !== node && reached.kind === "self" ? { ...reached, cast: true } : reached;
406
+ if (ts.isPropertyAccessExpression(parent) && parent.expression === current)
407
+ return this.#apply(parent, this.#step(handle, parent.name.text));
408
+ if (ts.isElementAccessExpression(parent) && parent.expression === current) return this.#keyed(parent, handle);
409
+ if (ts.isCallExpression(parent) && parent.expression === current) {
410
+ if (handle.kind === "getter") this.#follow(parent, { kind: "state" });
411
+ else if (handle.kind !== "fetch") this.#problem("unknown-name", parent, "the runtime object itself is called");
412
+ return;
413
+ }
414
+ const storeOfSignal = handle.kind === "signal" && ts.isCallExpression(parent) && parent.arguments[0] === current;
415
+ if (storeOfSignal && this.#isStoreFactory(parent.expression)) return;
416
+ if (ts.isVariableDeclaration(parent) && parent.initializer === current) return this.#declare(parent, handle);
417
+ if (ts.isExportAssignment(parent))
418
+ return this.#problem("re-exported", parent, "other files read the runtime through this one");
419
+ if (handle.kind === "state" && this.#handed(current, parent)) return;
420
+ const answer = handle.kind === "fetch" ? "name the endpoint here and pass that" : "read the names here";
421
+ this.#problem("passed-on", current, `the names read from it where it goes are not visible here; ${answer}`);
422
+ }
423
+
424
+ #keyed(node: ts.ElementAccessExpression, handle: RuntimeHandle) {
425
+ const names = this.#keys.namesOf(node.argumentExpression);
426
+ const steps = names && this.#stepsOf(handle, names);
427
+ if (steps) for (const step of steps) this.#apply(node, step);
428
+ else if (names) this.#problem("computed-access", node, "the names asserted for the key are read in different ways");
429
+ else if (!this.#sliceBuilt(node, handle)) {
430
+ const fromSlice = /sliceName|refName/.test(node.argumentExpression.getText(this.#source));
431
+ const other = fromSlice ? "take the slice as a `SliceMeta` parameter" : "name the endpoint";
432
+ const answer = fromSlice || handle.kind === "fetch" ? `${other}, or ${assertKey}` : assertKey;
433
+ this.#problem("computed-access", node, `the name is picked at run time; ${answer}`);
434
+ }
435
+ }
436
+
437
+ #stepsOf(handle: RuntimeHandle, names: string[]) {
438
+ const steps = names.map((name) => this.#step(handle, name));
439
+ return steps.length === 1 || steps.every(isPlain) ? steps : null;
440
+ }
441
+
442
+ #sliceBuilt(node: ts.ElementAccessExpression, handle: RuntimeHandle) {
443
+ const pieces = this.#slices.piecesOf(node.argumentExpression);
444
+ const table = this.#consumer;
445
+ if (!pieces || !table) return false;
446
+ if (!this.#recording) return true;
447
+ const reads: { leaf: RuntimeFamily; key: string; loads: RuntimeSlice["loads"] }[] = [];
448
+ for (const slice of RuntimeSliceKey.slicesOf(table)) {
449
+ const name = RuntimeSliceKey.nameOf(pieces, slice);
450
+ const step = name === null ? null : this.#step(handle, name);
451
+ if (!step || !isPlain(step)) return false;
452
+ if ("leaf" in step && table.lookup(step.leaf, step.key)) reads.push({ ...step, loads: slice.loads });
453
+ }
454
+ for (const { leaf, key, loads } of reads) this.#record(leaf, key, node, loads);
455
+ return reads.length > 0;
456
+ }
457
+
458
+ //? A slice written out carries no reference to its model, so the file writing it loads the model as if it named it.
459
+ #writtenSlice(literal: ts.ObjectLiteralExpression) {
460
+ const named = (key: string) => literal.properties.find(({ name }) => !!name && staticName(name) === key);
461
+ const sliceName = named("sliceName");
462
+ if (!sliceName || !named("refName")) return;
463
+ if (this.#recording) this.#reads = true;
464
+ const value = ts.isPropertyAssignment(sliceName)
465
+ ? sliceName.initializer
466
+ : ts.isShorthandPropertyAssignment(sliceName)
467
+ ? sliceName.name
468
+ : null;
469
+ if (value && this.#slices.copiesSliceName(value)) return;
470
+ const names = ts.isPropertyAssignment(sliceName) ? this.#keys.namesOf(sliceName.initializer) : null;
471
+ if (names) for (const name of names) this.#record("fetch.slice", name, sliceName);
472
+ else this.#problem("computed-access", sliceName, "a slice written by hand names its model at run time");
473
+ }
474
+
475
+ #handed(argument: ts.Expression, call: ts.Node) {
476
+ if (!ts.isCallExpression(call)) return false;
477
+ const index = call.arguments.indexOf(argument);
478
+ const callee = index < 0 ? null : declaredFunction(call.expression, this.#lexical);
479
+ const parameter = callee?.parameters.filter((parameter) => !isThisParameter(parameter))[index];
480
+ if (!callee?.body || !parameter || parameter.dotDotDotToken) return false;
481
+ if (call.arguments.slice(0, index).some(ts.isSpreadElement)) return false;
482
+ if (!ts.isArrowFunction(callee) && ownArguments(callee.body)) return false;
483
+ this.#bindName(parameter.name, { kind: "state" });
484
+ return true;
485
+ }
486
+
487
+ #apply(node: ts.Expression, step: Step) {
488
+ if ("leaf" in step) {
489
+ this.#record(step.leaf, step.key, node);
490
+ if (step.next) this.#follow(node, step.next);
491
+ } else if ("handle" in step) this.#follow(node, step.handle);
492
+ else if ("method" in step) this.#callMethod(node, step.method, step.own);
493
+ else if ("unknown" in step) this.#problem("unknown-name", node, "the runtime has no such member");
494
+ else if ("whole" in step) this.#problem("whole-runtime-import", node, "it hands out the whole client runtime");
495
+ }
496
+
497
+ #step(handle: RuntimeHandle, name: string): Step {
498
+ const to = (kind: RuntimeHandleKind): Step => ({ handle: { kind } });
499
+ switch (handle.kind) {
500
+ case "st":
501
+ if (name === "do" || name === "use" || name === "slice") return to(`st.${name}`);
502
+ if (stMethods.has(name)) return { method: name as StoreMethod };
503
+ return agenticMembers.has(name) ? { none: true } : { unknown: true };
504
+ case "root":
505
+ case "self":
506
+ if (name === "get" || name === "set" || name === "pick")
507
+ return { method: name, own: handle.kind === "self" && !handle.cast };
508
+ if (name === "slice") return to("st.slice");
509
+ if (handle.members?.has(name) && !this.#consumer?.lookup("st.do", name)) return { none: true };
510
+ return { leaf: "st.do", key: name };
511
+ case "state":
512
+ return { leaf: "st.use", key: name };
513
+ case "getter":
514
+ return { unknown: true };
515
+ case "fetch":
516
+ if (name === "slice" || name === "serializedSignal") return to(`fetch.${name}`);
517
+ if (fetchClientMembers.has(name) && !this.#consumer?.lookup("fetch", name)) return { none: true };
518
+ return { leaf: "fetch", key: name };
519
+ case "sig":
520
+ return { leaf: "sig", key: name, next: { kind: "signal" } };
521
+ case "signal":
522
+ if (name === "fetch") return to("fetch");
523
+ return signalData.has(name) ? { none: true } : { unknown: true };
524
+ case "akanjs/store":
525
+ if (name === "st") return to("st");
526
+ return RuntimeImports.frameworkWholeNames.has(name) ? { whole: true } : { none: true };
527
+ case "akanjs/client":
528
+ return name === "fetch" || name === "sig" ? to(name) : { none: true };
529
+ default:
530
+ return { leaf: handle.kind, key: name };
531
+ }
532
+ }
533
+
534
+ #callMethod(node: ts.Expression, method: StoreMethod, own = false) {
535
+ const { current, parent } = climbCasts(node);
536
+ if (method === "get" && ts.isVariableDeclaration(parent) && parent.initializer === current)
537
+ return this.#declare(parent, { kind: "getter" });
538
+ if (!ts.isCallExpression(parent) || parent.expression !== current)
539
+ return this.#problem("passed-on", node, "the store method is taken off the store");
540
+ const spread = parent.arguments.find(ts.isSpreadElement);
541
+ if (spread) return this.#problem("computed-access", spread, "a spread hides which argument lands where");
542
+ const [first, second] = parent.arguments;
543
+ if (method === "get") return this.#follow(parent, { kind: "state" });
544
+ if (method === "pick")
545
+ for (const key of parent.arguments) {
546
+ const names = this.#keys.namesOf(key);
547
+ if (names) for (const name of names) this.#record("st.use", name, key);
548
+ else this.#problem("computed-access", key, `the state key is picked at run time; ${assertKey}`);
549
+ }
550
+ else if (method === "set") {
551
+ if (first) this.#written(first, own);
552
+ } else {
553
+ const selector = first && inlineFunction(first);
554
+ if (first && !selector) this.#problem("passed-on", first, "the selector is not written inline");
555
+ if (selector) this.#bindCallback(selector, method === "sub" && !second ? 2 : 1);
556
+ }
557
+ }
558
+
559
+ #bindCallback(callback: ts.ArrowFunction | ts.FunctionExpression, count: number) {
560
+ if (ts.isFunctionExpression(callback)) {
561
+ const own = ownArguments(callback.body);
562
+ if (own) this.#problem("hidden-by-destructuring", own, "`arguments` hides which names it reads");
563
+ }
564
+ const parameters = callback.parameters.filter((parameter) => !isThisParameter(parameter));
565
+ for (const parameter of parameters.slice(0, count)) this.#bindParameter(parameter, { kind: "state" });
566
+ }
567
+
568
+ //? `own`: a store's uncast `this.set` looks up no module for keys a spread copies; a bare value may be an updater.
569
+ #written(argument: ts.Expression, own = false, spread = false) {
570
+ const value = uncast(argument);
571
+ const updater = inlineFunction(value);
572
+ if (updater) {
573
+ this.#bindCallback(updater, 1);
574
+ const returned = ts.isBlock(updater.body) ? returnsOf(updater.body) : [updater.body as ts.Expression];
575
+ for (const expression of returned) this.#written(expression, own);
576
+ } else if (ts.isConditionalExpression(value)) {
577
+ this.#written(value.whenTrue, own, spread);
578
+ this.#written(value.whenFalse, own, spread);
579
+ } else if (ts.isBinaryExpression(value) && value.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken)
580
+ this.#written(value.right, own, spread);
581
+ else if (!ts.isObjectLiteralExpression(value)) {
582
+ if (!own || !spread) this.#problem("computed-access", argument, "the state keys it writes are not written out");
583
+ } else
584
+ for (const property of value.properties) {
585
+ if (ts.isSpreadAssignment(property)) {
586
+ this.#written(property.expression, own, true);
587
+ continue;
588
+ }
589
+ const names = property.name && this.#keys.ofProperty(property.name);
590
+ if (names) for (const name of names) this.#record("st.use", name, property);
591
+ else this.#problem("computed-access", property, `the state key is computed; ${assertKey}`);
592
+ }
593
+ }
594
+
595
+ #declare(declaration: ts.VariableDeclaration, handle: RuntimeHandle) {
596
+ const list = declaration.parent;
597
+ const statement = list.parent;
598
+ const exported =
599
+ ts.isVariableStatement(statement) &&
600
+ !!statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword);
601
+ if (exported) return this.#problem("re-exported", declaration, "other files read the runtime through this one");
602
+ if (!ts.isVariableDeclarationList(list) || !(list.flags & ts.NodeFlags.Const))
603
+ return this.#problem("passed-on", declaration, "a reassignable variable may hold anything later");
604
+ this.#bindName(declaration.name, handle);
605
+ }
606
+
607
+ #bindParameter(parameter: ts.ParameterDeclaration | undefined, handle: RuntimeHandle) {
608
+ if (!parameter) return;
609
+ if (parameter.dotDotDotToken)
610
+ return this.#problem("hidden-by-destructuring", parameter, "a rest parameter hides which names it reads");
611
+ this.#bindName(parameter.name, handle);
612
+ }
613
+
614
+ #bindName(name: ts.BindingName, handle: RuntimeHandle) {
615
+ if (ts.isIdentifier(name)) {
616
+ this.#bindings.set(name, { type: "handle", handle });
617
+ return;
618
+ }
619
+ if (ts.isArrayBindingPattern(name))
620
+ return this.#problem("hidden-by-destructuring", name, "array destructuring hides which names it reads");
621
+ for (const element of name.elements) {
622
+ const names = element.dotDotDotToken ? null : this.#keys.ofProperty(element.propertyName ?? element.name);
623
+ const steps = names && this.#stepsOf(handle, names);
624
+ const why = names
625
+ ? "the names asserted for the key are read in different ways"
626
+ : `a rest or computed key hides which names it reads; ${assertKey}`;
627
+ if (!steps) this.#problem("hidden-by-destructuring", element, why);
628
+ for (const step of steps ?? []) this.#bindStep(element, step);
629
+ }
630
+ }
631
+
632
+ #bindStep(element: ts.BindingElement, step: Step) {
633
+ if ("leaf" in step) {
634
+ this.#record(step.leaf, step.key, element);
635
+ if (step.next) this.#bindName(element.name, step.next);
636
+ } else if ("handle" in step) this.#bindName(element.name, step.handle);
637
+ else if ("method" in step) this.#problem("passed-on", element, "the store method is taken off the store");
638
+ else if ("unknown" in step) this.#problem("unknown-name", element, "the runtime has no such member");
639
+ else if ("whole" in step) this.#problem("whole-runtime-import", element, "it hands out the whole client runtime");
640
+ }
641
+
642
+ #record(family: RuntimeFamily, key: string, node: ts.Node, loaded?: RuntimeSlice["loads"]) {
643
+ if (!this.#recording) return;
644
+ const table = this.#consumer;
645
+ if (!table)
646
+ return this.#problem("whole-runtime-import", node, "there is no generated client runtime to read names from");
647
+ const entry = table.lookup(family, key);
648
+ if (!entry)
649
+ return this.#problem(
650
+ "unknown-name",
651
+ node,
652
+ `${family}.${key} is not a name ${table.scope}'s client runtime answers`,
653
+ );
654
+ if (entry.base === "store") this.#baseStore = true;
655
+ if (entry.base === "descriptor") this.#baseDescriptor = true;
656
+ for (const owner of entry.owners) if (!loaded?.(owner, entry.needs)) this.#need(owner, entry.needs);
657
+ for (const owner of entry.uses) this.#need(owner, "descriptor");
658
+ }
659
+
660
+ #need(owner: RuntimeOwner, needs: RuntimeNeed) {
661
+ const id = `${owner.scope}/${owner.module}`;
662
+ const known = this.#owners.get(id);
663
+ if (!known || (known.needs === "descriptor" && needs === "store")) this.#owners.set(id, { ...owner, needs });
664
+ }
665
+
666
+ #problem(reason: RuntimeUseReason, node: ts.Node, why: string) {
667
+ if (!this.#recording) return;
668
+ const problem = problemAt(this.#source, reason, node, why);
669
+ if (this.#problems.some(({ position }) => position === problem.position && problem.reason === reason)) return;
670
+ this.#problems.push(problem);
671
+ }
672
+
673
+ static #membersOf(node: ts.ClassLikeDeclaration) {
674
+ const members = new Set<string>();
675
+ for (const member of node.members) {
676
+ const name = member.name && staticName(member.name);
677
+ const isStatic = !!(ts.getCombinedModifierFlags(member) & ts.ModifierFlags.Static);
678
+ if (name !== null && name !== undefined && !isStatic) members.add(name);
679
+ }
680
+ return members;
681
+ }
682
+
683
+ static #castInner(expression: ts.Expression): ts.Expression {
684
+ const value = unwrap(expression);
685
+ if (
686
+ (ts.isAsExpression(value) || ts.isTypeAssertionExpression(value)) &&
687
+ value.type.kind === ts.SyntaxKind.UnknownKeyword
688
+ )
689
+ return unwrap(value.expression);
690
+ return value;
691
+ }
692
+
693
+ static #kindOf(fileName: string) {
694
+ return fileName.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
695
+ }
696
+ }