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