@webpieces/nx-webpieces-rules 0.4.831 → 0.4.833

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 (46) hide show
  1. package/package.json +8 -8
  2. package/src/executors/generate/executor.js +2 -0
  3. package/src/executors/generate/executor.js.map +1 -1
  4. package/src/executors/openapi-components-generate/executor.d.ts +2 -1
  5. package/src/executors/openapi-components-generate/executor.js +5 -2
  6. package/src/executors/openapi-components-generate/executor.js.map +1 -1
  7. package/src/executors/openapi-generate/executor.d.ts +15 -1
  8. package/src/executors/openapi-generate/executor.js +30 -2
  9. package/src/executors/openapi-generate/executor.js.map +1 -1
  10. package/src/executors/validate-api-lib-tag/executor.d.ts +5 -3
  11. package/src/executors/validate-api-lib-tag/executor.js +7 -5
  12. package/src/executors/validate-api-lib-tag/executor.js.map +1 -1
  13. package/src/executors/validate-architecture-unchanged/executor.js +2 -0
  14. package/src/executors/validate-architecture-unchanged/executor.js.map +1 -1
  15. package/src/lib/api-docs/components-wiring.d.ts +6 -0
  16. package/src/lib/api-docs/components-wiring.js +18 -1
  17. package/src/lib/api-docs/components-wiring.js.map +1 -1
  18. package/src/lib/api-usage/api-doc-rules-scan.d.ts +17 -1
  19. package/src/lib/api-usage/api-doc-rules-scan.js +28 -3
  20. package/src/lib/api-usage/api-doc-rules-scan.js.map +1 -1
  21. package/src/lib/api-usage/api-lib-tag-validator.d.ts +50 -14
  22. package/src/lib/api-usage/api-lib-tag-validator.js +189 -22
  23. package/src/lib/api-usage/api-lib-tag-validator.js.map +1 -1
  24. package/src/lib/api-usage/api-scanner.d.ts +3 -1
  25. package/src/lib/api-usage/api-scanner.js +6 -3
  26. package/src/lib/api-usage/api-scanner.js.map +1 -1
  27. package/src/lib/api-usage/wire-closure.d.ts +49 -0
  28. package/src/lib/api-usage/wire-closure.js +126 -0
  29. package/src/lib/api-usage/wire-closure.js.map +1 -0
  30. package/src/lib/di-graph/analyzer-strategy.d.ts +1 -0
  31. package/src/lib/di-graph/analyzer-strategy.js +3 -0
  32. package/src/lib/di-graph/analyzer-strategy.js.map +1 -1
  33. package/src/lib/framework-resolver.d.ts +1 -1
  34. package/src/lib/framework-resolver.js +5 -2
  35. package/src/lib/framework-resolver.js.map +1 -1
  36. package/src/lib/graph-metadata.d.ts +9 -2
  37. package/src/lib/graph-metadata.js +12 -3
  38. package/src/lib/graph-metadata.js.map +1 -1
  39. package/src/lib/graph-visualizer.js +6 -0
  40. package/src/lib/graph-visualizer.js.map +1 -1
  41. package/src/lib/role-resolver.d.ts +9 -3
  42. package/src/lib/role-resolver.js +12 -4
  43. package/src/lib/role-resolver.js.map +1 -1
  44. package/src/lib/tag-truth.d.ts +106 -0
  45. package/src/lib/tag-truth.js +323 -0
  46. package/src/lib/tag-truth.js.map +1 -0
@@ -2,36 +2,192 @@
2
2
  /**
3
3
  * API-lib tag validator (two-way)
4
4
  *
5
- * Keeps the `role:api-lib` tag and the CODE in sync, both directions:
6
- * - a project tagged `role:api-lib` MUST export ≥1 API contract (an `abstract class` carrying
7
- * `@ApiPath`/`@Rpc`/`@PubSub`) — else the tag is a lie;
8
- * - a project that DOES export such a contract MUST be tagged `role:api-lib` — else the arch
9
- * graph, the edge line-styles, and validate-api-relations can't treat it as an api-lib.
5
+ * Keeps the two api roles and the CODE in sync, both directions (#1064, D1 + D3):
6
+ * - a project that exports an `@ApiPath`/`@Rpc`/`@PubSub` contract (or a vendor contract under
7
+ * `externalApiPaths`) MUST be tagged `role:api-lib` or `role:api-client` — else the arch graph, the
8
+ * edge line-styles, and validate-api-relations can't treat it as one;
9
+ * - a project tagged `role:api-lib` MUST export a contract or ONLY wire types — else the tag is a lie.
10
+ * A contract is any of: an `@ApiPath`/`@Rpc`/`@PubSub` class (from the scan), an IPC contract
11
+ * (`@WpInternal` / `@WpIpcEndpoint`), or an in-process abstract `…Api` behind a DI token. A DTO-only
12
+ * library exports interfaces, type aliases, enums and data classes (no methods) and nothing else;
13
+ * - a project tagged `role:api-client` MUST export a contract (its abstract `XxxApi`) — the bundled
14
+ * `XxxClient` beside it is the point of the role, so it is not judged as a wire type.
10
15
  *
11
- * "Exports an API contract" is answered by the same source scan that owns apiRelations
12
- * (scan.apiLibProjects), so the tag can never drift from the code.
16
+ * "Exports an @ApiPath contract" is answered by the same source scan that owns apiRelations
17
+ * (scan.apiLibProjects), so the tag can never drift from the code. The IPC / in-process / DTO-only
18
+ * reading is a parser-only pass over the project's own non-test `src/**` — {@link ApiLibExportShape}.
13
19
  */
14
20
  Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.ApiLibExportShape = exports.ApiLibTagViolation = void 0;
15
22
  exports.findApiLibTagViolations = findApiLibTagViolations;
16
23
  exports.describeApiLibTagViolation = describeApiLibTagViolation;
24
+ const tslib_1 = require("tslib");
25
+ const fs = tslib_1.__importStar(require("fs"));
26
+ const path = tslib_1.__importStar(require("path"));
27
+ const ts = tslib_1.__importStar(require("typescript"));
17
28
  const role_resolver_1 = require("../role-resolver");
29
+ const api_ast_1 = require("./api-ast");
18
30
  const API_LIB_ROLE = 'api-lib';
19
- /** Both-directions tag ⇔ code check. Uses the scan's detected api-lib set as ground truth. */
31
+ const API_CLIENT_ROLE = 'api-client';
32
+ /** The decorators that make an abstract class an IPC contract. */
33
+ const IPC_DECORATORS = ['WpInternal', 'WpIpcEndpoint'];
34
+ /**
35
+ * A tag/code mismatch:
36
+ * - 'missing-tag' — exports an API contract but is tagged neither role:api-lib nor role:api-client.
37
+ * - 'unnecessary-tag' — tagged role:api-lib / role:api-client but exports no contract, and (for
38
+ * api-lib) is not a DTO-only library either; `offenders` names what it exports.
39
+ */
40
+ class ApiLibTagViolation {
41
+ project;
42
+ kind;
43
+ role;
44
+ offenders;
45
+ constructor(project, kind,
46
+ /** The role it carries (for 'unnecessary-tag'), else the role it should carry. */
47
+ role,
48
+ /** Exports that are neither a contract nor a wire type — empty for 'missing-tag'. */
49
+ offenders = []) {
50
+ this.project = project;
51
+ this.kind = kind;
52
+ this.role = role;
53
+ this.offenders = offenders;
54
+ }
55
+ }
56
+ exports.ApiLibTagViolation = ApiLibTagViolation;
57
+ /** What a library's own source exports, sorted into contracts, wire types and everything else. */
58
+ class ApiLibExportShape {
59
+ exportsContract;
60
+ exportsWireType;
61
+ offenders;
62
+ constructor(
63
+ /** True when it exports an IPC contract or an in-process abstract `…Api`. */
64
+ exportsContract,
65
+ /** True when it exports at least one wire type (interface, alias, enum, data class). */
66
+ exportsWireType,
67
+ /** `kind Name (file)` of every export that is neither — the implementation an api-lib must not hold. */
68
+ offenders) {
69
+ this.exportsContract = exportsContract;
70
+ this.exportsWireType = exportsWireType;
71
+ this.offenders = offenders;
72
+ }
73
+ /** A role:api-lib passes when it holds a contract or wire types, and nothing else. */
74
+ isApiLib() {
75
+ return (this.exportsContract || this.exportsWireType) && this.offenders.length === 0;
76
+ }
77
+ /** Parser-only: every top-level EXPORTED declaration in the project's non-test `src/**`. */
78
+ // webpieces-disable no-function-outside-class -- static factory of this class
79
+ static read(projectDir) {
80
+ const srcDir = path.join(projectDir, 'src');
81
+ const acc = new ExportShapeAccumulator(projectDir);
82
+ if (fs.existsSync(srcDir)) {
83
+ for (const file of (0, api_ast_1.collectTsFiles)(srcDir)) {
84
+ if ((0, api_ast_1.isTestFile)(file))
85
+ continue;
86
+ const source = ts.createSourceFile(file, fs.readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true);
87
+ for (const statement of source.statements)
88
+ acc.add(statement, file);
89
+ }
90
+ }
91
+ return acc.shape();
92
+ }
93
+ }
94
+ exports.ApiLibExportShape = ApiLibExportShape;
95
+ /** Sorts each exported statement of one library into contract / wire type / offender. */
96
+ class ExportShapeAccumulator {
97
+ projectDir;
98
+ contract = false;
99
+ wire = false;
100
+ offenders = [];
101
+ constructor(projectDir) {
102
+ this.projectDir = projectDir;
103
+ }
104
+ add(statement, file) {
105
+ if (!this.isExported(statement))
106
+ return;
107
+ const where = path.relative(this.projectDir, file);
108
+ if (ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement) || ts.isEnumDeclaration(statement)) {
109
+ this.wire = true;
110
+ }
111
+ else if (ts.isClassDeclaration(statement)) {
112
+ this.addClass(statement, where);
113
+ }
114
+ else if (ts.isVariableStatement(statement)) {
115
+ for (const decl of statement.declarationList.declarations) {
116
+ if (this.isDiToken(decl.initializer))
117
+ continue;
118
+ this.offenders.push(`const ${decl.name.getText()} (${where})`);
119
+ }
120
+ }
121
+ else if (ts.isFunctionDeclaration(statement)) {
122
+ this.offenders.push(`function ${statement.name?.text ?? '<default>'} (${where})`);
123
+ }
124
+ }
125
+ shape() {
126
+ return new ApiLibExportShape(this.contract, this.wire, [...this.offenders].sort());
127
+ }
128
+ addClass(cls, where) {
129
+ const name = cls.name?.text ?? '<default>';
130
+ const isAbstract = (ts.getModifiers(cls) ?? []).some((m) => m.kind === ts.SyntaxKind.AbstractKeyword);
131
+ if (isAbstract && (name.endsWith('Api') || this.carriesIpc(cls))) {
132
+ this.contract = true;
133
+ return;
134
+ }
135
+ const hasMethod = cls.members.some((member) => ts.isMethodDeclaration(member) &&
136
+ !(ts.getModifiers(member) ?? []).some((m) => m.kind === ts.SyntaxKind.StaticKeyword));
137
+ if (hasMethod)
138
+ this.offenders.push(`class ${name} (${where}) — it has methods, so it is an implementation`);
139
+ else
140
+ this.wire = true;
141
+ }
142
+ /** `@WpInternal(...)` on the class or `@WpIpcEndpoint(...)` on any member. */
143
+ carriesIpc(cls) {
144
+ const named = (node) => (ts.canHaveDecorators(node) ? (ts.getDecorators(node) ?? []) : []).some((d) => {
145
+ const expr = ts.isCallExpression(d.expression) ? d.expression.expression : d.expression;
146
+ const text = ts.isPropertyAccessExpression(expr) ? expr.name.text : expr.getText();
147
+ return IPC_DECORATORS.includes(text);
148
+ });
149
+ return named(cls) || cls.members.some((member) => named(member));
150
+ }
151
+ /** `Symbol('x')`, `Symbol.for('x')`, or an object literal of them — the token an abstract `…Api` binds behind. */
152
+ isDiToken(init) {
153
+ if (init === undefined)
154
+ return false;
155
+ const expr = ts.isAsExpression(init) || ts.isSatisfiesExpression(init) ? init.expression : init;
156
+ if (ts.isCallExpression(expr)) {
157
+ const callee = expr.expression.getText();
158
+ return callee === 'Symbol' || callee === 'Symbol.for';
159
+ }
160
+ if (ts.isObjectLiteralExpression(expr)) {
161
+ return expr.properties.length > 0 && expr.properties.every((prop) => ts.isPropertyAssignment(prop) && this.isDiToken(prop.initializer));
162
+ }
163
+ return false;
164
+ }
165
+ isExported(statement) {
166
+ if (!ts.canHaveModifiers(statement))
167
+ return false;
168
+ return (ts.getModifiers(statement) ?? []).some((m) => m.kind === ts.SyntaxKind.ExportKeyword);
169
+ }
170
+ }
171
+ /** Both-directions tag ⇔ code check. Uses the scan's detected api-lib set as ground truth for @ApiPath. */
20
172
  // webpieces-disable no-function-outside-class -- validator-lib entry point, matches api-relations-validator.ts
21
- function findApiLibTagViolations(projectInfos, scan) {
173
+ function findApiLibTagViolations(projectInfos, scan, workspaceRoot) {
22
174
  const violations = [];
23
175
  for (const projectName of projectInfos.keys()) {
24
176
  const info = projectInfos.get(projectName);
25
- const isTagged = (0, role_resolver_1.resolveRole)(info).role === API_LIB_ROLE;
177
+ const role = (0, role_resolver_1.resolveRole)(info).role;
178
+ const isApiRole = role === API_LIB_ROLE || role === API_CLIENT_ROLE;
26
179
  const exportsApi = scan.apiLibProjects.has(projectName);
27
- if (exportsApi && !isTagged) {
28
- violations.push({ project: projectName, kind: 'missing-tag' });
29
- }
30
- // Only flag an unnecessary tag when we actually SCANNED the project's source — otherwise we
31
- // can't prove it exports no contract (an unscannable project would falsely look empty).
32
- if (isTagged && !exportsApi && scan.scannedProjects.has(projectName)) {
33
- violations.push({ project: projectName, kind: 'unnecessary-tag' });
180
+ if (exportsApi && !isApiRole) {
181
+ violations.push(new ApiLibTagViolation(projectName, 'missing-tag', API_LIB_ROLE));
34
182
  }
183
+ // Only judge a tag when we actually SCANNED the project's source — otherwise we can't prove it
184
+ // exports no contract (an unscannable project would falsely look empty).
185
+ if (!isApiRole || exportsApi || !scan.scannedProjects.has(projectName))
186
+ continue;
187
+ const shape = ApiLibExportShape.read(path.resolve(workspaceRoot, info.root));
188
+ const ok = role === API_CLIENT_ROLE ? shape.exportsContract : shape.isApiLib();
189
+ if (!ok)
190
+ violations.push(new ApiLibTagViolation(projectName, 'unnecessary-tag', role, shape.offenders));
35
191
  }
36
192
  return violations.sort((a, b) => a.project.localeCompare(b.project));
37
193
  }
@@ -40,11 +196,22 @@ function findApiLibTagViolations(projectInfos, scan) {
40
196
  function describeApiLibTagViolation(violation) {
41
197
  if (violation.kind === 'missing-tag') {
42
198
  return (` ❌ '${violation.project}' exports an API contract (an abstract @ApiPath/@Rpc/@PubSub class) ` +
43
- `but is not tagged 'role:api-lib'.\n` +
44
- ` Add "role:api-lib" to its project.json "tags" (replacing any "role:lib").`);
199
+ `but is tagged neither 'role:api-lib' nor 'role:api-client'.\n` +
200
+ ` Add "role:api-lib" to its project.json "tags" (replacing any "role:lib"), or "role:api-client" ` +
201
+ `when it also bundles the default implementation that talks to an outside system.`);
202
+ }
203
+ if (violation.role === API_CLIENT_ROLE) {
204
+ return (` ❌ '${violation.project}' is tagged 'role:api-client' but exports NO contract (no abstract ` +
205
+ `…Api class, no @WpInternal/@WpIpcEndpoint contract).\n` +
206
+ ` An api-client is a contract PLUS its default implementation: export the abstract XxxApi it ` +
207
+ `implements, or retag it (e.g. "role:lib").`);
45
208
  }
46
- return (` ❌ '${violation.project}' is tagged 'role:api-lib' but exports NO API contract ` +
47
- `(no abstract @ApiPath/@Rpc/@PubSub class).\n` +
48
- ` Either add the API contract it should own, or retag it (e.g. "role:lib").`);
209
+ const offenders = violation.offenders.length === 0
210
+ ? ''
211
+ : `\n It exports, besides contracts and wire types: ${violation.offenders.join('; ')}.`;
212
+ return (` ❌ '${violation.project}' is tagged 'role:api-lib' but is neither a contract library (@ApiPath/@Rpc/` +
213
+ `@PubSub, @WpInternal/@WpIpcEndpoint, or an abstract …Api behind a DI token) nor a DTO-only library ` +
214
+ `(interfaces, type aliases, enums and data classes only).${offenders}\n` +
215
+ ` Move the implementation out to a role:lib / role:designed-lib project, or retag it.`);
49
216
  }
50
217
  //# sourceMappingURL=api-lib-tag-validator.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"api-lib-tag-validator.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/lib/api-usage/api-lib-tag-validator.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;GAWG;;AAoBH,0DAoBC;AAID,gEAaC;AAtDD,oDAA+C;AAG/C,MAAM,YAAY,GAAG,SAAS,CAAC;AAY/B,8FAA8F;AAC9F,+GAA+G;AAC/G,SAAgB,uBAAuB,CACnC,YAAsC,EACtC,IAAmB;IAEnB,MAAM,UAAU,GAAyB,EAAE,CAAC;IAC5C,KAAK,MAAM,WAAW,IAAI,YAAY,CAAC,IAAI,EAAE,EAAE,CAAC;QAC5C,MAAM,IAAI,GAAG,YAAY,CAAC,GAAG,CAAC,WAAW,CAAE,CAAC;QAC5C,MAAM,QAAQ,GAAG,IAAA,2BAAW,EAAC,IAAI,CAAC,CAAC,IAAI,KAAK,YAAY,CAAC;QACzD,MAAM,UAAU,GAAG,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;QAExD,IAAI,UAAU,IAAI,CAAC,QAAQ,EAAE,CAAC;YAC1B,UAAU,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,WAAW,EAAE,IAAI,EAAE,aAAa,EAAE,CAAC,CAAC;QACnE,CAAC;QACD,4FAA4F;QAC5F,wFAAwF;QACxF,IAAI,QAAQ,IAAI,CAAC,UAAU,IAAI,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;YACnE,UAAU,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,WAAW,EAAE,IAAI,EAAE,iBAAiB,EAAE,CAAC,CAAC;QACvE,CAAC;IACL,CAAC;IACD,OAAO,UAAU,CAAC,IAAI,CAAC,CAAC,CAAqB,EAAE,CAAqB,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC;AACjH,CAAC;AAED,qEAAqE;AACrE,oGAAoG;AACpG,SAAgB,0BAA0B,CAAC,SAA6B;IACpE,IAAI,SAAS,CAAC,IAAI,KAAK,aAAa,EAAE,CAAC;QACnC,OAAO,CACH,QAAQ,SAAS,CAAC,OAAO,sEAAsE;YAC/F,qCAAqC;YACrC,gFAAgF,CACnF,CAAC;IACN,CAAC;IACD,OAAO,CACH,QAAQ,SAAS,CAAC,OAAO,yDAAyD;QAClF,8CAA8C;QAC9C,gFAAgF,CACnF,CAAC;AACN,CAAC","sourcesContent":["/**\n * API-lib tag validator (two-way)\n *\n * Keeps the `role:api-lib` tag and the CODE in sync, both directions:\n * - a project tagged `role:api-lib` MUST export ≥1 API contract (an `abstract class` carrying\n * `@ApiPath`/`@Rpc`/`@PubSub`) — else the tag is a lie;\n * - a project that DOES export such a contract MUST be tagged `role:api-lib` — else the arch\n * graph, the edge line-styles, and validate-api-relations can't treat it as an api-lib.\n *\n * \"Exports an API contract\" is answered by the same source scan that owns apiRelations\n * (scan.apiLibProjects), so the tag can never drift from the code.\n */\n\nimport { ProjectInfo } from '../project-info';\nimport { resolveRole } from '../role-resolver';\nimport { ApiScanResult } from './api-scanner';\n\nconst API_LIB_ROLE = 'api-lib';\n\n/**\n * A tag/code mismatch:\n * - 'missing-tag' — exports an API contract but is not tagged role:api-lib.\n * - 'unnecessary-tag' — tagged role:api-lib but exports no API contract.\n */\nexport interface ApiLibTagViolation {\n project: string;\n kind: 'missing-tag' | 'unnecessary-tag';\n}\n\n/** Both-directions tag ⇔ code check. Uses the scan's detected api-lib set as ground truth. */\n// webpieces-disable no-function-outside-class -- validator-lib entry point, matches api-relations-validator.ts\nexport function findApiLibTagViolations(\n projectInfos: Map<string, ProjectInfo>,\n scan: ApiScanResult,\n): ApiLibTagViolation[] {\n const violations: ApiLibTagViolation[] = [];\n for (const projectName of projectInfos.keys()) {\n const info = projectInfos.get(projectName)!;\n const isTagged = resolveRole(info).role === API_LIB_ROLE;\n const exportsApi = scan.apiLibProjects.has(projectName);\n\n if (exportsApi && !isTagged) {\n violations.push({ project: projectName, kind: 'missing-tag' });\n }\n // Only flag an unnecessary tag when we actually SCANNED the project's source — otherwise we\n // can't prove it exports no contract (an unscannable project would falsely look empty).\n if (isTagged && !exportsApi && scan.scannedProjects.has(projectName)) {\n violations.push({ project: projectName, kind: 'unnecessary-tag' });\n }\n }\n return violations.sort((a: ApiLibTagViolation, b: ApiLibTagViolation) => a.project.localeCompare(b.project));\n}\n\n/** Human-readable, fix-oriented report for one tag/code mismatch. */\n// webpieces-disable no-function-outside-class -- pure formatter, matches api-relations-validator.ts\nexport function describeApiLibTagViolation(violation: ApiLibTagViolation): string {\n if (violation.kind === 'missing-tag') {\n return (\n ` ❌ '${violation.project}' exports an API contract (an abstract @ApiPath/@Rpc/@PubSub class) ` +\n `but is not tagged 'role:api-lib'.\\n` +\n ` Add \"role:api-lib\" to its project.json \"tags\" (replacing any \"role:lib\").`\n );\n }\n return (\n ` ❌ '${violation.project}' is tagged 'role:api-lib' but exports NO API contract ` +\n `(no abstract @ApiPath/@Rpc/@PubSub class).\\n` +\n ` Either add the API contract it should own, or retag it (e.g. \"role:lib\").`\n );\n}\n"]}
1
+ {"version":3,"file":"api-lib-tag-validator.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/lib/api-usage/api-lib-tag-validator.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;GAiBG;;;AAkJH,0DAuBC;AAID,gEA2BC;;AAtMD,+CAAyB;AACzB,mDAA6B;AAC7B,uDAAiC;AAEjC,oDAA+C;AAE/C,uCAAuD;AAEvD,MAAM,YAAY,GAAG,SAAS,CAAC;AAC/B,MAAM,eAAe,GAAG,YAAY,CAAC;AAErC,kEAAkE;AAClE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B,CAAC,SAA6B;IACpE,IAAI,SAAS,CAAC,IAAI,KAAK,aAAa,EAAE,CAAC;QACnC,OAAO,CACH,QAAQ,SAAS,CAAC,OAAO,sEAAsE;YAC/F,+DAA+D;YAC/D,sGAAsG;YACtG,kFAAkF,CACrF,CAAC;IACN,CAAC;IACD,IAAI,SAAS,CAAC,IAAI,KAAK,eAAe,EAAE,CAAC;QACrC,OAAO,CACH,QAAQ,SAAS,CAAC,OAAO,qEAAqE;YAC9F,wDAAwD;YACxD,kGAAkG;YAClG,4CAA4C,CAC/C,CAAC;IACN,CAAC;IACD,MAAM,SAAS,GACX,SAAS,CAAC,SAAS,CAAC,MAAM,KAAK,CAAC;QAC5B,CAAC,CAAC,EAAE;QACJ,CAAC,CAAC,wDAAwD,SAAS,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC;IACpG,OAAO,CACH,QAAQ,SAAS,CAAC,OAAO,8EAA8E;QACvG,qGAAqG;QACrG,2DAA2D,SAAS,IAAI;QACxE,0FAA0F,CAC7F,CAAC;AACN,CAAC","sourcesContent":["/**\n * API-lib tag validator (two-way)\n *\n * Keeps the two api roles and the CODE in sync, both directions (#1064, D1 + D3):\n * - a project that exports an `@ApiPath`/`@Rpc`/`@PubSub` contract (or a vendor contract under\n * `externalApiPaths`) MUST be tagged `role:api-lib` or `role:api-client` — else the arch graph, the\n * edge line-styles, and validate-api-relations can't treat it as one;\n * - a project tagged `role:api-lib` MUST export a contract or ONLY wire types — else the tag is a lie.\n * A contract is any of: an `@ApiPath`/`@Rpc`/`@PubSub` class (from the scan), an IPC contract\n * (`@WpInternal` / `@WpIpcEndpoint`), or an in-process abstract `…Api` behind a DI token. A DTO-only\n * library exports interfaces, type aliases, enums and data classes (no methods) and nothing else;\n * - a project tagged `role:api-client` MUST export a contract (its abstract `XxxApi`) — the bundled\n * `XxxClient` beside it is the point of the role, so it is not judged as a wire type.\n *\n * \"Exports an @ApiPath contract\" is answered by the same source scan that owns apiRelations\n * (scan.apiLibProjects), so the tag can never drift from the code. The IPC / in-process / DTO-only\n * reading is a parser-only pass over the project's own non-test `src/**` — {@link ApiLibExportShape}.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as ts from 'typescript';\nimport { ProjectInfo } from '../project-info';\nimport { resolveRole } from '../role-resolver';\nimport { ApiScanResult } from './api-scanner';\nimport { collectTsFiles, isTestFile } from './api-ast';\n\nconst API_LIB_ROLE = 'api-lib';\nconst API_CLIENT_ROLE = 'api-client';\n\n/** The decorators that make an abstract class an IPC contract. */\nconst IPC_DECORATORS: readonly string[] = ['WpInternal', 'WpIpcEndpoint'];\n\n/**\n * A tag/code mismatch:\n * - 'missing-tag' — exports an API contract but is tagged neither role:api-lib nor role:api-client.\n * - 'unnecessary-tag' — tagged role:api-lib / role:api-client but exports no contract, and (for\n * api-lib) is not a DTO-only library either; `offenders` names what it exports.\n */\nexport class ApiLibTagViolation {\n constructor(\n public readonly project: string,\n public readonly kind: 'missing-tag' | 'unnecessary-tag',\n /** The role it carries (for 'unnecessary-tag'), else the role it should carry. */\n public readonly role: string,\n /** Exports that are neither a contract nor a wire type — empty for 'missing-tag'. */\n public readonly offenders: readonly string[] = [],\n ) {}\n}\n\n/** What a library's own source exports, sorted into contracts, wire types and everything else. */\nexport class ApiLibExportShape {\n constructor(\n /** True when it exports an IPC contract or an in-process abstract `…Api`. */\n public readonly exportsContract: boolean,\n /** True when it exports at least one wire type (interface, alias, enum, data class). */\n public readonly exportsWireType: boolean,\n /** `kind Name (file)` of every export that is neither — the implementation an api-lib must not hold. */\n public readonly offenders: readonly string[],\n ) {}\n\n /** A role:api-lib passes when it holds a contract or wire types, and nothing else. */\n isApiLib(): boolean {\n return (this.exportsContract || this.exportsWireType) && this.offenders.length === 0;\n }\n\n /** Parser-only: every top-level EXPORTED declaration in the project's non-test `src/**`. */\n // webpieces-disable no-function-outside-class -- static factory of this class\n static read(projectDir: string): ApiLibExportShape {\n const srcDir = path.join(projectDir, 'src');\n const acc = new ExportShapeAccumulator(projectDir);\n if (fs.existsSync(srcDir)) {\n for (const file of collectTsFiles(srcDir)) {\n if (isTestFile(file)) continue;\n const source = ts.createSourceFile(file, fs.readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true);\n for (const statement of source.statements) acc.add(statement, file);\n }\n }\n return acc.shape();\n }\n}\n\n/** Sorts each exported statement of one library into contract / wire type / offender. */\nclass ExportShapeAccumulator {\n private contract = false;\n private wire = false;\n private readonly offenders: string[] = [];\n\n constructor(private readonly projectDir: string) {}\n\n add(statement: ts.Statement, file: string): void {\n if (!this.isExported(statement)) return;\n const where = path.relative(this.projectDir, file);\n if (ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement) || ts.isEnumDeclaration(statement)) {\n this.wire = true;\n } else if (ts.isClassDeclaration(statement)) {\n this.addClass(statement, where);\n } else if (ts.isVariableStatement(statement)) {\n for (const decl of statement.declarationList.declarations) {\n if (this.isDiToken(decl.initializer)) continue;\n this.offenders.push(`const ${decl.name.getText()} (${where})`);\n }\n } else if (ts.isFunctionDeclaration(statement)) {\n this.offenders.push(`function ${statement.name?.text ?? '<default>'} (${where})`);\n }\n }\n\n shape(): ApiLibExportShape {\n return new ApiLibExportShape(this.contract, this.wire, [...this.offenders].sort());\n }\n\n private addClass(cls: ts.ClassDeclaration, where: string): void {\n const name = cls.name?.text ?? '<default>';\n const isAbstract = (ts.getModifiers(cls) ?? []).some((m: ts.Modifier) => m.kind === ts.SyntaxKind.AbstractKeyword);\n if (isAbstract && (name.endsWith('Api') || this.carriesIpc(cls))) {\n this.contract = true;\n return;\n }\n const hasMethod = cls.members.some(\n (member: ts.ClassElement) =>\n ts.isMethodDeclaration(member) &&\n !(ts.getModifiers(member) ?? []).some((m: ts.Modifier) => m.kind === ts.SyntaxKind.StaticKeyword),\n );\n if (hasMethod) this.offenders.push(`class ${name} (${where}) — it has methods, so it is an implementation`);\n else this.wire = true;\n }\n\n /** `@WpInternal(...)` on the class or `@WpIpcEndpoint(...)` on any member. */\n private carriesIpc(cls: ts.ClassDeclaration): boolean {\n const named = (node: ts.Node): boolean =>\n (ts.canHaveDecorators(node) ? (ts.getDecorators(node) ?? []) : []).some((d: ts.Decorator) => {\n const expr = ts.isCallExpression(d.expression) ? d.expression.expression : d.expression;\n const text = ts.isPropertyAccessExpression(expr) ? expr.name.text : expr.getText();\n return IPC_DECORATORS.includes(text);\n });\n return named(cls) || cls.members.some((member: ts.ClassElement) => named(member));\n }\n\n /** `Symbol('x')`, `Symbol.for('x')`, or an object literal of them — the token an abstract `…Api` binds behind. */\n private isDiToken(init: ts.Expression | undefined): boolean {\n if (init === undefined) return false;\n const expr = ts.isAsExpression(init) || ts.isSatisfiesExpression(init) ? init.expression : init;\n if (ts.isCallExpression(expr)) {\n const callee = expr.expression.getText();\n return callee === 'Symbol' || callee === 'Symbol.for';\n }\n if (ts.isObjectLiteralExpression(expr)) {\n return expr.properties.length > 0 && expr.properties.every(\n (prop: ts.ObjectLiteralElementLike) =>\n ts.isPropertyAssignment(prop) && this.isDiToken(prop.initializer),\n );\n }\n return false;\n }\n\n private isExported(statement: ts.Statement): boolean {\n if (!ts.canHaveModifiers(statement)) return false;\n return (ts.getModifiers(statement) ?? []).some((m: ts.Modifier) => m.kind === ts.SyntaxKind.ExportKeyword);\n }\n}\n\n/** Both-directions tag ⇔ code check. Uses the scan's detected api-lib set as ground truth for @ApiPath. */\n// webpieces-disable no-function-outside-class -- validator-lib entry point, matches api-relations-validator.ts\nexport function findApiLibTagViolations(\n projectInfos: Map<string, ProjectInfo>,\n scan: ApiScanResult,\n workspaceRoot: string,\n): ApiLibTagViolation[] {\n const violations: ApiLibTagViolation[] = [];\n for (const projectName of projectInfos.keys()) {\n const info = projectInfos.get(projectName)!;\n const role = resolveRole(info).role;\n const isApiRole = role === API_LIB_ROLE || role === API_CLIENT_ROLE;\n const exportsApi = scan.apiLibProjects.has(projectName);\n\n if (exportsApi && !isApiRole) {\n violations.push(new ApiLibTagViolation(projectName, 'missing-tag', API_LIB_ROLE));\n }\n // Only judge a tag when we actually SCANNED the project's source — otherwise we can't prove it\n // exports no contract (an unscannable project would falsely look empty).\n if (!isApiRole || exportsApi || !scan.scannedProjects.has(projectName)) continue;\n const shape = ApiLibExportShape.read(path.resolve(workspaceRoot, info.root));\n const ok = role === API_CLIENT_ROLE ? shape.exportsContract : shape.isApiLib();\n if (!ok) violations.push(new ApiLibTagViolation(projectName, 'unnecessary-tag', role, shape.offenders));\n }\n return violations.sort((a: ApiLibTagViolation, b: ApiLibTagViolation) => a.project.localeCompare(b.project));\n}\n\n/** Human-readable, fix-oriented report for one tag/code mismatch. */\n// webpieces-disable no-function-outside-class -- pure formatter, matches api-relations-validator.ts\nexport function describeApiLibTagViolation(violation: ApiLibTagViolation): string {\n if (violation.kind === 'missing-tag') {\n return (\n ` ❌ '${violation.project}' exports an API contract (an abstract @ApiPath/@Rpc/@PubSub class) ` +\n `but is tagged neither 'role:api-lib' nor 'role:api-client'.\\n` +\n ` Add \"role:api-lib\" to its project.json \"tags\" (replacing any \"role:lib\"), or \"role:api-client\" ` +\n `when it also bundles the default implementation that talks to an outside system.`\n );\n }\n if (violation.role === API_CLIENT_ROLE) {\n return (\n ` ❌ '${violation.project}' is tagged 'role:api-client' but exports NO contract (no abstract ` +\n `…Api class, no @WpInternal/@WpIpcEndpoint contract).\\n` +\n ` An api-client is a contract PLUS its default implementation: export the abstract XxxApi it ` +\n `implements, or retag it (e.g. \"role:lib\").`\n );\n }\n const offenders =\n violation.offenders.length === 0\n ? ''\n : `\\n It exports, besides contracts and wire types: ${violation.offenders.join('; ')}.`;\n return (\n ` ❌ '${violation.project}' is tagged 'role:api-lib' but is neither a contract library (@ApiPath/@Rpc/` +\n `@PubSub, @WpInternal/@WpIpcEndpoint, or an abstract …Api behind a DI token) nor a DTO-only library ` +\n `(interfaces, type aliases, enums and data classes only).${offenders}\\n` +\n ` Move the implementation out to a role:lib / role:designed-lib project, or retag it.`\n );\n}\n"]}
@@ -32,6 +32,7 @@ import { ProjectInfo } from '../project-info';
32
32
  import { ApiClassInfo, ApiContracts, EmptiedApiContract, NonLiteralDecoratorArg, ProjectApiRelations, UndeclaredExternalCaller, UndeclaredEndpointOperation, UnresolvedApiCall, UnresolvedEndpointPath } from './api-relations';
33
33
  import { RootUnionFindings, RootUnionRule } from './root-union-scan';
34
34
  import { ApiDocRule, ApiDocRulesFindings } from './api-doc-rules';
35
+ import { WireClosureRule } from './wire-closure';
35
36
  /** The whole-workspace result of a scan. */
36
37
  export interface ApiScanResult {
37
38
  /** projectName -> { apiLibProject -> relation }; only projects with ≥1 relation appear. */
@@ -95,6 +96,7 @@ export declare class ApiUsageScanner {
95
96
  private readonly openApiRule;
96
97
  /** `api-rules-for-mcp`'s switches — read from the config, which MUST state them (#1017). */
97
98
  private readonly mcpRule;
99
+ private readonly wireClosureRule;
98
100
  private readonly locator;
99
101
  private readonly relationsByProject;
100
102
  private readonly scannedProjects;
@@ -109,7 +111,7 @@ export declare class ApiUsageScanner {
109
111
  /** `api-rules-for-openapi`'s switches — read from the config, which MUST state them (#1017). */
110
112
  openApiRule?: ApiDocRule,
111
113
  /** `api-rules-for-mcp`'s switches — read from the config, which MUST state them (#1017). */
112
- mcpRule?: ApiDocRule);
114
+ mcpRule?: ApiDocRule, wireClosureRule?: WireClosureRule);
113
115
  scan(): ApiScanResult;
114
116
  private scanProject;
115
117
  private visit;
@@ -46,6 +46,7 @@ const api_contract_errors_1 = require("./api-contract-errors");
46
46
  const root_union_scan_1 = require("./root-union-scan");
47
47
  const api_doc_rules_1 = require("./api-doc-rules");
48
48
  const api_doc_rules_scan_1 = require("./api-doc-rules-scan");
49
+ const wire_closure_1 = require("./wire-closure");
49
50
  const api_ast_1 = require("./api-ast");
50
51
  const RPC_CLIENT_METHOD = 'createRpcClient';
51
52
  const PUBSUB_CLIENT_METHOD = 'createPubSubClient';
@@ -210,6 +211,7 @@ class ApiUsageScanner {
210
211
  rootUnionRule;
211
212
  openApiRule;
212
213
  mcpRule;
214
+ wireClosureRule;
213
215
  locator;
214
216
  relationsByProject = new Map();
215
217
  scannedProjects = new Set();
@@ -224,13 +226,14 @@ class ApiUsageScanner {
224
226
  /** `api-rules-for-openapi`'s switches — read from the config, which MUST state them (#1017). */
225
227
  openApiRule = api_doc_rules_1.ApiDocRule.off(api_doc_rules_1.OPENAPI_RULE),
226
228
  /** `api-rules-for-mcp`'s switches — read from the config, which MUST state them (#1017). */
227
- mcpRule = api_doc_rules_1.ApiDocRule.off(api_doc_rules_1.MCP_RULE)) {
229
+ mcpRule = api_doc_rules_1.ApiDocRule.off(api_doc_rules_1.MCP_RULE), wireClosureRule = wire_closure_1.WireClosureRule.withoutSuffixes()) {
228
230
  this.workspaceRoot = workspaceRoot;
229
231
  this.projectInfos = projectInfos;
230
232
  this.externalApiPaths = externalApiPaths;
231
233
  this.rootUnionRule = rootUnionRule;
232
234
  this.openApiRule = openApiRule;
233
235
  this.mcpRule = mcpRule;
236
+ this.wireClosureRule = wireClosureRule;
234
237
  this.locator = new ProjectLocator(workspaceRoot, projectInfos);
235
238
  this.decoratorArgDiagnostics = new api_ast_1.DecoratorArgDiagnostics(workspaceRoot);
236
239
  }
@@ -255,7 +258,7 @@ class ApiUsageScanner {
255
258
  undeclaredExternalCallers: this.decoratorArgDiagnostics.undeclaredExternalCallers(),
256
259
  undeclaredEndpointOperations: this.decoratorArgDiagnostics.undeclaredEndpointOperations(),
257
260
  rootUnions: new root_union_scan_1.RootUnionScan(this.workspaceRoot, this.projectInfos, this.rootUnionRule).run(),
258
- apiDocRules: new api_doc_rules_scan_1.ApiDocRulesScan(this.workspaceRoot, this.projectInfos, this.openApiRule, this.mcpRule).run(),
261
+ apiDocRules: new api_doc_rules_scan_1.ApiDocRulesScan(this.workspaceRoot, this.projectInfos, this.openApiRule, this.mcpRule, this.wireClosureRule).run(),
259
262
  };
260
263
  }
261
264
  scanProject(info) {
@@ -400,7 +403,7 @@ exports.ApiUsageScanner = ApiUsageScanner;
400
403
  */
401
404
  // webpieces-disable no-function-outside-class -- module entry point, mirrors generateReducedGraph/collectBindings
402
405
  function scanAndAttachApiRelations(workspaceRoot, graph, projectInfos, externalApiPaths = []) {
403
- const result = new ApiUsageScanner(workspaceRoot, projectInfos, externalApiPaths, root_union_scan_1.RootUnionRule.fromConfig(workspaceRoot), api_doc_rules_1.ApiDocRule.fromConfig(workspaceRoot, api_doc_rules_1.OPENAPI_RULE), api_doc_rules_1.ApiDocRule.fromConfig(workspaceRoot, api_doc_rules_1.MCP_RULE)).scan();
406
+ const result = new ApiUsageScanner(workspaceRoot, projectInfos, externalApiPaths, root_union_scan_1.RootUnionRule.fromConfig(workspaceRoot), api_doc_rules_1.ApiDocRule.fromConfig(workspaceRoot, api_doc_rules_1.OPENAPI_RULE), api_doc_rules_1.ApiDocRule.fromConfig(workspaceRoot, api_doc_rules_1.MCP_RULE), wire_closure_1.WireClosureRule.fromConfig(workspaceRoot)).scan();
404
407
  for (const projectName of result.relationsByProject.keys()) {
405
408
  const entry = graph[projectName];
406
409
  if (entry)
@@ -1 +1 @@
1
- {"version":3,"file":"api-scanner.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/lib/api-usage/api-scanner.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;;;AA2eH,8DAmBC;AAuBD,8CA8CC;AAUD,0EAgBC;AASD,0EAmBC;;AAvnBD,uDAAiC;AACjC,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAyD;AAGzD,iDAA0D;AAC1D,mDAA+D;AAC/D,mDAiByB;AACzB,+DAS+B;AAC/B,uDAAoF;AACpF,mDAA0F;AAC1F,6DAAuD;AACvD,uCAamB;AAEnB,MAAM,iBAAiB,GAAG,iBAAiB,CAAC;AAC5C,MAAM,oBAAoB,GAAG,oBAAoB,CAAC;AAClD,MAAM,iBAAiB,GAAG,WAAW,CAAC;AAsDtC,qGAAqG;AACrG,MAAM,cAAc;IACC,KAAK,CAAgB;I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AC,CAAC,CAAC,IAAI,CAAC;AACtE,CAAC","sourcesContent":["/**\n * API Usage Scanner\n *\n * Derives, by scanning real source (not a declaration file), how every project\n * relates to the api-lib projects it depends on. This is the single source of\n * truth for the `apiRelations` field in architecture/dependencies.json AND for\n * the runtime microservice graph.\n *\n * Signals (all resolved through the TypeScript checker, so re-exports resolve):\n * - IMPLEMENTS: `apiFactory.addRoutes(XxxApi, XxxController)` — the registration\n * that actually SERVES the contract over the wire. We deliberately\n * do NOT use `class Ctrl extends XxxApi`: a class can extend an API\n * as an in-process test double / simulator (e.g. Server2Simulator)\n * without ever serving it — only `addRoutes` proves a served route.\n * - USES: `factory.createRpcClient(XxxApi, ...)` → rpc client\n * `factory.createPubSubClient(XxxApi, ...)` → pubsub (Cloud Tasks) client\n * The config argument (`new ClientConfig('helper-fsdb')`) names WHICH service the\n * client talks to and is kept as `ApiRef.targetService` — see targetServiceOf.\n * An api-lib is DETECTED, not tagged: a project exporting an `abstract class`\n * carrying `@ApiPath` owns that API. Its transport is `@PubSub` → 'pubsub', else 'rpc'.\n *\n * Contracts are indexed from SOURCE in a pre-pass (ApiSourceIndexBuilder) rather than\n * from wherever the checker resolves an import to. A consumer without a tsconfig.base\n * `paths` entry resolves `import { XxxApi } from '@scope/xxx-api'` through node_modules\n * to the package's BUILT `dist/**.d.ts` — and tsc ERASES decorators when emitting\n * declarations, so `@ApiPath` can never be read there. Keying off the resolved\n * declaration therefore dropped whole services from the graph, silently. See\n * `recoverFromDeclaration`.\n */\n\nimport * as ts from 'typescript';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { matchesAnyGlob } from '@webpieces/rules-config';\nimport type { EnhancedGraph } from '../graph-sorter';\nimport { ProjectInfo } from '../project-info';\nimport { findProjectTsconfig } from '../di-graph/program';\nimport { resolveClassDeclaration } from '../di-graph/bindings';\nimport {\n ApiClassInfo,\n ApiContract,\n ApiContracts,\n ApiRef,\n ApiRelation,\n EmptiedApiContract,\n EndpointKind,\n NonLiteralDecoratorArg,\n ProjectApiRelations,\n UndeclaredExternalCaller,\n UndeclaredEndpointOperation,\n UnresolvedApiCall,\n UnresolvedEndpointPath,\n apiRefKey,\n deriveApiRelationKind,\n sortApiRefs,\n} from './api-relations';\nimport {\n ApiRulesForMcpError,\n ApiRulesForOpenApiError,\n EmptiedApiContractError,\n MissingBasePathError,\n RootUnionApiTypeError,\n UndeclaredExternalCallerError,\n UndeclaredEndpointOperationError,\n UnresolvedEndpointPathError,\n} from './api-contract-errors';\nimport { RootUnionFindings, RootUnionRule, RootUnionScan } from './root-union-scan';\nimport { ApiDocRule, ApiDocRulesFindings, MCP_RULE, OPENAPI_RULE } from './api-doc-rules';\nimport { ApiDocRulesScan } from './api-doc-rules-scan';\nimport {\n DecoratorArgDiagnostics,\n apiClassInfoFrom,\n apiClassInfoFromNode,\n calleeMethodName,\n collectTsFiles,\n constructorParamsOf,\n externalApiInfoFrom,\n implementedTypeNames,\n isAbstractClass,\n isTestFile,\n targetServiceOf,\n typeReferenceName,\n} from './api-ast';\n\nconst RPC_CLIENT_METHOD = 'createRpcClient';\nconst PUBSUB_CLIENT_METHOD = 'createPubSubClient';\nconst ADD_ROUTES_METHOD = 'addRoutes';\n\n/** The whole-workspace result of a scan. */\nexport interface ApiScanResult {\n /** projectName -> { apiLibProject -> relation }; only projects with ≥1 relation appear. */\n relationsByProject: Map<string, ProjectApiRelations>;\n /** Every project that owns ≥1 API contract class. */\n apiLibProjects: Set<string>;\n /** apiClassName -> where it lives + its transport. */\n apiIndex: Map<string, ApiClassInfo>;\n /**\n * Projects whose production (non-test) source was actually scanned. A project with only test\n * files (e.g. an e2e harness), or one the compiler couldn't load, is ABSENT — callers must not\n * conclude \"no implements/uses\" for it, because its behavior was never observed.\n */\n scannedProjects: Set<string>;\n /**\n * Call sites naming a contract we could not map back to workspace source. Non-empty means the\n * graph is INCOMPLETE — callers must surface these rather than emit a green, wrong graph.\n */\n unresolvedApiCalls: UnresolvedApiCall[];\n /**\n * Decorator arguments that were present but could not be reduced to a string (a cross-module\n * constant, a computed expression). Each one costs the graph a basePath, a method, or — when it\n * takes out every method of a class — the whole contract, so they must be surfaced.\n */\n nonLiteralDecoratorArgs: NonLiteralDecoratorArg[];\n /**\n * The subset of the above that is FATAL: an `@Endpoint` path that could not be read. Every client\n * builds its URL as `basePath + path`, so this is missing routing, not missing metadata —\n * buildApiContracts throws on a non-empty list rather than shipping a contract without it.\n */\n unresolvedEndpointPaths: UnresolvedEndpointPath[];\n /**\n * Contract classes that declared `@Endpoint` methods and kept none — the exact shape that used to\n * slip out through buildApiContracts' zero-method skip, taking a whole service's queues with it.\n */\n emptiedApiContracts: EmptiedApiContract[];\n /**\n * `external` endpoints that did not say WHO calls them. Fatal: the inbound box on the runtime\n * graph exists to name that system, and with nothing to name it restates our own contract name.\n */\n undeclaredExternalCallers: UndeclaredExternalCaller[];\n /** Endpoints lacking the explicit side-effect contract used for retry safety and MCP hints. */\n undeclaredEndpointOperations: UndeclaredEndpointOperation[];\n /** `no-root-union-api-type`'s findings. Fatal in buildApiContracts — see root-union-scan.ts. */\n rootUnions: RootUnionFindings;\n /**\n * `api-rules-for-openapi` / `api-rules-for-mcp` findings (#1011). Both ship OFF, so this is\n * EMPTY unless a repo stated otherwise — no rule in this framework has a default (#1017).\n */\n apiDocRules: ApiDocRulesFindings;\n}\n\n/** Maps an absolute source-file path to the workspace project that owns it (longest-root-prefix). */\nclass ProjectLocator {\n private readonly roots: ProjectRoot[];\n\n constructor(workspaceRoot: string, projectInfos: Map<string, ProjectInfo>) {\n const roots: ProjectRoot[] = [];\n for (const info of projectInfos.values()) {\n if (info.root === '' || info.root === '.') continue;\n roots.push(new ProjectRoot(info.name, path.resolve(workspaceRoot, info.root)));\n }\n // Longest root first so a nested project wins over its parent.\n this.roots = roots.sort((a: ProjectRoot, b: ProjectRoot) => b.abs.length - a.abs.length);\n }\n\n projectOf(absFile: string): string | null {\n const normalized = path.resolve(absFile);\n for (const root of this.roots) {\n if (normalized === root.abs || normalized.startsWith(root.abs + path.sep))\n return root.name;\n }\n return null;\n }\n}\n\nclass ProjectRoot {\n constructor(\n public readonly name: string,\n public readonly abs: string,\n ) {}\n}\n\n/**\n * Every API contract in the workspace, keyed by class name, read from SOURCE.\n *\n * Name-keyed because a call site only ever gives us a name once its import has resolved into a\n * decorator-erased declaration. Two api-libs exporting the same class name collide (last wins) —\n * the same collision the published `apiIndex` has always had.\n */\nclass ApiSourceIndex {\n constructor(\n public readonly byName: Map<string, ApiClassInfo>,\n public readonly owners: Set<string>,\n ) {}\n\n lookup(api: string): ApiClassInfo | null {\n return this.byName.get(api) ?? null;\n }\n}\n\n/**\n * Builds the ApiSourceIndex by parsing each project's own `src/**` directly.\n *\n * Deliberately parser-only (no ts.Program, no checker): we need the decorators exactly as\n * written, and a plain parse cannot be diverted to a `.d.ts` by module resolution — which is\n * the entire bug this guards against. It is also cheap enough to run over every project.\n */\nclass ApiSourceIndexBuilder {\n private readonly byName = new Map<string, ApiClassInfo>();\n private readonly owners = new Set<string>();\n\n constructor(\n private readonly workspaceRoot: string,\n private readonly projectInfos: Map<string, ProjectInfo>,\n /** Globs of project roots holding vendor contracts — see ExternalApiIndex. */\n private readonly externalApiPaths: readonly string[],\n /** Sink for decorator arguments this parser-only pass cannot reduce to a string. */\n private readonly diagnostics: DecoratorArgDiagnostics,\n ) {}\n\n build(): ApiSourceIndex {\n for (const info of this.projectInfos.values()) {\n if (info.root === '' || info.root === '.') continue;\n this.indexProject(info);\n }\n return new ApiSourceIndex(this.byName, this.owners);\n }\n\n private indexProject(info: ProjectInfo): void {\n const srcDir = path.join(path.resolve(this.workspaceRoot, info.root), 'src');\n if (!fs.existsSync(srcDir)) return;\n const external = matchesAnyGlob(info.root, this.externalApiPaths);\n for (const file of collectTsFiles(srcDir)) {\n if (isTestFile(file)) continue; // tests are not production topology\n const text = fs.readFileSync(file, 'utf8');\n const sourceFile = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true);\n this.indexNode(sourceFile, info.name, external);\n }\n }\n\n private indexNode(node: ts.Node, project: string, external: boolean): void {\n const info = external\n ? externalApiInfoFrom(node, project)\n : apiClassInfoFromNode(node, project, this.diagnostics);\n if (info) {\n this.owners.add(project);\n this.byName.set(info.api, info);\n }\n ts.forEachChild(node, (child: ts.Node) => this.indexNode(child, project, external));\n }\n}\n/** Per-owner accumulator that dedupes API refs while a single project is scanned. */\nclass RelationAccumulator {\n private readonly implementsByOwner = new Map<string, Map<string, ApiRef>>();\n private readonly usesByOwner = new Map<string, Map<string, ApiRef>>();\n\n addImplements(owner: string, ref: ApiRef): void {\n ensureRefMap(this.implementsByOwner, owner).set(apiRefKey(ref), ref);\n }\n\n /**\n * Keyed by api + targetService: one project legitimately binds the SAME contract against two\n * different services (a WarmupApi client per data server), and those are two relations, not one.\n */\n addUses(owner: string, ref: ApiRef): void {\n ensureRefMap(this.usesByOwner, owner).set(apiRefKey(ref), ref);\n }\n\n /** Build the deterministic { owner -> relation } record, owners in sorted order. */\n toRelations(): ProjectApiRelations {\n const owners = new Set<string>([\n ...this.implementsByOwner.keys(),\n ...this.usesByOwner.keys(),\n ]);\n const relations: ProjectApiRelations = {};\n for (const owner of [...owners].sort()) {\n const implementsRefs = sortApiRefs([\n ...(this.implementsByOwner.get(owner)?.values() ?? []),\n ]);\n const usesRefs = sortApiRefs([...(this.usesByOwner.get(owner)?.values() ?? [])]);\n const relation: ApiRelation = {\n kind: deriveApiRelationKind(implementsRefs, usesRefs),\n implements: implementsRefs,\n uses: usesRefs,\n };\n relations[owner] = relation;\n }\n return relations;\n }\n\n isEmpty(): boolean {\n return this.implementsByOwner.size === 0 && this.usesByOwner.size === 0;\n }\n}\n\n// webpieces-disable no-function-outside-class -- tiny map helper, matching the AST-helper style of di-graph/bindings.ts\nfunction ensureRefMap(map: Map<string, Map<string, ApiRef>>, owner: string): Map<string, ApiRef> {\n let inner = map.get(owner);\n if (!inner) {\n inner = new Map<string, ApiRef>();\n map.set(owner, inner);\n }\n return inner;\n}\n\n/** Statically scans every project for its api-lib implements/uses relationships. */\nexport class ApiUsageScanner {\n private readonly locator: ProjectLocator;\n private readonly relationsByProject = new Map<string, ProjectApiRelations>();\n private readonly scannedProjects = new Set<string>();\n private readonly unresolvedApiCalls: UnresolvedApiCall[] = [];\n private readonly decoratorArgDiagnostics: DecoratorArgDiagnostics;\n private sourceIndex = new ApiSourceIndex(new Map<string, ApiClassInfo>(), new Set<string>());\n\n constructor(\n private readonly workspaceRoot: string,\n private readonly projectInfos: Map<string, ProjectInfo>,\n /** Globs of project roots whose exported `*Api` types are contracts for outside systems. */\n private readonly externalApiPaths: readonly string[] = [],\n /** `no-root-union-api-type`'s switches — ARMED unless scanAndAttachApiRelations read otherwise. */\n private readonly rootUnionRule: RootUnionRule = RootUnionRule.enabledEverywhere(),\n /** `api-rules-for-openapi`'s switches — read from the config, which MUST state them (#1017). */\n private readonly openApiRule: ApiDocRule = ApiDocRule.off(OPENAPI_RULE),\n /** `api-rules-for-mcp`'s switches — read from the config, which MUST state them (#1017). */\n private readonly mcpRule: ApiDocRule = ApiDocRule.off(MCP_RULE),\n ) {\n this.locator = new ProjectLocator(workspaceRoot, projectInfos);\n this.decoratorArgDiagnostics = new DecoratorArgDiagnostics(workspaceRoot);\n }\n\n scan(): ApiScanResult {\n // Pre-pass: every contract, from source, BEFORE any call site is resolved — a call site in\n // one project routinely names a contract owned by a project we have not walked yet.\n this.sourceIndex = new ApiSourceIndexBuilder(\n this.workspaceRoot,\n this.projectInfos,\n this.externalApiPaths,\n this.decoratorArgDiagnostics,\n ).build();\n for (const info of this.projectInfos.values()) {\n if (info.root === '' || info.root === '.') continue;\n this.scanProject(info);\n }\n return {\n relationsByProject: this.relationsByProject,\n apiLibProjects: this.sourceIndex.owners,\n apiIndex: this.sourceIndex.byName,\n scannedProjects: this.scannedProjects,\n unresolvedApiCalls: this.unresolvedApiCalls,\n nonLiteralDecoratorArgs: this.decoratorArgDiagnostics.all(),\n unresolvedEndpointPaths: this.decoratorArgDiagnostics.unresolvedEndpointPaths(),\n emptiedApiContracts: this.decoratorArgDiagnostics.emptiedContracts(),\n undeclaredExternalCallers: this.decoratorArgDiagnostics.undeclaredExternalCallers(),\n undeclaredEndpointOperations:\n this.decoratorArgDiagnostics.undeclaredEndpointOperations(),\n rootUnions: new RootUnionScan(\n this.workspaceRoot,\n this.projectInfos,\n this.rootUnionRule,\n ).run(),\n apiDocRules: new ApiDocRulesScan(\n this.workspaceRoot,\n this.projectInfos,\n this.openApiRule,\n this.mcpRule,\n ).run(),\n };\n }\n\n private scanProject(info: ProjectInfo): void {\n const program = createScanProgram(path.resolve(this.workspaceRoot, info.root));\n if (!program) return;\n const checker = program.getTypeChecker();\n const accumulator = new RelationAccumulator();\n let scannedProductionFile = false;\n\n for (const sourceFile of program.getSourceFiles()) {\n if (sourceFile.isDeclarationFile || sourceFile.fileName.includes('/node_modules/'))\n continue;\n if (isTestFile(sourceFile.fileName)) continue; // tests are not production topology\n // Only this project's OWN files — imported api-lib source is in the program too.\n if (this.locator.projectOf(sourceFile.fileName) !== info.name) continue;\n scannedProductionFile = true;\n this.visit(sourceFile, checker, info.name, accumulator);\n }\n\n // Record coverage only when we actually saw production source — an all-test project (e2e)\n // stays absent so the validator won't wrongly flag its api-lib deps as unused.\n if (scannedProductionFile) this.scannedProjects.add(info.name);\n if (!accumulator.isEmpty())\n this.relationsByProject.set(info.name, accumulator.toRelations());\n }\n\n private visit(\n node: ts.Node,\n checker: ts.TypeChecker,\n project: string,\n acc: RelationAccumulator,\n ): void {\n // In-repo contract classes are indexed by the source pre-pass, so only calls matter for them.\n if (ts.isCallExpression(node)) this.recordCall(node, checker, project, acc);\n // A VENDOR contract has no client-factory call site to key off — it arrives by injection —\n // so classes have to be inspected too.\n if (ts.isClassDeclaration(node)) this.recordExternalUses(node, acc);\n ts.forEachChild(node, (child: ts.Node) => this.visit(child, checker, project, acc));\n }\n\n /**\n * Record a `uses` for every vendor contract this class receives by CONSTRUCTOR INJECTION —\n * `constructor(@inject(GMAIL_TYPES.GmailApi) private readonly gmail: GmailApi)`.\n *\n * The parameter TYPE is the signal, not the token: a token is an opaque Symbol whose name we\n * would have to guess at, while the type is written right there and is what the class actually\n * calls. Matching happens by name against the external index, so an import that resolves to a\n * built `.d.ts` works exactly as well as one resolving to source.\n *\n * A class that IMPLEMENTS the contract is skipped — that is the vendor adapter (`GmailClient`)\n * or a test double (`InMemoryFirestore`, `MockTts`), which IS the seam rather than a caller of\n * it. Counting those would draw an edge from every service embedding a fake to a vendor it never\n * actually reaches.\n */\n private recordExternalUses(cls: ts.ClassDeclaration, acc: RelationAccumulator): void {\n const implemented = implementedTypeNames(cls);\n for (const param of constructorParamsOf(cls)) {\n const typeName = typeReferenceName(param.type);\n if (typeName === null || implemented.has(typeName)) continue;\n const info = this.sourceIndex.lookup(typeName);\n if (info === null || info.type !== 'external') continue;\n acc.addUses(info.owner, { api: info.api, type: 'external' });\n }\n }\n\n private recordCall(\n call: ts.CallExpression,\n checker: ts.TypeChecker,\n project: string,\n acc: RelationAccumulator,\n ): void {\n const method = calleeMethodName(call);\n if (method === null || call.arguments.length === 0) return;\n if (method === ADD_ROUTES_METHOD) {\n const info = this.apiInfoFromExpr(call.arguments[0], checker, project);\n if (info) acc.addImplements(info.owner, { api: info.api, type: info.type });\n return;\n }\n if (method === RPC_CLIENT_METHOD || method === PUBSUB_CLIENT_METHOD) {\n const info = this.apiInfoFromExpr(call.arguments[0], checker, project);\n if (!info) return;\n // Argument 2 names WHICH service this client talks to. Keeping it is what lets the\n // runtime graph draw ONE edge instead of one per implementer of the contract.\n const targetService = targetServiceOf(call);\n const ref: ApiRef = { api: info.api, type: info.type };\n if (targetService !== null) ref.targetService = targetService;\n acc.addUses(info.owner, ref);\n }\n }\n\n /** Resolve an expression to the API contract it names, or null if it is not one. */\n private apiInfoFromExpr(\n expr: ts.Expression,\n checker: ts.TypeChecker,\n project: string,\n ): ApiClassInfo | null {\n const decl = resolveClassDeclaration(expr, checker);\n if (!decl) return null;\n const fromSource = this.apiClassInfoFor(decl);\n return fromSource ?? this.recoverFromDeclaration(decl, expr, project);\n }\n\n /**\n * The checker landed on a BUILT declaration instead of source — the consumer has no\n * tsconfig.base `paths` entry for the api-lib, so the import went through node_modules to\n * `dist/**.d.ts`. tsc erases decorators when emitting declarations, so `@ApiPath` is simply\n * not there and never will be. Recover the contract by name from the source index; the graph\n * is then correct no matter how the consumer's tsconfig is laid out.\n */\n private recoverFromDeclaration(\n decl: ts.ClassDeclaration,\n expr: ts.Expression,\n project: string,\n ): ApiClassInfo | null {\n // An abstract class is the shape of a contract; a non-abstract argument is genuinely not one.\n if (!decl.getSourceFile().isDeclarationFile || !isAbstractClass(decl) || !decl.name)\n return null;\n const recovered = this.sourceIndex.lookup(decl.name.text);\n if (recovered) return recovered;\n // Abstract, in a .d.ts, yet no workspace source owns it — the scan is blind here. Say so.\n this.unresolvedApiCalls.push(\n new UnresolvedApiCall(\n project,\n decl.name.text,\n this.relativeLocation(expr),\n this.relativePath(decl.getSourceFile().fileName),\n ),\n );\n return null;\n }\n\n /** `path/to/file.ts:LINE` for `node`, workspace-relative, for a human-readable report. */\n private relativeLocation(node: ts.Node): string {\n const sourceFile = node.getSourceFile();\n const position = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n return `${this.relativePath(sourceFile.fileName)}:${position.line + 1}`;\n }\n\n private relativePath(absFile: string): string {\n return path.relative(this.workspaceRoot, absFile);\n }\n\n /**\n * {api, owner, type, methods} when `cls` is an `abstract class` carrying `@ApiPath` IN SOURCE,\n * else null. Only the OWNER differs from the index pre-pass — here it comes from the file's\n * location rather than from the project being walked — so the contract test itself is delegated\n * to apiClassInfoFrom, keeping one definition of \"this is a contract\".\n */\n private apiClassInfoFor(cls: ts.ClassDeclaration): ApiClassInfo | null {\n const owner = this.locator.projectOf(cls.getSourceFile().fileName);\n if (owner === null) return null;\n return apiClassInfoFrom(cls, owner);\n }\n}\n\n/**\n * Run the scan and attach the derived `apiRelations` onto each graph entry in\n * place. Shared by `architecture:generate` (which then saves) and\n * `architecture:validate-architecture-unchanged` (which regenerates in memory\n * and must attach the SAME field, or it would see a phantom diff). Returns the\n * full scan so callers (validators, runtime graph) can reuse the api index.\n */\n// webpieces-disable no-function-outside-class -- module entry point, mirrors generateReducedGraph/collectBindings\nexport function scanAndAttachApiRelations(\n workspaceRoot: string,\n graph: EnhancedGraph,\n projectInfos: Map<string, ProjectInfo>,\n externalApiPaths: readonly string[] = [],\n): ApiScanResult {\n const result = new ApiUsageScanner(\n workspaceRoot,\n projectInfos,\n externalApiPaths,\n RootUnionRule.fromConfig(workspaceRoot),\n ApiDocRule.fromConfig(workspaceRoot, OPENAPI_RULE),\n ApiDocRule.fromConfig(workspaceRoot, MCP_RULE),\n ).scan();\n for (const projectName of result.relationsByProject.keys()) {\n const entry = graph[projectName];\n if (entry) entry.apiRelations = result.relationsByProject.get(projectName);\n }\n return result;\n}\n\n/**\n * The committed api contract table (one `architecture/apis/<ApiName>.json` per entry), from a\n * completed scan.\n *\n * Only contracts with ≥1 endpoint are emitted: a vendor seam has no routes, so a table entry for it\n * would be an empty shell, and its identity is already carried by the `external` refs in\n * apiRelations. Sorted by api name, methods left in declaration order, so the file is deterministic.\n *\n * THROWS on the ways an entry can be wrong-but-green, checked root cause first:\n * 1. an `@Endpoint` path the scan could not read (UnresolvedEndpointPathError) — the other half of\n * the URL a consumer computes, and the cause of most emptied contracts;\n * 2. a class that declared endpoints and kept none (EmptiedApiContractError), which would otherwise\n * leave silently through the zero-method skip above;\n * 3. a method without an explicit operation (UndeclaredEndpointOperationError);\n * 4. an `external` method that never said WHO calls it (UndeclaredExternalCallerError);\n * 5. a routed contract with no basePath (MissingBasePathError).\n * All are worse than an absent entry: a consumer joining `basePath + path` computes a\n * confidently wrong URL with no signal that anything is off, because every other entry is complete.\n * Each error aggregates EVERY offender, so a developer fixing five constants sees five in one run.\n */\n// webpieces-disable no-function-outside-class -- module entry point, mirrors scanAndAttachApiRelations\nexport function buildApiContracts(scan: ApiScanResult): ApiContracts {\n // Root cause before symptom: an unreadable path is what empties a contract, so naming the paths\n // is what the author can actually act on.\n if (scan.unresolvedEndpointPaths.length > 0)\n throw new UnresolvedEndpointPathError(scan.unresolvedEndpointPaths);\n if (scan.emptiedApiContracts.length > 0)\n throw new EmptiedApiContractError(scan.emptiedApiContracts);\n if (scan.undeclaredEndpointOperations.length > 0) {\n throw new UndeclaredEndpointOperationError(scan.undeclaredEndpointOperations);\n }\n // A shape no function-calling API will accept, read perfectly well — unlike the four above, which\n // are contracts the scan could not READ at all.\n if (!scan.rootUnions.isEmpty()) throw new RootUnionApiTypeError(scan.rootUnions);\n // Contract shapes that are not PUBLISHABLE, read by the generator's own extractor (#1011).\n // After the root union, which is the one shape no function-calling API will accept at all, and\n // before the caller checks below, which are about the architecture graph rather than a document.\n if (!scan.apiDocRules.openApi.isEmpty()) {\n throw new ApiRulesForOpenApiError(scan.apiDocRules.openApi);\n }\n if (!scan.apiDocRules.mcp.isEmpty()) {\n throw new ApiRulesForMcpError(scan.apiDocRules.mcp, scan.apiDocRules.mcpExclusions);\n }\n // After the two above: an unreadable path is what empties a contract, and a contract that lost\n // every method has no external endpoint left to complain about.\n if (scan.undeclaredExternalCallers.length > 0) {\n throw new UndeclaredExternalCallerError(scan.undeclaredExternalCallers);\n }\n const contracts: ApiContracts = {};\n const missing: string[] = [];\n for (const api of [...scan.apiIndex.keys()].sort()) {\n const info = scan.apiIndex.get(api)!;\n if (info.methods.length === 0) continue;\n if (info.basePath === undefined) {\n missing.push(`${api} (owner ${info.owner})`);\n continue;\n }\n const contract: ApiContract = {\n owner: info.owner,\n apiKind: info.type,\n basePath: info.basePath,\n methods: info.methods,\n };\n contracts[api] = contract;\n }\n if (missing.length > 0) throw new MissingBasePathError(missing);\n return contracts;\n}\n\n/**\n * Loud, actionable report for decorator arguments the scan could not reduce to a string.\n *\n * Same-module constants resolve, so anything reaching here is genuinely out of reach of a\n * parser-only pass — and every one of them silently shrinks the graph. Empty string when there is\n * nothing to say, so callers can test it without special-casing.\n */\n// webpieces-disable no-function-outside-class -- pure formatter, mirrors describeUnresolvedApiCalls\nexport function describeNonLiteralDecoratorArgs(args: readonly NonLiteralDecoratorArg[]): string {\n if (args.length === 0) return '';\n const lines = [\n `⚠️ ${args.length} decorator argument(s) are not string literals and could not be resolved.`,\n ` Each one drops data from the graph: a missing basePath, a missing method, or a whole contract:`,\n ];\n for (const arg of args) {\n const where = arg.method === null ? arg.api : `${arg.api}.${arg.method}`;\n lines.push(` • @${arg.decorator}(${arg.argument}) on ${where} at ${arg.at}`);\n }\n lines.push(\n ` A constant declared in the SAME module resolves. One imported from another module does not —`,\n ` this scan is parser-only by design (module resolution can land on a decorator-erased .d.ts).`,\n ` Fix by inlining the string literal, or by moving the constant into the contract's own module.`,\n );\n return lines.join('\\n');\n}\n\n/**\n * Every contract method whose declared @Endpoint kind its api kind cannot deliver — an rpc method on\n * a @PubSub contract (nothing calls a queue synchronously), or a cloudtasks/cron method on an @Rpc\n * contract (naming a queue or schedule nothing could deliver to). Mirrors core-util's\n * ENDPOINT_KINDS_BY_API_KIND at BUILD time, where it can name the file instead of throwing at wiring.\n */\n// webpieces-disable no-function-outside-class -- pure formatter, mirrors describeUnresolvedApiCalls\nexport function describeMismatchedEndpointKinds(contracts: ApiContracts): string[] {\n const allowedByKind: Record<string, readonly EndpointKind[]> = {\n rpc: ['rpc', 'external'],\n pubsub: ['cloudtasks', 'cron', 'external'],\n };\n const problems: string[] = [];\n for (const api of Object.keys(contracts)) {\n const contract = contracts[api];\n const allowed = allowedByKind[contract.apiKind];\n if (allowed === undefined) continue;\n for (const method of contract.methods) {\n if (allowed.includes(method.kind)) continue;\n problems.push(\n `${api}.${method.name} declares @Endpoint(${method.httpMethod ?? 'POST'}, '${method.path}', ${method.operation}, ${method.kind}) but ${api} is ` +\n `@${contract.apiKind === 'pubsub' ? 'PubSub' : 'Rpc'} — allowed kinds are ${allowed.join(' | ')}.`,\n );\n }\n }\n return problems;\n}\n\n/**\n * Build a program for scanning ONE project. Prefers the project's compile tsconfig; but when that\n * is a solution-style tsconfig (only `references`, no `files`/`include` — e.g. legacy-server), it\n * yields zero files, so we fall back to globbing the project's own `src/**` and reuse the resolved\n * compiler options (which carry tsconfig.base `paths` for cross-package @webpieces resolution).\n *\n * `paths` is a PREFERENCE, not a precondition: it lets imports resolve straight to source. Without\n * it they land on a decorator-erased `dist/**.d.ts`, which the source index recovers from — see\n * ApiUsageScanner.recoverFromDeclaration.\n */\n// webpieces-disable no-function-outside-class -- ts Program factory, mirrors di-graph/program.ts\nfunction createScanProgram(projectRootAbs: string): ts.Program | null {\n const configPath = findProjectTsconfig(projectRootAbs);\n if (!configPath) return buildProgramFromSrc(projectRootAbs, {});\n const host = Object.assign({}, ts.sys, {\n onUnRecoverableConfigFileDiagnostic: (): void => undefined,\n }) as ts.ParseConfigFileHost;\n const parsed = ts.getParsedCommandLineOfConfigFile(configPath, {}, host);\n if (!parsed) return null;\n if (parsed.fileNames.length > 0) return ts.createProgram(parsed.fileNames, parsed.options);\n return buildProgramFromSrc(projectRootAbs, parsed.options);\n}\n\n// webpieces-disable no-function-outside-class -- ts Program factory helper, mirrors di-graph/program.ts\nfunction buildProgramFromSrc(\n projectRootAbs: string,\n options: ts.CompilerOptions,\n): ts.Program | null {\n const srcDir = path.join(projectRootAbs, 'src');\n if (!fs.existsSync(srcDir)) return null;\n const files = collectTsFiles(srcDir);\n return files.length > 0 ? ts.createProgram(files, options) : null;\n}\n"]}
1
+ {"version":3,"file":"api-scanner.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/lib/api-usage/api-scanner.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;;;AA6eH,8DAoBC;AAuBD,8CA8CC;AAUD,0EAgBC;AASD,0EAmBC;;AA1nBD,uDAAiC;AACjC,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAyD;AAGzD,iDAA0D;AAC1D,mDAA+D;AAC/D,mDAiByB;AACzB,+DA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;AAC/D,CAAC;AAED,wGAAwG;AACxG,SAAS,mBAAmB,CACxB,cAAsB,EACtB,OAA2B;IAE3B,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE,KAAK,CAAC,CAAC;IAChD,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC;QAAE,OAAO,IAAI,CAAC;IACxC,MAAM,KAAK,GAAG,IAAA,wBAAc,EAAC,MAAM,CAAC,CAAC;IACrC,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,aAAa,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AACtE,CAAC","sourcesContent":["/**\n * API Usage Scanner\n *\n * Derives, by scanning real source (not a declaration file), how every project\n * relates to the api-lib projects it depends on. This is the single source of\n * truth for the `apiRelations` field in architecture/dependencies.json AND for\n * the runtime microservice graph.\n *\n * Signals (all resolved through the TypeScript checker, so re-exports resolve):\n * - IMPLEMENTS: `apiFactory.addRoutes(XxxApi, XxxController)` — the registration\n * that actually SERVES the contract over the wire. We deliberately\n * do NOT use `class Ctrl extends XxxApi`: a class can extend an API\n * as an in-process test double / simulator (e.g. Server2Simulator)\n * without ever serving it — only `addRoutes` proves a served route.\n * - USES: `factory.createRpcClient(XxxApi, ...)` → rpc client\n * `factory.createPubSubClient(XxxApi, ...)` → pubsub (Cloud Tasks) client\n * The config argument (`new ClientConfig('helper-fsdb')`) names WHICH service the\n * client talks to and is kept as `ApiRef.targetService` — see targetServiceOf.\n * An api-lib is DETECTED, not tagged: a project exporting an `abstract class`\n * carrying `@ApiPath` owns that API. Its transport is `@PubSub` → 'pubsub', else 'rpc'.\n *\n * Contracts are indexed from SOURCE in a pre-pass (ApiSourceIndexBuilder) rather than\n * from wherever the checker resolves an import to. A consumer without a tsconfig.base\n * `paths` entry resolves `import { XxxApi } from '@scope/xxx-api'` through node_modules\n * to the package's BUILT `dist/**.d.ts` — and tsc ERASES decorators when emitting\n * declarations, so `@ApiPath` can never be read there. Keying off the resolved\n * declaration therefore dropped whole services from the graph, silently. See\n * `recoverFromDeclaration`.\n */\n\nimport * as ts from 'typescript';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { matchesAnyGlob } from '@webpieces/rules-config';\nimport type { EnhancedGraph } from '../graph-sorter';\nimport { ProjectInfo } from '../project-info';\nimport { findProjectTsconfig } from '../di-graph/program';\nimport { resolveClassDeclaration } from '../di-graph/bindings';\nimport {\n ApiClassInfo,\n ApiContract,\n ApiContracts,\n ApiRef,\n ApiRelation,\n EmptiedApiContract,\n EndpointKind,\n NonLiteralDecoratorArg,\n ProjectApiRelations,\n UndeclaredExternalCaller,\n UndeclaredEndpointOperation,\n UnresolvedApiCall,\n UnresolvedEndpointPath,\n apiRefKey,\n deriveApiRelationKind,\n sortApiRefs,\n} from './api-relations';\nimport {\n ApiRulesForMcpError,\n ApiRulesForOpenApiError,\n EmptiedApiContractError,\n MissingBasePathError,\n RootUnionApiTypeError,\n UndeclaredExternalCallerError,\n UndeclaredEndpointOperationError,\n UnresolvedEndpointPathError,\n} from './api-contract-errors';\nimport { RootUnionFindings, RootUnionRule, RootUnionScan } from './root-union-scan';\nimport { ApiDocRule, ApiDocRulesFindings, MCP_RULE, OPENAPI_RULE } from './api-doc-rules';\nimport { ApiDocRulesScan } from './api-doc-rules-scan';\nimport { WireClosureRule } from './wire-closure';\nimport {\n DecoratorArgDiagnostics,\n apiClassInfoFrom,\n apiClassInfoFromNode,\n calleeMethodName,\n collectTsFiles,\n constructorParamsOf,\n externalApiInfoFrom,\n implementedTypeNames,\n isAbstractClass,\n isTestFile,\n targetServiceOf,\n typeReferenceName,\n} from './api-ast';\n\nconst RPC_CLIENT_METHOD = 'createRpcClient';\nconst PUBSUB_CLIENT_METHOD = 'createPubSubClient';\nconst ADD_ROUTES_METHOD = 'addRoutes';\n\n/** The whole-workspace result of a scan. */\nexport interface ApiScanResult {\n /** projectName -> { apiLibProject -> relation }; only projects with ≥1 relation appear. */\n relationsByProject: Map<string, ProjectApiRelations>;\n /** Every project that owns ≥1 API contract class. */\n apiLibProjects: Set<string>;\n /** apiClassName -> where it lives + its transport. */\n apiIndex: Map<string, ApiClassInfo>;\n /**\n * Projects whose production (non-test) source was actually scanned. A project with only test\n * files (e.g. an e2e harness), or one the compiler couldn't load, is ABSENT — callers must not\n * conclude \"no implements/uses\" for it, because its behavior was never observed.\n */\n scannedProjects: Set<string>;\n /**\n * Call sites naming a contract we could not map back to workspace source. Non-empty means the\n * graph is INCOMPLETE — callers must surface these rather than emit a green, wrong graph.\n */\n unresolvedApiCalls: UnresolvedApiCall[];\n /**\n * Decorator arguments that were present but could not be reduced to a string (a cross-module\n * constant, a computed expression). Each one costs the graph a basePath, a method, or — when it\n * takes out every method of a class — the whole contract, so they must be surfaced.\n */\n nonLiteralDecoratorArgs: NonLiteralDecoratorArg[];\n /**\n * The subset of the above that is FATAL: an `@Endpoint` path that could not be read. Every client\n * builds its URL as `basePath + path`, so this is missing routing, not missing metadata —\n * buildApiContracts throws on a non-empty list rather than shipping a contract without it.\n */\n unresolvedEndpointPaths: UnresolvedEndpointPath[];\n /**\n * Contract classes that declared `@Endpoint` methods and kept none — the exact shape that used to\n * slip out through buildApiContracts' zero-method skip, taking a whole service's queues with it.\n */\n emptiedApiContracts: EmptiedApiContract[];\n /**\n * `external` endpoints that did not say WHO calls them. Fatal: the inbound box on the runtime\n * graph exists to name that system, and with nothing to name it restates our own contract name.\n */\n undeclaredExternalCallers: UndeclaredExternalCaller[];\n /** Endpoints lacking the explicit side-effect contract used for retry safety and MCP hints. */\n undeclaredEndpointOperations: UndeclaredEndpointOperation[];\n /** `no-root-union-api-type`'s findings. Fatal in buildApiContracts — see root-union-scan.ts. */\n rootUnions: RootUnionFindings;\n /**\n * `api-rules-for-openapi` / `api-rules-for-mcp` findings (#1011). Both ship OFF, so this is\n * EMPTY unless a repo stated otherwise — no rule in this framework has a default (#1017).\n */\n apiDocRules: ApiDocRulesFindings;\n}\n\n/** Maps an absolute source-file path to the workspace project that owns it (longest-root-prefix). */\nclass ProjectLocator {\n private readonly roots: ProjectRoot[];\n\n constructor(workspaceRoot: string, projectInfos: Map<string, ProjectInfo>) {\n const roots: ProjectRoot[] = [];\n for (const info of projectInfos.values()) {\n if (info.root === '' || info.root === '.') continue;\n roots.push(new ProjectRoot(info.name, path.resolve(workspaceRoot, info.root)));\n }\n // Longest root first so a nested project wins over its parent.\n this.roots = roots.sort((a: ProjectRoot, b: ProjectRoot) => b.abs.length - a.abs.length);\n }\n\n projectOf(absFile: string): string | null {\n const normalized = path.resolve(absFile);\n for (const root of this.roots) {\n if (normalized === root.abs || normalized.startsWith(root.abs + path.sep))\n return root.name;\n }\n return null;\n }\n}\n\nclass ProjectRoot {\n constructor(\n public readonly name: string,\n public readonly abs: string,\n ) {}\n}\n\n/**\n * Every API contract in the workspace, keyed by class name, read from SOURCE.\n *\n * Name-keyed because a call site only ever gives us a name once its import has resolved into a\n * decorator-erased declaration. Two api-libs exporting the same class name collide (last wins) —\n * the same collision the published `apiIndex` has always had.\n */\nclass ApiSourceIndex {\n constructor(\n public readonly byName: Map<string, ApiClassInfo>,\n public readonly owners: Set<string>,\n ) {}\n\n lookup(api: string): ApiClassInfo | null {\n return this.byName.get(api) ?? null;\n }\n}\n\n/**\n * Builds the ApiSourceIndex by parsing each project's own `src/**` directly.\n *\n * Deliberately parser-only (no ts.Program, no checker): we need the decorators exactly as\n * written, and a plain parse cannot be diverted to a `.d.ts` by module resolution — which is\n * the entire bug this guards against. It is also cheap enough to run over every project.\n */\nclass ApiSourceIndexBuilder {\n private readonly byName = new Map<string, ApiClassInfo>();\n private readonly owners = new Set<string>();\n\n constructor(\n private readonly workspaceRoot: string,\n private readonly projectInfos: Map<string, ProjectInfo>,\n /** Globs of project roots holding vendor contracts — see ExternalApiIndex. */\n private readonly externalApiPaths: readonly string[],\n /** Sink for decorator arguments this parser-only pass cannot reduce to a string. */\n private readonly diagnostics: DecoratorArgDiagnostics,\n ) {}\n\n build(): ApiSourceIndex {\n for (const info of this.projectInfos.values()) {\n if (info.root === '' || info.root === '.') continue;\n this.indexProject(info);\n }\n return new ApiSourceIndex(this.byName, this.owners);\n }\n\n private indexProject(info: ProjectInfo): void {\n const srcDir = path.join(path.resolve(this.workspaceRoot, info.root), 'src');\n if (!fs.existsSync(srcDir)) return;\n const external = matchesAnyGlob(info.root, this.externalApiPaths);\n for (const file of collectTsFiles(srcDir)) {\n if (isTestFile(file)) continue; // tests are not production topology\n const text = fs.readFileSync(file, 'utf8');\n const sourceFile = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true);\n this.indexNode(sourceFile, info.name, external);\n }\n }\n\n private indexNode(node: ts.Node, project: string, external: boolean): void {\n const info = external\n ? externalApiInfoFrom(node, project)\n : apiClassInfoFromNode(node, project, this.diagnostics);\n if (info) {\n this.owners.add(project);\n this.byName.set(info.api, info);\n }\n ts.forEachChild(node, (child: ts.Node) => this.indexNode(child, project, external));\n }\n}\n/** Per-owner accumulator that dedupes API refs while a single project is scanned. */\nclass RelationAccumulator {\n private readonly implementsByOwner = new Map<string, Map<string, ApiRef>>();\n private readonly usesByOwner = new Map<string, Map<string, ApiRef>>();\n\n addImplements(owner: string, ref: ApiRef): void {\n ensureRefMap(this.implementsByOwner, owner).set(apiRefKey(ref), ref);\n }\n\n /**\n * Keyed by api + targetService: one project legitimately binds the SAME contract against two\n * different services (a WarmupApi client per data server), and those are two relations, not one.\n */\n addUses(owner: string, ref: ApiRef): void {\n ensureRefMap(this.usesByOwner, owner).set(apiRefKey(ref), ref);\n }\n\n /** Build the deterministic { owner -> relation } record, owners in sorted order. */\n toRelations(): ProjectApiRelations {\n const owners = new Set<string>([\n ...this.implementsByOwner.keys(),\n ...this.usesByOwner.keys(),\n ]);\n const relations: ProjectApiRelations = {};\n for (const owner of [...owners].sort()) {\n const implementsRefs = sortApiRefs([\n ...(this.implementsByOwner.get(owner)?.values() ?? []),\n ]);\n const usesRefs = sortApiRefs([...(this.usesByOwner.get(owner)?.values() ?? [])]);\n const relation: ApiRelation = {\n kind: deriveApiRelationKind(implementsRefs, usesRefs),\n implements: implementsRefs,\n uses: usesRefs,\n };\n relations[owner] = relation;\n }\n return relations;\n }\n\n isEmpty(): boolean {\n return this.implementsByOwner.size === 0 && this.usesByOwner.size === 0;\n }\n}\n\n// webpieces-disable no-function-outside-class -- tiny map helper, matching the AST-helper style of di-graph/bindings.ts\nfunction ensureRefMap(map: Map<string, Map<string, ApiRef>>, owner: string): Map<string, ApiRef> {\n let inner = map.get(owner);\n if (!inner) {\n inner = new Map<string, ApiRef>();\n map.set(owner, inner);\n }\n return inner;\n}\n\n/** Statically scans every project for its api-lib implements/uses relationships. */\nexport class ApiUsageScanner {\n private readonly locator: ProjectLocator;\n private readonly relationsByProject = new Map<string, ProjectApiRelations>();\n private readonly scannedProjects = new Set<string>();\n private readonly unresolvedApiCalls: UnresolvedApiCall[] = [];\n private readonly decoratorArgDiagnostics: DecoratorArgDiagnostics;\n private sourceIndex = new ApiSourceIndex(new Map<string, ApiClassInfo>(), new Set<string>());\n\n constructor(\n private readonly workspaceRoot: string,\n private readonly projectInfos: Map<string, ProjectInfo>,\n /** Globs of project roots whose exported `*Api` types are contracts for outside systems. */\n private readonly externalApiPaths: readonly string[] = [],\n /** `no-root-union-api-type`'s switches — ARMED unless scanAndAttachApiRelations read otherwise. */\n private readonly rootUnionRule: RootUnionRule = RootUnionRule.enabledEverywhere(),\n /** `api-rules-for-openapi`'s switches — read from the config, which MUST state them (#1017). */\n private readonly openApiRule: ApiDocRule = ApiDocRule.off(OPENAPI_RULE),\n /** `api-rules-for-mcp`'s switches — read from the config, which MUST state them (#1017). */\n private readonly mcpRule: ApiDocRule = ApiDocRule.off(MCP_RULE),\n private readonly wireClosureRule: WireClosureRule = WireClosureRule.withoutSuffixes(), // #1064 D4\n ) {\n this.locator = new ProjectLocator(workspaceRoot, projectInfos);\n this.decoratorArgDiagnostics = new DecoratorArgDiagnostics(workspaceRoot);\n }\n\n scan(): ApiScanResult {\n // Pre-pass: every contract, from source, BEFORE any call site is resolved — a call site in\n // one project routinely names a contract owned by a project we have not walked yet.\n this.sourceIndex = new ApiSourceIndexBuilder(\n this.workspaceRoot,\n this.projectInfos,\n this.externalApiPaths,\n this.decoratorArgDiagnostics,\n ).build();\n for (const info of this.projectInfos.values()) {\n if (info.root === '' || info.root === '.') continue;\n this.scanProject(info);\n }\n return {\n relationsByProject: this.relationsByProject,\n apiLibProjects: this.sourceIndex.owners,\n apiIndex: this.sourceIndex.byName,\n scannedProjects: this.scannedProjects,\n unresolvedApiCalls: this.unresolvedApiCalls,\n nonLiteralDecoratorArgs: this.decoratorArgDiagnostics.all(),\n unresolvedEndpointPaths: this.decoratorArgDiagnostics.unresolvedEndpointPaths(),\n emptiedApiContracts: this.decoratorArgDiagnostics.emptiedContracts(),\n undeclaredExternalCallers: this.decoratorArgDiagnostics.undeclaredExternalCallers(),\n undeclaredEndpointOperations:\n this.decoratorArgDiagnostics.undeclaredEndpointOperations(),\n rootUnions: new RootUnionScan(\n this.workspaceRoot,\n this.projectInfos,\n this.rootUnionRule,\n ).run(),\n apiDocRules: new ApiDocRulesScan(\n this.workspaceRoot,\n this.projectInfos,\n this.openApiRule,\n this.mcpRule, this.wireClosureRule,\n ).run(),\n };\n }\n\n private scanProject(info: ProjectInfo): void {\n const program = createScanProgram(path.resolve(this.workspaceRoot, info.root));\n if (!program) return;\n const checker = program.getTypeChecker();\n const accumulator = new RelationAccumulator();\n let scannedProductionFile = false;\n\n for (const sourceFile of program.getSourceFiles()) {\n if (sourceFile.isDeclarationFile || sourceFile.fileName.includes('/node_modules/'))\n continue;\n if (isTestFile(sourceFile.fileName)) continue; // tests are not production topology\n // Only this project's OWN files — imported api-lib source is in the program too.\n if (this.locator.projectOf(sourceFile.fileName) !== info.name) continue;\n scannedProductionFile = true;\n this.visit(sourceFile, checker, info.name, accumulator);\n }\n\n // Record coverage only when we actually saw production source — an all-test project (e2e)\n // stays absent so the validator won't wrongly flag its api-lib deps as unused.\n if (scannedProductionFile) this.scannedProjects.add(info.name);\n if (!accumulator.isEmpty())\n this.relationsByProject.set(info.name, accumulator.toRelations());\n }\n\n private visit(\n node: ts.Node,\n checker: ts.TypeChecker,\n project: string,\n acc: RelationAccumulator,\n ): void {\n // In-repo contract classes are indexed by the source pre-pass, so only calls matter for them.\n if (ts.isCallExpression(node)) this.recordCall(node, checker, project, acc);\n // A VENDOR contract has no client-factory call site to key off — it arrives by injection —\n // so classes have to be inspected too.\n if (ts.isClassDeclaration(node)) this.recordExternalUses(node, acc);\n ts.forEachChild(node, (child: ts.Node) => this.visit(child, checker, project, acc));\n }\n\n /**\n * Record a `uses` for every vendor contract this class receives by CONSTRUCTOR INJECTION —\n * `constructor(@inject(GMAIL_TYPES.GmailApi) private readonly gmail: GmailApi)`.\n *\n * The parameter TYPE is the signal, not the token: a token is an opaque Symbol whose name we\n * would have to guess at, while the type is written right there and is what the class actually\n * calls. Matching happens by name against the external index, so an import that resolves to a\n * built `.d.ts` works exactly as well as one resolving to source.\n *\n * A class that IMPLEMENTS the contract is skipped — that is the vendor adapter (`GmailClient`)\n * or a test double (`InMemoryFirestore`, `MockTts`), which IS the seam rather than a caller of\n * it. Counting those would draw an edge from every service embedding a fake to a vendor it never\n * actually reaches.\n */\n private recordExternalUses(cls: ts.ClassDeclaration, acc: RelationAccumulator): void {\n const implemented = implementedTypeNames(cls);\n for (const param of constructorParamsOf(cls)) {\n const typeName = typeReferenceName(param.type);\n if (typeName === null || implemented.has(typeName)) continue;\n const info = this.sourceIndex.lookup(typeName);\n if (info === null || info.type !== 'external') continue;\n acc.addUses(info.owner, { api: info.api, type: 'external' });\n }\n }\n\n private recordCall(\n call: ts.CallExpression,\n checker: ts.TypeChecker,\n project: string,\n acc: RelationAccumulator,\n ): void {\n const method = calleeMethodName(call);\n if (method === null || call.arguments.length === 0) return;\n if (method === ADD_ROUTES_METHOD) {\n const info = this.apiInfoFromExpr(call.arguments[0], checker, project);\n if (info) acc.addImplements(info.owner, { api: info.api, type: info.type });\n return;\n }\n if (method === RPC_CLIENT_METHOD || method === PUBSUB_CLIENT_METHOD) {\n const info = this.apiInfoFromExpr(call.arguments[0], checker, project);\n if (!info) return;\n // Argument 2 names WHICH service this client talks to. Keeping it is what lets the\n // runtime graph draw ONE edge instead of one per implementer of the contract.\n const targetService = targetServiceOf(call);\n const ref: ApiRef = { api: info.api, type: info.type };\n if (targetService !== null) ref.targetService = targetService;\n acc.addUses(info.owner, ref);\n }\n }\n\n /** Resolve an expression to the API contract it names, or null if it is not one. */\n private apiInfoFromExpr(\n expr: ts.Expression,\n checker: ts.TypeChecker,\n project: string,\n ): ApiClassInfo | null {\n const decl = resolveClassDeclaration(expr, checker);\n if (!decl) return null;\n const fromSource = this.apiClassInfoFor(decl);\n return fromSource ?? this.recoverFromDeclaration(decl, expr, project);\n }\n\n /**\n * The checker landed on a BUILT declaration instead of source — the consumer has no\n * tsconfig.base `paths` entry for the api-lib, so the import went through node_modules to\n * `dist/**.d.ts`. tsc erases decorators when emitting declarations, so `@ApiPath` is simply\n * not there and never will be. Recover the contract by name from the source index; the graph\n * is then correct no matter how the consumer's tsconfig is laid out.\n */\n private recoverFromDeclaration(\n decl: ts.ClassDeclaration,\n expr: ts.Expression,\n project: string,\n ): ApiClassInfo | null {\n // An abstract class is the shape of a contract; a non-abstract argument is genuinely not one.\n if (!decl.getSourceFile().isDeclarationFile || !isAbstractClass(decl) || !decl.name)\n return null;\n const recovered = this.sourceIndex.lookup(decl.name.text);\n if (recovered) return recovered;\n // Abstract, in a .d.ts, yet no workspace source owns it — the scan is blind here. Say so.\n this.unresolvedApiCalls.push(\n new UnresolvedApiCall(\n project,\n decl.name.text,\n this.relativeLocation(expr),\n this.relativePath(decl.getSourceFile().fileName),\n ),\n );\n return null;\n }\n\n /** `path/to/file.ts:LINE` for `node`, workspace-relative, for a human-readable report. */\n private relativeLocation(node: ts.Node): string {\n const sourceFile = node.getSourceFile();\n const position = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n return `${this.relativePath(sourceFile.fileName)}:${position.line + 1}`;\n }\n\n private relativePath(absFile: string): string {\n return path.relative(this.workspaceRoot, absFile);\n }\n\n /**\n * {api, owner, type, methods} when `cls` is an `abstract class` carrying `@ApiPath` IN SOURCE,\n * else null. Only the OWNER differs from the index pre-pass — here it comes from the file's\n * location rather than from the project being walked — so the contract test itself is delegated\n * to apiClassInfoFrom, keeping one definition of \"this is a contract\".\n */\n private apiClassInfoFor(cls: ts.ClassDeclaration): ApiClassInfo | null {\n const owner = this.locator.projectOf(cls.getSourceFile().fileName);\n if (owner === null) return null;\n return apiClassInfoFrom(cls, owner);\n }\n}\n\n/**\n * Run the scan and attach the derived `apiRelations` onto each graph entry in\n * place. Shared by `architecture:generate` (which then saves) and\n * `architecture:validate-architecture-unchanged` (which regenerates in memory\n * and must attach the SAME field, or it would see a phantom diff). Returns the\n * full scan so callers (validators, runtime graph) can reuse the api index.\n */\n// webpieces-disable no-function-outside-class -- module entry point, mirrors generateReducedGraph/collectBindings\nexport function scanAndAttachApiRelations(\n workspaceRoot: string,\n graph: EnhancedGraph,\n projectInfos: Map<string, ProjectInfo>,\n externalApiPaths: readonly string[] = [],\n): ApiScanResult {\n const result = new ApiUsageScanner(\n workspaceRoot,\n projectInfos,\n externalApiPaths,\n RootUnionRule.fromConfig(workspaceRoot),\n ApiDocRule.fromConfig(workspaceRoot, OPENAPI_RULE),\n ApiDocRule.fromConfig(workspaceRoot, MCP_RULE),\n WireClosureRule.fromConfig(workspaceRoot),\n ).scan();\n for (const projectName of result.relationsByProject.keys()) {\n const entry = graph[projectName];\n if (entry) entry.apiRelations = result.relationsByProject.get(projectName);\n }\n return result;\n}\n\n/**\n * The committed api contract table (one `architecture/apis/<ApiName>.json` per entry), from a\n * completed scan.\n *\n * Only contracts with ≥1 endpoint are emitted: a vendor seam has no routes, so a table entry for it\n * would be an empty shell, and its identity is already carried by the `external` refs in\n * apiRelations. Sorted by api name, methods left in declaration order, so the file is deterministic.\n *\n * THROWS on the ways an entry can be wrong-but-green, checked root cause first:\n * 1. an `@Endpoint` path the scan could not read (UnresolvedEndpointPathError) — the other half of\n * the URL a consumer computes, and the cause of most emptied contracts;\n * 2. a class that declared endpoints and kept none (EmptiedApiContractError), which would otherwise\n * leave silently through the zero-method skip above;\n * 3. a method without an explicit operation (UndeclaredEndpointOperationError);\n * 4. an `external` method that never said WHO calls it (UndeclaredExternalCallerError);\n * 5. a routed contract with no basePath (MissingBasePathError).\n * All are worse than an absent entry: a consumer joining `basePath + path` computes a\n * confidently wrong URL with no signal that anything is off, because every other entry is complete.\n * Each error aggregates EVERY offender, so a developer fixing five constants sees five in one run.\n */\n// webpieces-disable no-function-outside-class -- module entry point, mirrors scanAndAttachApiRelations\nexport function buildApiContracts(scan: ApiScanResult): ApiContracts {\n // Root cause before symptom: an unreadable path is what empties a contract, so naming the paths\n // is what the author can actually act on.\n if (scan.unresolvedEndpointPaths.length > 0)\n throw new UnresolvedEndpointPathError(scan.unresolvedEndpointPaths);\n if (scan.emptiedApiContracts.length > 0)\n throw new EmptiedApiContractError(scan.emptiedApiContracts);\n if (scan.undeclaredEndpointOperations.length > 0) {\n throw new UndeclaredEndpointOperationError(scan.undeclaredEndpointOperations);\n }\n // A shape no function-calling API will accept, read perfectly well — unlike the four above, which\n // are contracts the scan could not READ at all.\n if (!scan.rootUnions.isEmpty()) throw new RootUnionApiTypeError(scan.rootUnions);\n // Contract shapes that are not PUBLISHABLE, read by the generator's own extractor (#1011).\n // After the root union, which is the one shape no function-calling API will accept at all, and\n // before the caller checks below, which are about the architecture graph rather than a document.\n if (!scan.apiDocRules.openApi.isEmpty()) {\n throw new ApiRulesForOpenApiError(scan.apiDocRules.openApi);\n }\n if (!scan.apiDocRules.mcp.isEmpty()) {\n throw new ApiRulesForMcpError(scan.apiDocRules.mcp, scan.apiDocRules.mcpExclusions);\n }\n // After the two above: an unreadable path is what empties a contract, and a contract that lost\n // every method has no external endpoint left to complain about.\n if (scan.undeclaredExternalCallers.length > 0) {\n throw new UndeclaredExternalCallerError(scan.undeclaredExternalCallers);\n }\n const contracts: ApiContracts = {};\n const missing: string[] = [];\n for (const api of [...scan.apiIndex.keys()].sort()) {\n const info = scan.apiIndex.get(api)!;\n if (info.methods.length === 0) continue;\n if (info.basePath === undefined) {\n missing.push(`${api} (owner ${info.owner})`);\n continue;\n }\n const contract: ApiContract = {\n owner: info.owner,\n apiKind: info.type,\n basePath: info.basePath,\n methods: info.methods,\n };\n contracts[api] = contract;\n }\n if (missing.length > 0) throw new MissingBasePathError(missing);\n return contracts;\n}\n\n/**\n * Loud, actionable report for decorator arguments the scan could not reduce to a string.\n *\n * Same-module constants resolve, so anything reaching here is genuinely out of reach of a\n * parser-only pass — and every one of them silently shrinks the graph. Empty string when there is\n * nothing to say, so callers can test it without special-casing.\n */\n// webpieces-disable no-function-outside-class -- pure formatter, mirrors describeUnresolvedApiCalls\nexport function describeNonLiteralDecoratorArgs(args: readonly NonLiteralDecoratorArg[]): string {\n if (args.length === 0) return '';\n const lines = [\n `⚠️ ${args.length} decorator argument(s) are not string literals and could not be resolved.`,\n ` Each one drops data from the graph: a missing basePath, a missing method, or a whole contract:`,\n ];\n for (const arg of args) {\n const where = arg.method === null ? arg.api : `${arg.api}.${arg.method}`;\n lines.push(` • @${arg.decorator}(${arg.argument}) on ${where} at ${arg.at}`);\n }\n lines.push(\n ` A constant declared in the SAME module resolves. One imported from another module does not —`,\n ` this scan is parser-only by design (module resolution can land on a decorator-erased .d.ts).`,\n ` Fix by inlining the string literal, or by moving the constant into the contract's own module.`,\n );\n return lines.join('\\n');\n}\n\n/**\n * Every contract method whose declared @Endpoint kind its api kind cannot deliver — an rpc method on\n * a @PubSub contract (nothing calls a queue synchronously), or a cloudtasks/cron method on an @Rpc\n * contract (naming a queue or schedule nothing could deliver to). Mirrors core-util's\n * ENDPOINT_KINDS_BY_API_KIND at BUILD time, where it can name the file instead of throwing at wiring.\n */\n// webpieces-disable no-function-outside-class -- pure formatter, mirrors describeUnresolvedApiCalls\nexport function describeMismatchedEndpointKinds(contracts: ApiContracts): string[] {\n const allowedByKind: Record<string, readonly EndpointKind[]> = {\n rpc: ['rpc', 'external'],\n pubsub: ['cloudtasks', 'cron', 'external'],\n };\n const problems: string[] = [];\n for (const api of Object.keys(contracts)) {\n const contract = contracts[api];\n const allowed = allowedByKind[contract.apiKind];\n if (allowed === undefined) continue;\n for (const method of contract.methods) {\n if (allowed.includes(method.kind)) continue;\n problems.push(\n `${api}.${method.name} declares @Endpoint(${method.httpMethod ?? 'POST'}, '${method.path}', ${method.operation}, ${method.kind}) but ${api} is ` +\n `@${contract.apiKind === 'pubsub' ? 'PubSub' : 'Rpc'} — allowed kinds are ${allowed.join(' | ')}.`,\n );\n }\n }\n return problems;\n}\n\n/**\n * Build a program for scanning ONE project. Prefers the project's compile tsconfig; but when that\n * is a solution-style tsconfig (only `references`, no `files`/`include` — e.g. legacy-server), it\n * yields zero files, so we fall back to globbing the project's own `src/**` and reuse the resolved\n * compiler options (which carry tsconfig.base `paths` for cross-package @webpieces resolution).\n *\n * `paths` is a PREFERENCE, not a precondition: it lets imports resolve straight to source. Without\n * it they land on a decorator-erased `dist/**.d.ts`, which the source index recovers from — see\n * ApiUsageScanner.recoverFromDeclaration.\n */\n// webpieces-disable no-function-outside-class -- ts Program factory, mirrors di-graph/program.ts\nfunction createScanProgram(projectRootAbs: string): ts.Program | null {\n const configPath = findProjectTsconfig(projectRootAbs);\n if (!configPath) return buildProgramFromSrc(projectRootAbs, {});\n const host = Object.assign({}, ts.sys, {\n onUnRecoverableConfigFileDiagnostic: (): void => undefined,\n }) as ts.ParseConfigFileHost;\n const parsed = ts.getParsedCommandLineOfConfigFile(configPath, {}, host);\n if (!parsed) return null;\n if (parsed.fileNames.length > 0) return ts.createProgram(parsed.fileNames, parsed.options);\n return buildProgramFromSrc(projectRootAbs, parsed.options);\n}\n\n// webpieces-disable no-function-outside-class -- ts Program factory helper, mirrors di-graph/program.ts\nfunction buildProgramFromSrc(\n projectRootAbs: string,\n options: ts.CompilerOptions,\n): ts.Program | null {\n const srcDir = path.join(projectRootAbs, 'src');\n if (!fs.existsSync(srcDir)) return null;\n const files = collectTsFiles(srcDir);\n return files.length > 0 ? ts.createProgram(files, options) : null;\n}\n"]}