@granular-software/fractory 0.0.0-stage → 0.1.25

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 (285) hide show
  1. package/LICENSE +4 -0
  2. package/README.md +28 -2
  3. package/dist/activity-volume.d.ts +18 -0
  4. package/dist/activity-volume.js +94 -0
  5. package/dist/annotations.d.ts +122 -0
  6. package/dist/annotations.js +304 -0
  7. package/dist/benchmark-cli.d.ts +1 -0
  8. package/dist/benchmark-cli.js +95 -0
  9. package/dist/benchmark-worker.d.ts +2 -0
  10. package/dist/benchmark-worker.js +22 -0
  11. package/dist/benchmarks.d.ts +19 -0
  12. package/dist/benchmarks.js +414 -0
  13. package/dist/bin.d.ts +2 -0
  14. package/dist/bin.js +63 -0
  15. package/dist/block-cli.d.ts +1 -0
  16. package/dist/block-cli.js +88 -0
  17. package/dist/block-documents.d.ts +35 -0
  18. package/dist/block-documents.js +84 -0
  19. package/dist/change-impact.d.ts +55 -0
  20. package/dist/change-impact.js +223 -0
  21. package/dist/check-source.d.ts +2 -0
  22. package/dist/check-source.js +66 -0
  23. package/dist/checks-model.d.ts +64 -0
  24. package/dist/checks-model.js +36 -0
  25. package/dist/cli.d.ts +2 -0
  26. package/dist/cli.js +359 -0
  27. package/dist/code-model.d.ts +38 -0
  28. package/dist/code-model.js +94 -0
  29. package/dist/code-store.d.ts +9 -0
  30. package/dist/code-store.js +79 -0
  31. package/dist/compare-artifact.d.ts +6 -0
  32. package/dist/compare-artifact.js +277 -0
  33. package/dist/compare.d.ts +81 -0
  34. package/dist/compare.js +291 -0
  35. package/dist/compiler.d.ts +10 -0
  36. package/dist/compiler.js +1240 -0
  37. package/dist/compose.d.ts +9 -0
  38. package/dist/compose.js +72 -0
  39. package/dist/core.d.ts +87 -0
  40. package/dist/core.js +207 -0
  41. package/dist/coverage-cli.d.ts +1 -0
  42. package/dist/coverage-cli.js +42 -0
  43. package/dist/declaration-sources.d.ts +3 -0
  44. package/dist/declaration-sources.js +51 -0
  45. package/dist/declared-graph.d.ts +3 -0
  46. package/dist/declared-graph.js +67 -0
  47. package/dist/display-name.d.ts +2 -0
  48. package/dist/display-name.js +8 -0
  49. package/dist/error-heat.d.ts +58 -0
  50. package/dist/error-heat.js +96 -0
  51. package/dist/evidence.d.ts +3 -0
  52. package/dist/evidence.js +68 -0
  53. package/dist/factory-graph.d.ts +7 -0
  54. package/dist/factory-graph.js +389 -0
  55. package/dist/factory-model.d.ts +111 -0
  56. package/dist/factory-model.js +1 -0
  57. package/dist/git-code.d.ts +47 -0
  58. package/dist/git-code.js +352 -0
  59. package/dist/git-refs.d.ts +4 -0
  60. package/dist/git-refs.js +37 -0
  61. package/dist/history-activity.d.ts +4 -0
  62. package/dist/history-activity.js +129 -0
  63. package/dist/history-churn.d.ts +36 -0
  64. package/dist/history-churn.js +302 -0
  65. package/dist/history-git.d.ts +21 -0
  66. package/dist/history-git.js +125 -0
  67. package/dist/history-ledger.d.ts +43 -0
  68. package/dist/history-ledger.js +450 -0
  69. package/dist/history-ownership.d.ts +10 -0
  70. package/dist/history-ownership.js +75 -0
  71. package/dist/history-source.d.ts +13 -0
  72. package/dist/history-source.js +100 -0
  73. package/dist/integrations-cli.d.ts +2 -0
  74. package/dist/integrations-cli.js +159 -0
  75. package/dist/interface-map.d.ts +15 -0
  76. package/dist/interface-map.js +125 -0
  77. package/dist/issue-cache.d.ts +9 -0
  78. package/dist/issue-cache.js +68 -0
  79. package/dist/issue-cli.d.ts +1 -0
  80. package/dist/issue-cli.js +89 -0
  81. package/dist/issue-links.d.ts +15 -0
  82. package/dist/issue-links.js +125 -0
  83. package/dist/linear-issues.d.ts +19 -0
  84. package/dist/linear-issues.js +124 -0
  85. package/dist/local-runtime.d.ts +8 -0
  86. package/dist/local-runtime.js +59 -0
  87. package/dist/map-activity.d.ts +73 -0
  88. package/dist/map-activity.js +234 -0
  89. package/dist/map-model.d.ts +5 -0
  90. package/dist/map-model.js +166 -0
  91. package/dist/map-quality.d.ts +20 -0
  92. package/dist/map-quality.js +61 -0
  93. package/dist/mapping-coverage.d.ts +87 -0
  94. package/dist/mapping-coverage.js +404 -0
  95. package/dist/model.d.ts +186 -0
  96. package/dist/model.js +66 -0
  97. package/dist/operation-benchmark-worker.d.ts +2 -0
  98. package/dist/operation-benchmark-worker.js +60 -0
  99. package/dist/operation-benchmark.d.ts +29 -0
  100. package/dist/operation-benchmark.js +1 -0
  101. package/dist/otel-metrics.d.ts +21 -0
  102. package/dist/otel-metrics.js +146 -0
  103. package/dist/performance-model.d.ts +185 -0
  104. package/dist/performance-model.js +396 -0
  105. package/dist/product-map.d.ts +71 -0
  106. package/dist/product-map.js +197 -0
  107. package/dist/provider-access.cjs +207 -0
  108. package/dist/provider-access.d.cts +14 -0
  109. package/dist/public-boundaries.d.ts +13 -0
  110. package/dist/public-boundaries.js +115 -0
  111. package/dist/reports-cli.d.ts +1 -0
  112. package/dist/reports-cli.js +111 -0
  113. package/dist/reports-model.d.ts +27 -0
  114. package/dist/reports-model.js +39 -0
  115. package/dist/reports.d.ts +23 -0
  116. package/dist/reports.js +223 -0
  117. package/dist/repository-map.d.ts +22 -0
  118. package/dist/repository-map.js +153 -0
  119. package/dist/resource-cache.d.ts +17 -0
  120. package/dist/resource-cache.js +65 -0
  121. package/dist/review-cli.d.ts +19 -0
  122. package/dist/review-cli.js +224 -0
  123. package/dist/review.d.ts +48 -0
  124. package/dist/review.js +289 -0
  125. package/dist/runtime-metrics.d.ts +26 -0
  126. package/dist/runtime-metrics.js +290 -0
  127. package/dist/scope.d.ts +14 -0
  128. package/dist/scope.js +168 -0
  129. package/dist/sentry-activity.d.ts +39 -0
  130. package/dist/sentry-activity.js +174 -0
  131. package/dist/sentry.d.ts +130 -0
  132. package/dist/sentry.js +369 -0
  133. package/dist/service-release.d.ts +16 -0
  134. package/dist/service-release.js +14 -0
  135. package/dist/setup-cli.d.ts +2 -0
  136. package/dist/setup-cli.js +52 -0
  137. package/dist/setup-kit.cjs +163 -0
  138. package/dist/setup-kit.d.cts +32 -0
  139. package/dist/source-index.d.ts +37 -0
  140. package/dist/source-index.js +170 -0
  141. package/dist/source-review-git.d.ts +7 -0
  142. package/dist/source-review-git.js +105 -0
  143. package/dist/source-review.d.ts +18 -0
  144. package/dist/source-review.js +573 -0
  145. package/dist/telemetry.d.ts +17 -0
  146. package/dist/telemetry.js +51 -0
  147. package/dist/time-window.d.ts +9 -0
  148. package/dist/time-window.js +35 -0
  149. package/dist/trace-evidence.d.ts +23 -0
  150. package/dist/trace-evidence.js +55 -0
  151. package/dist/trace-model.d.ts +26 -0
  152. package/dist/trace-model.js +1 -0
  153. package/dist/tracing.d.ts +44 -0
  154. package/dist/tracing.js +123 -0
  155. package/dist/work-check.d.ts +18 -0
  156. package/dist/work-check.js +115 -0
  157. package/dist/work-cli.d.ts +1 -0
  158. package/dist/work-cli.js +176 -0
  159. package/dist/work-context.d.ts +59 -0
  160. package/dist/work-context.js +594 -0
  161. package/dist/work-intents.d.ts +6 -0
  162. package/dist/work-intents.js +140 -0
  163. package/dist/work-items.d.ts +58 -0
  164. package/dist/work-items.js +86 -0
  165. package/dist/work-lock-check.d.ts +12 -0
  166. package/dist/work-lock-check.js +339 -0
  167. package/dist/work-locks.d.ts +10 -0
  168. package/dist/work-locks.js +98 -0
  169. package/dist/work-model.d.ts +119 -0
  170. package/dist/work-model.js +310 -0
  171. package/dist/work-review-git.d.ts +8 -0
  172. package/dist/work-review-git.js +111 -0
  173. package/dist/work-review.d.ts +26 -0
  174. package/dist/work-review.js +426 -0
  175. package/dist/work-switcher-model.d.ts +43 -0
  176. package/dist/work-switcher-model.js +79 -0
  177. package/dist/work-switcher.d.ts +6 -0
  178. package/dist/work-switcher.js +171 -0
  179. package/dist/working-cli.d.ts +1 -0
  180. package/dist/working-cli.js +33 -0
  181. package/dist/working-code.d.ts +74 -0
  182. package/dist/working-code.js +421 -0
  183. package/dist/workspace-notes.d.ts +71 -0
  184. package/dist/workspace-notes.js +177 -0
  185. package/dist/workspace-tests.d.ts +21 -0
  186. package/dist/workspace-tests.js +573 -0
  187. package/package.json +547 -4
  188. package/src/activity-volume.ts +149 -0
  189. package/src/annotations.ts +485 -0
  190. package/src/benchmark-cli.ts +118 -0
  191. package/src/benchmark-worker.ts +22 -0
  192. package/src/benchmarks.ts +493 -0
  193. package/src/bin.ts +54 -0
  194. package/src/block-cli.ts +106 -0
  195. package/src/block-documents.ts +117 -0
  196. package/src/change-impact.ts +280 -0
  197. package/src/check-source.ts +82 -0
  198. package/src/checks-model.ts +108 -0
  199. package/src/cli.ts +440 -0
  200. package/src/code-model.ts +159 -0
  201. package/src/code-store.ts +98 -0
  202. package/src/compare-artifact.ts +314 -0
  203. package/src/compare.ts +440 -0
  204. package/src/compiler.ts +1512 -0
  205. package/src/compose.ts +94 -0
  206. package/src/core.ts +361 -0
  207. package/src/coverage-cli.ts +52 -0
  208. package/src/declaration-sources.ts +69 -0
  209. package/src/declared-graph.ts +75 -0
  210. package/src/display-name.ts +8 -0
  211. package/src/error-heat.ts +161 -0
  212. package/src/evidence.ts +94 -0
  213. package/src/factory-graph.ts +462 -0
  214. package/src/factory-model.ts +82 -0
  215. package/src/git-code.ts +461 -0
  216. package/src/git-refs.ts +43 -0
  217. package/src/history-activity.ts +146 -0
  218. package/src/history-churn.ts +416 -0
  219. package/src/history-git.ts +163 -0
  220. package/src/history-ledger.ts +636 -0
  221. package/src/history-ownership.ts +116 -0
  222. package/src/history-source.ts +117 -0
  223. package/src/integrations-cli.ts +187 -0
  224. package/src/interface-map.ts +166 -0
  225. package/src/issue-cache.ts +96 -0
  226. package/src/issue-cli.ts +137 -0
  227. package/src/issue-links.ts +153 -0
  228. package/src/linear-issues.ts +154 -0
  229. package/src/local-runtime.ts +70 -0
  230. package/src/map-activity.ts +309 -0
  231. package/src/map-model.ts +213 -0
  232. package/src/map-quality.ts +66 -0
  233. package/src/mapping-coverage.ts +570 -0
  234. package/src/model.ts +228 -0
  235. package/src/operation-benchmark-worker.ts +60 -0
  236. package/src/operation-benchmark.ts +28 -0
  237. package/src/otel-metrics.ts +176 -0
  238. package/src/performance-model.ts +575 -0
  239. package/src/product-map.ts +271 -0
  240. package/src/provider-access.cjs +207 -0
  241. package/src/provider-access.d.cts +14 -0
  242. package/src/public-boundaries.ts +143 -0
  243. package/src/reports-cli.ts +125 -0
  244. package/src/reports-model.ts +73 -0
  245. package/src/reports.ts +276 -0
  246. package/src/repository-map.ts +191 -0
  247. package/src/resource-cache.ts +76 -0
  248. package/src/review-cli.ts +256 -0
  249. package/src/review.ts +376 -0
  250. package/src/runtime-metrics.ts +386 -0
  251. package/src/scope.ts +192 -0
  252. package/src/sentry-activity.ts +234 -0
  253. package/src/sentry.ts +545 -0
  254. package/src/service-release.ts +18 -0
  255. package/src/setup-cli.ts +58 -0
  256. package/src/setup-kit.cjs +163 -0
  257. package/src/setup-kit.d.cts +32 -0
  258. package/src/source-index.ts +208 -0
  259. package/src/source-review-git.ts +131 -0
  260. package/src/source-review.ts +736 -0
  261. package/src/telemetry.ts +68 -0
  262. package/src/time-window.ts +51 -0
  263. package/src/trace-evidence.ts +80 -0
  264. package/src/trace-model.ts +26 -0
  265. package/src/tracing.ts +165 -0
  266. package/src/work-check.ts +149 -0
  267. package/src/work-cli.ts +229 -0
  268. package/src/work-context.ts +753 -0
  269. package/src/work-intents.ts +196 -0
  270. package/src/work-items.ts +151 -0
  271. package/src/work-lock-check.ts +549 -0
  272. package/src/work-locks.ts +108 -0
  273. package/src/work-model.ts +466 -0
  274. package/src/work-review-git.ts +130 -0
  275. package/src/work-review.ts +573 -0
  276. package/src/work-switcher-model.ts +121 -0
  277. package/src/work-switcher.ts +191 -0
  278. package/src/working-cli.ts +38 -0
  279. package/src/working-code.ts +582 -0
  280. package/src/workspace-notes.ts +203 -0
  281. package/src/workspace-tests.ts +654 -0
  282. package/toolkit/GUIDE.md +354 -0
  283. package/toolkit/SKILL.md +142 -0
  284. package/toolkit/bin/fractory +2 -0
  285. package/toolkit/build.json +1 -0
@@ -0,0 +1,1512 @@
1
+ /** Build-time only: collect declarations and types without importing application code. */
2
+ import ts from "typescript";
3
+ import { factoryGraph as checkedFactoryGraph } from "./factory-graph";
4
+ import { createHash } from "node:crypto";
5
+ import { resolve, relative, dirname, isAbsolute, join } from "node:path";
6
+ import { readdirSync, readFileSync, existsSync } from "node:fs";
7
+ import { fileURLToPath } from "node:url";
8
+ import type {
9
+ FactoryModel,
10
+ FactoryAttachments,
11
+ FactoryBlock,
12
+ FactoryMethod,
13
+ } from "./factory-model";
14
+ import type { SourceRef } from "./model";
15
+
16
+ const digest = (value: string) =>
17
+ createHash("sha256").update(value).digest("hex");
18
+ const names = new Set(["Block", "Interface", "Method", "Process"]);
19
+ /** Incremental build entry discovery: inspect source text, never import app modules. */
20
+ export function annotatedFiles(
21
+ root: string,
22
+ directories = ["apps", "packages", "src"],
23
+ ) {
24
+ const files: string[] = [];
25
+ const visit = (directory: string) => {
26
+ if (!existsSync(directory)) return;
27
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
28
+ if (
29
+ (entry.isDirectory() && entry.name.startsWith(".")) ||
30
+ [
31
+ "node_modules",
32
+ ".git",
33
+ ".next",
34
+ ".next-fractal",
35
+ "dist",
36
+ "generated",
37
+ "__tests__",
38
+ "test",
39
+ "e2e",
40
+ ].includes(entry.name)
41
+ )
42
+ continue;
43
+ const file = join(directory, entry.name);
44
+ if (entry.isDirectory()) visit(file);
45
+ else if (
46
+ /\.tsx?$/.test(entry.name) &&
47
+ !/\.(test|spec|d)\.tsx?$/.test(entry.name) &&
48
+ /from\s*["']@granular-software\/fract(?:al|ory)(?:\/annotations)?["']/.test(
49
+ readFileSync(file, "utf8"),
50
+ )
51
+ )
52
+ files.push(relative(root, file));
53
+ }
54
+ };
55
+ for (const directory of directories) visit(resolve(root, directory));
56
+ return files.sort();
57
+ }
58
+ export function compileFactory(options: {
59
+ root: string;
60
+ files: string[];
61
+ /** Canonical annotation source shipped beside the standalone desktop CLI. */
62
+ sdkSource?: string;
63
+ }): FactoryModel {
64
+ const root = resolve(options.root);
65
+ const sdkSource =
66
+ options.sdkSource ||
67
+ resolve(dirname(fileURLToPath(import.meta.url)), "../src/annotations.ts");
68
+ // Public workspace packages point to dist for consumers. Architecture and
69
+ // contracts must come from source, regardless of local build state.
70
+ // Runtime hosts may carry a generated copy (e.g. a standalone CommonJS
71
+ // container). Always resolve the annotation API to this compiler's canonical
72
+ // SDK source so build artifacts cannot silently erase declarations.
73
+ const paths: Record<string, string[]> = {
74
+ "@granular-software/fractal/annotations": [sdkSource],
75
+ "@granular-software/fractory/annotations": [sdkSource],
76
+ };
77
+ const packages = new Set<string>();
78
+ for (const file of options.files) {
79
+ let directory = dirname(resolve(root, file));
80
+ while (directory !== root && !relative(root, directory).startsWith("..")) {
81
+ const manifest = join(directory, "package.json");
82
+ if (existsSync(manifest)) {
83
+ if (!packages.has(directory)) {
84
+ packages.add(directory);
85
+ const name = JSON.parse(readFileSync(manifest, "utf8")).name;
86
+ const entry = ["src/index.ts", "src/index.tsx"]
87
+ .map((path) => join(directory, path))
88
+ .find(existsSync);
89
+ if (typeof name === "string" && entry) paths[name] = [entry];
90
+ }
91
+ break;
92
+ }
93
+ directory = dirname(directory);
94
+ }
95
+ }
96
+ const compilerOptions: ts.CompilerOptions = {
97
+ target: ts.ScriptTarget.ES2022,
98
+ module: ts.ModuleKind.ESNext,
99
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
100
+ skipLibCheck: true,
101
+ noEmit: true,
102
+ types: [],
103
+ allowJs: true,
104
+ resolveJsonModule: true,
105
+ baseUrl: root,
106
+ paths,
107
+ };
108
+ // Alias resolution belongs to the importing host, not one monorepo-wide base
109
+ // folder. Reuse its real tsconfig paths while retaining canonical SDK source.
110
+ const host = ts.createCompilerHost(compilerOptions);
111
+ const resolutions = new Map<
112
+ string,
113
+ { options: ts.CompilerOptions; cache: ts.ModuleResolutionCache }
114
+ >();
115
+ host.resolveModuleNames = (names, containingFile) => {
116
+ const config = ts.findConfigFile(
117
+ dirname(containingFile),
118
+ ts.sys.fileExists,
119
+ "tsconfig.json",
120
+ );
121
+ const key = config || root;
122
+ if (!resolutions.has(key)) {
123
+ let localPaths: Record<string, string[]> = {};
124
+ if (config) {
125
+ const read = ts.readConfigFile(config, ts.sys.readFile);
126
+ if (!read.error) {
127
+ const parsed = ts.parseJsonConfigFileContent(
128
+ { ...read.config, files: [], include: [], exclude: [] },
129
+ ts.sys,
130
+ dirname(config),
131
+ );
132
+ const base = parsed.options.baseUrl || dirname(config);
133
+ localPaths = Object.fromEntries(
134
+ Object.entries(parsed.options.paths || {}).map(([name, values]) => [
135
+ name,
136
+ values.map((value) => resolve(base, value)),
137
+ ]),
138
+ );
139
+ }
140
+ }
141
+ const options = {
142
+ ...compilerOptions,
143
+ paths: { ...localPaths, ...paths },
144
+ };
145
+ resolutions.set(key, {
146
+ options,
147
+ cache: ts.createModuleResolutionCache(root, (f) => f, options),
148
+ });
149
+ }
150
+ const resolution = resolutions.get(key)!;
151
+ return names.map(
152
+ (name) =>
153
+ ts.resolveModuleName(
154
+ name,
155
+ containingFile,
156
+ resolution.options,
157
+ host,
158
+ resolution.cache,
159
+ ).resolvedModule,
160
+ );
161
+ };
162
+ const program = ts.createProgram(
163
+ options.files.map((file) => resolve(root, file)),
164
+ compilerOptions,
165
+ host,
166
+ );
167
+ const checker = program.getTypeChecker();
168
+ const model: FactoryModel = {
169
+ schema: "fractal.factory.v2",
170
+ revision: "",
171
+ blocks: [],
172
+ interfaces: [],
173
+ methods: [],
174
+ processes: [],
175
+ dependencies: [],
176
+ diagnostics: [],
177
+ };
178
+ const blocks = new Map<ts.Node, FactoryBlock>();
179
+ const apis = new Map<ts.Node, string>();
180
+ const pending: { node: ts.Node; call: ts.CallExpression; kind: string }[] =
181
+ [];
182
+ const methodDeclarations = new Map<ts.Node, FactoryMethod>();
183
+ const fileName = (node: ts.Node) =>
184
+ relative(root, node.getSourceFile().fileName).replaceAll("\\", "/");
185
+ const source = (node: ts.Node): SourceRef => ({
186
+ file: fileName(node),
187
+ line:
188
+ node.getSourceFile().getLineAndCharacterOfPosition(node.getStart()).line +
189
+ 1,
190
+ digest: digest(node.getSourceFile().text).slice(0, 16),
191
+ });
192
+ const problem = (node: ts.Node, message: string) =>
193
+ model.diagnostics.push({
194
+ file: fileName(node),
195
+ line: source(node).line,
196
+ message,
197
+ });
198
+ const symbol = (node: ts.Node): ts.Symbol | undefined => {
199
+ let value = checker.getSymbolAtLocation(node);
200
+ if (value && value.flags & ts.SymbolFlags.Alias)
201
+ value = checker.getAliasedSymbol(value);
202
+ return value;
203
+ };
204
+ const annotation = (call: ts.CallExpression) => {
205
+ const value = symbol(call.expression);
206
+ if (!value || !names.has(value.name)) return;
207
+ // Only our SDK: a different library's @Method must not enter this model.
208
+ if (
209
+ !value.declarations?.some(
210
+ (decl) =>
211
+ resolve(decl.getSourceFile().fileName) === resolve(sdkSource) ||
212
+ /(?:^|\/)fractal\/src\/annotations\.ts$/.test(
213
+ decl.getSourceFile().fileName.replaceAll("\\", "/"),
214
+ ),
215
+ )
216
+ )
217
+ return;
218
+ return value.name;
219
+ };
220
+ const property = (
221
+ node: ts.Node | undefined,
222
+ key: string,
223
+ ): ts.Expression | undefined => {
224
+ if (!node || !ts.isObjectLiteralExpression(node)) return;
225
+ const member = node.properties.find(
226
+ (p) => p.name?.getText().replace(/['"]/g, "") === key,
227
+ );
228
+ return member && ts.isPropertyAssignment(member)
229
+ ? member.initializer
230
+ : undefined;
231
+ };
232
+ const text = (node: ts.Node | undefined): string | undefined =>
233
+ node &&
234
+ (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node))
235
+ ? node.text
236
+ : undefined;
237
+ const strings = (node: ts.Node | undefined) =>
238
+ !node
239
+ ? []
240
+ : ts.isArrayLiteralExpression(node)
241
+ ? node.elements.flatMap((e) => (text(e) ? [text(e)!] : []))
242
+ : text(node)
243
+ ? [text(node)!]
244
+ : [];
245
+ const attachments = (
246
+ config: ts.Node | undefined,
247
+ owner: ts.Node,
248
+ ): FactoryAttachments => {
249
+ const paths = (key: string) =>
250
+ strings(property(config, key)).map((path) => {
251
+ const [file, fragment] = path.split("#");
252
+ const full = isAbsolute(file)
253
+ ? file
254
+ : resolve(dirname(owner.getSourceFile().fileName), file);
255
+ return (
256
+ relative(root, full).replaceAll("\\", "/") +
257
+ (fragment ? `#${fragment}` : "")
258
+ );
259
+ });
260
+ const auth = property(config, "auth");
261
+ const documented: ts.Node[] = [owner];
262
+ let container = owner.parent;
263
+ while (
264
+ container &&
265
+ documented.length < 8 &&
266
+ (ts.isCallExpression(container) ||
267
+ ts.isVariableDeclaration(container) ||
268
+ ts.isVariableDeclarationList(container) ||
269
+ ts.isVariableStatement(container) ||
270
+ ts.isExpressionStatement(container) ||
271
+ ts.isParenthesizedExpression(container) ||
272
+ ts.isPropertyAssignment(container))
273
+ ) {
274
+ documented.push(container);
275
+ container = container.parent;
276
+ }
277
+ const documentation = documented
278
+ .filter((node): node is ts.Node => !!node)
279
+ .flatMap((node) => ts.getJSDocCommentsAndTags(node))
280
+ .find((node) => node.kind === ts.SyntaxKind.JSDoc) as
281
+ | ts.JSDoc
282
+ | undefined;
283
+ const comment =
284
+ typeof documentation?.comment === "string"
285
+ ? documentation.comment
286
+ : documentation?.comment?.map((part) => part.text).join("");
287
+ const description =
288
+ text(property(config, "description")) ||
289
+ comment
290
+ ?.split(/\n\s*\n/)[0]
291
+ .replace(/\s+/g, " ")
292
+ .trim();
293
+ return {
294
+ docs: paths("docs"),
295
+ tests: paths("tests"),
296
+ ...(paths("benchmarks").length
297
+ ? { benchmarks: paths("benchmarks") }
298
+ : {}),
299
+ ...(description ? { description } : {}),
300
+ ...(auth
301
+ ? {
302
+ auth: {
303
+ symbol: symbol(auth)?.name || "inline policy",
304
+ source: source(auth),
305
+ },
306
+ }
307
+ : {}),
308
+ };
309
+ };
310
+ const configOf = (call: ts.CallExpression) =>
311
+ ts.isObjectLiteralExpression(call.arguments[0])
312
+ ? call.arguments[0]
313
+ : call.arguments[1];
314
+ const resolvedNode = (
315
+ expression: ts.Node | undefined,
316
+ ): ts.Node | undefined => {
317
+ if (!expression) return;
318
+ if (ts.isArrowFunction(expression)) {
319
+ if (ts.isBlock(expression.body)) {
320
+ const statement = expression.body.statements.find(ts.isReturnStatement);
321
+ return resolvedNode(statement?.expression);
322
+ }
323
+ return resolvedNode(expression.body);
324
+ }
325
+ if (
326
+ ts.isParenthesizedExpression(expression) ||
327
+ ts.isAsExpression(expression)
328
+ )
329
+ return resolvedNode(expression.expression);
330
+ const declaration =
331
+ symbol(expression)?.valueDeclaration ||
332
+ symbol(expression)?.declarations?.[0];
333
+ if (
334
+ declaration &&
335
+ (ts.isVariableDeclaration(declaration) ||
336
+ ts.isExportAssignment(declaration)) &&
337
+ (ts.isVariableDeclaration(declaration)
338
+ ? declaration.initializer
339
+ : declaration.expression)
340
+ ) {
341
+ const value = ts.isVariableDeclaration(declaration)
342
+ ? declaration.initializer!
343
+ : declaration.expression;
344
+ if (
345
+ ts.isCallExpression(value) &&
346
+ ts.isCallExpression(value.expression) &&
347
+ annotation(value.expression) &&
348
+ value.arguments[0] &&
349
+ (callable(value.arguments[0]) ||
350
+ annotation(value.expression) === "Block")
351
+ )
352
+ return value.arguments[0];
353
+ if (ts.isIdentifier(value) || ts.isPropertyAccessExpression(value))
354
+ return resolvedNode(value);
355
+ }
356
+ return declaration;
357
+ };
358
+ const nearestBlock = (node: ts.Node): FactoryBlock | undefined => {
359
+ let parent = node.parent;
360
+ while (parent) {
361
+ if (blocks.has(parent)) return blocks.get(parent);
362
+ parent = parent.parent;
363
+ }
364
+ };
365
+ const callable = (node: ts.Node): ts.SignatureDeclaration | undefined => {
366
+ if (
367
+ ts.isMethodDeclaration(node) ||
368
+ ts.isFunctionDeclaration(node) ||
369
+ ts.isFunctionExpression(node) ||
370
+ ts.isArrowFunction(node)
371
+ )
372
+ return node;
373
+ return;
374
+ };
375
+ const typeSources = (declaration: ts.SignatureDeclaration): SourceRef[] => {
376
+ const seen = new Set<ts.Node>(),
377
+ files = new Map<string, SourceRef>();
378
+ const pending: ts.Node[] = [
379
+ ...declaration.parameters.flatMap((parameter) =>
380
+ parameter.type ? [parameter.type] : [],
381
+ ),
382
+ ...(declaration.type ? [declaration.type] : []),
383
+ ];
384
+ while (pending.length && seen.size < 256) {
385
+ const node = pending.pop()!;
386
+ if (seen.has(node)) continue;
387
+ seen.add(node);
388
+ const visit = (part: ts.Node) => {
389
+ if (ts.isTypeReferenceNode(part) || ts.isTypeQueryNode(part)) {
390
+ const target = resolvedNode(
391
+ ts.isTypeReferenceNode(part) ? part.typeName : part.exprName,
392
+ );
393
+ if (target) {
394
+ const file = fileName(target);
395
+ if (
396
+ !file.startsWith("..") &&
397
+ !file.includes("node_modules/") &&
398
+ !target.getSourceFile().isDeclarationFile
399
+ ) {
400
+ if (!files.has(file)) files.set(file, source(target));
401
+ if (
402
+ ts.isInterfaceDeclaration(target) ||
403
+ ts.isTypeAliasDeclaration(target) ||
404
+ ts.isTypeParameterDeclaration(target)
405
+ )
406
+ pending.push(target);
407
+ }
408
+ }
409
+ }
410
+ ts.forEachChild(part, visit);
411
+ };
412
+ visit(node);
413
+ }
414
+ return [...files.values()].sort((a, b) => a.file.localeCompare(b.file));
415
+ };
416
+ const allFiles = program
417
+ .getSourceFiles()
418
+ .filter(
419
+ (file) =>
420
+ !file.isDeclarationFile &&
421
+ !file.fileName.includes("node_modules") &&
422
+ !relative(root, file.fileName).startsWith(".."),
423
+ );
424
+ for (const file of allFiles) {
425
+ const visit = (node: ts.Node) => {
426
+ if (ts.canHaveDecorators(node))
427
+ for (const decorator of ts.getDecorators(node) || []) {
428
+ if (!ts.isCallExpression(decorator.expression)) continue;
429
+ const kind = annotation(decorator.expression);
430
+ if (kind) pending.push({ node, call: decorator.expression, kind });
431
+ }
432
+ // Native inline form: Method(() => Owner.interface)(existing function expression).
433
+ if (ts.isCallExpression(node) && ts.isCallExpression(node.expression)) {
434
+ const kind = annotation(node.expression);
435
+ if (
436
+ kind &&
437
+ node.arguments[0] &&
438
+ (callable(node.arguments[0]) || kind === "Block")
439
+ )
440
+ pending.push({
441
+ node: node.arguments[0],
442
+ call: node.expression,
443
+ kind,
444
+ });
445
+ }
446
+ if (
447
+ ts.isVariableDeclaration(node) &&
448
+ node.initializer &&
449
+ ts.isCallExpression(node.initializer) &&
450
+ annotation(node.initializer) === "Interface" &&
451
+ (property(node.initializer.arguments[0], "parent") ||
452
+ text(node.initializer.arguments[0]))
453
+ )
454
+ pending.push({ node, call: node.initializer, kind: "Interface" });
455
+ ts.forEachChild(node, visit);
456
+ };
457
+ visit(file);
458
+ }
459
+ for (const item of pending.filter(
460
+ (p) => p.kind === "Block" || p.kind === "Process",
461
+ )) {
462
+ const { node, call, kind } = item;
463
+ const config = configOf(call);
464
+ const id = text(call.arguments[0]) || text(property(config, "id"));
465
+ if (!id?.trim()) {
466
+ problem(node, "Block/process needs one stable literal identity");
467
+ continue;
468
+ }
469
+ if (model.blocks.some((block) => block.id === id)) {
470
+ problem(node, `Duplicate block identity: ${id}`);
471
+ continue;
472
+ }
473
+ const label = text(property(config, "label")) || id.split("/").at(-1)!;
474
+ const block = {
475
+ id,
476
+ ...(text(property(config, "inputLabel"))
477
+ ? { inputLabel: text(property(config, "inputLabel")) }
478
+ : {}),
479
+ ...(text(property(config, "eventLabel"))
480
+ ? { eventLabel: text(property(config, "eventLabel")) }
481
+ : {}),
482
+ label,
483
+ source: source(node),
484
+ attachments: attachments(config, node),
485
+ };
486
+ blocks.set(node, block);
487
+ model.blocks.push(block);
488
+ if (
489
+ kind === "Block" &&
490
+ !ts.isClassDeclaration(node) &&
491
+ !callable(node) &&
492
+ !ts.isNewExpression(node) &&
493
+ !ts.isObjectLiteralExpression(node) &&
494
+ !ts.isCallExpression(node)
495
+ )
496
+ problem(node, "@Block requires an existing class, function or object");
497
+ if (kind === "Process" && !callable(node))
498
+ problem(node, "@Process requires an existing callable");
499
+ }
500
+ for (const item of pending.filter(
501
+ (p) => p.kind === "Block" || p.kind === "Process",
502
+ )) {
503
+ const block = blocks.get(item.node);
504
+ if (!block) continue;
505
+ const parentRef = property(configOf(item.call), "parent");
506
+ const parentNode = resolvedNode(parentRef);
507
+ const parent = parentRef
508
+ ? parentNode && blocks.get(parentNode)
509
+ : nearestBlock(item.node);
510
+ if (parentRef && !parent)
511
+ problem(
512
+ item.node,
513
+ "Logical parent must reference an annotated block/process declaration",
514
+ );
515
+ if (parent) block.parent = parent.id;
516
+ }
517
+ const exposures = (config: ts.Node | undefined, node: ts.Node) => {
518
+ const value = property(config, "exposedBy");
519
+ if (!value) return undefined;
520
+ if (!ts.isArrayLiteralExpression(value)) {
521
+ problem(node, "exposedBy must reference enclosing annotated blocks");
522
+ return undefined;
523
+ }
524
+ return value.elements.flatMap((entry) => {
525
+ const declaration = resolvedNode(entry),
526
+ block = declaration && blocks.get(declaration);
527
+ if (!block) {
528
+ problem(
529
+ node,
530
+ "exposedBy must reference an annotated block/process declaration",
531
+ );
532
+ return [];
533
+ }
534
+ return [block.id];
535
+ });
536
+ };
537
+ for (const item of pending.filter(
538
+ (entry) => entry.kind === "Block" || entry.kind === "Process",
539
+ )) {
540
+ const block = blocks.get(item.node);
541
+ if (block) block.exposedBy = exposures(configOf(item.call), item.node);
542
+ if (!block || !ts.isClassDeclaration(item.node)) continue;
543
+ const ctor = item.node.members.find(ts.isConstructorDeclaration);
544
+ if (
545
+ ctor &&
546
+ ts
547
+ .getModifiers(ctor)
548
+ ?.some((modifier) =>
549
+ [
550
+ ts.SyntaxKind.PrivateKeyword,
551
+ ts.SyntaxKind.ProtectedKeyword,
552
+ ].includes(modifier.kind),
553
+ )
554
+ )
555
+ continue;
556
+ model.interfaces.push({
557
+ id: `${block.id}::construct`,
558
+ blockId: block.id,
559
+ name: "construct",
560
+ label: `Create ${block.label}`,
561
+ source: source(ctor || item.node),
562
+ attachments: {
563
+ docs: [],
564
+ tests: [],
565
+ description: `Public constructor of ${block.label}.`,
566
+ },
567
+ methods: [],
568
+ constructorContract: {
569
+ signature: ctor
570
+ ? ctor
571
+ .getText()
572
+ .slice(
573
+ 0,
574
+ ctor.body ? ctor.body.getStart() - ctor.getStart() : undefined,
575
+ )
576
+ .trim()
577
+ : `new ${item.node.name?.text || block.label}()`,
578
+ args: (ctor?.parameters || []).map((parameter) => ({
579
+ name: parameter.name.getText(),
580
+ type: parameter.type?.getText() || "unknown",
581
+ optional: !!parameter.questionToken || !!parameter.initializer,
582
+ rest: !!parameter.dotDotDotToken,
583
+ })),
584
+ result: item.node.name?.text || block.label,
585
+ },
586
+ });
587
+ }
588
+ for (const { node, call } of pending.filter((p) => p.kind === "Interface")) {
589
+ const config =
590
+ call.arguments[0] && ts.isStringLiteral(call.arguments[0])
591
+ ? call.arguments[1]
592
+ : call.arguments[0];
593
+ const standalone = ts.isVariableDeclaration(node);
594
+ if (
595
+ !standalone &&
596
+ (!ts.isPropertyDeclaration(node) ||
597
+ !ts
598
+ .getModifiers(node)
599
+ ?.some((m) => m.kind === ts.SyntaxKind.StaticKeyword) ||
600
+ ts
601
+ .getModifiers(node)
602
+ ?.some((m) => m.kind === ts.SyntaxKind.PrivateKeyword) ||
603
+ ts.isPrivateIdentifier(node.name))
604
+ ) {
605
+ problem(node, "@Interface requires a public static field");
606
+ continue;
607
+ }
608
+ const ownerNode = standalone
609
+ ? resolvedNode(property(config, "parent"))
610
+ : node.parent;
611
+ const owner = ownerNode && blocks.get(ownerNode);
612
+ if (!owner && (!standalone || property(config, "parent"))) {
613
+ problem(node, "Interface must reference an annotated block");
614
+ continue;
615
+ }
616
+ const explicitId = text(call.arguments[0]) || text(property(config, "id"));
617
+ if (standalone && !explicitId) {
618
+ problem(node, "A standalone interface needs one stable identity");
619
+ continue;
620
+ }
621
+ const name = standalone
622
+ ? explicitId!.split("/").at(-1)!
623
+ : (node as ts.PropertyDeclaration).name.getText().replace(/['"]/g, "");
624
+ const id = explicitId || `${owner!.id}::${name}`;
625
+ const blockId =
626
+ owner?.id ||
627
+ (id.includes("/") ? id.slice(0, id.lastIndexOf("/")) : "factory");
628
+ if (model.interfaces.some((api) => api.id === id)) {
629
+ problem(node, `Duplicate interface: ${id}`);
630
+ continue;
631
+ }
632
+ apis.set(node, id);
633
+ model.interfaces.push({
634
+ id,
635
+ blockId,
636
+ name,
637
+ ...(text(property(config, "label"))
638
+ ? { label: text(property(config, "label")) }
639
+ : {}),
640
+ source: source(node),
641
+ attachments: attachments(config, node),
642
+ methods: [],
643
+ exposedBy: exposures(config, node),
644
+ });
645
+ }
646
+ for (const { node, call, kind } of pending.filter(
647
+ (p) =>
648
+ p.kind === "Method" ||
649
+ (p.kind === "Block" && !!callable(p.node)) ||
650
+ (p.kind === "Process" &&
651
+ !pending.some(
652
+ (other) => other.node === p.node && other.kind === "Method",
653
+ )),
654
+ )) {
655
+ const declaration = callable(node);
656
+ if (!declaration) {
657
+ problem(node, "A method/process annotation requires a callable");
658
+ continue;
659
+ }
660
+ const apiNode =
661
+ kind === "Method" ? resolvedNode(call.arguments[0]) : undefined;
662
+ let interfaceId = apiNode && apis.get(apiNode);
663
+ const api = model.interfaces.find((api) => api.id === interfaceId);
664
+ if (kind === "Method" && !api) {
665
+ problem(node, "@Method must reference a declared interface");
666
+ continue;
667
+ }
668
+ const block =
669
+ kind === "Process" || kind === "Block"
670
+ ? blocks.get(node)
671
+ : blocks.get(node) ||
672
+ model.blocks.find((block) => block.id === api?.blockId) ||
673
+ (api ? { id: api.blockId } : undefined);
674
+ if (!block) continue;
675
+ if (kind === "Block") {
676
+ interfaceId = `${block.id}::entry`;
677
+ model.interfaces.push({
678
+ id: interfaceId,
679
+ blockId: block.id,
680
+ name: "entry",
681
+ label: blocks.get(node)?.label || block.id,
682
+ source: source(node),
683
+ attachments: attachments(configOf(call), node),
684
+ methods: [],
685
+ entrypoint: true,
686
+ });
687
+ }
688
+ let parent = node.parent;
689
+ while (
690
+ parent &&
691
+ (ts.isCallExpression(parent) ||
692
+ ts.isParenthesizedExpression(parent) ||
693
+ ts.isAsExpression(parent))
694
+ )
695
+ parent = parent.parent;
696
+ const inferredName =
697
+ declaration.name?.getText() ||
698
+ (ts.isVariableDeclaration(parent) ? parent.name.getText() : undefined);
699
+ const name = text(property(call.arguments[1], "name")) || inferredName;
700
+ if (!name) {
701
+ problem(
702
+ node,
703
+ "Anonymous callable must be assigned to a named declaration",
704
+ );
705
+ continue;
706
+ }
707
+ const id = `${interfaceId || block.id}#${name}`;
708
+ if (model.methods.some((method) => method.id === id)) {
709
+ problem(node, `Duplicate interface member: ${id}`);
710
+ continue;
711
+ }
712
+ const signature = checker.getSignatureFromDeclaration(declaration);
713
+ const type = (node: ts.Node) =>
714
+ checker.typeToString(
715
+ checker.getTypeAtLocation(node),
716
+ node,
717
+ ts.TypeFormatFlags.NoTruncation,
718
+ );
719
+ const config = kind === "Method" ? call.arguments[1] : configOf(call);
720
+ let route: ts.Node | undefined = node.parent;
721
+ let endpoint: FactoryMethod["endpoint"];
722
+ while (route && !ts.isSourceFile(route) && !ts.isFunctionLike(route)) {
723
+ if (
724
+ ts.isCallExpression(route) &&
725
+ ts.isPropertyAccessExpression(route.expression) &&
726
+ /^(get|post|put|patch|delete|all|options|head)$/.test(
727
+ route.expression.name.text,
728
+ ) &&
729
+ text(route.arguments[0])
730
+ ) {
731
+ endpoint = {
732
+ method: route.expression.name.text.toUpperCase(),
733
+ path: text(route.arguments[0])!,
734
+ };
735
+ break;
736
+ }
737
+ route = route.parent;
738
+ }
739
+ if (
740
+ !endpoint &&
741
+ ts.isVariableDeclaration(parent) &&
742
+ ts.isIdentifier(parent.name) &&
743
+ /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/.test(parent.name.text) &&
744
+ ts.isVariableStatement(parent.parent.parent) &&
745
+ parent.parent.parent.modifiers?.some(
746
+ (modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword,
747
+ )
748
+ ) {
749
+ const nextRoute = fileName(node).match(
750
+ /(?:^|\/)(?:src\/)?app(\/api\/.*)\/route\.[cm]?[jt]s$/,
751
+ );
752
+ if (nextRoute)
753
+ endpoint = { method: parent.name.text, path: nextRoute[1] };
754
+ }
755
+ const method: FactoryMethod = {
756
+ ...(text(property(config, "label"))
757
+ ? { label: text(property(config, "label")) }
758
+ : {}),
759
+ ...(endpoint ? { endpoint } : {}),
760
+ id,
761
+ blockId: block.id,
762
+ ...(interfaceId ? { interfaceId } : {}),
763
+ name,
764
+ source: source(node),
765
+ signature: signature
766
+ ? checker.signatureToString(
767
+ signature,
768
+ declaration,
769
+ ts.TypeFormatFlags.NoTruncation,
770
+ )
771
+ : declaration.getText().split("{")[0],
772
+ contract: {
773
+ args: declaration.parameters.map((parameter) => ({
774
+ name: parameter.name.getText(),
775
+ type: type(parameter),
776
+ optional: !!parameter.questionToken || !!parameter.initializer,
777
+ rest: !!parameter.dotDotDotToken,
778
+ })),
779
+ result: signature
780
+ ? checker.typeToString(
781
+ checker.getReturnTypeOfSignature(signature),
782
+ declaration,
783
+ ts.TypeFormatFlags.NoTruncation,
784
+ )
785
+ : "unknown",
786
+ typeSources: typeSources(declaration),
787
+ runtimeValidation: !!property(config, "contract"),
788
+ },
789
+ attachments: attachments(config, node),
790
+ };
791
+ if (!method.attachments.description && kind === "Method") {
792
+ const process = pending.find(
793
+ (item) => item.node === node && item.kind === "Process",
794
+ );
795
+ if (process)
796
+ method.attachments.description = attachments(
797
+ configOf(process.call),
798
+ node,
799
+ ).description;
800
+ }
801
+ model.methods.push(method);
802
+ methodDeclarations.set(node, method);
803
+ if (ts.isVariableDeclaration(parent))
804
+ methodDeclarations.set(parent, method);
805
+ api?.methods.push(id);
806
+ if (
807
+ kind === "Process" ||
808
+ (blocks.has(node) &&
809
+ pending.some(
810
+ (other) => other.node === node && other.kind === "Process",
811
+ ))
812
+ )
813
+ model.processes.push({ blockId: block.id, entryMethodId: id });
814
+ if (ts.isFunctionExpression(node) && !node.name)
815
+ problem(
816
+ node,
817
+ "Inline functions need a function name for matching runtime identity; use a named function expression",
818
+ );
819
+ }
820
+ // Bodies belong to declared boundaries, not files. Follow real typed helpers
821
+ // between those boundaries; keep helpers as evidence rather than inventing boxes.
822
+ const owners = new Map<ts.Node, string>();
823
+ for (const [node, method] of methodDeclarations) {
824
+ const process = model.processes.find((p) => p.entryMethodId === method.id);
825
+ owners.set(node, process?.blockId || method.id);
826
+ }
827
+ for (const [node, block] of blocks)
828
+ if (callable(node)) owners.set(node, block.id);
829
+ else if (ts.isObjectLiteralExpression(node)) owners.set(node, block.id);
830
+ else if (ts.isClassDeclaration(node)) {
831
+ // Public implementation belongs to the declared black box even when a
832
+ // forwarding method is not a separate mapped method. Private helpers are
833
+ // followed only when called; no extra cards or inferred file owners.
834
+ for (const member of node.members)
835
+ if (
836
+ (ts.isMethodDeclaration(member) ||
837
+ ts.isGetAccessorDeclaration(member) ||
838
+ ts.isSetAccessorDeclaration(member)) &&
839
+ !member.modifiers?.some((modifier) =>
840
+ [
841
+ ts.SyntaxKind.PrivateKeyword,
842
+ ts.SyntaxKind.ProtectedKeyword,
843
+ ts.SyntaxKind.StaticKeyword,
844
+ ].includes(modifier.kind),
845
+ ) &&
846
+ !(member.name && ts.isPrivateIdentifier(member.name)) &&
847
+ !owners.has(member)
848
+ ) {
849
+ // TypeScript public members are real callable contracts too. Preserve
850
+ // their exact signatures instead of representing them as calls to the
851
+ // owning box (or incorrectly treating them as constructor calls).
852
+ const name = `${ts.isGetAccessorDeclaration(member) ? "get:" : ts.isSetAccessorDeclaration(member) ? "set:" : ""}${member.name.getText()}`,
853
+ id = `${block.id}::public`;
854
+ const signature = checker.getSignatureFromDeclaration(member);
855
+ const method: FactoryMethod = {
856
+ id: `${id}#${name}`,
857
+ blockId: block.id,
858
+ interfaceId: id,
859
+ name,
860
+ source: source(member),
861
+ signature: signature
862
+ ? checker.signatureToString(
863
+ signature,
864
+ member,
865
+ ts.TypeFormatFlags.NoTruncation,
866
+ )
867
+ : member.getText().split("{")[0],
868
+ contract: {
869
+ args: member.parameters.map((parameter) => ({
870
+ name: parameter.name.getText(),
871
+ type: checker.typeToString(
872
+ checker.getTypeAtLocation(parameter),
873
+ parameter,
874
+ ts.TypeFormatFlags.NoTruncation,
875
+ ),
876
+ optional: !!parameter.questionToken || !!parameter.initializer,
877
+ rest: !!parameter.dotDotDotToken,
878
+ })),
879
+ result: signature
880
+ ? checker.typeToString(
881
+ checker.getReturnTypeOfSignature(signature),
882
+ member,
883
+ ts.TypeFormatFlags.NoTruncation,
884
+ )
885
+ : "unknown",
886
+ typeSources: typeSources(member),
887
+ runtimeValidation: false,
888
+ },
889
+ attachments: attachments(undefined, member),
890
+ };
891
+ const existing = model.interfaces.find((api) => api.id === id);
892
+ if (existing) existing.methods.push(method.id);
893
+ else
894
+ model.interfaces.push({
895
+ id,
896
+ blockId: block.id,
897
+ name: "public",
898
+ label: `${block.label} public API`,
899
+ source: source(member),
900
+ attachments: method.attachments,
901
+ methods: [method.id],
902
+ });
903
+ model.methods.push(method);
904
+ owners.set(member, method.id);
905
+ }
906
+ }
907
+ const bodyOf = (node: ts.Node | undefined): ts.Node | undefined => {
908
+ if (!node) return;
909
+ if (ts.isVariableDeclaration(node) && node.initializer) {
910
+ const value = node.initializer;
911
+ if (ts.isArrowFunction(value) || ts.isFunctionExpression(value))
912
+ return value;
913
+ if (ts.isCallExpression(value)) {
914
+ if (
915
+ ts.isCallExpression(value.expression) &&
916
+ annotation(value.expression)
917
+ )
918
+ return value.arguments[0];
919
+ // useCallback/useMemo and ordinary function factories retain inline bodies.
920
+ const callbacks = value.arguments.filter(
921
+ (arg) => ts.isArrowFunction(arg) || ts.isFunctionExpression(arg),
922
+ );
923
+ if (callbacks.length === 1) return callbacks[0];
924
+ }
925
+ }
926
+ return callable(node) ||
927
+ ts.isObjectLiteralExpression(node) ||
928
+ ts.isGetAccessorDeclaration(node) ||
929
+ ts.isSetAccessorDeclaration(node)
930
+ ? node
931
+ : undefined;
932
+ };
933
+ const local = (node: ts.Node) =>
934
+ !node.getSourceFile().isDeclarationFile &&
935
+ !node.getSourceFile().fileName.includes("node_modules") &&
936
+ !relative(root, node.getSourceFile().fileName).startsWith("..");
937
+ // Resolve parameter-property injection only from actual production constructor
938
+ // bindings. An interface's list of implementers is never evidence of a call.
939
+ const injected = new Map<
940
+ string,
941
+ Map<ts.ClassDeclaration | undefined, ts.Node[]>
942
+ >();
943
+ const fieldKey = (owner: ts.ClassDeclaration, name: string) =>
944
+ `${owner.getSourceFile().fileName}:${owner.pos}:${name}`;
945
+ const concreteClass = (
946
+ expression: ts.Expression,
947
+ ): ts.ClassDeclaration | undefined => {
948
+ let value = expression;
949
+ const declaration = resolvedNode(value);
950
+ if (
951
+ declaration &&
952
+ ts.isVariableDeclaration(declaration) &&
953
+ declaration.initializer &&
954
+ ts.isVariableDeclarationList(declaration.parent) &&
955
+ declaration.parent.flags & ts.NodeFlags.Const
956
+ )
957
+ value = declaration.initializer;
958
+ return checker
959
+ .getTypeAtLocation(value)
960
+ .getSymbol()
961
+ ?.declarations?.find(ts.isClassDeclaration);
962
+ };
963
+ for (const file of program.getSourceFiles().filter(local)) {
964
+ const collect = (node: ts.Node) => {
965
+ if (ts.isNewExpression(node)) {
966
+ const constructor = checker.getResolvedSignature(node)?.declaration;
967
+ if (
968
+ constructor &&
969
+ local(constructor) &&
970
+ ts.isConstructorDeclaration(constructor) &&
971
+ ts.isClassDeclaration(constructor.parent)
972
+ ) {
973
+ for (const [index, parameter] of constructor.parameters.entries()) {
974
+ if (
975
+ !ts.isIdentifier(parameter.name) ||
976
+ !parameter.modifiers?.some(
977
+ (modifier) => modifier.kind === ts.SyntaxKind.ReadonlyKeyword,
978
+ )
979
+ )
980
+ continue;
981
+ let reassigned = false;
982
+ const fieldName = parameter.name.text;
983
+ const checkWrites = (child: ts.Node) => {
984
+ if (
985
+ ts.isBinaryExpression(child) &&
986
+ child.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
987
+ child.operatorToken.kind <= ts.SyntaxKind.LastAssignment &&
988
+ ts.isPropertyAccessExpression(child.left) &&
989
+ child.left.expression.kind === ts.SyntaxKind.ThisKeyword &&
990
+ child.left.name.text === fieldName
991
+ )
992
+ reassigned = true;
993
+ ts.forEachChild(child, checkWrites);
994
+ };
995
+ checkWrites(constructor.parent);
996
+ if (reassigned) continue;
997
+ const argument = node.arguments?.[index] || parameter.initializer;
998
+ // An omitted optional dependency does not introduce an implementation.
999
+ if (!argument && parameter.questionToken) continue;
1000
+ const key = fieldKey(constructor.parent, parameter.name.text);
1001
+ const bindings = injected.get(key) || new Map();
1002
+ const implementation = argument
1003
+ ? concreteClass(argument)
1004
+ : undefined;
1005
+ bindings.set(implementation, [
1006
+ ...(bindings.get(implementation) || []),
1007
+ node,
1008
+ ]);
1009
+ injected.set(key, bindings);
1010
+ }
1011
+ }
1012
+ }
1013
+ ts.forEachChild(node, collect);
1014
+ };
1015
+ collect(file);
1016
+ }
1017
+ const injectionEvidence = new Map<ts.Node, SourceRef[]>();
1018
+ const readonlyBinding = (value: ts.Expression) => {
1019
+ if (
1020
+ !ts.isPropertyAccessExpression(value) ||
1021
+ value.expression.kind !== ts.SyntaxKind.ThisKeyword
1022
+ )
1023
+ return;
1024
+ let parent: ts.Node | undefined = value.parent;
1025
+ while (parent && !ts.isClassDeclaration(parent)) parent = parent.parent;
1026
+ return parent && ts.isClassDeclaration(parent)
1027
+ ? injected.get(fieldKey(parent, value.name.text))
1028
+ : undefined;
1029
+ };
1030
+ const parameterBindings = new Map<
1031
+ ts.ParameterDeclaration,
1032
+ Map<ts.ClassDeclaration | undefined, ts.Node[]>
1033
+ >();
1034
+ for (const file of program.getSourceFiles().filter(local)) {
1035
+ const collect = (node: ts.Node) => {
1036
+ if (ts.isCallExpression(node)) {
1037
+ const resolved = resolvedNode(node.expression),
1038
+ body = bodyOf(resolved);
1039
+ if (body && owners.has(body) && ts.isFunctionLike(body))
1040
+ for (const [index, parameter] of body.parameters.entries()) {
1041
+ if (!ts.isIdentifier(parameter.name)) continue;
1042
+ let reassigned = false;
1043
+ const check = (child: ts.Node) => {
1044
+ if (
1045
+ ts.isBinaryExpression(child) &&
1046
+ child.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
1047
+ child.operatorToken.kind <= ts.SyntaxKind.LastAssignment &&
1048
+ ts.isIdentifier(child.left) &&
1049
+ checker.getSymbolAtLocation(child.left) ===
1050
+ checker.getSymbolAtLocation(parameter.name)
1051
+ )
1052
+ reassigned = true;
1053
+ ts.forEachChild(child, check);
1054
+ };
1055
+ check(body);
1056
+ const argument = node.arguments[index] || parameter.initializer;
1057
+ if (!argument && parameter.questionToken) continue;
1058
+ const values = argument && readonlyBinding(argument);
1059
+ const bindings = parameterBindings.get(parameter) || new Map();
1060
+ if (!reassigned && values?.size === 1 && !values.has(undefined)) {
1061
+ const [implementation, sites] = [...values][0];
1062
+ bindings.set(implementation, [
1063
+ ...(bindings.get(implementation) || []),
1064
+ ...sites,
1065
+ node,
1066
+ ]);
1067
+ } else {
1068
+ const implementation =
1069
+ !reassigned && argument ? concreteClass(argument) : undefined;
1070
+ bindings.set(implementation, [
1071
+ ...(bindings.get(implementation) || []),
1072
+ node,
1073
+ ]);
1074
+ }
1075
+ parameterBindings.set(parameter, bindings);
1076
+ }
1077
+ }
1078
+ ts.forEachChild(node, collect);
1079
+ };
1080
+ collect(file);
1081
+ }
1082
+ const httpTargets = new Map<string, ts.Node>();
1083
+ const httpAppRoots = new Set<string>();
1084
+ for (const [node, method] of methodDeclarations) {
1085
+ const app = method.source.file.match(/^(.*?)(?:src\/)?app\/api\//)?.[1];
1086
+ const body = bodyOf(node);
1087
+ if (app !== undefined && method.endpoint && body) {
1088
+ httpAppRoots.add(app);
1089
+ httpTargets.set(
1090
+ `${app} ${method.endpoint.method} ${method.endpoint.path}`,
1091
+ body,
1092
+ );
1093
+ }
1094
+ }
1095
+ const httpCalls = new Map<ts.Node, { label: string }>();
1096
+ const sameOriginTarget = (
1097
+ expression: ts.Expression,
1098
+ call: ts.CallExpression,
1099
+ ) => {
1100
+ if (!ts.isIdentifier(expression) || expression.text !== "fetch") return;
1101
+ const value = checker.getSymbolAtLocation(expression);
1102
+ if (
1103
+ value &&
1104
+ (value.flags & ts.SymbolFlags.Alias || value.declarations?.some(local))
1105
+ )
1106
+ return;
1107
+ const app = [...httpAppRoots]
1108
+ .sort((a, b) => b.length - a.length)
1109
+ .find(
1110
+ (root) =>
1111
+ fileName(call).startsWith(root + "src/") ||
1112
+ fileName(call).startsWith(root + "app/"),
1113
+ );
1114
+ const url = call.arguments[0];
1115
+ if (
1116
+ app === undefined ||
1117
+ !url ||
1118
+ !ts.isStringLiteral(url) ||
1119
+ !url.text.startsWith("/api/")
1120
+ )
1121
+ return;
1122
+ const options = call.arguments[1];
1123
+ let method: string | undefined = !options ? "GET" : undefined;
1124
+ if (
1125
+ options &&
1126
+ ts.isObjectLiteralExpression(options) &&
1127
+ !options.properties.some(ts.isSpreadAssignment)
1128
+ ) {
1129
+ const member = property(options, "method");
1130
+ method = !member
1131
+ ? "GET"
1132
+ : ts.isStringLiteral(member)
1133
+ ? member.text.toUpperCase()
1134
+ : undefined;
1135
+ }
1136
+ if (!method) return;
1137
+ const path = url.text.split("?")[0],
1138
+ target = httpTargets.get(`${app} ${method} ${path}`);
1139
+ if (target) httpCalls.set(call, { label: `${method} ${path}` });
1140
+ return target;
1141
+ };
1142
+ const injectedTarget = (
1143
+ expression: ts.Expression,
1144
+ call: ts.CallExpression,
1145
+ ) => {
1146
+ if (!ts.isPropertyAccessExpression(expression)) return;
1147
+ const receiver = expression.expression;
1148
+ const parameter = ts.isIdentifier(receiver)
1149
+ ? checker.getSymbolAtLocation(receiver)?.valueDeclaration
1150
+ : undefined;
1151
+ const bindings =
1152
+ parameter && ts.isParameter(parameter)
1153
+ ? parameterBindings.get(parameter)
1154
+ : readonlyBinding(receiver);
1155
+ if (!bindings || bindings.size !== 1 || bindings.has(undefined)) return;
1156
+ const [implementation, sites] = [...bindings][0];
1157
+ const member =
1158
+ implementation?.name &&
1159
+ checker.getPropertyOfType(
1160
+ checker.getTypeAtLocation(implementation.name),
1161
+ expression.name.text,
1162
+ )?.valueDeclaration;
1163
+ const body = member && bodyOf(member);
1164
+ if (!body || !local(body)) return;
1165
+ injectionEvidence.set(call, sites.map(source));
1166
+ return body;
1167
+ };
1168
+ const callTarget = (expression: ts.Expression, call?: ts.CallExpression) => {
1169
+ const resolved = resolvedNode(expression);
1170
+ if (resolved && owners.has(resolved)) return resolved;
1171
+ const body = bodyOf(resolved);
1172
+ if (body && local(body)) return body;
1173
+ if (call) {
1174
+ const http = sameOriginTarget(expression, call);
1175
+ if (http) return http;
1176
+ const injectedBody = injectedTarget(expression, call);
1177
+ if (injectedBody) return injectedBody;
1178
+ const declaration = checker.getResolvedSignature(call)?.declaration;
1179
+ if (declaration && local(declaration)) return bodyOf(declaration);
1180
+ }
1181
+ };
1182
+ const shortType = (node: ts.Node) =>
1183
+ checker.typeToString(
1184
+ checker.getTypeAtLocation(node),
1185
+ node,
1186
+ ts.TypeFormatFlags.NoTruncation,
1187
+ );
1188
+ const seenEdges = new Set<string>();
1189
+ const add = (edge: FactoryModel["dependencies"][number]) => {
1190
+ if (edge.source === edge.target) return;
1191
+ const key = [
1192
+ edge.source,
1193
+ edge.target,
1194
+ edge.relation || "calls",
1195
+ edge.at.file,
1196
+ edge.at.line,
1197
+ edge.label || "",
1198
+ ].join("|");
1199
+ if (!seenEdges.has(key)) {
1200
+ seenEdges.add(key);
1201
+ model.dependencies.push(edge);
1202
+ }
1203
+ };
1204
+ const rootBodies = new Set<ts.Node>();
1205
+ const roots = [...owners].filter(([node]) => {
1206
+ const body = bodyOf(node);
1207
+ if (!body || rootBodies.has(body)) return false;
1208
+ rootBodies.add(body);
1209
+ return true;
1210
+ });
1211
+ for (const [entry, owner] of roots) {
1212
+ const visited = new Set<ts.Node>();
1213
+ let scanned = 0;
1214
+ const scan = (declaration: ts.Node, via: SourceRef[], depth: number) => {
1215
+ const fn = bodyOf(declaration);
1216
+ if (!fn || !local(fn) || visited.has(fn)) return;
1217
+ visited.add(fn);
1218
+ if (depth > 14 || ++scanned > 1600) {
1219
+ (model.interactionGaps ||= []).push({
1220
+ source: source(fn),
1221
+ expression: owner,
1222
+ reason:
1223
+ "Interaction traversal limit reached; no additional relationships were invented.",
1224
+ });
1225
+ return;
1226
+ }
1227
+ const follow = (
1228
+ target: ts.Node | undefined,
1229
+ at: ts.Node,
1230
+ relation: "calls" | "delegates" = "calls",
1231
+ ) => {
1232
+ if (!target) return;
1233
+ if (
1234
+ ts.isMethodDeclaration(target) &&
1235
+ target.modifiers?.some((modifier) =>
1236
+ [
1237
+ ts.SyntaxKind.PrivateKeyword,
1238
+ ts.SyntaxKind.ProtectedKeyword,
1239
+ ].includes(modifier.kind),
1240
+ )
1241
+ ) {
1242
+ const receiver = nearestBlock(target);
1243
+ // Access belongs to the lexical call site. A returned closure can
1244
+ // legally call its class's private helper even when an outside entry
1245
+ // caused us to traverse it; that caller does not own the closure body.
1246
+ let sender =
1247
+ nearestBlock(at)?.id ||
1248
+ model.methods.find((method) => method.id === owner)?.blockId ||
1249
+ model.interfaces.find((api) => api.id === owner)?.blockId ||
1250
+ owner;
1251
+ const seen = new Set<string>();
1252
+ while (receiver && sender !== receiver.id && !seen.has(sender)) {
1253
+ seen.add(sender);
1254
+ sender =
1255
+ model.blocks.find((block) => block.id === sender)?.parent || "";
1256
+ }
1257
+ if (receiver && sender !== receiver.id) {
1258
+ problem(
1259
+ at,
1260
+ `Private member ${target.name.getText()} cannot receive calls from outside ${receiver.label}; use its public interface.`,
1261
+ );
1262
+ return;
1263
+ }
1264
+ }
1265
+ const boundVia = [...via, ...(injectionEvidence.get(at) || [])];
1266
+ const boundary = owners.get(target);
1267
+ if (boundary) {
1268
+ const signature = ts.isCallExpression(at)
1269
+ ? checker.getResolvedSignature(at)
1270
+ : undefined;
1271
+ const exchange =
1272
+ signature && ts.isCallExpression(at)
1273
+ ? {
1274
+ inputs: at.arguments.map((arg, index) => ({
1275
+ name:
1276
+ signature.parameters[index]?.name || `arg${index + 1}`,
1277
+ type: shortType(arg),
1278
+ })),
1279
+ output: checker.typeToString(signature.getReturnType()),
1280
+ }
1281
+ : undefined;
1282
+ add({
1283
+ source: owner,
1284
+ target: boundary,
1285
+ ...(httpCalls.has(at)
1286
+ ? { label: httpCalls.get(at)!.label, transport: "HTTP" }
1287
+ : {}),
1288
+ ...(blocks.get(target)?.inputLabel
1289
+ ? { label: blocks.get(target)!.inputLabel }
1290
+ : {}),
1291
+ at: source(at),
1292
+ ...(relation !== "calls" ? { relation } : {}),
1293
+ ...(boundVia.length ? { via: boundVia } : {}),
1294
+ ...(exchange ? { exchange } : {}),
1295
+ });
1296
+ return;
1297
+ }
1298
+ if (local(target)) scan(target, [...boundVia, source(at)], depth + 1);
1299
+ };
1300
+ const visit = (child: ts.Node) => {
1301
+ if (
1302
+ ts.isObjectLiteralExpression(fn) &&
1303
+ (ts.isPropertyAssignment(child) ||
1304
+ ts.isShorthandPropertyAssignment(child))
1305
+ ) {
1306
+ const value = ts.isPropertyAssignment(child)
1307
+ ? child.initializer
1308
+ : child.name;
1309
+ const wrapped =
1310
+ ts.isCallExpression(value) &&
1311
+ ts.isCallExpression(value.expression) &&
1312
+ annotation(value.expression)
1313
+ ? value.arguments[0]
1314
+ : undefined;
1315
+ const target =
1316
+ wrapped ||
1317
+ (ts.isShorthandPropertyAssignment(child)
1318
+ ? checker.getShorthandAssignmentValueSymbol(child)
1319
+ ?.valueDeclaration
1320
+ : resolvedNode(value));
1321
+ const boundary = target && owners.get(target);
1322
+ if (boundary && boundary !== owner) {
1323
+ const path = [child.name.getText()];
1324
+ let parent: ts.Node | undefined = child.parent;
1325
+ while (parent && parent !== fn) {
1326
+ if (ts.isPropertyAssignment(parent))
1327
+ path.unshift(parent.name.getText());
1328
+ parent = parent.parent;
1329
+ }
1330
+ // This object exposes the supplied handler. It is registration
1331
+ // evidence, never a claim that the callback was invoked.
1332
+ add({
1333
+ source: owner,
1334
+ target: boundary,
1335
+ relation: "exposes",
1336
+ label: path.join("."),
1337
+ at: source(child.name),
1338
+ });
1339
+ }
1340
+ }
1341
+ if (child !== fn && owners.has(child)) return;
1342
+ if (
1343
+ (ts.isFunctionDeclaration(child) || ts.isMethodDeclaration(child)) &&
1344
+ child !== fn
1345
+ )
1346
+ return;
1347
+ if (
1348
+ child !== fn &&
1349
+ (ts.isArrowFunction(child) || ts.isFunctionExpression(child)) &&
1350
+ ts.isVariableDeclaration(child.parent)
1351
+ )
1352
+ return;
1353
+ if (
1354
+ ts.isJsxOpeningElement(child) ||
1355
+ ts.isJsxSelfClosingElement(child)
1356
+ ) {
1357
+ const target = callTarget(child.tagName as ts.Expression),
1358
+ boundary = target && owners.get(target);
1359
+ const attrs = child.attributes.properties.filter(ts.isJsxAttribute);
1360
+ if (boundary) {
1361
+ const values = attrs.filter(
1362
+ (attr) =>
1363
+ attr.name.getText() !== "key" && attr.name.getText() !== "ref",
1364
+ );
1365
+ const inputs = values
1366
+ .filter((attr) => !/^on[A-Z]/.test(attr.name.getText()))
1367
+ .map((attr) => ({
1368
+ name: attr.name.getText(),
1369
+ type:
1370
+ attr.initializer && ts.isStringLiteral(attr.initializer)
1371
+ ? "string"
1372
+ : attr.initializer &&
1373
+ ts.isJsxExpression(attr.initializer) &&
1374
+ attr.initializer.expression
1375
+ ? shortType(attr.initializer.expression)
1376
+ : "boolean",
1377
+ }));
1378
+ add({
1379
+ source: owner,
1380
+ target: boundary,
1381
+ relation: "renders",
1382
+ label:
1383
+ blocks.get(target!)?.inputLabel ||
1384
+ inputs
1385
+ .slice(0, 3)
1386
+ .map((input) => input.name)
1387
+ .join(" · ") ||
1388
+ "UI",
1389
+ exchange: { inputs },
1390
+ at: source(child),
1391
+ ...(via.length ? { via } : {}),
1392
+ });
1393
+ for (const attr of values.filter((attr) =>
1394
+ /^on[A-Z]/.test(attr.name.getText()),
1395
+ )) {
1396
+ if (
1397
+ !attr.initializer ||
1398
+ !ts.isJsxExpression(attr.initializer) ||
1399
+ !attr.initializer.expression
1400
+ )
1401
+ continue;
1402
+ const callback = attr.initializer.expression,
1403
+ signature = checker.getSignaturesOfType(
1404
+ checker.getTypeAtLocation(callback),
1405
+ ts.SignatureKind.Call,
1406
+ )[0];
1407
+ if (!signature) continue;
1408
+ // An actual callback is supplied here. This is a capability to call
1409
+ // back, not a claim that the callback ran or a fabricated sequence.
1410
+ add({
1411
+ source: boundary,
1412
+ target: owner,
1413
+ relation: "callbacks",
1414
+ label: attr.name.getText(),
1415
+ ...(blocks.get(target!)?.eventLabel
1416
+ ? { displayLabel: blocks.get(target!)!.eventLabel }
1417
+ : {}),
1418
+ exchange: {
1419
+ inputs: signature.parameters.map((p) => ({
1420
+ name: p.name,
1421
+ type: checker.typeToString(
1422
+ checker.getTypeOfSymbolAtLocation(p, callback),
1423
+ ),
1424
+ })),
1425
+ output: checker.typeToString(signature.getReturnType()),
1426
+ },
1427
+ at: source(attr),
1428
+ ...(via.length ? { via } : {}),
1429
+ });
1430
+ }
1431
+ } else if (target && local(target))
1432
+ scan(target, [...via, source(child)], depth + 1);
1433
+ }
1434
+ if (ts.isCallExpression(child)) {
1435
+ follow(callTarget(child.expression, child), child);
1436
+ // Callback registration is different from invocation (e.g. SWR fetchers).
1437
+ const signature = checker.getResolvedSignature(child);
1438
+ for (const [index, arg] of child.arguments.entries()) {
1439
+ const parameter =
1440
+ signature?.parameters[
1441
+ Math.min(index, signature.parameters.length - 1)
1442
+ ];
1443
+ const acceptsCallback = (type: ts.Type): boolean =>
1444
+ checker.getSignaturesOfType(
1445
+ checker.getNonNullableType(type),
1446
+ ts.SignatureKind.Call,
1447
+ ).length > 0 ||
1448
+ (type.isUnion() && type.types.some(acceptsCallback));
1449
+ if (
1450
+ !parameter ||
1451
+ !acceptsCallback(
1452
+ checker.getTypeOfSymbolAtLocation(parameter, child),
1453
+ )
1454
+ )
1455
+ continue;
1456
+ if (ts.isIdentifier(arg) || ts.isPropertyAccessExpression(arg)) {
1457
+ const target = callTarget(arg);
1458
+ if (target) follow(target, arg, "delegates");
1459
+ }
1460
+ }
1461
+ }
1462
+ ts.forEachChild(child, visit);
1463
+ };
1464
+ visit(fn);
1465
+ };
1466
+ scan(entry, [], 0);
1467
+ }
1468
+ for (const block of model.blocks) {
1469
+ const seen = new Set<string>();
1470
+ let current: FactoryBlock | undefined = block;
1471
+ while (current) {
1472
+ if (seen.has(current.id)) {
1473
+ problem(
1474
+ [...blocks].find(([, b]) => b.id === block.id)![0],
1475
+ `Ownership cycle at ${block.id}`,
1476
+ );
1477
+ break;
1478
+ }
1479
+ seen.add(current.id);
1480
+ current = model.blocks.find(
1481
+ (candidate) => candidate.id === current!.parent,
1482
+ );
1483
+ }
1484
+ }
1485
+ for (const collection of [model.blocks, model.interfaces, model.methods])
1486
+ collection.sort((a, b) => a.id.localeCompare(b.id));
1487
+ model.processes.sort((a, b) => a.blockId.localeCompare(b.blockId));
1488
+ for (const api of model.interfaces) api.methods.sort();
1489
+ model.dependencies.sort((a, b) =>
1490
+ `${a.source}:${a.target}:${a.at.line}`.localeCompare(
1491
+ `${b.source}:${b.target}:${b.at.line}`,
1492
+ ),
1493
+ );
1494
+ model.revision = digest(JSON.stringify({ ...model, revision: "" })).slice(
1495
+ 0,
1496
+ 16,
1497
+ );
1498
+ if (!model.diagnostics.length) {
1499
+ try {
1500
+ checkedFactoryGraph(model);
1501
+ } catch (error) {
1502
+ model.diagnostics.push({
1503
+ file: "<public interfaces>",
1504
+ line: 1,
1505
+ message: error instanceof Error ? error.message : String(error),
1506
+ });
1507
+ }
1508
+ }
1509
+ return model;
1510
+ }
1511
+
1512
+ export { factoryGraph } from "./factory-graph";