@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,478 @@
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
+ * - MODIFIED_FILES: Flag ALL violations in files that were modified
27
+ *
28
+ * ============================================================================
29
+ * ESCAPE HATCH
30
+ * ============================================================================
31
+ * Add comment above the violation:
32
+ * // webpieces-disable no-direct-api-resolver -- [your justification]
33
+ * const myApi = inject(MyApi);
34
+ */
35
+
36
+ import type { ExecutorContext } from '@nx/devkit';
37
+ import { execSync } from 'child_process';
38
+ import * as fs from 'fs';
39
+ import * as path from 'path';
40
+ import * as ts from 'typescript';
41
+ import { getFileDiff, getChangedLineNumbers } from '../diff-utils';
42
+
43
+ export type NoDirectApiResolverMode = 'OFF' | 'MODIFIED_CODE' | 'MODIFIED_FILES';
44
+
45
+ export interface ValidateNoDirectApiResolverOptions {
46
+ mode?: NoDirectApiResolverMode;
47
+ disableAllowed?: boolean;
48
+ ignoreModifiedUntilEpoch?: number;
49
+ enforcePaths?: string[];
50
+ }
51
+
52
+ export interface ExecutorResult {
53
+ success: boolean;
54
+ }
55
+
56
+ interface Violation {
57
+ file: string;
58
+ line: number;
59
+ column: number;
60
+ context: string;
61
+ }
62
+
63
+ interface ViolationInfo {
64
+ line: number;
65
+ column: number;
66
+ context: string;
67
+ hasDisableComment: boolean;
68
+ }
69
+
70
+ /**
71
+ * Get changed TypeScript files between base and head (or working tree if head not specified).
72
+ */
73
+ // webpieces-disable max-lines-new-methods -- Git command handling with untracked files requires multiple code paths
74
+ function getChangedTypeScriptFiles(workspaceRoot: string, base: string, head?: string): string[] {
75
+ try {
76
+ const diffTarget = head ? `${base} ${head}` : base;
77
+ const output = execSync(`git diff --name-only ${diffTarget} -- '*.ts' '*.tsx'`, {
78
+ cwd: workspaceRoot,
79
+ encoding: 'utf-8',
80
+ });
81
+ const changedFiles = output
82
+ .trim()
83
+ .split('\n')
84
+ .filter((f) => f && !f.includes('.spec.ts') && !f.includes('.test.ts'));
85
+
86
+ if (!head) {
87
+ try {
88
+ const untrackedOutput = execSync(`git ls-files --others --exclude-standard '*.ts' '*.tsx'`, {
89
+ cwd: workspaceRoot,
90
+ encoding: 'utf-8',
91
+ });
92
+ const untrackedFiles = untrackedOutput
93
+ .trim()
94
+ .split('\n')
95
+ .filter((f) => f && !f.includes('.spec.ts') && !f.includes('.test.ts'));
96
+ const allFiles = new Set([...changedFiles, ...untrackedFiles]);
97
+ return Array.from(allFiles);
98
+ } catch {
99
+ return changedFiles;
100
+ }
101
+ }
102
+
103
+ return changedFiles;
104
+ } catch {
105
+ return [];
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Check if a line contains a webpieces-disable comment for no-direct-api-resolver.
111
+ */
112
+ function hasDisableComment(lines: string[], lineNumber: number): boolean {
113
+ const startCheck = Math.max(0, lineNumber - 5);
114
+ for (let i = lineNumber - 2; i >= startCheck; i--) {
115
+ const line = lines[i]?.trim() ?? '';
116
+ if (line.startsWith('function ') || line.startsWith('class ') || line.endsWith('}')) {
117
+ break;
118
+ }
119
+ if (line.includes('webpieces-disable') && line.includes('no-direct-api-resolver')) {
120
+ return true;
121
+ }
122
+ }
123
+ return false;
124
+ }
125
+
126
+ /**
127
+ * Auto-detect the base branch by finding the merge-base with origin/main.
128
+ */
129
+ function detectBase(workspaceRoot: string): string | null {
130
+ try {
131
+ const mergeBase = execSync('git merge-base HEAD origin/main', {
132
+ cwd: workspaceRoot,
133
+ encoding: 'utf-8',
134
+ stdio: ['pipe', 'pipe', 'pipe'],
135
+ }).trim();
136
+
137
+ if (mergeBase) {
138
+ return mergeBase;
139
+ }
140
+ } catch {
141
+ try {
142
+ const mergeBase = execSync('git merge-base HEAD main', {
143
+ cwd: workspaceRoot,
144
+ encoding: 'utf-8',
145
+ stdio: ['pipe', 'pipe', 'pipe'],
146
+ }).trim();
147
+
148
+ if (mergeBase) {
149
+ return mergeBase;
150
+ }
151
+ } catch {
152
+ // Ignore
153
+ }
154
+ }
155
+ return null;
156
+ }
157
+
158
+ /**
159
+ * Find inject(XxxApi) calls in *.routes.ts files.
160
+ * Flags any CallExpression where callee is `inject` and the first argument is an identifier ending with `Api`.
161
+ */
162
+ function findDirectApiInjections(filePath: string, workspaceRoot: string, disableAllowed: boolean): ViolationInfo[] {
163
+ if (!filePath.endsWith('.routes.ts')) return [];
164
+
165
+ const fullPath = path.join(workspaceRoot, filePath);
166
+ if (!fs.existsSync(fullPath)) return [];
167
+
168
+ const content = fs.readFileSync(fullPath, 'utf-8');
169
+ const fileLines = content.split('\n');
170
+ const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
171
+
172
+ const violations: ViolationInfo[] = [];
173
+
174
+ function visit(node: ts.Node): void {
175
+ try {
176
+ if (ts.isCallExpression(node)) {
177
+ const callee = node.expression;
178
+ if (ts.isIdentifier(callee) && callee.text === 'inject') {
179
+ const firstArg = node.arguments[0];
180
+ if (firstArg && ts.isIdentifier(firstArg) && firstArg.text.endsWith('Api')) {
181
+ const startPos = node.getStart(sourceFile);
182
+ if (startPos >= 0) {
183
+ const pos = sourceFile.getLineAndCharacterOfPosition(startPos);
184
+ const line = pos.line + 1;
185
+ const column = pos.character + 1;
186
+ const disabled = hasDisableComment(fileLines, line);
187
+
188
+ if (!disableAllowed && disabled) {
189
+ violations.push({ line, column, context: `inject(${firstArg.text}) in route resolver`, hasDisableComment: false });
190
+ } else {
191
+ violations.push({ line, column, context: `inject(${firstArg.text}) in route resolver`, hasDisableComment: disabled });
192
+ }
193
+ }
194
+ }
195
+ }
196
+ }
197
+ } catch {
198
+ // Skip nodes that cause errors during analysis
199
+ }
200
+
201
+ ts.forEachChild(node, visit);
202
+ }
203
+
204
+ visit(sourceFile);
205
+ return violations;
206
+ }
207
+
208
+ /**
209
+ * Find this.<field>.snapshot.data access patterns in *.component.ts files.
210
+ * Flags PropertyAccessExpression chains: this.<anything>.snapshot.data
211
+ */
212
+ function findSnapshotDataAccess(filePath: string, workspaceRoot: string, disableAllowed: boolean): ViolationInfo[] {
213
+ if (!filePath.endsWith('.component.ts')) return [];
214
+
215
+ const fullPath = path.join(workspaceRoot, filePath);
216
+ if (!fs.existsSync(fullPath)) return [];
217
+
218
+ const content = fs.readFileSync(fullPath, 'utf-8');
219
+ const fileLines = content.split('\n');
220
+ const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
221
+
222
+ const violations: ViolationInfo[] = [];
223
+
224
+ function visit(node: ts.Node): void {
225
+ try {
226
+ // Looking for: this.<field>.snapshot.data
227
+ // AST shape: PropertyAccessExpression(.data) -> PropertyAccessExpression(.snapshot) -> PropertyAccessExpression(.<field>) -> this
228
+ if (ts.isPropertyAccessExpression(node) && node.name.text === 'data') {
229
+ const snapshotAccess = node.expression;
230
+ if (ts.isPropertyAccessExpression(snapshotAccess) && snapshotAccess.name.text === 'snapshot') {
231
+ const fieldAccess = snapshotAccess.expression;
232
+ if (ts.isPropertyAccessExpression(fieldAccess)) {
233
+ const receiver = fieldAccess.expression;
234
+ if (receiver.kind === ts.SyntaxKind.ThisKeyword) {
235
+ const fieldName = fieldAccess.name.text;
236
+ const startPos = node.getStart(sourceFile);
237
+ if (startPos >= 0) {
238
+ const pos = sourceFile.getLineAndCharacterOfPosition(startPos);
239
+ const line = pos.line + 1;
240
+ const column = pos.character + 1;
241
+ const disabled = hasDisableComment(fileLines, line);
242
+
243
+ if (!disableAllowed && disabled) {
244
+ violations.push({ line, column, context: `this.${fieldName}.snapshot.data in component`, hasDisableComment: false });
245
+ } else {
246
+ violations.push({ line, column, context: `this.${fieldName}.snapshot.data in component`, hasDisableComment: disabled });
247
+ }
248
+ }
249
+ }
250
+ }
251
+ }
252
+ }
253
+ } catch {
254
+ // Skip nodes that cause errors during analysis
255
+ }
256
+
257
+ ts.forEachChild(node, visit);
258
+ }
259
+
260
+ visit(sourceFile);
261
+ return violations;
262
+ }
263
+
264
+ /**
265
+ * Find all violations in a file (both inject(Api) and snapshot.data patterns).
266
+ */
267
+ function findViolationsInFile(filePath: string, workspaceRoot: string, disableAllowed: boolean): ViolationInfo[] {
268
+ const apiViolations = findDirectApiInjections(filePath, workspaceRoot, disableAllowed);
269
+ const snapshotViolations = findSnapshotDataAccess(filePath, workspaceRoot, disableAllowed);
270
+ return [...apiViolations, ...snapshotViolations];
271
+ }
272
+
273
+ /**
274
+ * MODIFIED_CODE mode: Flag violations on changed lines in diff hunks.
275
+ */
276
+ // webpieces-disable max-lines-new-methods -- File iteration with diff parsing and line filtering
277
+ function findViolationsForModifiedCode(
278
+ workspaceRoot: string,
279
+ changedFiles: string[],
280
+ base: string,
281
+ head: string | undefined,
282
+ disableAllowed: boolean
283
+ ): Violation[] {
284
+ const violations: Violation[] = [];
285
+
286
+ for (const file of changedFiles) {
287
+ const diff = getFileDiff(workspaceRoot, file, base, head);
288
+ const changedLines = getChangedLineNumbers(diff);
289
+
290
+ if (changedLines.size === 0) continue;
291
+
292
+ const allViolations = findViolationsInFile(file, workspaceRoot, disableAllowed);
293
+
294
+ for (const v of allViolations) {
295
+ if (disableAllowed && v.hasDisableComment) continue;
296
+ // LINE-BASED: Only include if the violation is on a changed line
297
+ if (!changedLines.has(v.line)) continue;
298
+
299
+ violations.push({
300
+ file,
301
+ line: v.line,
302
+ column: v.column,
303
+ context: v.context,
304
+ });
305
+ }
306
+ }
307
+
308
+ return violations;
309
+ }
310
+
311
+ /**
312
+ * MODIFIED_FILES mode: Flag ALL violations in files that were modified.
313
+ */
314
+ function findViolationsForModifiedFiles(workspaceRoot: string, changedFiles: string[], disableAllowed: boolean): Violation[] {
315
+ const violations: Violation[] = [];
316
+
317
+ for (const file of changedFiles) {
318
+ const allViolations = findViolationsInFile(file, workspaceRoot, disableAllowed);
319
+
320
+ for (const v of allViolations) {
321
+ if (disableAllowed && v.hasDisableComment) continue;
322
+
323
+ violations.push({
324
+ file,
325
+ line: v.line,
326
+ column: v.column,
327
+ context: v.context,
328
+ });
329
+ }
330
+ }
331
+
332
+ return violations;
333
+ }
334
+
335
+ /**
336
+ * Report violations to console.
337
+ */
338
+ // webpieces-disable max-lines-new-methods -- Console output with examples and escape hatch information
339
+ function reportViolations(violations: Violation[], mode: NoDirectApiResolverMode, disableAllowed: boolean): void {
340
+ console.error('');
341
+ console.error('\u274c Direct API usage in resolvers or snapshot.data in components found!');
342
+ console.error('');
343
+ console.error('\ud83d\udcda Resolvers should use services, and components should subscribe to service observables:');
344
+ console.error('');
345
+ console.error(' BAD (in *.routes.ts resolver):');
346
+ console.error(' const myApi = inject(MyApi);');
347
+ console.error(' resolve: () => inject(MyApi).fetchData()');
348
+ console.error('');
349
+ console.error(' GOOD (in *.routes.ts resolver):');
350
+ console.error(' const myService = inject(MyService);');
351
+ console.error(' resolve: () => inject(MyService).loadData()');
352
+ console.error('');
353
+ console.error(' BAD (in *.component.ts):');
354
+ console.error(' const data = this.route.snapshot.data;');
355
+ console.error('');
356
+ console.error(' GOOD (in *.component.ts):');
357
+ console.error(' this.myService.data$.subscribe(data => ...)');
358
+ console.error('');
359
+
360
+ for (const v of violations) {
361
+ console.error(` \u274c ${v.file}:${v.line}:${v.column}`);
362
+ console.error(` ${v.context}`);
363
+ }
364
+ console.error('');
365
+
366
+ if (disableAllowed) {
367
+ console.error(' Escape hatch (use sparingly):');
368
+ console.error(' // webpieces-disable no-direct-api-resolver -- [your reason]');
369
+ } else {
370
+ console.error(' Escape hatch: DISABLED (disableAllowed: false)');
371
+ console.error(' Disable comments are ignored. Fix the pattern directly.');
372
+ }
373
+ console.error('');
374
+ console.error(` Current mode: ${mode}`);
375
+ console.error('');
376
+ }
377
+
378
+ /**
379
+ * Resolve mode considering ignoreModifiedUntilEpoch override.
380
+ * When active, downgrades to OFF. When expired, logs a warning.
381
+ */
382
+ function resolveMode(normalMode: NoDirectApiResolverMode, epoch: number | undefined): NoDirectApiResolverMode {
383
+ if (epoch === undefined || normalMode === 'OFF') {
384
+ return normalMode;
385
+ }
386
+ const nowSeconds = Date.now() / 1000;
387
+ if (nowSeconds < epoch) {
388
+ const expiresDate = new Date(epoch * 1000).toISOString().split('T')[0];
389
+ console.log(`\n\u23ed\ufe0f Skipping no-direct-api-resolver validation (ignoreModifiedUntilEpoch active, expires: ${expiresDate})`);
390
+ console.log('');
391
+ return 'OFF';
392
+ }
393
+ return normalMode;
394
+ }
395
+
396
+ /**
397
+ * Filter changed files to only those under enforcePaths (if configured).
398
+ */
399
+ function filterByEnforcePaths(changedFiles: string[], enforcePaths: string[] | undefined): string[] {
400
+ if (!enforcePaths || enforcePaths.length === 0) {
401
+ return changedFiles;
402
+ }
403
+ return changedFiles.filter((file) =>
404
+ enforcePaths.some((prefix) => file.startsWith(prefix))
405
+ );
406
+ }
407
+
408
+ /**
409
+ * Filter to only relevant Angular files (*.routes.ts and *.component.ts).
410
+ */
411
+ function filterRelevantFiles(changedFiles: string[]): string[] {
412
+ return changedFiles.filter((file) =>
413
+ file.endsWith('.routes.ts') || file.endsWith('.component.ts')
414
+ );
415
+ }
416
+
417
+ export default async function runExecutor(
418
+ options: ValidateNoDirectApiResolverOptions,
419
+ context: ExecutorContext
420
+ ): Promise<ExecutorResult> {
421
+ const workspaceRoot = context.root;
422
+ const mode: NoDirectApiResolverMode = resolveMode(options.mode ?? 'OFF', options.ignoreModifiedUntilEpoch);
423
+ const disableAllowed = options.disableAllowed ?? true;
424
+
425
+ if (mode === 'OFF') {
426
+ console.log('\n\u23ed\ufe0f Skipping no-direct-api-resolver validation (mode: OFF)');
427
+ console.log('');
428
+ return { success: true };
429
+ }
430
+
431
+ console.log('\n\ud83d\udccf Validating No Direct API in Resolver\n');
432
+ console.log(` Mode: ${mode}`);
433
+
434
+ let base = process.env['NX_BASE'];
435
+ const head = process.env['NX_HEAD'];
436
+
437
+ if (!base) {
438
+ base = detectBase(workspaceRoot) ?? undefined;
439
+
440
+ if (!base) {
441
+ console.log('\n\u23ed\ufe0f Skipping no-direct-api-resolver validation (could not detect base branch)');
442
+ console.log('');
443
+ return { success: true };
444
+ }
445
+ }
446
+
447
+ console.log(` Base: ${base}`);
448
+ console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);
449
+ console.log('');
450
+
451
+ const allChangedFiles = getChangedTypeScriptFiles(workspaceRoot, base, head);
452
+ const scopedFiles = filterByEnforcePaths(allChangedFiles, options.enforcePaths);
453
+ const changedFiles = filterRelevantFiles(scopedFiles);
454
+
455
+ if (changedFiles.length === 0) {
456
+ console.log('\u2705 No relevant Angular files changed (*.routes.ts, *.component.ts)');
457
+ return { success: true };
458
+ }
459
+
460
+ console.log(`\ud83d\udcc2 Checking ${changedFiles.length} changed file(s)...`);
461
+
462
+ let violations: Violation[] = [];
463
+
464
+ if (mode === 'MODIFIED_CODE') {
465
+ violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed);
466
+ } else if (mode === 'MODIFIED_FILES') {
467
+ violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);
468
+ }
469
+
470
+ if (violations.length === 0) {
471
+ console.log('\u2705 No direct API resolver patterns found');
472
+ return { success: true };
473
+ }
474
+
475
+ reportViolations(violations, mode, disableAllowed);
476
+
477
+ return { success: false };
478
+ }
@@ -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", "MODIFIED_FILES"],
10
+ "description": "OFF: skip validation. MODIFIED_CODE: only changed lines in diff. 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
+ }
package/executors.json CHANGED
@@ -94,6 +94,11 @@
94
94
  "implementation": "./architecture/executors/validate-no-destructure/executor",
95
95
  "schema": "./architecture/executors/validate-no-destructure/schema.json",
96
96
  "description": "Validate no destructuring patterns are used - use explicit property access instead"
97
+ },
98
+ "validate-no-direct-api-resolver": {
99
+ "implementation": "./architecture/executors/validate-no-direct-api-resolver/executor",
100
+ "schema": "./architecture/executors/validate-no-direct-api-resolver/schema.json",
101
+ "description": "Validate resolvers use services (not APIs) and components subscribe to observables (not route.snapshot.data)"
97
102
  }
98
103
  }
99
104
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/dev-config",
3
- "version": "0.2.89",
3
+ "version": "0.2.90",
4
4
  "description": "Development configuration, scripts, and patterns for WebPieces projects",
5
5
  "type": "commonjs",
6
6
  "bin": {