@webpieces/dev-config 0.2.89 → 0.2.91

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,666 @@
1
+ /**
2
+ * Validate No Direct API in Resolver Executor
3
+ *
4
+ * Validates two Angular anti-patterns using LINE-BASED detection:
5
+ *
6
+ * ============================================================================
7
+ * VIOLATIONS (BAD) - These patterns are flagged:
8
+ * ============================================================================
9
+ *
10
+ * 1. In *.routes.ts files: inject(XxxApi) — resolvers should inject services, not APIs directly
11
+ * 2. In *.component.ts files: this.<field>.snapshot.data — components should subscribe to
12
+ * service BehaviorSubjects, not read route snapshot data
13
+ *
14
+ * ============================================================================
15
+ * CORRECT PATTERNS (GOOD)
16
+ * ============================================================================
17
+ *
18
+ * 1. In resolvers: inject(XxxService) which calls the API internally
19
+ * 2. In components: this.myService.someObservable$ (subscribe to service BehaviorSubjects)
20
+ *
21
+ * ============================================================================
22
+ * MODES (LINE-BASED)
23
+ * ============================================================================
24
+ * - OFF: Skip validation entirely
25
+ * - MODIFIED_CODE: Flag violations on changed lines (lines in diff hunks)
26
+ * - NEW_AND_MODIFIED_METHODS: Flag violations in new/modified method/route scopes
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
+
37
+ import type { ExecutorContext } from '@nx/devkit';
38
+ import { execSync } from 'child_process';
39
+ import * as fs from 'fs';
40
+ import * as path from 'path';
41
+ import * as ts from 'typescript';
42
+ import { getFileDiff, getChangedLineNumbers, findNewMethodSignaturesInDiff } from '../diff-utils';
43
+
44
+ export type NoDirectApiResolverMode = 'OFF' | 'MODIFIED_CODE' | 'NEW_AND_MODIFIED_METHODS' | 'MODIFIED_FILES';
45
+
46
+ export interface ValidateNoDirectApiResolverOptions {
47
+ mode?: NoDirectApiResolverMode;
48
+ disableAllowed?: boolean;
49
+ ignoreModifiedUntilEpoch?: number;
50
+ enforcePaths?: string[];
51
+ }
52
+
53
+ export interface ExecutorResult {
54
+ success: boolean;
55
+ }
56
+
57
+ interface Violation {
58
+ file: string;
59
+ line: number;
60
+ column: number;
61
+ context: string;
62
+ }
63
+
64
+ interface ViolationInfo {
65
+ line: number;
66
+ column: number;
67
+ context: string;
68
+ hasDisableComment: boolean;
69
+ }
70
+
71
+ /**
72
+ * Get changed TypeScript files between base and head (or working tree if head not specified).
73
+ */
74
+ // webpieces-disable max-lines-new-methods -- Git command handling with untracked files requires multiple code paths
75
+ function getChangedTypeScriptFiles(workspaceRoot: string, base: string, head?: string): string[] {
76
+ try {
77
+ const diffTarget = head ? `${base} ${head}` : base;
78
+ const output = execSync(`git diff --name-only ${diffTarget} -- '*.ts' '*.tsx'`, {
79
+ cwd: workspaceRoot,
80
+ encoding: 'utf-8',
81
+ });
82
+ const changedFiles = output
83
+ .trim()
84
+ .split('\n')
85
+ .filter((f) => f && !f.includes('.spec.ts') && !f.includes('.test.ts'));
86
+
87
+ if (!head) {
88
+ try {
89
+ const untrackedOutput = execSync(`git ls-files --others --exclude-standard '*.ts' '*.tsx'`, {
90
+ cwd: workspaceRoot,
91
+ encoding: 'utf-8',
92
+ });
93
+ const untrackedFiles = untrackedOutput
94
+ .trim()
95
+ .split('\n')
96
+ .filter((f) => f && !f.includes('.spec.ts') && !f.includes('.test.ts'));
97
+ const allFiles = new Set([...changedFiles, ...untrackedFiles]);
98
+ return Array.from(allFiles);
99
+ } catch {
100
+ return changedFiles;
101
+ }
102
+ }
103
+
104
+ return changedFiles;
105
+ } catch {
106
+ return [];
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Check if a line contains a webpieces-disable comment for no-direct-api-resolver.
112
+ */
113
+ function hasDisableComment(lines: string[], lineNumber: number): boolean {
114
+ const startCheck = Math.max(0, lineNumber - 5);
115
+ for (let i = lineNumber - 2; i >= startCheck; i--) {
116
+ const line = lines[i]?.trim() ?? '';
117
+ if (line.startsWith('function ') || line.startsWith('class ') || line.endsWith('}')) {
118
+ break;
119
+ }
120
+ if (line.includes('webpieces-disable') && line.includes('no-direct-api-resolver')) {
121
+ return true;
122
+ }
123
+ }
124
+ return false;
125
+ }
126
+
127
+ /**
128
+ * Auto-detect the base branch by finding the merge-base with origin/main.
129
+ */
130
+ function detectBase(workspaceRoot: string): string | null {
131
+ try {
132
+ const mergeBase = execSync('git merge-base HEAD origin/main', {
133
+ cwd: workspaceRoot,
134
+ encoding: 'utf-8',
135
+ stdio: ['pipe', 'pipe', 'pipe'],
136
+ }).trim();
137
+
138
+ if (mergeBase) {
139
+ return mergeBase;
140
+ }
141
+ } catch {
142
+ try {
143
+ const mergeBase = execSync('git merge-base HEAD main', {
144
+ cwd: workspaceRoot,
145
+ encoding: 'utf-8',
146
+ stdio: ['pipe', 'pipe', 'pipe'],
147
+ }).trim();
148
+
149
+ if (mergeBase) {
150
+ return mergeBase;
151
+ }
152
+ } catch {
153
+ // Ignore
154
+ }
155
+ }
156
+ return null;
157
+ }
158
+
159
+ /**
160
+ * Find inject(XxxApi) calls in *.routes.ts files.
161
+ * Flags any CallExpression where callee is `inject` and the first argument is an identifier ending with `Api`.
162
+ */
163
+ function findDirectApiInjections(filePath: string, workspaceRoot: string, disableAllowed: boolean): ViolationInfo[] {
164
+ if (!filePath.endsWith('.routes.ts')) return [];
165
+
166
+ const fullPath = path.join(workspaceRoot, filePath);
167
+ if (!fs.existsSync(fullPath)) return [];
168
+
169
+ const content = fs.readFileSync(fullPath, 'utf-8');
170
+ const fileLines = content.split('\n');
171
+ const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
172
+
173
+ const violations: ViolationInfo[] = [];
174
+
175
+ function visit(node: ts.Node): void {
176
+ try {
177
+ if (ts.isCallExpression(node)) {
178
+ const callee = node.expression;
179
+ if (ts.isIdentifier(callee) && callee.text === 'inject') {
180
+ const firstArg = node.arguments[0];
181
+ if (firstArg && ts.isIdentifier(firstArg) && firstArg.text.endsWith('Api')) {
182
+ const startPos = node.getStart(sourceFile);
183
+ if (startPos >= 0) {
184
+ const pos = sourceFile.getLineAndCharacterOfPosition(startPos);
185
+ const line = pos.line + 1;
186
+ const column = pos.character + 1;
187
+ const disabled = hasDisableComment(fileLines, line);
188
+
189
+ if (!disableAllowed && disabled) {
190
+ violations.push({ line, column, context: `inject(${firstArg.text}) in route resolver`, hasDisableComment: false });
191
+ } else {
192
+ violations.push({ line, column, context: `inject(${firstArg.text}) in route resolver`, hasDisableComment: disabled });
193
+ }
194
+ }
195
+ }
196
+ }
197
+ }
198
+ } catch {
199
+ // Skip nodes that cause errors during analysis
200
+ }
201
+
202
+ ts.forEachChild(node, visit);
203
+ }
204
+
205
+ visit(sourceFile);
206
+ return violations;
207
+ }
208
+
209
+ /**
210
+ * Find this.<field>.snapshot.data access patterns in *.component.ts files.
211
+ * Flags PropertyAccessExpression chains: this.<anything>.snapshot.data
212
+ */
213
+ function findSnapshotDataAccess(filePath: string, workspaceRoot: string, disableAllowed: boolean): ViolationInfo[] {
214
+ if (!filePath.endsWith('.component.ts')) return [];
215
+
216
+ const fullPath = path.join(workspaceRoot, filePath);
217
+ if (!fs.existsSync(fullPath)) return [];
218
+
219
+ const content = fs.readFileSync(fullPath, 'utf-8');
220
+ const fileLines = content.split('\n');
221
+ const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
222
+
223
+ const violations: ViolationInfo[] = [];
224
+
225
+ function visit(node: ts.Node): void {
226
+ try {
227
+ // Looking for: this.<field>.snapshot.data
228
+ // AST shape: PropertyAccessExpression(.data) -> PropertyAccessExpression(.snapshot) -> PropertyAccessExpression(.<field>) -> this
229
+ if (ts.isPropertyAccessExpression(node) && node.name.text === 'data') {
230
+ const snapshotAccess = node.expression;
231
+ if (ts.isPropertyAccessExpression(snapshotAccess) && snapshotAccess.name.text === 'snapshot') {
232
+ const fieldAccess = snapshotAccess.expression;
233
+ if (ts.isPropertyAccessExpression(fieldAccess)) {
234
+ const receiver = fieldAccess.expression;
235
+ if (receiver.kind === ts.SyntaxKind.ThisKeyword) {
236
+ const fieldName = fieldAccess.name.text;
237
+ const startPos = node.getStart(sourceFile);
238
+ if (startPos >= 0) {
239
+ const pos = sourceFile.getLineAndCharacterOfPosition(startPos);
240
+ const line = pos.line + 1;
241
+ const column = pos.character + 1;
242
+ const disabled = hasDisableComment(fileLines, line);
243
+
244
+ if (!disableAllowed && disabled) {
245
+ violations.push({ line, column, context: `this.${fieldName}.snapshot.data in component`, hasDisableComment: false });
246
+ } else {
247
+ violations.push({ line, column, context: `this.${fieldName}.snapshot.data in component`, hasDisableComment: disabled });
248
+ }
249
+ }
250
+ }
251
+ }
252
+ }
253
+ }
254
+ } catch {
255
+ // Skip nodes that cause errors during analysis
256
+ }
257
+
258
+ ts.forEachChild(node, visit);
259
+ }
260
+
261
+ visit(sourceFile);
262
+ return violations;
263
+ }
264
+
265
+ /**
266
+ * Find all violations in a file (both inject(Api) and snapshot.data patterns).
267
+ */
268
+ function findViolationsInFile(filePath: string, workspaceRoot: string, disableAllowed: boolean): ViolationInfo[] {
269
+ const apiViolations = findDirectApiInjections(filePath, workspaceRoot, disableAllowed);
270
+ const snapshotViolations = findSnapshotDataAccess(filePath, workspaceRoot, disableAllowed);
271
+ return [...apiViolations, ...snapshotViolations];
272
+ }
273
+
274
+ /**
275
+ * MODIFIED_CODE mode: Flag violations on changed lines in diff hunks.
276
+ */
277
+ // webpieces-disable max-lines-new-methods -- File iteration with diff parsing and line filtering
278
+ function findViolationsForModifiedCode(
279
+ workspaceRoot: string,
280
+ changedFiles: string[],
281
+ base: string,
282
+ head: string | undefined,
283
+ disableAllowed: boolean
284
+ ): Violation[] {
285
+ const violations: Violation[] = [];
286
+
287
+ for (const file of changedFiles) {
288
+ const diff = getFileDiff(workspaceRoot, file, base, head);
289
+ const changedLines = getChangedLineNumbers(diff);
290
+
291
+ if (changedLines.size === 0) continue;
292
+
293
+ const allViolations = findViolationsInFile(file, workspaceRoot, disableAllowed);
294
+
295
+ for (const v of allViolations) {
296
+ if (disableAllowed && v.hasDisableComment) continue;
297
+ // LINE-BASED: Only include if the violation is on a changed line
298
+ if (!changedLines.has(v.line)) continue;
299
+
300
+ violations.push({
301
+ file,
302
+ line: v.line,
303
+ column: v.column,
304
+ context: v.context,
305
+ });
306
+ }
307
+ }
308
+
309
+ return violations;
310
+ }
311
+
312
+ /**
313
+ * MODIFIED_FILES mode: Flag ALL violations in files that were modified.
314
+ */
315
+ function findViolationsForModifiedFiles(workspaceRoot: string, changedFiles: string[], disableAllowed: boolean): Violation[] {
316
+ const violations: Violation[] = [];
317
+
318
+ for (const file of changedFiles) {
319
+ const allViolations = findViolationsInFile(file, workspaceRoot, disableAllowed);
320
+
321
+ for (const v of allViolations) {
322
+ if (disableAllowed && v.hasDisableComment) continue;
323
+
324
+ violations.push({
325
+ file,
326
+ line: v.line,
327
+ column: v.column,
328
+ context: v.context,
329
+ });
330
+ }
331
+ }
332
+
333
+ return violations;
334
+ }
335
+
336
+ interface RangeInfo {
337
+ name: string;
338
+ startLine: number;
339
+ endLine: number;
340
+ }
341
+
342
+ /**
343
+ * Find route object ranges in *.routes.ts files.
344
+ * A route object is an ObjectLiteralExpression that contains (directly or in descendants)
345
+ * a `resolve` property. Returns the line range of each such top-level route object.
346
+ */
347
+ function findRouteObjectRanges(filePath: string, workspaceRoot: string): RangeInfo[] {
348
+ const fullPath = path.join(workspaceRoot, filePath);
349
+ if (!fs.existsSync(fullPath)) return [];
350
+
351
+ const content = fs.readFileSync(fullPath, 'utf-8');
352
+ const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
353
+
354
+ const ranges: RangeInfo[] = [];
355
+
356
+ function hasResolveProperty(node: ts.Node): boolean {
357
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === 'resolve') {
358
+ return true;
359
+ }
360
+ let found = false;
361
+ ts.forEachChild(node, (child) => {
362
+ if (hasResolveProperty(child)) {
363
+ found = true;
364
+ }
365
+ });
366
+ return found;
367
+ }
368
+
369
+ function visitTopLevel(node: ts.Node): void {
370
+ if (ts.isObjectLiteralExpression(node) && hasResolveProperty(node)) {
371
+ const start = sourceFile.getLineAndCharacterOfPosition(node.getStart());
372
+ const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());
373
+ ranges.push({
374
+ name: `route@${start.line + 1}`,
375
+ startLine: start.line + 1,
376
+ endLine: end.line + 1,
377
+ });
378
+ return;
379
+ }
380
+ ts.forEachChild(node, visitTopLevel);
381
+ }
382
+
383
+ visitTopLevel(sourceFile);
384
+ return ranges;
385
+ }
386
+
387
+ /**
388
+ * Find method/function ranges in *.component.ts files.
389
+ * Returns ranges for class methods, function declarations, and arrow functions in variable declarations.
390
+ */
391
+ function findMethodRanges(filePath: string, workspaceRoot: string): RangeInfo[] {
392
+ const fullPath = path.join(workspaceRoot, filePath);
393
+ if (!fs.existsSync(fullPath)) return [];
394
+
395
+ const content = fs.readFileSync(fullPath, 'utf-8');
396
+ const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
397
+
398
+ const ranges: RangeInfo[] = [];
399
+
400
+ function visit(node: ts.Node): void {
401
+ let methodName: string | undefined;
402
+ let startLine: number | undefined;
403
+ let endLine: number | undefined;
404
+
405
+ if (ts.isMethodDeclaration(node) && node.name) {
406
+ methodName = node.name.getText(sourceFile);
407
+ const start = sourceFile.getLineAndCharacterOfPosition(node.getStart());
408
+ const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());
409
+ startLine = start.line + 1;
410
+ endLine = end.line + 1;
411
+ } else if (ts.isFunctionDeclaration(node) && node.name) {
412
+ methodName = node.name.getText(sourceFile);
413
+ const start = sourceFile.getLineAndCharacterOfPosition(node.getStart());
414
+ const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());
415
+ startLine = start.line + 1;
416
+ endLine = end.line + 1;
417
+ } else if (ts.isArrowFunction(node)) {
418
+ if (ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name)) {
419
+ methodName = node.parent.name.getText(sourceFile);
420
+ const start = sourceFile.getLineAndCharacterOfPosition(node.getStart());
421
+ const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());
422
+ startLine = start.line + 1;
423
+ endLine = end.line + 1;
424
+ }
425
+ }
426
+
427
+ if (methodName && startLine !== undefined && endLine !== undefined) {
428
+ ranges.push({ name: methodName, startLine, endLine });
429
+ }
430
+
431
+ ts.forEachChild(node, visit);
432
+ }
433
+
434
+ visit(sourceFile);
435
+ return ranges;
436
+ }
437
+
438
+ /**
439
+ * NEW_AND_MODIFIED_METHODS mode: Flag violations in new/modified method/route scopes.
440
+ * - For *.routes.ts: If any line in a route object is changed, flag all inject(XxxApi) violations in that route
441
+ * - For *.component.ts: If a method is new/modified, flag all snapshot.data violations in that method
442
+ */
443
+ // webpieces-disable max-lines-new-methods -- Method-scoped validation with route objects and component methods
444
+ function findViolationsForModifiedMethods(
445
+ workspaceRoot: string,
446
+ changedFiles: string[],
447
+ base: string,
448
+ head: string | undefined,
449
+ disableAllowed: boolean
450
+ ): Violation[] {
451
+ const violations: Violation[] = [];
452
+
453
+ for (const file of changedFiles) {
454
+ const diff = getFileDiff(workspaceRoot, file, base, head);
455
+ const changedLines = getChangedLineNumbers(diff);
456
+ const newMethodNames = findNewMethodSignaturesInDiff(diff);
457
+
458
+ if (changedLines.size === 0 && newMethodNames.size === 0) continue;
459
+
460
+ if (file.endsWith('.routes.ts')) {
461
+ const routeRanges = findRouteObjectRanges(file, workspaceRoot);
462
+ const allViolations = findDirectApiInjections(file, workspaceRoot, disableAllowed);
463
+
464
+ for (const range of routeRanges) {
465
+ let rangeHasChanges = false;
466
+ for (let line = range.startLine; line <= range.endLine; line++) {
467
+ if (changedLines.has(line)) {
468
+ rangeHasChanges = true;
469
+ break;
470
+ }
471
+ }
472
+ if (!rangeHasChanges) continue;
473
+
474
+ for (const v of allViolations) {
475
+ if (disableAllowed && v.hasDisableComment) continue;
476
+ if (v.line >= range.startLine && v.line <= range.endLine) {
477
+ violations.push({
478
+ file,
479
+ line: v.line,
480
+ column: v.column,
481
+ context: v.context,
482
+ });
483
+ }
484
+ }
485
+ }
486
+ } else if (file.endsWith('.component.ts')) {
487
+ const methodRanges = findMethodRanges(file, workspaceRoot);
488
+ const allViolations = findSnapshotDataAccess(file, workspaceRoot, disableAllowed);
489
+
490
+ for (const range of methodRanges) {
491
+ const isNewMethod = newMethodNames.has(range.name);
492
+ let rangeHasChanges = false;
493
+ if (!isNewMethod) {
494
+ for (let line = range.startLine; line <= range.endLine; line++) {
495
+ if (changedLines.has(line)) {
496
+ rangeHasChanges = true;
497
+ break;
498
+ }
499
+ }
500
+ }
501
+ if (!isNewMethod && !rangeHasChanges) continue;
502
+
503
+ for (const v of allViolations) {
504
+ if (disableAllowed && v.hasDisableComment) continue;
505
+ if (v.line >= range.startLine && v.line <= range.endLine) {
506
+ violations.push({
507
+ file,
508
+ line: v.line,
509
+ column: v.column,
510
+ context: v.context,
511
+ });
512
+ }
513
+ }
514
+ }
515
+ }
516
+ }
517
+
518
+ return violations;
519
+ }
520
+
521
+ /**
522
+ * Report violations to console.
523
+ */
524
+ // webpieces-disable max-lines-new-methods -- Console output with examples and escape hatch information
525
+ function reportViolations(violations: Violation[], mode: NoDirectApiResolverMode, disableAllowed: boolean): void {
526
+ console.error('');
527
+ console.error('\u274c Direct API usage in resolvers or snapshot.data in components found!');
528
+ console.error('');
529
+ console.error('\ud83d\udcda Resolvers should use services, and components should subscribe to service observables:');
530
+ console.error('');
531
+ console.error(' BAD (in *.routes.ts resolver):');
532
+ console.error(' const myApi = inject(MyApi);');
533
+ console.error(' resolve: () => inject(MyApi).fetchData()');
534
+ console.error('');
535
+ console.error(' GOOD (in *.routes.ts resolver):');
536
+ console.error(' const myService = inject(MyService);');
537
+ console.error(' resolve: () => inject(MyService).loadData()');
538
+ console.error('');
539
+ console.error(' BAD (in *.component.ts):');
540
+ console.error(' const data = this.route.snapshot.data;');
541
+ console.error('');
542
+ console.error(' GOOD (in *.component.ts):');
543
+ console.error(' this.myService.data$.subscribe(data => ...)');
544
+ console.error('');
545
+
546
+ for (const v of violations) {
547
+ console.error(` \u274c ${v.file}:${v.line}:${v.column}`);
548
+ console.error(` ${v.context}`);
549
+ }
550
+ console.error('');
551
+
552
+ if (disableAllowed) {
553
+ console.error(' Escape hatch (use sparingly):');
554
+ console.error(' // webpieces-disable no-direct-api-resolver -- [your reason]');
555
+ } else {
556
+ console.error(' Escape hatch: DISABLED (disableAllowed: false)');
557
+ console.error(' Disable comments are ignored. Fix the pattern directly.');
558
+ }
559
+ console.error('');
560
+ console.error(` Current mode: ${mode}`);
561
+ console.error('');
562
+ }
563
+
564
+ /**
565
+ * Resolve mode considering ignoreModifiedUntilEpoch override.
566
+ * When active, downgrades to OFF. When expired, logs a warning.
567
+ */
568
+ function resolveMode(normalMode: NoDirectApiResolverMode, epoch: number | undefined): NoDirectApiResolverMode {
569
+ if (epoch === undefined || normalMode === 'OFF') {
570
+ return normalMode;
571
+ }
572
+ const nowSeconds = Date.now() / 1000;
573
+ if (nowSeconds < epoch) {
574
+ const expiresDate = new Date(epoch * 1000).toISOString().split('T')[0];
575
+ console.log(`\n\u23ed\ufe0f Skipping no-direct-api-resolver validation (ignoreModifiedUntilEpoch active, expires: ${expiresDate})`);
576
+ console.log('');
577
+ return 'OFF';
578
+ }
579
+ return normalMode;
580
+ }
581
+
582
+ /**
583
+ * Filter changed files to only those under enforcePaths (if configured).
584
+ */
585
+ function filterByEnforcePaths(changedFiles: string[], enforcePaths: string[] | undefined): string[] {
586
+ if (!enforcePaths || enforcePaths.length === 0) {
587
+ return changedFiles;
588
+ }
589
+ return changedFiles.filter((file) =>
590
+ enforcePaths.some((prefix) => file.startsWith(prefix))
591
+ );
592
+ }
593
+
594
+ /**
595
+ * Filter to only relevant Angular files (*.routes.ts and *.component.ts).
596
+ */
597
+ function filterRelevantFiles(changedFiles: string[]): string[] {
598
+ return changedFiles.filter((file) =>
599
+ file.endsWith('.routes.ts') || file.endsWith('.component.ts')
600
+ );
601
+ }
602
+
603
+ export default async function runExecutor(
604
+ options: ValidateNoDirectApiResolverOptions,
605
+ context: ExecutorContext
606
+ ): Promise<ExecutorResult> {
607
+ const workspaceRoot = context.root;
608
+ const mode: NoDirectApiResolverMode = resolveMode(options.mode ?? 'OFF', options.ignoreModifiedUntilEpoch);
609
+ const disableAllowed = options.disableAllowed ?? true;
610
+
611
+ if (mode === 'OFF') {
612
+ console.log('\n\u23ed\ufe0f Skipping no-direct-api-resolver validation (mode: OFF)');
613
+ console.log('');
614
+ return { success: true };
615
+ }
616
+
617
+ console.log('\n\ud83d\udccf Validating No Direct API in Resolver\n');
618
+ console.log(` Mode: ${mode}`);
619
+
620
+ let base = process.env['NX_BASE'];
621
+ const head = process.env['NX_HEAD'];
622
+
623
+ if (!base) {
624
+ base = detectBase(workspaceRoot) ?? undefined;
625
+
626
+ if (!base) {
627
+ console.log('\n\u23ed\ufe0f Skipping no-direct-api-resolver validation (could not detect base branch)');
628
+ console.log('');
629
+ return { success: true };
630
+ }
631
+ }
632
+
633
+ console.log(` Base: ${base}`);
634
+ console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);
635
+ console.log('');
636
+
637
+ const allChangedFiles = getChangedTypeScriptFiles(workspaceRoot, base, head);
638
+ const scopedFiles = filterByEnforcePaths(allChangedFiles, options.enforcePaths);
639
+ const changedFiles = filterRelevantFiles(scopedFiles);
640
+
641
+ if (changedFiles.length === 0) {
642
+ console.log('\u2705 No relevant Angular files changed (*.routes.ts, *.component.ts)');
643
+ return { success: true };
644
+ }
645
+
646
+ console.log(`\ud83d\udcc2 Checking ${changedFiles.length} changed file(s)...`);
647
+
648
+ let violations: Violation[] = [];
649
+
650
+ if (mode === 'MODIFIED_CODE') {
651
+ violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed);
652
+ } else if (mode === 'NEW_AND_MODIFIED_METHODS') {
653
+ violations = findViolationsForModifiedMethods(workspaceRoot, changedFiles, base, head, disableAllowed);
654
+ } else if (mode === 'MODIFIED_FILES') {
655
+ violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);
656
+ }
657
+
658
+ if (violations.length === 0) {
659
+ console.log('\u2705 No direct API resolver patterns found');
660
+ return { success: true };
661
+ }
662
+
663
+ reportViolations(violations, mode, disableAllowed);
664
+
665
+ return { success: false };
666
+ }
@@ -0,0 +1,29 @@
1
+ {
2
+ "$schema": "http://json-schema.org/schema",
3
+ "title": "Validate No Direct API in Resolver Executor",
4
+ "description": "Validates resolvers use services (not APIs) and components subscribe to service observables (not route.snapshot.data). Uses LINE-BASED detection for git diff filtering.",
5
+ "type": "object",
6
+ "properties": {
7
+ "mode": {
8
+ "type": "string",
9
+ "enum": ["OFF", "MODIFIED_CODE", "NEW_AND_MODIFIED_METHODS", "MODIFIED_FILES"],
10
+ "description": "OFF: skip validation. MODIFIED_CODE: only changed lines in diff. NEW_AND_MODIFIED_METHODS: violations in new/modified method/route scopes. MODIFIED_FILES: all in modified files.",
11
+ "default": "OFF"
12
+ },
13
+ "disableAllowed": {
14
+ "type": "boolean",
15
+ "description": "Whether disable comments work. When false, no escape hatch.",
16
+ "default": true
17
+ },
18
+ "ignoreModifiedUntilEpoch": {
19
+ "type": "number",
20
+ "description": "Epoch seconds. Until this time, skip validation entirely. When expired, normal mode resumes. Omit when not needed."
21
+ },
22
+ "enforcePaths": {
23
+ "type": "array",
24
+ "items": { "type": "string" },
25
+ "description": "Array of directory prefixes (relative to workspace root) to scope validation to. When set, only files under these paths are checked. When empty/omitted, all changed files are checked."
26
+ }
27
+ },
28
+ "required": []
29
+ }