@webpieces/dev-config 0.2.89 → 0.2.90

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.
@@ -0,0 +1,402 @@
1
+ "use strict";
2
+ /**
3
+ * Validate No Direct API in Resolver Executor
4
+ *
5
+ * Validates two Angular anti-patterns using LINE-BASED detection:
6
+ *
7
+ * ============================================================================
8
+ * VIOLATIONS (BAD) - These patterns are flagged:
9
+ * ============================================================================
10
+ *
11
+ * 1. In *.routes.ts files: inject(XxxApi) — resolvers should inject services, not APIs directly
12
+ * 2. In *.component.ts files: this.<field>.snapshot.data — components should subscribe to
13
+ * service BehaviorSubjects, not read route snapshot data
14
+ *
15
+ * ============================================================================
16
+ * CORRECT PATTERNS (GOOD)
17
+ * ============================================================================
18
+ *
19
+ * 1. In resolvers: inject(XxxService) which calls the API internally
20
+ * 2. In components: this.myService.someObservable$ (subscribe to service BehaviorSubjects)
21
+ *
22
+ * ============================================================================
23
+ * MODES (LINE-BASED)
24
+ * ============================================================================
25
+ * - OFF: Skip validation entirely
26
+ * - MODIFIED_CODE: Flag violations on changed lines (lines in diff hunks)
27
+ * - MODIFIED_FILES: Flag ALL violations in files that were modified
28
+ *
29
+ * ============================================================================
30
+ * ESCAPE HATCH
31
+ * ============================================================================
32
+ * Add comment above the violation:
33
+ * // webpieces-disable no-direct-api-resolver -- [your justification]
34
+ * const myApi = inject(MyApi);
35
+ */
36
+ Object.defineProperty(exports, "__esModule", { value: true });
37
+ exports.default = runExecutor;
38
+ const tslib_1 = require("tslib");
39
+ const child_process_1 = require("child_process");
40
+ const fs = tslib_1.__importStar(require("fs"));
41
+ const path = tslib_1.__importStar(require("path"));
42
+ const ts = tslib_1.__importStar(require("typescript"));
43
+ const diff_utils_1 = require("../diff-utils");
44
+ /**
45
+ * Get changed TypeScript files between base and head (or working tree if head not specified).
46
+ */
47
+ // webpieces-disable max-lines-new-methods -- Git command handling with untracked files requires multiple code paths
48
+ function getChangedTypeScriptFiles(workspaceRoot, base, head) {
49
+ try {
50
+ const diffTarget = head ? `${base} ${head}` : base;
51
+ const output = (0, child_process_1.execSync)(`git diff --name-only ${diffTarget} -- '*.ts' '*.tsx'`, {
52
+ cwd: workspaceRoot,
53
+ encoding: 'utf-8',
54
+ });
55
+ const changedFiles = output
56
+ .trim()
57
+ .split('\n')
58
+ .filter((f) => f && !f.includes('.spec.ts') && !f.includes('.test.ts'));
59
+ if (!head) {
60
+ try {
61
+ const untrackedOutput = (0, child_process_1.execSync)(`git ls-files --others --exclude-standard '*.ts' '*.tsx'`, {
62
+ cwd: workspaceRoot,
63
+ encoding: 'utf-8',
64
+ });
65
+ const untrackedFiles = untrackedOutput
66
+ .trim()
67
+ .split('\n')
68
+ .filter((f) => f && !f.includes('.spec.ts') && !f.includes('.test.ts'));
69
+ const allFiles = new Set([...changedFiles, ...untrackedFiles]);
70
+ return Array.from(allFiles);
71
+ }
72
+ catch {
73
+ return changedFiles;
74
+ }
75
+ }
76
+ return changedFiles;
77
+ }
78
+ catch {
79
+ return [];
80
+ }
81
+ }
82
+ /**
83
+ * Check if a line contains a webpieces-disable comment for no-direct-api-resolver.
84
+ */
85
+ function hasDisableComment(lines, lineNumber) {
86
+ const startCheck = Math.max(0, lineNumber - 5);
87
+ for (let i = lineNumber - 2; i >= startCheck; i--) {
88
+ const line = lines[i]?.trim() ?? '';
89
+ if (line.startsWith('function ') || line.startsWith('class ') || line.endsWith('}')) {
90
+ break;
91
+ }
92
+ if (line.includes('webpieces-disable') && line.includes('no-direct-api-resolver')) {
93
+ return true;
94
+ }
95
+ }
96
+ return false;
97
+ }
98
+ /**
99
+ * Auto-detect the base branch by finding the merge-base with origin/main.
100
+ */
101
+ function detectBase(workspaceRoot) {
102
+ try {
103
+ const mergeBase = (0, child_process_1.execSync)('git merge-base HEAD origin/main', {
104
+ cwd: workspaceRoot,
105
+ encoding: 'utf-8',
106
+ stdio: ['pipe', 'pipe', 'pipe'],
107
+ }).trim();
108
+ if (mergeBase) {
109
+ return mergeBase;
110
+ }
111
+ }
112
+ catch {
113
+ try {
114
+ const mergeBase = (0, child_process_1.execSync)('git merge-base HEAD main', {
115
+ cwd: workspaceRoot,
116
+ encoding: 'utf-8',
117
+ stdio: ['pipe', 'pipe', 'pipe'],
118
+ }).trim();
119
+ if (mergeBase) {
120
+ return mergeBase;
121
+ }
122
+ }
123
+ catch {
124
+ // Ignore
125
+ }
126
+ }
127
+ return null;
128
+ }
129
+ /**
130
+ * Find inject(XxxApi) calls in *.routes.ts files.
131
+ * Flags any CallExpression where callee is `inject` and the first argument is an identifier ending with `Api`.
132
+ */
133
+ function findDirectApiInjections(filePath, workspaceRoot, disableAllowed) {
134
+ if (!filePath.endsWith('.routes.ts'))
135
+ return [];
136
+ const fullPath = path.join(workspaceRoot, filePath);
137
+ if (!fs.existsSync(fullPath))
138
+ return [];
139
+ const content = fs.readFileSync(fullPath, 'utf-8');
140
+ const fileLines = content.split('\n');
141
+ const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
142
+ const violations = [];
143
+ function visit(node) {
144
+ try {
145
+ if (ts.isCallExpression(node)) {
146
+ const callee = node.expression;
147
+ if (ts.isIdentifier(callee) && callee.text === 'inject') {
148
+ const firstArg = node.arguments[0];
149
+ if (firstArg && ts.isIdentifier(firstArg) && firstArg.text.endsWith('Api')) {
150
+ const startPos = node.getStart(sourceFile);
151
+ if (startPos >= 0) {
152
+ const pos = sourceFile.getLineAndCharacterOfPosition(startPos);
153
+ const line = pos.line + 1;
154
+ const column = pos.character + 1;
155
+ const disabled = hasDisableComment(fileLines, line);
156
+ if (!disableAllowed && disabled) {
157
+ violations.push({ line, column, context: `inject(${firstArg.text}) in route resolver`, hasDisableComment: false });
158
+ }
159
+ else {
160
+ violations.push({ line, column, context: `inject(${firstArg.text}) in route resolver`, hasDisableComment: disabled });
161
+ }
162
+ }
163
+ }
164
+ }
165
+ }
166
+ }
167
+ catch {
168
+ // Skip nodes that cause errors during analysis
169
+ }
170
+ ts.forEachChild(node, visit);
171
+ }
172
+ visit(sourceFile);
173
+ return violations;
174
+ }
175
+ /**
176
+ * Find this.<field>.snapshot.data access patterns in *.component.ts files.
177
+ * Flags PropertyAccessExpression chains: this.<anything>.snapshot.data
178
+ */
179
+ function findSnapshotDataAccess(filePath, workspaceRoot, disableAllowed) {
180
+ if (!filePath.endsWith('.component.ts'))
181
+ return [];
182
+ const fullPath = path.join(workspaceRoot, filePath);
183
+ if (!fs.existsSync(fullPath))
184
+ return [];
185
+ const content = fs.readFileSync(fullPath, 'utf-8');
186
+ const fileLines = content.split('\n');
187
+ const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
188
+ const violations = [];
189
+ function visit(node) {
190
+ try {
191
+ // Looking for: this.<field>.snapshot.data
192
+ // AST shape: PropertyAccessExpression(.data) -> PropertyAccessExpression(.snapshot) -> PropertyAccessExpression(.<field>) -> this
193
+ if (ts.isPropertyAccessExpression(node) && node.name.text === 'data') {
194
+ const snapshotAccess = node.expression;
195
+ if (ts.isPropertyAccessExpression(snapshotAccess) && snapshotAccess.name.text === 'snapshot') {
196
+ const fieldAccess = snapshotAccess.expression;
197
+ if (ts.isPropertyAccessExpression(fieldAccess)) {
198
+ const receiver = fieldAccess.expression;
199
+ if (receiver.kind === ts.SyntaxKind.ThisKeyword) {
200
+ const fieldName = fieldAccess.name.text;
201
+ const startPos = node.getStart(sourceFile);
202
+ if (startPos >= 0) {
203
+ const pos = sourceFile.getLineAndCharacterOfPosition(startPos);
204
+ const line = pos.line + 1;
205
+ const column = pos.character + 1;
206
+ const disabled = hasDisableComment(fileLines, line);
207
+ if (!disableAllowed && disabled) {
208
+ violations.push({ line, column, context: `this.${fieldName}.snapshot.data in component`, hasDisableComment: false });
209
+ }
210
+ else {
211
+ violations.push({ line, column, context: `this.${fieldName}.snapshot.data in component`, hasDisableComment: disabled });
212
+ }
213
+ }
214
+ }
215
+ }
216
+ }
217
+ }
218
+ }
219
+ catch {
220
+ // Skip nodes that cause errors during analysis
221
+ }
222
+ ts.forEachChild(node, visit);
223
+ }
224
+ visit(sourceFile);
225
+ return violations;
226
+ }
227
+ /**
228
+ * Find all violations in a file (both inject(Api) and snapshot.data patterns).
229
+ */
230
+ function findViolationsInFile(filePath, workspaceRoot, disableAllowed) {
231
+ const apiViolations = findDirectApiInjections(filePath, workspaceRoot, disableAllowed);
232
+ const snapshotViolations = findSnapshotDataAccess(filePath, workspaceRoot, disableAllowed);
233
+ return [...apiViolations, ...snapshotViolations];
234
+ }
235
+ /**
236
+ * MODIFIED_CODE mode: Flag violations on changed lines in diff hunks.
237
+ */
238
+ // webpieces-disable max-lines-new-methods -- File iteration with diff parsing and line filtering
239
+ function findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed) {
240
+ const violations = [];
241
+ for (const file of changedFiles) {
242
+ const diff = (0, diff_utils_1.getFileDiff)(workspaceRoot, file, base, head);
243
+ const changedLines = (0, diff_utils_1.getChangedLineNumbers)(diff);
244
+ if (changedLines.size === 0)
245
+ continue;
246
+ const allViolations = findViolationsInFile(file, workspaceRoot, disableAllowed);
247
+ for (const v of allViolations) {
248
+ if (disableAllowed && v.hasDisableComment)
249
+ continue;
250
+ // LINE-BASED: Only include if the violation is on a changed line
251
+ if (!changedLines.has(v.line))
252
+ continue;
253
+ violations.push({
254
+ file,
255
+ line: v.line,
256
+ column: v.column,
257
+ context: v.context,
258
+ });
259
+ }
260
+ }
261
+ return violations;
262
+ }
263
+ /**
264
+ * MODIFIED_FILES mode: Flag ALL violations in files that were modified.
265
+ */
266
+ function findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed) {
267
+ const violations = [];
268
+ for (const file of changedFiles) {
269
+ const allViolations = findViolationsInFile(file, workspaceRoot, disableAllowed);
270
+ for (const v of allViolations) {
271
+ if (disableAllowed && v.hasDisableComment)
272
+ continue;
273
+ violations.push({
274
+ file,
275
+ line: v.line,
276
+ column: v.column,
277
+ context: v.context,
278
+ });
279
+ }
280
+ }
281
+ return violations;
282
+ }
283
+ /**
284
+ * Report violations to console.
285
+ */
286
+ // webpieces-disable max-lines-new-methods -- Console output with examples and escape hatch information
287
+ function reportViolations(violations, mode, disableAllowed) {
288
+ console.error('');
289
+ console.error('\u274c Direct API usage in resolvers or snapshot.data in components found!');
290
+ console.error('');
291
+ console.error('\ud83d\udcda Resolvers should use services, and components should subscribe to service observables:');
292
+ console.error('');
293
+ console.error(' BAD (in *.routes.ts resolver):');
294
+ console.error(' const myApi = inject(MyApi);');
295
+ console.error(' resolve: () => inject(MyApi).fetchData()');
296
+ console.error('');
297
+ console.error(' GOOD (in *.routes.ts resolver):');
298
+ console.error(' const myService = inject(MyService);');
299
+ console.error(' resolve: () => inject(MyService).loadData()');
300
+ console.error('');
301
+ console.error(' BAD (in *.component.ts):');
302
+ console.error(' const data = this.route.snapshot.data;');
303
+ console.error('');
304
+ console.error(' GOOD (in *.component.ts):');
305
+ console.error(' this.myService.data$.subscribe(data => ...)');
306
+ console.error('');
307
+ for (const v of violations) {
308
+ console.error(` \u274c ${v.file}:${v.line}:${v.column}`);
309
+ console.error(` ${v.context}`);
310
+ }
311
+ console.error('');
312
+ if (disableAllowed) {
313
+ console.error(' Escape hatch (use sparingly):');
314
+ console.error(' // webpieces-disable no-direct-api-resolver -- [your reason]');
315
+ }
316
+ else {
317
+ console.error(' Escape hatch: DISABLED (disableAllowed: false)');
318
+ console.error(' Disable comments are ignored. Fix the pattern directly.');
319
+ }
320
+ console.error('');
321
+ console.error(` Current mode: ${mode}`);
322
+ console.error('');
323
+ }
324
+ /**
325
+ * Resolve mode considering ignoreModifiedUntilEpoch override.
326
+ * When active, downgrades to OFF. When expired, logs a warning.
327
+ */
328
+ function resolveMode(normalMode, epoch) {
329
+ if (epoch === undefined || normalMode === 'OFF') {
330
+ return normalMode;
331
+ }
332
+ const nowSeconds = Date.now() / 1000;
333
+ if (nowSeconds < epoch) {
334
+ const expiresDate = new Date(epoch * 1000).toISOString().split('T')[0];
335
+ console.log(`\n\u23ed\ufe0f Skipping no-direct-api-resolver validation (ignoreModifiedUntilEpoch active, expires: ${expiresDate})`);
336
+ console.log('');
337
+ return 'OFF';
338
+ }
339
+ return normalMode;
340
+ }
341
+ /**
342
+ * Filter changed files to only those under enforcePaths (if configured).
343
+ */
344
+ function filterByEnforcePaths(changedFiles, enforcePaths) {
345
+ if (!enforcePaths || enforcePaths.length === 0) {
346
+ return changedFiles;
347
+ }
348
+ return changedFiles.filter((file) => enforcePaths.some((prefix) => file.startsWith(prefix)));
349
+ }
350
+ /**
351
+ * Filter to only relevant Angular files (*.routes.ts and *.component.ts).
352
+ */
353
+ function filterRelevantFiles(changedFiles) {
354
+ return changedFiles.filter((file) => file.endsWith('.routes.ts') || file.endsWith('.component.ts'));
355
+ }
356
+ async function runExecutor(options, context) {
357
+ const workspaceRoot = context.root;
358
+ const mode = resolveMode(options.mode ?? 'OFF', options.ignoreModifiedUntilEpoch);
359
+ const disableAllowed = options.disableAllowed ?? true;
360
+ if (mode === 'OFF') {
361
+ console.log('\n\u23ed\ufe0f Skipping no-direct-api-resolver validation (mode: OFF)');
362
+ console.log('');
363
+ return { success: true };
364
+ }
365
+ console.log('\n\ud83d\udccf Validating No Direct API in Resolver\n');
366
+ console.log(` Mode: ${mode}`);
367
+ let base = process.env['NX_BASE'];
368
+ const head = process.env['NX_HEAD'];
369
+ if (!base) {
370
+ base = detectBase(workspaceRoot) ?? undefined;
371
+ if (!base) {
372
+ console.log('\n\u23ed\ufe0f Skipping no-direct-api-resolver validation (could not detect base branch)');
373
+ console.log('');
374
+ return { success: true };
375
+ }
376
+ }
377
+ console.log(` Base: ${base}`);
378
+ console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);
379
+ console.log('');
380
+ const allChangedFiles = getChangedTypeScriptFiles(workspaceRoot, base, head);
381
+ const scopedFiles = filterByEnforcePaths(allChangedFiles, options.enforcePaths);
382
+ const changedFiles = filterRelevantFiles(scopedFiles);
383
+ if (changedFiles.length === 0) {
384
+ console.log('\u2705 No relevant Angular files changed (*.routes.ts, *.component.ts)');
385
+ return { success: true };
386
+ }
387
+ console.log(`\ud83d\udcc2 Checking ${changedFiles.length} changed file(s)...`);
388
+ let violations = [];
389
+ if (mode === 'MODIFIED_CODE') {
390
+ violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed);
391
+ }
392
+ else if (mode === 'MODIFIED_FILES') {
393
+ violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);
394
+ }
395
+ if (violations.length === 0) {
396
+ console.log('\u2705 No direct API resolver patterns found');
397
+ return { success: true };
398
+ }
399
+ reportViolations(violations, mode, disableAllowed);
400
+ return { success: false };
401
+ }
402
+ //# sourceMappingURL=executor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/dev-config/architecture/executors/validate-no-direct-api-resolver/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;;AA+XH,8BA6DC;;AAzbD,iDAAyC;AACzC,+CAAyB;AACzB,mDAA6B;AAC7B,uDAAiC;AACjC,8CAAmE;AA6BnE;;GAEG;AACH,oHAAoH;AACpH,SAAS,yBAAyB,CAAC,aAAqB,EAAE,IAAY,EAAE,IAAa;IACjF,IAAI,CAAC;QACD,MAAM,UAAU,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;QACnD,MAAM,MAAM,GAAG,IAAA,wBAAQ,EAAC,wBAAwB,UAAU,oBAAoB,EAAE;YAC5E,GAAG,EAAE,aAAa;YAClB,QAAQ,EAAE,OAAO;SACpB,CAAC,CAAC;QACH,MAAM,YAAY,GAAG,MAAM;aACtB,IAAI,EAAE;aACN,KAAK,CAAC,IAAI,CAAC;aACX,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAA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AC;QAC5D,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7B,CAAC;IAED,gBAAgB,CAAC,UAAU,EAAE,IAAI,EAAE,cAAc,CAAC,CAAC;IAEnD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC9B,CAAC","sourcesContent":["/**\n * Validate No Direct API in Resolver Executor\n *\n * Validates two Angular anti-patterns using LINE-BASED detection:\n *\n * ============================================================================\n * VIOLATIONS (BAD) - These patterns are flagged:\n * ============================================================================\n *\n * 1. In *.routes.ts files: inject(XxxApi) — resolvers should inject services, not APIs directly\n * 2. In *.component.ts files: this.<field>.snapshot.data — components should subscribe to\n * service BehaviorSubjects, not read route snapshot data\n *\n * ============================================================================\n * CORRECT PATTERNS (GOOD)\n * ============================================================================\n *\n * 1. In resolvers: inject(XxxService) which calls the API internally\n * 2. In components: this.myService.someObservable$ (subscribe to service BehaviorSubjects)\n *\n * ============================================================================\n * MODES (LINE-BASED)\n * ============================================================================\n * - OFF: Skip validation entirely\n * - MODIFIED_CODE: Flag violations on changed lines (lines in diff hunks)\n * - MODIFIED_FILES: Flag ALL violations in files that were modified\n *\n * ============================================================================\n * ESCAPE HATCH\n * ============================================================================\n * Add comment above the violation:\n * // webpieces-disable no-direct-api-resolver -- [your justification]\n * const myApi = inject(MyApi);\n */\n\nimport type { ExecutorContext } from '@nx/devkit';\nimport { execSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as ts from 'typescript';\nimport { getFileDiff, getChangedLineNumbers } from '../diff-utils';\n\nexport type NoDirectApiResolverMode = 'OFF' | 'MODIFIED_CODE' | 'MODIFIED_FILES';\n\nexport interface ValidateNoDirectApiResolverOptions {\n mode?: NoDirectApiResolverMode;\n disableAllowed?: boolean;\n ignoreModifiedUntilEpoch?: number;\n enforcePaths?: string[];\n}\n\nexport interface ExecutorResult {\n success: boolean;\n}\n\ninterface Violation {\n file: string;\n line: number;\n column: number;\n context: string;\n}\n\ninterface ViolationInfo {\n line: number;\n column: number;\n context: string;\n hasDisableComment: boolean;\n}\n\n/**\n * Get changed TypeScript files between base and head (or working tree if head not specified).\n */\n// webpieces-disable max-lines-new-methods -- Git command handling with untracked files requires multiple code paths\nfunction getChangedTypeScriptFiles(workspaceRoot: string, base: string, head?: string): string[] {\n try {\n const diffTarget = head ? `${base} ${head}` : base;\n const output = execSync(`git diff --name-only ${diffTarget} -- '*.ts' '*.tsx'`, {\n cwd: workspaceRoot,\n encoding: 'utf-8',\n });\n const changedFiles = output\n .trim()\n .split('\\n')\n .filter((f) => f && !f.includes('.spec.ts') && !f.includes('.test.ts'));\n\n if (!head) {\n try {\n const untrackedOutput = execSync(`git ls-files --others --exclude-standard '*.ts' '*.tsx'`, {\n cwd: workspaceRoot,\n encoding: 'utf-8',\n });\n const untrackedFiles = untrackedOutput\n .trim()\n .split('\\n')\n .filter((f) => f && !f.includes('.spec.ts') && !f.includes('.test.ts'));\n const allFiles = new Set([...changedFiles, ...untrackedFiles]);\n return Array.from(allFiles);\n } catch {\n return changedFiles;\n }\n }\n\n return changedFiles;\n } catch {\n return [];\n }\n}\n\n/**\n * Check if a line contains a webpieces-disable comment for no-direct-api-resolver.\n */\nfunction hasDisableComment(lines: string[], lineNumber: number): boolean {\n const startCheck = Math.max(0, lineNumber - 5);\n for (let i = lineNumber - 2; i >= startCheck; i--) {\n const line = lines[i]?.trim() ?? '';\n if (line.startsWith('function ') || line.startsWith('class ') || line.endsWith('}')) {\n break;\n }\n if (line.includes('webpieces-disable') && line.includes('no-direct-api-resolver')) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Auto-detect the base branch by finding the merge-base with origin/main.\n */\nfunction detectBase(workspaceRoot: string): string | null {\n try {\n const mergeBase = execSync('git merge-base HEAD origin/main', {\n cwd: workspaceRoot,\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n\n if (mergeBase) {\n return mergeBase;\n }\n } catch {\n try {\n const mergeBase = execSync('git merge-base HEAD main', {\n cwd: workspaceRoot,\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n\n if (mergeBase) {\n return mergeBase;\n }\n } catch {\n // Ignore\n }\n }\n return null;\n}\n\n/**\n * Find inject(XxxApi) calls in *.routes.ts files.\n * Flags any CallExpression where callee is `inject` and the first argument is an identifier ending with `Api`.\n */\nfunction findDirectApiInjections(filePath: string, workspaceRoot: string, disableAllowed: boolean): ViolationInfo[] {\n if (!filePath.endsWith('.routes.ts')) return [];\n\n const fullPath = path.join(workspaceRoot, filePath);\n if (!fs.existsSync(fullPath)) return [];\n\n const content = fs.readFileSync(fullPath, 'utf-8');\n const fileLines = content.split('\\n');\n const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);\n\n const violations: ViolationInfo[] = [];\n\n function visit(node: ts.Node): void {\n try {\n if (ts.isCallExpression(node)) {\n const callee = node.expression;\n if (ts.isIdentifier(callee) && callee.text === 'inject') {\n const firstArg = node.arguments[0];\n if (firstArg && ts.isIdentifier(firstArg) && firstArg.text.endsWith('Api')) {\n const startPos = node.getStart(sourceFile);\n if (startPos >= 0) {\n const pos = sourceFile.getLineAndCharacterOfPosition(startPos);\n const line = pos.line + 1;\n const column = pos.character + 1;\n const disabled = hasDisableComment(fileLines, line);\n\n if (!disableAllowed && disabled) {\n violations.push({ line, column, context: `inject(${firstArg.text}) in route resolver`, hasDisableComment: false });\n } else {\n violations.push({ line, column, context: `inject(${firstArg.text}) in route resolver`, hasDisableComment: disabled });\n }\n }\n }\n }\n }\n } catch {\n // Skip nodes that cause errors during analysis\n }\n\n ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return violations;\n}\n\n/**\n * Find this.<field>.snapshot.data access patterns in *.component.ts files.\n * Flags PropertyAccessExpression chains: this.<anything>.snapshot.data\n */\nfunction findSnapshotDataAccess(filePath: string, workspaceRoot: string, disableAllowed: boolean): ViolationInfo[] {\n if (!filePath.endsWith('.component.ts')) return [];\n\n const fullPath = path.join(workspaceRoot, filePath);\n if (!fs.existsSync(fullPath)) return [];\n\n const content = fs.readFileSync(fullPath, 'utf-8');\n const fileLines = content.split('\\n');\n const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);\n\n const violations: ViolationInfo[] = [];\n\n function visit(node: ts.Node): void {\n try {\n // Looking for: this.<field>.snapshot.data\n // AST shape: PropertyAccessExpression(.data) -> PropertyAccessExpression(.snapshot) -> PropertyAccessExpression(.<field>) -> this\n if (ts.isPropertyAccessExpression(node) && node.name.text === 'data') {\n const snapshotAccess = node.expression;\n if (ts.isPropertyAccessExpression(snapshotAccess) && snapshotAccess.name.text === 'snapshot') {\n const fieldAccess = snapshotAccess.expression;\n if (ts.isPropertyAccessExpression(fieldAccess)) {\n const receiver = fieldAccess.expression;\n if (receiver.kind === ts.SyntaxKind.ThisKeyword) {\n const fieldName = fieldAccess.name.text;\n const startPos = node.getStart(sourceFile);\n if (startPos >= 0) {\n const pos = sourceFile.getLineAndCharacterOfPosition(startPos);\n const line = pos.line + 1;\n const column = pos.character + 1;\n const disabled = hasDisableComment(fileLines, line);\n\n if (!disableAllowed && disabled) {\n violations.push({ line, column, context: `this.${fieldName}.snapshot.data in component`, hasDisableComment: false });\n } else {\n violations.push({ line, column, context: `this.${fieldName}.snapshot.data in component`, hasDisableComment: disabled });\n }\n }\n }\n }\n }\n }\n } catch {\n // Skip nodes that cause errors during analysis\n }\n\n ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return violations;\n}\n\n/**\n * Find all violations in a file (both inject(Api) and snapshot.data patterns).\n */\nfunction findViolationsInFile(filePath: string, workspaceRoot: string, disableAllowed: boolean): ViolationInfo[] {\n const apiViolations = findDirectApiInjections(filePath, workspaceRoot, disableAllowed);\n const snapshotViolations = findSnapshotDataAccess(filePath, workspaceRoot, disableAllowed);\n return [...apiViolations, ...snapshotViolations];\n}\n\n/**\n * MODIFIED_CODE mode: Flag violations on changed lines in diff hunks.\n */\n// webpieces-disable max-lines-new-methods -- File iteration with diff parsing and line filtering\nfunction findViolationsForModifiedCode(\n workspaceRoot: string,\n changedFiles: string[],\n base: string,\n head: string | undefined,\n disableAllowed: boolean\n): Violation[] {\n const violations: Violation[] = [];\n\n for (const file of changedFiles) {\n const diff = getFileDiff(workspaceRoot, file, base, head);\n const changedLines = getChangedLineNumbers(diff);\n\n if (changedLines.size === 0) continue;\n\n const allViolations = findViolationsInFile(file, workspaceRoot, disableAllowed);\n\n for (const v of allViolations) {\n if (disableAllowed && v.hasDisableComment) continue;\n // LINE-BASED: Only include if the violation is on a changed line\n if (!changedLines.has(v.line)) continue;\n\n violations.push({\n file,\n line: v.line,\n column: v.column,\n context: v.context,\n });\n }\n }\n\n return violations;\n}\n\n/**\n * MODIFIED_FILES mode: Flag ALL violations in files that were modified.\n */\nfunction findViolationsForModifiedFiles(workspaceRoot: string, changedFiles: string[], disableAllowed: boolean): Violation[] {\n const violations: Violation[] = [];\n\n for (const file of changedFiles) {\n const allViolations = findViolationsInFile(file, workspaceRoot, disableAllowed);\n\n for (const v of allViolations) {\n if (disableAllowed && v.hasDisableComment) continue;\n\n violations.push({\n file,\n line: v.line,\n column: v.column,\n context: v.context,\n });\n }\n }\n\n return violations;\n}\n\n/**\n * Report violations to console.\n */\n// webpieces-disable max-lines-new-methods -- Console output with examples and escape hatch information\nfunction reportViolations(violations: Violation[], mode: NoDirectApiResolverMode, disableAllowed: boolean): void {\n console.error('');\n console.error('\\u274c Direct API usage in resolvers or snapshot.data in components found!');\n console.error('');\n console.error('\\ud83d\\udcda Resolvers should use services, and components should subscribe to service observables:');\n console.error('');\n console.error(' BAD (in *.routes.ts resolver):');\n console.error(' const myApi = inject(MyApi);');\n console.error(' resolve: () => inject(MyApi).fetchData()');\n console.error('');\n console.error(' GOOD (in *.routes.ts resolver):');\n console.error(' const myService = inject(MyService);');\n console.error(' resolve: () => inject(MyService).loadData()');\n console.error('');\n console.error(' BAD (in *.component.ts):');\n console.error(' const data = this.route.snapshot.data;');\n console.error('');\n console.error(' GOOD (in *.component.ts):');\n console.error(' this.myService.data$.subscribe(data => ...)');\n console.error('');\n\n for (const v of violations) {\n console.error(` \\u274c ${v.file}:${v.line}:${v.column}`);\n console.error(` ${v.context}`);\n }\n console.error('');\n\n if (disableAllowed) {\n console.error(' Escape hatch (use sparingly):');\n console.error(' // webpieces-disable no-direct-api-resolver -- [your reason]');\n } else {\n console.error(' Escape hatch: DISABLED (disableAllowed: false)');\n console.error(' Disable comments are ignored. Fix the pattern directly.');\n }\n console.error('');\n console.error(` Current mode: ${mode}`);\n console.error('');\n}\n\n/**\n * Resolve mode considering ignoreModifiedUntilEpoch override.\n * When active, downgrades to OFF. When expired, logs a warning.\n */\nfunction resolveMode(normalMode: NoDirectApiResolverMode, epoch: number | undefined): NoDirectApiResolverMode {\n if (epoch === undefined || normalMode === 'OFF') {\n return normalMode;\n }\n const nowSeconds = Date.now() / 1000;\n if (nowSeconds < epoch) {\n const expiresDate = new Date(epoch * 1000).toISOString().split('T')[0];\n console.log(`\\n\\u23ed\\ufe0f Skipping no-direct-api-resolver validation (ignoreModifiedUntilEpoch active, expires: ${expiresDate})`);\n console.log('');\n return 'OFF';\n }\n return normalMode;\n}\n\n/**\n * Filter changed files to only those under enforcePaths (if configured).\n */\nfunction filterByEnforcePaths(changedFiles: string[], enforcePaths: string[] | undefined): string[] {\n if (!enforcePaths || enforcePaths.length === 0) {\n return changedFiles;\n }\n return changedFiles.filter((file) =>\n enforcePaths.some((prefix) => file.startsWith(prefix))\n );\n}\n\n/**\n * Filter to only relevant Angular files (*.routes.ts and *.component.ts).\n */\nfunction filterRelevantFiles(changedFiles: string[]): string[] {\n return changedFiles.filter((file) =>\n file.endsWith('.routes.ts') || file.endsWith('.component.ts')\n );\n}\n\nexport default async function runExecutor(\n options: ValidateNoDirectApiResolverOptions,\n context: ExecutorContext\n): Promise<ExecutorResult> {\n const workspaceRoot = context.root;\n const mode: NoDirectApiResolverMode = resolveMode(options.mode ?? 'OFF', options.ignoreModifiedUntilEpoch);\n const disableAllowed = options.disableAllowed ?? true;\n\n if (mode === 'OFF') {\n console.log('\\n\\u23ed\\ufe0f Skipping no-direct-api-resolver validation (mode: OFF)');\n console.log('');\n return { success: true };\n }\n\n console.log('\\n\\ud83d\\udccf Validating No Direct API in Resolver\\n');\n console.log(` Mode: ${mode}`);\n\n let base = process.env['NX_BASE'];\n const head = process.env['NX_HEAD'];\n\n if (!base) {\n base = detectBase(workspaceRoot) ?? undefined;\n\n if (!base) {\n console.log('\\n\\u23ed\\ufe0f Skipping no-direct-api-resolver validation (could not detect base branch)');\n console.log('');\n return { success: true };\n }\n }\n\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);\n console.log('');\n\n const allChangedFiles = getChangedTypeScriptFiles(workspaceRoot, base, head);\n const scopedFiles = filterByEnforcePaths(allChangedFiles, options.enforcePaths);\n const changedFiles = filterRelevantFiles(scopedFiles);\n\n if (changedFiles.length === 0) {\n console.log('\\u2705 No relevant Angular files changed (*.routes.ts, *.component.ts)');\n return { success: true };\n }\n\n console.log(`\\ud83d\\udcc2 Checking ${changedFiles.length} changed file(s)...`);\n\n let violations: Violation[] = [];\n\n if (mode === 'MODIFIED_CODE') {\n violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed);\n } else if (mode === 'MODIFIED_FILES') {\n violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);\n }\n\n if (violations.length === 0) {\n console.log('\\u2705 No direct API resolver patterns found');\n return { success: true };\n }\n\n reportViolations(violations, mode, disableAllowed);\n\n return { success: false };\n}\n"]}