@webpieces/code-rules 0.4.976 → 0.4.977

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 (70) hide show
  1. package/package.json +6 -6
  2. package/src/api-lib-source-rule.js +5 -5
  3. package/src/api-lib-source-rule.js.map +1 -1
  4. package/src/code-policy-composition.js +2 -0
  5. package/src/code-policy-composition.js.map +1 -1
  6. package/src/code-rules-bootstrap.js +3 -3
  7. package/src/code-rules-bootstrap.js.map +1 -1
  8. package/src/project-scan-targets.d.ts +1 -1
  9. package/src/project-scan-targets.js +7 -7
  10. package/src/project-scan-targets.js.map +1 -1
  11. package/src/rule-debug-run.d.ts +2 -2
  12. package/src/rule-debug-run.js +7 -7
  13. package/src/rule-debug-run.js.map +1 -1
  14. package/src/scan-scope.d.ts +4 -4
  15. package/src/scan-scope.js +28 -23
  16. package/src/scan-scope.js.map +1 -1
  17. package/src/tag-rule.js +2 -2
  18. package/src/tag-rule.js.map +1 -1
  19. package/src/validate-catch-error-pattern.js +6 -5
  20. package/src/validate-catch-error-pattern.js.map +1 -1
  21. package/src/validate-catch-must-propagate.js +3 -3
  22. package/src/validate-catch-must-propagate.js.map +1 -1
  23. package/src/validate-dtos.js +15 -12
  24. package/src/validate-dtos.js.map +1 -1
  25. package/src/validate-ensure-we-are-secure.js +2 -2
  26. package/src/validate-ensure-we-are-secure.js.map +1 -1
  27. package/src/validate-framework-packages.js +2 -2
  28. package/src/validate-framework-packages.js.map +1 -1
  29. package/src/validate-framework-tsconfig.js +2 -2
  30. package/src/validate-framework-tsconfig.js.map +1 -1
  31. package/src/validate-inject-annotation-not-needed-for-concrete-class.js +5 -5
  32. package/src/validate-inject-annotation-not-needed-for-concrete-class.js.map +1 -1
  33. package/src/validate-match-rules.js +5 -5
  34. package/src/validate-match-rules.js.map +1 -1
  35. package/src/validate-modified-files.js +2 -2
  36. package/src/validate-modified-files.js.map +1 -1
  37. package/src/validate-modified-methods.js +6 -5
  38. package/src/validate-modified-methods.js.map +1 -1
  39. package/src/validate-new-methods.js +6 -5
  40. package/src/validate-new-methods.js.map +1 -1
  41. package/src/validate-no-any-unknown.js +6 -6
  42. package/src/validate-no-any-unknown.js.map +1 -1
  43. package/src/validate-no-client-creation-outside-server-or-client.js +7 -7
  44. package/src/validate-no-client-creation-outside-server-or-client.js.map +1 -1
  45. package/src/validate-no-custom-css.js +5 -5
  46. package/src/validate-no-custom-css.js.map +1 -1
  47. package/src/validate-no-destructure.js +6 -6
  48. package/src/validate-no-destructure.js.map +1 -1
  49. package/src/validate-no-direct-api-resolver.js +10 -10
  50. package/src/validate-no-direct-api-resolver.js.map +1 -1
  51. package/src/validate-no-function-outside-class.js +5 -5
  52. package/src/validate-no-function-outside-class.js.map +1 -1
  53. package/src/validate-no-implicit-any.js +6 -5
  54. package/src/validate-no-implicit-any.js.map +1 -1
  55. package/src/validate-no-inline-types.js +10 -10
  56. package/src/validate-no-inline-types.js.map +1 -1
  57. package/src/validate-no-process-exit-outside-main.js +6 -5
  58. package/src/validate-no-process-exit-outside-main.js.map +1 -1
  59. package/src/validate-no-state-paths-in-templates.js +5 -5
  60. package/src/validate-no-state-paths-in-templates.js.map +1 -1
  61. package/src/validate-no-symbol-di-tokens.js +6 -5
  62. package/src/validate-no-symbol-di-tokens.js.map +1 -1
  63. package/src/validate-no-unmanaged-exceptions.js +6 -5
  64. package/src/validate-no-unmanaged-exceptions.js.map +1 -1
  65. package/src/validate-prisma-converters.js +13 -11
  66. package/src/validate-prisma-converters.js.map +1 -1
  67. package/src/validate-return-types.js +10 -10
  68. package/src/validate-return-types.js.map +1 -1
  69. package/src/wp-ci.js +2 -2
  70. package/src/wp-ci.js.map +1 -1
package/src/scan-scope.js CHANGED
@@ -48,28 +48,28 @@ let ProjectCatalog = class ProjectCatalog {
48
48
  constructor(diffScope) {
49
49
  this.diffScope = diffScope;
50
50
  }
51
- all(workspaceRoot) {
51
+ async all(workspaceRoot) {
52
52
  if (this.cachedRoot !== workspaceRoot) {
53
- this.cached = this.load(workspaceRoot);
53
+ this.cached = await this.load(workspaceRoot);
54
54
  this.cachedRoot = workspaceRoot;
55
55
  }
56
56
  return this.cached;
57
57
  }
58
58
  /** The project owning `relFile`, or undefined when no project directory contains it. */
59
- ownerOf(workspaceRoot, relFile) {
59
+ async ownerOf(workspaceRoot, relFile) {
60
60
  const file = relFile.split(path.sep).join('/');
61
61
  let best;
62
- for (const project of this.all(workspaceRoot)) {
62
+ for (const project of await this.all(workspaceRoot)) {
63
63
  const inside = project.dir === '' || file.startsWith(`${project.dir}/`);
64
64
  if (inside && (best === undefined || project.dir.length > best.dir.length))
65
65
  best = project;
66
66
  }
67
67
  return best;
68
68
  }
69
- load(workspaceRoot) {
69
+ async load(workspaceRoot) {
70
70
  // OUTSIDE any rule run's path exclusions (#1253): the catalog is cached across rules, so one rule's
71
71
  // excludePaths must never hide a project from the next. Excluded FILES are dropped by their listing.
72
- const listed = new rules_config_1.RuleFileScope().outside(() => this.diffScope.getAllFiles(workspaceRoot, { tsOnly: false }));
72
+ const listed = await new rules_config_1.RuleFileScope().outside(() => this.diffScope.getAllFiles(workspaceRoot, { tsOnly: false }));
73
73
  const jsons = listed
74
74
  .filter((f) => f === 'project.json' || f.endsWith('/project.json'));
75
75
  return jsons.map((rel) => {
@@ -136,8 +136,8 @@ let ScanScope = class ScanScope {
136
136
  * The files a rule in `mode` judges, restricted to the debug run's `--projects` when there is one.
137
137
  * `opts` is passed through to the git listing (`tsOnly: false` for a rule that reads templates/CSS).
138
138
  */
139
- files(workspaceRoot, mode, base, head, opts) {
140
- return this.restrict(workspaceRoot, this.unrestricted(workspaceRoot, mode, base, head, opts));
139
+ async files(workspaceRoot, mode, base, head, opts) {
140
+ return this.restrict(workspaceRoot, await this.unrestricted(workspaceRoot, mode, base, head, opts));
141
141
  }
142
142
  /** Record every violating site a rule found, for the debug run's per-project count. */
143
143
  recordSites(ruleName, relFiles) {
@@ -145,43 +145,48 @@ let ScanScope = class ScanScope {
145
145
  this.sites.push(new RecordedSite(ruleName, relFile));
146
146
  }
147
147
  /** Sites recorded so far, counted per owning project name (`(no project)` for a file outside one). */
148
- countsByProject(workspaceRoot) {
148
+ async countsByProject(workspaceRoot) {
149
149
  const counts = new Map();
150
150
  for (const site of this.sites) {
151
- const name = this.catalog.ownerOf(workspaceRoot, site.relFile)?.name ?? '(no project)';
151
+ const name = (await this.catalog.ownerOf(workspaceRoot, site.relFile))?.name ?? '(no project)';
152
152
  counts.set(name, (counts.get(name) ?? 0) + 1);
153
153
  }
154
154
  return counts;
155
155
  }
156
- unrestricted(workspaceRoot, mode, base, head, opts) {
156
+ async unrestricted(workspaceRoot, mode, base, head, opts) {
157
157
  if (mode === 'RUN_EVERY_TIME')
158
158
  return this.diffScope.getAllFiles(workspaceRoot, opts);
159
- const changed = this.diffScope.getChangedFiles(workspaceRoot, base, head, opts);
159
+ const changed = await this.diffScope.getChangedFiles(workspaceRoot, base, head, opts);
160
160
  if (mode !== 'MODIFIED_PROJECTS')
161
161
  return changed;
162
162
  // A project is TOUCHED by any changed file it owns — not only the files this rule reads — so a
163
163
  // project.json or README edit counts, exactly as nx affected would see it.
164
164
  const touched = new Set();
165
- for (const f of this.diffScope.getChangedFiles(workspaceRoot, base, head, { tsOnly: false })) {
166
- const owner = this.catalog.ownerOf(workspaceRoot, f);
165
+ for (const f of await this.diffScope.getChangedFiles(workspaceRoot, base, head, { tsOnly: false })) {
166
+ const owner = await this.catalog.ownerOf(workspaceRoot, f);
167
167
  if (owner !== undefined)
168
168
  touched.add(owner.dir);
169
169
  }
170
- const inTouched = this.diffScope.getAllFiles(workspaceRoot, opts).filter((f) => {
171
- const owner = this.catalog.ownerOf(workspaceRoot, f);
172
- return owner !== undefined && touched.has(owner.dir);
173
- });
170
+ const inTouched = [];
171
+ for (const f of await this.diffScope.getAllFiles(workspaceRoot, opts)) {
172
+ const owner = await this.catalog.ownerOf(workspaceRoot, f);
173
+ if (owner !== undefined && touched.has(owner.dir))
174
+ inTouched.push(f);
175
+ }
174
176
  return Array.from(new Set([...changed, ...inTouched]));
175
177
  }
176
- restrict(workspaceRoot, files) {
178
+ async restrict(workspaceRoot, files) {
177
179
  const names = this.restriction.projectNames;
178
180
  if (names === undefined)
179
181
  return files;
180
182
  const wanted = new Set(names);
181
- return files.filter((f) => {
182
- const owner = this.catalog.ownerOf(workspaceRoot, f);
183
- return owner !== undefined && wanted.has(owner.name);
184
- });
183
+ const kept = [];
184
+ for (const f of files) {
185
+ const owner = await this.catalog.ownerOf(workspaceRoot, f);
186
+ if (owner !== undefined && wanted.has(owner.name))
187
+ kept.push(f);
188
+ }
189
+ return kept;
185
190
  }
186
191
  };
187
192
  exports.ScanScope = ScanScope;
@@ -1 +1 @@
1
- {"version":3,"file":"scan-scope.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/scan-scope.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;GAiBG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAwF;AAExF,8DAA0D;AAC1D,iEAA6D;AAC7D,yCAA2D;AAE3D,oGAAoG;AACpG,MAAa,YAAY;IAER;IACA;IAFb,YACa,IAAY,EACZ,GAAW;QADX,SAAI,GAAJ,IAAI,CAAQ;QACZ,QAAG,GAAH,GAAG,CAAQ;IACrB,CAAC;CACP;AALD,oCAKC;AAKD;;;;GAIG;AAEI,IAAM,cAAc,GAApB,MAAM,cAAc;IAIM;IAHrB,UAAU,CAAqB;IAC/B,MAAM,GAAmB,EAAE,CAAC;IAEpC,YAA6B,SAAoB;QAApB,cAAS,GAAT,SAAS,CAAW;IAAG,CAAC;IAErD,GAAG,CAAC,aAAqB;QACrB,IAAI,IAAI,CAAC,UAAU,KAAK,aAAa,EAAE,CAAC;YACpC,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;YACvC,IAAI,CAAC,UAAU,GAAG,aAAa,CAAC;QACpC,CAAC;QACD,OAAO,IAAI,CAAC,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AC;IAEO,QAAQ,CAAC,aAAqB,EAAE,KAAe;QACnD,MAAM,KAAK,GAAG,IAAI,CAAC,WAAW,CAAC,YAAY,CAAC;QAC5C,IAAI,KAAK,KAAK,SAAS;YAAE,OAAO,KAAK,CAAC;QACtC,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC;QAC9B,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,CAAS,EAAE,EAAE;YAC9B,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC;YACrD,OAAO,KAAK,KAAK,SAAS,IAAI,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACzD,CAAC,CAAC,CAAC;IACP,CAAC;CACJ,CAAA;AAhEY,8BAAS;oBAAT,SAAS;IADrB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAKL,wBAAS;QACX,cAAc;QACV,eAAe;GANxC,SAAS,CAgErB;AAED;;;GAGG;AACH,MAAa,aAAc,SAAQ,SAAS;IACxC;QACI,MAAM,SAAS,GAAG,IAAI,wBAAS,EAAE,CAAC;QAClC,KAAK,CAAC,SAAS,EAAE,IAAI,cAAc,CAAC,SAAS,CAAC,EAAE,IAAI,eAAe,CAAC,SAAS,CAAC,CAAC,CAAC;IACpF,CAAC;CACJ;AALD,sCAKC","sourcesContent":["/**\n * Which FILES a diff-scoped code rule judges, for every mode it offers — and the one place the per-run\n * `--projects` restriction of the debug run (#1027) is applied.\n *\n * NEW_AND_MODIFIED_CODE — the changed files (the rule then keeps only sites on changed lines)\n * NEW_AND_MODIFIED_FILES — the changed files, whole\n * MODIFIED_PROJECTS — every in-scope file of every project the diff touches, whole, plus the\n * changed files themselves (so it is never narrower than NEW_AND_MODIFIED_FILES)\n * RUN_EVERY_TIME — every in-scope file in the repo, whole, every run\n *\n * The two whole-scope modes are NEW_AND_MODIFIED_FILES over a bigger file set — the rule's own detection,\n * disable handling and failure text are untouched, which is what lets a debug run print exactly what the\n * gate would print. A rule asks {@link ScanScope.files} instead of `getChangedFiles`, and asks\n * {@link ScanScope.isLineScoped} instead of comparing its mode to NEW_AND_MODIFIED_CODE.\n *\n * Every rule that reads its files here also reports its sites through {@link ScanScope.recordSites}, so\n * the debug run can print a count per project without parsing any rule's output.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { ChangedFilesOptions, DiffScope, RuleFileScope } from \"@webpieces/rules-config\";\nimport { ModifiedCodeMode } from '@webpieces/rules-sdk';\nimport { InformAiError } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { injectable, bindingScopeValues } from 'inversify';\n\n/** One nx project: its name and its directory (repo-relative, '/'-separated, no trailing slash). */\nexport class ProjectEntry {\n constructor(\n readonly name: string,\n readonly dir: string,\n ) {}\n}\n\n/** The only field of a project.json this catalog reads. */\ntype RawProjectName = { name?: string };\n\n/**\n * The repo's nx projects, found from the `project.json` files git knows about (tracked or untracked,\n * never ignored), and the owner lookup every whole-scope mode and `--projects` filter uses: a file\n * belongs to the DEEPEST project directory containing it.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ProjectCatalog {\n private cachedRoot: string | undefined;\n private cached: ProjectEntry[] = [];\n\n constructor(private readonly diffScope: DiffScope) {}\n\n all(workspaceRoot: string): ProjectEntry[] {\n if (this.cachedRoot !== workspaceRoot) {\n this.cached = this.load(workspaceRoot);\n this.cachedRoot = workspaceRoot;\n }\n return this.cached;\n }\n\n /** The project owning `relFile`, or undefined when no project directory contains it. */\n ownerOf(workspaceRoot: string, relFile: string): ProjectEntry | undefined {\n const file = relFile.split(path.sep).join('/');\n let best: ProjectEntry | undefined;\n for (const project of this.all(workspaceRoot)) {\n const inside = project.dir === '' || file.startsWith(`${project.dir}/`);\n if (inside && (best === undefined || project.dir.length > best.dir.length)) best = project;\n }\n return best;\n }\n\n private load(workspaceRoot: string): ProjectEntry[] {\n // OUTSIDE any rule run's path exclusions (#1253): the catalog is cached across rules, so one rule's\n // excludePaths must never hide a project from the next. Excluded FILES are dropped by their listing.\n const listed = new RuleFileScope().outside(() => this.diffScope.getAllFiles(workspaceRoot, { tsOnly: false }));\n const jsons = listed\n .filter((f: string) => f === 'project.json' || f.endsWith('/project.json'));\n return jsons.map((rel: string) => {\n const dir = path.posix.dirname(rel) === '.' ? '' : path.posix.dirname(rel);\n return new ProjectEntry(this.readName(path.join(workspaceRoot, rel)) ?? path.posix.basename(dir), dir);\n });\n }\n\n private readName(fullPath: string): string | undefined {\n // webpieces-disable no-unmanaged-exceptions -- add the exact project.json path while preserving the parse/read failure as cause\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const parsed = JSON.parse(fs.readFileSync(fullPath, 'utf-8')) as RawProjectName;\n return typeof parsed.name === 'string' && parsed.name.length > 0 ? parsed.name : undefined;\n } catch (err: unknown) {\n const error = toError(err);\n throw new InformAiError(`Cannot read nx project identity from ${fullPath} — fix project.json and retry.`, {\n cause: error,\n });\n }\n }\n}\n\n/**\n * The per-run project restriction. Bound at the composition root: `undefined` for every normal run (the\n * gate), the `--projects` names for a debug run. Data-only.\n */\nexport class ScanRestriction {\n constructor(readonly projectNames: readonly string[] | undefined) {}\n}\n\n/** One recorded violating site: which rule, which file. Data-only. */\nexport class RecordedSite {\n constructor(\n readonly ruleName: string,\n readonly relFile: string,\n ) {}\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class ScanScope {\n private readonly sites: RecordedSite[] = [];\n\n constructor(\n private readonly diffScope: DiffScope,\n private readonly catalog: ProjectCatalog,\n private readonly restriction: ScanRestriction,\n ) {}\n\n /** True when the rule keeps only sites on changed lines; every other active mode judges whole files. */\n isLineScoped(mode: ModifiedCodeMode): boolean {\n return mode === 'NEW_AND_MODIFIED_CODE';\n }\n\n /**\n * The files a rule in `mode` judges, restricted to the debug run's `--projects` when there is one.\n * `opts` is passed through to the git listing (`tsOnly: false` for a rule that reads templates/CSS).\n */\n files(workspaceRoot: string, mode: ModifiedCodeMode, base: string, head: string | undefined, opts?: ChangedFilesOptions): string[] {\n return this.restrict(workspaceRoot, this.unrestricted(workspaceRoot, mode, base, head, opts));\n }\n\n /** Record every violating site a rule found, for the debug run's per-project count. */\n recordSites(ruleName: string, relFiles: readonly string[]): void {\n for (const relFile of relFiles) this.sites.push(new RecordedSite(ruleName, relFile));\n }\n\n /** Sites recorded so far, counted per owning project name (`(no project)` for a file outside one). */\n countsByProject(workspaceRoot: string): Map<string, number> {\n const counts = new Map<string, number>();\n for (const site of this.sites) {\n const name = this.catalog.ownerOf(workspaceRoot, site.relFile)?.name ?? '(no project)';\n counts.set(name, (counts.get(name) ?? 0) + 1);\n }\n return counts;\n }\n\n private unrestricted(workspaceRoot: string, mode: ModifiedCodeMode, base: string, head: string | undefined, opts?: ChangedFilesOptions): string[] {\n if (mode === 'RUN_EVERY_TIME') return this.diffScope.getAllFiles(workspaceRoot, opts);\n const changed = this.diffScope.getChangedFiles(workspaceRoot, base, head, opts);\n if (mode !== 'MODIFIED_PROJECTS') return changed;\n // A project is TOUCHED by any changed file it owns — not only the files this rule reads — so a\n // project.json or README edit counts, exactly as nx affected would see it.\n const touched = new Set<string>();\n for (const f of this.diffScope.getChangedFiles(workspaceRoot, base, head, { tsOnly: false })) {\n const owner = this.catalog.ownerOf(workspaceRoot, f);\n if (owner !== undefined) touched.add(owner.dir);\n }\n const inTouched = this.diffScope.getAllFiles(workspaceRoot, opts).filter((f: string) => {\n const owner = this.catalog.ownerOf(workspaceRoot, f);\n return owner !== undefined && touched.has(owner.dir);\n });\n return Array.from(new Set([...changed, ...inTouched]));\n }\n\n private restrict(workspaceRoot: string, files: string[]): string[] {\n const names = this.restriction.projectNames;\n if (names === undefined) return files;\n const wanted = new Set(names);\n return files.filter((f: string) => {\n const owner = this.catalog.ownerOf(workspaceRoot, f);\n return owner !== undefined && wanted.has(owner.name);\n });\n }\n}\n\n/**\n * The gate's {@link ScanScope} — the diff, no project restriction — for a caller that builds a validator\n * outside the DI container: the single-rule nx executors (`validate-no-any-unknown` and friends) and specs.\n */\nexport class GateScanScope extends ScanScope {\n constructor() {\n const diffScope = new DiffScope();\n super(diffScope, new ProjectCatalog(diffScope), new ScanRestriction(undefined));\n }\n}\n"]}
1
+ {"version":3,"file":"scan-scope.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/scan-scope.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;GAiBG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAwF;AAExF,8DAA0D;AAC1D,iEAA6D;AAC7D,yCAA2D;AAE3D,oGAAoG;AACpG,MAAa,YAAY;IAER;IACA;IAFb,YACa,IAAY,EACZ,GAAW;QADX,SAAI,GAAJ,IAAI,CAAQ;QACZ,QAAG,GAAH,GAAG,CAAQ;IACrB,CAAC;CACP;AALD,oCAKC;AAKD;;;;GAIG;AAEI,IAAM,cAAc,GAApB,MAAM,cAAc;IAIM;IAHrB,UAAU,CAAqB;IAC/B,MAAM,GAAmB,EAAE,CAAC;IAEpC,YAA6B,SAAoB;QAApB,cAAS,GAAT,SAAS,CAAW;IAAG,CAAC;IAErD,KAAK,CAAC,GAAG,CAAC,aAAqB;QAC3B,IAAI,IAAI,CAAC,UAAU,KAAK,aAAa,EAAE,CAAC;YACpC,IAAI,CAAC,MAAM,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;YAC7C,IAAI,CAAC,UAAU,GAAG,aAAa,CAAC;QACpC,CAAC;QACD,OAAO,IAAI,CAAC,MAAM,CAAC;IACvB,CAAC;IAED,wFAAwF;IACxF,KAAK,CAAC,OAAO,CAAC,aAAqB,EAAE,OAAe;QAChD,MAAM,IAAI,GAAG,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC/C,IAAI,IAA8B,CAAC;QACnC,KAAK,MAAM,OAAO,IAAI,MAAM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C,WAAW,CAAC,YAAY,CAAC;QAC5C,IAAI,KAAK,KAAK,SAAS;YAAE,OAAO,KAAK,CAAC;QACtC,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC;QAC9B,MAAM,IAAI,GAAa,EAAE,CAAC;QAC1B,KAAK,MAAM,CAAC,IAAI,KAAK,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC;YAC3D,IAAI,KAAK,KAAK,SAAS,IAAI,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC;gBAAE,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACpE,CAAC;QACD,OAAO,IAAI,CAAC;IAChB,CAAC;CACJ,CAAA;AAnEY,8BAAS;oBAAT,SAAS;IADrB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAKL,wBAAS;QACX,cAAc;QACV,eAAe;GANxC,SAAS,CAmErB;AAED;;;GAGG;AACH,MAAa,aAAc,SAAQ,SAAS;IACxC;QACI,MAAM,SAAS,GAAG,IAAI,wBAAS,EAAE,CAAC;QAClC,KAAK,CAAC,SAAS,EAAE,IAAI,cAAc,CAAC,SAAS,CAAC,EAAE,IAAI,eAAe,CAAC,SAAS,CAAC,CAAC,CAAC;IACpF,CAAC;CACJ;AALD,sCAKC","sourcesContent":["/**\n * Which FILES a diff-scoped code rule judges, for every mode it offers — and the one place the per-run\n * `--projects` restriction of the debug run (#1027) is applied.\n *\n * NEW_AND_MODIFIED_CODE — the changed files (the rule then keeps only sites on changed lines)\n * NEW_AND_MODIFIED_FILES — the changed files, whole\n * MODIFIED_PROJECTS — every in-scope file of every project the diff touches, whole, plus the\n * changed files themselves (so it is never narrower than NEW_AND_MODIFIED_FILES)\n * RUN_EVERY_TIME — every in-scope file in the repo, whole, every run\n *\n * The two whole-scope modes are NEW_AND_MODIFIED_FILES over a bigger file set — the rule's own detection,\n * disable handling and failure text are untouched, which is what lets a debug run print exactly what the\n * gate would print. A rule asks {@link ScanScope.files} instead of `getChangedFiles`, and asks\n * {@link ScanScope.isLineScoped} instead of comparing its mode to NEW_AND_MODIFIED_CODE.\n *\n * Every rule that reads its files here also reports its sites through {@link ScanScope.recordSites}, so\n * the debug run can print a count per project without parsing any rule's output.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { ChangedFilesOptions, DiffScope, RuleFileScope } from \"@webpieces/rules-config\";\nimport { ModifiedCodeMode } from '@webpieces/rules-sdk';\nimport { InformAiError } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { injectable, bindingScopeValues } from 'inversify';\n\n/** One nx project: its name and its directory (repo-relative, '/'-separated, no trailing slash). */\nexport class ProjectEntry {\n constructor(\n readonly name: string,\n readonly dir: string,\n ) {}\n}\n\n/** The only field of a project.json this catalog reads. */\ntype RawProjectName = { name?: string };\n\n/**\n * The repo's nx projects, found from the `project.json` files git knows about (tracked or untracked,\n * never ignored), and the owner lookup every whole-scope mode and `--projects` filter uses: a file\n * belongs to the DEEPEST project directory containing it.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ProjectCatalog {\n private cachedRoot: string | undefined;\n private cached: ProjectEntry[] = [];\n\n constructor(private readonly diffScope: DiffScope) {}\n\n async all(workspaceRoot: string): Promise<ProjectEntry[]> {\n if (this.cachedRoot !== workspaceRoot) {\n this.cached = await this.load(workspaceRoot);\n this.cachedRoot = workspaceRoot;\n }\n return this.cached;\n }\n\n /** The project owning `relFile`, or undefined when no project directory contains it. */\n async ownerOf(workspaceRoot: string, relFile: string): Promise<ProjectEntry | undefined> {\n const file = relFile.split(path.sep).join('/');\n let best: ProjectEntry | undefined;\n for (const project of await this.all(workspaceRoot)) {\n const inside = project.dir === '' || file.startsWith(`${project.dir}/`);\n if (inside && (best === undefined || project.dir.length > best.dir.length)) best = project;\n }\n return best;\n }\n\n private async load(workspaceRoot: string): Promise<ProjectEntry[]> {\n // OUTSIDE any rule run's path exclusions (#1253): the catalog is cached across rules, so one rule's\n // excludePaths must never hide a project from the next. Excluded FILES are dropped by their listing.\n const listed = await new RuleFileScope().outside(() => this.diffScope.getAllFiles(workspaceRoot, { tsOnly: false }));\n const jsons = listed\n .filter((f: string) => f === 'project.json' || f.endsWith('/project.json'));\n return jsons.map((rel: string) => {\n const dir = path.posix.dirname(rel) === '.' ? '' : path.posix.dirname(rel);\n return new ProjectEntry(this.readName(path.join(workspaceRoot, rel)) ?? path.posix.basename(dir), dir);\n });\n }\n\n private readName(fullPath: string): string | undefined {\n // webpieces-disable no-unmanaged-exceptions -- add the exact project.json path while preserving the parse/read failure as cause\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const parsed = JSON.parse(fs.readFileSync(fullPath, 'utf-8')) as RawProjectName;\n return typeof parsed.name === 'string' && parsed.name.length > 0 ? parsed.name : undefined;\n } catch (err: unknown) {\n const error = toError(err);\n throw new InformAiError(`Cannot read nx project identity from ${fullPath} — fix project.json and retry.`, {\n cause: error,\n });\n }\n }\n}\n\n/**\n * The per-run project restriction. Bound at the composition root: `undefined` for every normal run (the\n * gate), the `--projects` names for a debug run. Data-only.\n */\nexport class ScanRestriction {\n constructor(readonly projectNames: readonly string[] | undefined) {}\n}\n\n/** One recorded violating site: which rule, which file. Data-only. */\nexport class RecordedSite {\n constructor(\n readonly ruleName: string,\n readonly relFile: string,\n ) {}\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class ScanScope {\n private readonly sites: RecordedSite[] = [];\n\n constructor(\n private readonly diffScope: DiffScope,\n private readonly catalog: ProjectCatalog,\n private readonly restriction: ScanRestriction,\n ) {}\n\n /** True when the rule keeps only sites on changed lines; every other active mode judges whole files. */\n isLineScoped(mode: ModifiedCodeMode): boolean {\n return mode === 'NEW_AND_MODIFIED_CODE';\n }\n\n /**\n * The files a rule in `mode` judges, restricted to the debug run's `--projects` when there is one.\n * `opts` is passed through to the git listing (`tsOnly: false` for a rule that reads templates/CSS).\n */\n async files(workspaceRoot: string, mode: ModifiedCodeMode, base: string, head: string | undefined, opts?: ChangedFilesOptions): Promise<string[]> {\n return this.restrict(workspaceRoot, await this.unrestricted(workspaceRoot, mode, base, head, opts));\n }\n\n /** Record every violating site a rule found, for the debug run's per-project count. */\n recordSites(ruleName: string, relFiles: readonly string[]): void {\n for (const relFile of relFiles) this.sites.push(new RecordedSite(ruleName, relFile));\n }\n\n /** Sites recorded so far, counted per owning project name (`(no project)` for a file outside one). */\n async countsByProject(workspaceRoot: string): Promise<Map<string, number>> {\n const counts = new Map<string, number>();\n for (const site of this.sites) {\n const name = (await this.catalog.ownerOf(workspaceRoot, site.relFile))?.name ?? '(no project)';\n counts.set(name, (counts.get(name) ?? 0) + 1);\n }\n return counts;\n }\n\n private async unrestricted(workspaceRoot: string, mode: ModifiedCodeMode, base: string, head: string | undefined, opts?: ChangedFilesOptions): Promise<string[]> {\n if (mode === 'RUN_EVERY_TIME') return this.diffScope.getAllFiles(workspaceRoot, opts);\n const changed = await this.diffScope.getChangedFiles(workspaceRoot, base, head, opts);\n if (mode !== 'MODIFIED_PROJECTS') return changed;\n // A project is TOUCHED by any changed file it owns — not only the files this rule reads — so a\n // project.json or README edit counts, exactly as nx affected would see it.\n const touched = new Set<string>();\n for (const f of await this.diffScope.getChangedFiles(workspaceRoot, base, head, { tsOnly: false })) {\n const owner = await this.catalog.ownerOf(workspaceRoot, f);\n if (owner !== undefined) touched.add(owner.dir);\n }\n const inTouched: string[] = [];\n for (const f of await this.diffScope.getAllFiles(workspaceRoot, opts)) {\n const owner = await this.catalog.ownerOf(workspaceRoot, f);\n if (owner !== undefined && touched.has(owner.dir)) inTouched.push(f);\n }\n return Array.from(new Set([...changed, ...inTouched]));\n }\n\n private async restrict(workspaceRoot: string, files: string[]): Promise<string[]> {\n const names = this.restriction.projectNames;\n if (names === undefined) return files;\n const wanted = new Set(names);\n const kept: string[] = [];\n for (const f of files) {\n const owner = await this.catalog.ownerOf(workspaceRoot, f);\n if (owner !== undefined && wanted.has(owner.name)) kept.push(f);\n }\n return kept;\n }\n}\n\n/**\n * The gate's {@link ScanScope} — the diff, no project restriction — for a caller that builds a validator\n * outside the DI container: the single-rule nx executors (`validate-no-any-unknown` and friends) and specs.\n */\nexport class GateScanScope extends ScanScope {\n constructor() {\n const diffScope = new DiffScope();\n super(diffScope, new ProjectCatalog(diffScope), new ScanRestriction(undefined));\n }\n}\n"]}
package/src/tag-rule.js CHANGED
@@ -195,7 +195,7 @@ async function runTagValidator(options, workspaceRoot, spec) {
195
195
  let base = process.env['NX_BASE'];
196
196
  const head = process.env['NX_HEAD'];
197
197
  if (!base) {
198
- base = (0, rules_config_1.detectBase)(workspaceRoot) ?? undefined;
198
+ base = await (0, rules_config_1.detectBase)(workspaceRoot) ?? undefined;
199
199
  if (!base) {
200
200
  console.log(`\n⏭️ Skipping ${spec.ruleName} validation (could not detect base branch)`);
201
201
  console.log('');
@@ -207,7 +207,7 @@ async function runTagValidator(options, workspaceRoot, spec) {
207
207
  console.log('');
208
208
  // Project-level rule: ANY changed file (not just .ts) makes its owning
209
209
  // project require a tag, so include non-code files too.
210
- const changedFiles = (0, rules_config_1.getChangedFiles)(workspaceRoot, base, head, { tsOnly: false });
210
+ const changedFiles = await (0, rules_config_1.getChangedFiles)(workspaceRoot, base, head, { tsOnly: false });
211
211
  if (changedFiles.length === 0) {
212
212
  console.log('✅ No changed files in any project');
213
213
  return { success: true };
@@ -1 +1 @@
1
- {"version":3,"file":"tag-rule.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/tag-rule.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;AA+IH,wDAcC;AASD,4EAiBC;AAGD,0CA2DC;;AAnPD,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAsE;AAEtE,iEAA6D;AAG7D,2EAA2E;AAC3E,MAAa,iBAAiB;IAEN;IACA;IAFpB,YACoB,IAAY,EACZ,eAAuB;QADv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AE,IAAI,CAAC,CAAC;IAC3C,CAAC;IACD,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,mBAAmB,KAAK,IAAI,EAAE,CAAC;QAC1D,IAAI,CAAC,mBAAmB,CAAC,OAAO,EAAE,UAAU,EAAE,IAAI,CAAC,CAAC;IACxD,CAAC;IACD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC9B,CAAC","sourcesContent":["/**\n * Shared \"every modified project must carry a `<prefix>` nx tag\" rule engine.\n *\n * Both `framework-tag` (prefix `framework:`) and `role-tag` (prefix `role:`) are\n * the same rule with different prefix/known-values/messages, so the\n * project-walking + diff-scoping + mode logic lives here once and each concrete\n * rule supplies only a {@link TagRuleSpec}.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { detectBase, getChangedFiles } from \"@webpieces/rules-config\";\nimport { ProjectMode } from \"./configs/rule-configs\";\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { ExecutorResult } from './code-validator';\n\n/** A project (identified by its project.json) missing the required tag. */\nexport class MissingTagProject {\n constructor(\n public readonly name: string,\n public readonly projectJsonPath: string\n ) {}\n}\n\n/**\n * A project carrying one or more `<prefix>` tag VALUES outside the known set\n * (e.g. `framework:all`). `role-tag` never uses this — only rules that opt into\n * value validation via {@link TagRuleSpec.validateValues}.\n */\nexport class InvalidTagProject {\n constructor(\n public readonly name: string,\n public readonly projectJsonPath: string,\n public readonly badValues: string[]\n ) {}\n}\n\n/** Print the invalid-value report for projects carrying out-of-set tag values. */\nexport type ReportInvalidValues = (\n invalid: InvalidTagProject[],\n knownTypes: string[],\n mode: ProjectMode\n) => void;\n\n/** The knobs and messages that make a concrete tag rule out of the shared engine. */\nexport class TagRuleSpec {\n constructor(\n /** Tag prefix, e.g. `framework:` or `role:`. */\n public readonly tagPrefix: string,\n /** Rule id, e.g. `framework-tag` / `role-tag` (used in skip/validating logs). */\n public readonly ruleName: string,\n /** Human label for the \"Validating X\" banner, e.g. `Framework Tag`. */\n public readonly ruleLabel: string,\n /** Default allowed values when config.knownTypes is empty. */\n public readonly defaultKnownTypes: string[],\n /** Print the violation report for the missing-tag projects. */\n public readonly report: (untagged: MissingTagProject[], knownTypes: string[], mode: ProjectMode) => void,\n /**\n * When true, ALSO validate that every `<prefix>` tag value is in the\n * known set (framework-tag opts in to reject `framework:all` and typos;\n * role-tag leaves this false so its single-value behavior is unchanged).\n */\n public readonly validateValues: boolean = false,\n /** Report for out-of-set values; required when {@link validateValues} is true. */\n public readonly reportInvalidValues: ReportInvalidValues | null = null\n ) {}\n}\n\n/** The config fields the shared engine reads (shared by every tag rule config). */\nexport interface TagRuleConfig {\n mode?: ProjectMode;\n knownTypes?: string[];\n turnOffRuleUntilEpoch?: number;\n turnOffRuleWhileOnBranch?: string | null;\n}\n\ntype RawProjectJson = { name?: string; tags?: string[] };\n\nclass ProjectJson {\n constructor(\n public readonly name: string | null,\n public readonly tags: string[]\n ) {}\n}\n\n/**\n * Parse `name` + `tags` from a project.json. Returns an empty ProjectJson when\n * unreadable/unparseable — config validation owns malformed-json reporting; this\n * rule just nudges for a tag and must never crash the build.\n */\nfunction readProjectJson(projectJsonPath: string, workspaceRoot: string): ProjectJson {\n const fullPath = path.join(workspaceRoot, projectJsonPath);\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const parsed: RawProjectJson = JSON.parse(fs.readFileSync(fullPath, 'utf-8'));\n const name = typeof parsed.name === 'string' && parsed.name.length > 0 ? parsed.name : null;\n const tags = Array.isArray(parsed.tags) ? parsed.tags.filter((tag: string) => typeof tag === 'string') : [];\n return new ProjectJson(name, tags);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // swallow — malformed project.json is not this rule's concern\n return new ProjectJson(null, []);\n }\n}\n\n/**\n * Walk up from a changed file to the nearest ancestor directory containing a\n * project.json (the file's owning nx project). Returns the repo-relative\n * project.json path, or null when the file belongs to no project.\n */\nfunction findOwningProjectJson(changedFile: string, workspaceRoot: string): string | null {\n let dir = path.dirname(changedFile);\n while (true) {\n const candidate = path.join(dir, 'project.json');\n if (fs.existsSync(path.join(workspaceRoot, candidate))) {\n return candidate;\n }\n const parent = path.dirname(dir);\n if (parent === dir || dir === '.' || dir === '') {\n return null;\n }\n dir = parent;\n }\n}\n\nfunction hasTag(tags: string[], tagPrefix: string): boolean {\n return tags.some((tag: string) => tag.startsWith(tagPrefix) && tag.slice(tagPrefix.length).trim().length > 0);\n}\n\n/** The non-empty values of every `<tagPrefix>` tag on a project (the env/role set). */\nfunction tagValues(tags: string[], tagPrefix: string): string[] {\n return tags\n .filter((tag: string) => tag.startsWith(tagPrefix))\n .map((tag: string) => tag.slice(tagPrefix.length).trim())\n .filter((value: string) => value.length > 0);\n}\n\n/** The distinct owning project.json paths of a set of changed files. */\nfunction collectOwningProjectJsons(workspaceRoot: string, changedFiles: string[]): string[] {\n const projectJsonPaths = new Set<string>();\n for (const file of changedFiles) {\n const owning = findOwningProjectJson(file, workspaceRoot);\n if (owning !== null) {\n projectJsonPaths.add(owning);\n }\n }\n return Array.from(projectJsonPaths).sort();\n}\n\n/** Every owning project of a changed file that is missing a `<tagPrefix>` tag. */\nexport function findProjectsMissingTag(\n workspaceRoot: string,\n changedFiles: string[],\n tagPrefix: string\n): MissingTagProject[] {\n const missing: MissingTagProject[] = [];\n for (const projectJsonPath of collectOwningProjectJsons(workspaceRoot, changedFiles)) {\n const projectJson = readProjectJson(projectJsonPath, workspaceRoot);\n if (!hasTag(projectJson.tags, tagPrefix)) {\n const name = projectJson.name ?? path.dirname(projectJsonPath);\n missing.push(new MissingTagProject(name, projectJsonPath));\n }\n }\n return missing;\n}\n\n/**\n * Every owning project of a changed file that carries one or more `<tagPrefix>`\n * tag VALUES outside `knownTypes`. Multiple values per project are allowed (an\n * env set) — this only flags values not in the known set (e.g. `framework:all`\n * or a typo). Projects with no `<tagPrefix>` tag are skipped here (the\n * missing-tag scan owns that case).\n */\nexport function findProjectsWithInvalidTagValues(\n workspaceRoot: string,\n changedFiles: string[],\n tagPrefix: string,\n knownTypes: string[]\n): InvalidTagProject[] {\n const known = new Set(knownTypes);\n const invalid: InvalidTagProject[] = [];\n for (const projectJsonPath of collectOwningProjectJsons(workspaceRoot, changedFiles)) {\n const projectJson = readProjectJson(projectJsonPath, workspaceRoot);\n const badValues = tagValues(projectJson.tags, tagPrefix).filter((value: string) => !known.has(value));\n if (badValues.length > 0) {\n const name = projectJson.name ?? path.dirname(projectJsonPath);\n invalid.push(new InvalidTagProject(name, projectJsonPath, badValues));\n }\n }\n return invalid;\n}\n\n/** Run a concrete tag rule (framework-tag / role-tag) against the git diff. */\nexport async function runTagValidator(\n options: TagRuleConfig,\n workspaceRoot: string,\n spec: TagRuleSpec\n): Promise<ExecutorResult> {\n const mode: ProjectMode = options.mode ?? 'OFF';\n const knownTypes = options.knownTypes && options.knownTypes.length > 0 ? options.knownTypes : spec.defaultKnownTypes;\n\n if (mode === 'OFF') {\n console.log(`\\n⏭️ Skipping ${spec.ruleName} validation (mode: OFF)`);\n console.log('');\n return { success: true };\n }\n\n console.log(`\\n📏 Validating ${spec.ruleLabel}\\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 if (!base) {\n console.log(`\\n⏭️ Skipping ${spec.ruleName} 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 // Project-level rule: ANY changed file (not just .ts) makes its owning\n // project require a tag, so include non-code files too.\n const changedFiles = getChangedFiles(workspaceRoot, base, head, { tsOnly: false });\n if (changedFiles.length === 0) {\n console.log('✅ No changed files in any project');\n return { success: true };\n }\n\n const missing = findProjectsMissingTag(workspaceRoot, changedFiles, spec.tagPrefix);\n const invalid =\n spec.validateValues && spec.reportInvalidValues !== null\n ? findProjectsWithInvalidTagValues(workspaceRoot, changedFiles, spec.tagPrefix, knownTypes)\n : [];\n\n if (missing.length === 0 && invalid.length === 0) {\n console.log(`✅ Every modified project declares a valid ${spec.tagPrefix.replace(/:$/, '')} tag`);\n return { success: true };\n }\n\n if (missing.length > 0) {\n spec.report(missing, knownTypes, mode);\n }\n if (invalid.length > 0 && spec.reportInvalidValues !== null) {\n spec.reportInvalidValues(invalid, knownTypes, mode);\n }\n return { success: false };\n}\n"]}
1
+ {"version":3,"file":"tag-rule.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/tag-rule.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;AA+IH,wDAcC;AASD,4EAiBC;AAGD,0CA2DC;;AAnPD,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAsE;AAEtE,iEAA6D;AAG7D,2EAA2E;AAC3E,MAAa,iBAAiB;IAEN;IACA;IAFpB,YACoB,IAAY,EACZ,eAAuB;QADvB,SAAI,GAAJ,IAAI,CAAQ;QACZ,oBAAe,GAAf,eAAe,CAAQ;IACxC,CAAC;CACP;AALD,8CAKC;AAED;;;;GAIG;AACH,MAAa,iBAAiB;IAEN;IACA;IACA;IAHpB,YACoB,IAAY,EACZ,eAAuB,EACvB,SAAmB;QAFnB,SAAI,GAAJ,IAAI,CAAQ;QACZ,oBAAe,GAAf,eAAe,CAAQ;QACvB,cAAS,GAAT,SAAS,CAAU;IACpC,CAAC;CACP;AAND,8CAMC;AASD,qFAAqF;AACrF,MAAa,WAAW;IAGA;IAEA;IAEA;IAEA;IAEA;IAMA;IAEA;IAlBpB;IACI,gDAAgD;IAChC,SAAiB;IACjC,iFAAiF;IACjE,QAAgB;IAChC,uEAAuE;IACvD,SAAiB;IACjC,8DAA8D;IAC9C,iBAA2B;IAC3C,+DAA+D;IAC/C,MAAwF;IACxG;;;;OAIG;IACa,iBAA0B,KAAK;IAC/C,kFAAkF;IAClE,sBAAkD,IAAI;QAhBtD,cAAS,GAAT,SAAS,CAAQ;QAEjB,aAAQ,GA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AAC,CAAC;IACpF,MAAM,OAAO,GACT,IAAI,CAAC,cAAc,IAAI,IAAI,CAAC,mBAAmB,KAAK,IAAI;QACpD,CAAC,CAAC,gCAAgC,CAAC,aAAa,EAAE,YAAY,EAAE,IAAI,CAAC,SAAS,EAAE,UAAU,CAAC;QAC3F,CAAC,CAAC,EAAE,CAAC;IAEb,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC/C,OAAO,CAAC,GAAG,CAAC,6CAA6C,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC;QACjG,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7B,CAAC;IAED,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACrB,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,UAAU,EAAE,IAAI,CAAC,CAAC;IAC3C,CAAC;IACD,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,mBAAmB,KAAK,IAAI,EAAE,CAAC;QAC1D,IAAI,CAAC,mBAAmB,CAAC,OAAO,EAAE,UAAU,EAAE,IAAI,CAAC,CAAC;IACxD,CAAC;IACD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC9B,CAAC","sourcesContent":["/**\n * Shared \"every modified project must carry a `<prefix>` nx tag\" rule engine.\n *\n * Both `framework-tag` (prefix `framework:`) and `role-tag` (prefix `role:`) are\n * the same rule with different prefix/known-values/messages, so the\n * project-walking + diff-scoping + mode logic lives here once and each concrete\n * rule supplies only a {@link TagRuleSpec}.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { detectBase, getChangedFiles } from \"@webpieces/rules-config\";\nimport { ProjectMode } from \"./configs/rule-configs\";\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { ExecutorResult } from './code-validator';\n\n/** A project (identified by its project.json) missing the required tag. */\nexport class MissingTagProject {\n constructor(\n public readonly name: string,\n public readonly projectJsonPath: string\n ) {}\n}\n\n/**\n * A project carrying one or more `<prefix>` tag VALUES outside the known set\n * (e.g. `framework:all`). `role-tag` never uses this — only rules that opt into\n * value validation via {@link TagRuleSpec.validateValues}.\n */\nexport class InvalidTagProject {\n constructor(\n public readonly name: string,\n public readonly projectJsonPath: string,\n public readonly badValues: string[]\n ) {}\n}\n\n/** Print the invalid-value report for projects carrying out-of-set tag values. */\nexport type ReportInvalidValues = (\n invalid: InvalidTagProject[],\n knownTypes: string[],\n mode: ProjectMode\n) => void;\n\n/** The knobs and messages that make a concrete tag rule out of the shared engine. */\nexport class TagRuleSpec {\n constructor(\n /** Tag prefix, e.g. `framework:` or `role:`. */\n public readonly tagPrefix: string,\n /** Rule id, e.g. `framework-tag` / `role-tag` (used in skip/validating logs). */\n public readonly ruleName: string,\n /** Human label for the \"Validating X\" banner, e.g. `Framework Tag`. */\n public readonly ruleLabel: string,\n /** Default allowed values when config.knownTypes is empty. */\n public readonly defaultKnownTypes: string[],\n /** Print the violation report for the missing-tag projects. */\n public readonly report: (untagged: MissingTagProject[], knownTypes: string[], mode: ProjectMode) => void,\n /**\n * When true, ALSO validate that every `<prefix>` tag value is in the\n * known set (framework-tag opts in to reject `framework:all` and typos;\n * role-tag leaves this false so its single-value behavior is unchanged).\n */\n public readonly validateValues: boolean = false,\n /** Report for out-of-set values; required when {@link validateValues} is true. */\n public readonly reportInvalidValues: ReportInvalidValues | null = null\n ) {}\n}\n\n/** The config fields the shared engine reads (shared by every tag rule config). */\nexport interface TagRuleConfig {\n mode?: ProjectMode;\n knownTypes?: string[];\n turnOffRuleUntilEpoch?: number;\n turnOffRuleWhileOnBranch?: string | null;\n}\n\ntype RawProjectJson = { name?: string; tags?: string[] };\n\nclass ProjectJson {\n constructor(\n public readonly name: string | null,\n public readonly tags: string[]\n ) {}\n}\n\n/**\n * Parse `name` + `tags` from a project.json. Returns an empty ProjectJson when\n * unreadable/unparseable — config validation owns malformed-json reporting; this\n * rule just nudges for a tag and must never crash the build.\n */\nfunction readProjectJson(projectJsonPath: string, workspaceRoot: string): ProjectJson {\n const fullPath = path.join(workspaceRoot, projectJsonPath);\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const parsed: RawProjectJson = JSON.parse(fs.readFileSync(fullPath, 'utf-8'));\n const name = typeof parsed.name === 'string' && parsed.name.length > 0 ? parsed.name : null;\n const tags = Array.isArray(parsed.tags) ? parsed.tags.filter((tag: string) => typeof tag === 'string') : [];\n return new ProjectJson(name, tags);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // swallow — malformed project.json is not this rule's concern\n return new ProjectJson(null, []);\n }\n}\n\n/**\n * Walk up from a changed file to the nearest ancestor directory containing a\n * project.json (the file's owning nx project). Returns the repo-relative\n * project.json path, or null when the file belongs to no project.\n */\nfunction findOwningProjectJson(changedFile: string, workspaceRoot: string): string | null {\n let dir = path.dirname(changedFile);\n while (true) {\n const candidate = path.join(dir, 'project.json');\n if (fs.existsSync(path.join(workspaceRoot, candidate))) {\n return candidate;\n }\n const parent = path.dirname(dir);\n if (parent === dir || dir === '.' || dir === '') {\n return null;\n }\n dir = parent;\n }\n}\n\nfunction hasTag(tags: string[], tagPrefix: string): boolean {\n return tags.some((tag: string) => tag.startsWith(tagPrefix) && tag.slice(tagPrefix.length).trim().length > 0);\n}\n\n/** The non-empty values of every `<tagPrefix>` tag on a project (the env/role set). */\nfunction tagValues(tags: string[], tagPrefix: string): string[] {\n return tags\n .filter((tag: string) => tag.startsWith(tagPrefix))\n .map((tag: string) => tag.slice(tagPrefix.length).trim())\n .filter((value: string) => value.length > 0);\n}\n\n/** The distinct owning project.json paths of a set of changed files. */\nfunction collectOwningProjectJsons(workspaceRoot: string, changedFiles: string[]): string[] {\n const projectJsonPaths = new Set<string>();\n for (const file of changedFiles) {\n const owning = findOwningProjectJson(file, workspaceRoot);\n if (owning !== null) {\n projectJsonPaths.add(owning);\n }\n }\n return Array.from(projectJsonPaths).sort();\n}\n\n/** Every owning project of a changed file that is missing a `<tagPrefix>` tag. */\nexport function findProjectsMissingTag(\n workspaceRoot: string,\n changedFiles: string[],\n tagPrefix: string\n): MissingTagProject[] {\n const missing: MissingTagProject[] = [];\n for (const projectJsonPath of collectOwningProjectJsons(workspaceRoot, changedFiles)) {\n const projectJson = readProjectJson(projectJsonPath, workspaceRoot);\n if (!hasTag(projectJson.tags, tagPrefix)) {\n const name = projectJson.name ?? path.dirname(projectJsonPath);\n missing.push(new MissingTagProject(name, projectJsonPath));\n }\n }\n return missing;\n}\n\n/**\n * Every owning project of a changed file that carries one or more `<tagPrefix>`\n * tag VALUES outside `knownTypes`. Multiple values per project are allowed (an\n * env set) — this only flags values not in the known set (e.g. `framework:all`\n * or a typo). Projects with no `<tagPrefix>` tag are skipped here (the\n * missing-tag scan owns that case).\n */\nexport function findProjectsWithInvalidTagValues(\n workspaceRoot: string,\n changedFiles: string[],\n tagPrefix: string,\n knownTypes: string[]\n): InvalidTagProject[] {\n const known = new Set(knownTypes);\n const invalid: InvalidTagProject[] = [];\n for (const projectJsonPath of collectOwningProjectJsons(workspaceRoot, changedFiles)) {\n const projectJson = readProjectJson(projectJsonPath, workspaceRoot);\n const badValues = tagValues(projectJson.tags, tagPrefix).filter((value: string) => !known.has(value));\n if (badValues.length > 0) {\n const name = projectJson.name ?? path.dirname(projectJsonPath);\n invalid.push(new InvalidTagProject(name, projectJsonPath, badValues));\n }\n }\n return invalid;\n}\n\n/** Run a concrete tag rule (framework-tag / role-tag) against the git diff. */\nexport async function runTagValidator(\n options: TagRuleConfig,\n workspaceRoot: string,\n spec: TagRuleSpec\n): Promise<ExecutorResult> {\n const mode: ProjectMode = options.mode ?? 'OFF';\n const knownTypes = options.knownTypes && options.knownTypes.length > 0 ? options.knownTypes : spec.defaultKnownTypes;\n\n if (mode === 'OFF') {\n console.log(`\\n⏭️ Skipping ${spec.ruleName} validation (mode: OFF)`);\n console.log('');\n return { success: true };\n }\n\n console.log(`\\n📏 Validating ${spec.ruleLabel}\\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 = await detectBase(workspaceRoot) ?? undefined;\n if (!base) {\n console.log(`\\n⏭️ Skipping ${spec.ruleName} 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 // Project-level rule: ANY changed file (not just .ts) makes its owning\n // project require a tag, so include non-code files too.\n const changedFiles = await getChangedFiles(workspaceRoot, base, head, { tsOnly: false });\n if (changedFiles.length === 0) {\n console.log('✅ No changed files in any project');\n return { success: true };\n }\n\n const missing = findProjectsMissingTag(workspaceRoot, changedFiles, spec.tagPrefix);\n const invalid =\n spec.validateValues && spec.reportInvalidValues !== null\n ? findProjectsWithInvalidTagValues(workspaceRoot, changedFiles, spec.tagPrefix, knownTypes)\n : [];\n\n if (missing.length === 0 && invalid.length === 0) {\n console.log(`✅ Every modified project declares a valid ${spec.tagPrefix.replace(/:$/, '')} tag`);\n return { success: true };\n }\n\n if (missing.length > 0) {\n spec.report(missing, knownTypes, mode);\n }\n if (invalid.length > 0 && spec.reportInvalidValues !== null) {\n spec.reportInvalidValues(invalid, knownTypes, mode);\n }\n return { success: false };\n}\n"]}
@@ -243,10 +243,11 @@ function findCatchViolationsInFile(filePath, workspaceRoot, disableAllowed) {
243
243
  /**
244
244
  * NEW_AND_MODIFIED_CODE mode: Flag violations on changed lines.
245
245
  */
246
- function findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed) {
246
+ // webpieces-disable no-function-outside-class -- pre-existing module helper, made async only because DiffScope now reaches git through the injected process edge (#1381)
247
+ async function findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed) {
247
248
  const violations = [];
248
249
  for (const file of changedFiles) {
249
- const diff = (0, rules_config_1.getFileDiff)(workspaceRoot, file, base, head);
250
+ const diff = await (0, rules_config_1.getFileDiff)(workspaceRoot, file, base, head);
250
251
  const changedLines = (0, rules_config_1.getChangedLineNumbers)(diff);
251
252
  if (changedLines.size === 0)
252
253
  continue;
@@ -329,7 +330,7 @@ async function runValidatorImpl(scan, options, workspaceRoot) {
329
330
  let base = process.env['NX_BASE'];
330
331
  const head = process.env['NX_HEAD'];
331
332
  if (!base) {
332
- base = (0, rules_config_1.detectBase)(workspaceRoot) ?? undefined;
333
+ base = await (0, rules_config_1.detectBase)(workspaceRoot) ?? undefined;
333
334
  if (!base) {
334
335
  console.log('\n\u23ed\ufe0f Skipping catch-error-pattern validation (could not detect base branch)');
335
336
  console.log('');
@@ -339,7 +340,7 @@ async function runValidatorImpl(scan, options, workspaceRoot) {
339
340
  console.log(` Base: ${base}`);
340
341
  console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);
341
342
  console.log('');
342
- const changedFiles = scan.files(workspaceRoot, mode, base, head);
343
+ const changedFiles = await scan.files(workspaceRoot, mode, base, head);
343
344
  if (changedFiles.length === 0) {
344
345
  console.log('\u2705 No TypeScript files changed');
345
346
  return { success: true };
@@ -347,7 +348,7 @@ async function runValidatorImpl(scan, options, workspaceRoot) {
347
348
  console.log(`\ud83d\udcc2 Checking ${changedFiles.length} changed file(s)...`);
348
349
  let violations = [];
349
350
  if (mode === 'NEW_AND_MODIFIED_CODE') {
350
- violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed);
351
+ violations = await findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed);
351
352
  }
352
353
  else {
353
354
  // NEW_AND_MODIFIED_FILES and the whole-scope modes (#1027) all judge every site of every file.
@@ -1 +1 @@
1
- {"version":3,"file":"validate-catch-error-pattern.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-catch-error-pattern.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAo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AAK,EAAE,CAAC;AAC9B,CAAC;AAGM,IAAM,0BAA0B,GAAhC,MAAM,0BAA2B,SAAQ,8BAAsC;IACpB;IAA9D,YAAY,MAA+B,EAAmB,SAAoB;QAC9E,KAAK,CAAC,MAAM,EAAE,qBAAqB,EAAE,qBAAqB,CAAC,CAAC;QADF,cAAS,GAAT,SAAS,CAAW;IAElF,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,aAAqB;QAC3B,OAAO,gBAAgB,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IACxE,CAAC;CACJ,CAAA;AARY,gEAA0B;qCAA1B,0BAA0B;IADtC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEjB,sCAAuB,EAA8B,sBAAS;GADzE,0BAA0B,CAQtC","sourcesContent":["/**\n * Validate Catch Error Pattern Executor\n *\n * Validates that catch blocks follow the standardized error handling pattern.\n * Uses TypeScript AST for detection and LINE-BASED git diff filtering.\n *\n * ============================================================================\n * REQUIRED PATTERN\n * ============================================================================\n *\n * Standard: catch (err: unknown) { const error = toError(err); ... }\n * Ignored: catch (err: unknown) { //const error = toError(err); ... }\n * Nested: catch (err2: unknown) { const error2 = toError(err2); ... }\n *\n * ============================================================================\n * VIOLATIONS (BAD) - These patterns are flagged:\n * ============================================================================\n *\n * - catch (e) { ... } — wrong parameter name\n * - catch (err) { ... } — missing : unknown type annotation\n * - catch (err: unknown) { ... } — missing toError() as first statement\n * - catch (err: unknown) { const x = toError(err); } — wrong variable name\n *\n * ============================================================================\n * MODES (LINE-BASED)\n * ============================================================================\n * - OFF: Skip validation entirely\n * - NEW_AND_MODIFIED_CODE: Flag catch violations on changed lines (lines in diff hunks)\n * - NEW_AND_MODIFIED_FILES: Flag ALL catch violations in files that were modified\n *\n * ============================================================================\n * ESCAPE HATCH\n * ============================================================================\n * Add comment above the violation:\n * // webpieces-disable catch-error-pattern -- [your justification]\n * } catch (err: unknown) {\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as ts from 'typescript';\nimport { hasDisable, detectBase, getFileDiff, getChangedLineNumbers } from \"@webpieces/rules-config\";\nimport { CatchErrorPatternConfig } from \"./configs/rule-configs\";\nimport { ModifiedCodeMode } from '@webpieces/rules-sdk';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { ScanScope } from './scan-scope';\n\ninterface CatchViolation {\n file: string;\n line: number;\n message: string;\n context: string;\n}\n\ninterface CatchViolationInfo {\n line: number;\n message: string;\n context: string;\n hasDisableComment: boolean;\n}\n\n/**\n * Check if a line contains a disable comment for catch-error-pattern.\n * Recognizes both webpieces-disable and eslint-disable-next-line @webpieces/ formats.\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 (hasDisable(line, \"catch-error-pattern\")) {\n return true;\n }\n if (line.includes('@webpieces/catch-error-pattern')) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Check if the catch block contains a disable comment for catch-error-pattern.\n */\nfunction hasBlockLevelDisable(sourceText: string, blockStart: number, blockEnd: number): boolean {\n const blockText = sourceText.substring(blockStart, blockEnd);\n return hasDisable(blockText, \"catch-error-pattern\") ||\n blockText.includes('@webpieces/catch-error-pattern');\n}\n\n/**\n * Check if the catch block body text contains the commented-out ignore pattern.\n */\nfunction hasIgnoreComment(\n sourceText: string,\n blockStart: number,\n blockEnd: number,\n expectedVarName: string,\n actualParamName: string,\n): boolean {\n const blockText = sourceText.substring(blockStart, blockEnd);\n const ignorePattern = new RegExp(\n `//\\\\s*const\\\\s+${expectedVarName}\\\\s*=\\\\s*toError\\\\(${actualParamName}\\\\)`,\n );\n return ignorePattern.test(blockText);\n}\n\n/**\n * Validate a single CatchClause node.\n */\n// webpieces-disable max-lines-new-methods -- AST validation with multiple check paths for param name, type, and toError\nfunction validateCatchClause(\n node: ts.CatchClause,\n sourceFile: ts.SourceFile,\n fileLines: string[],\n depth: number,\n disableAllowed: boolean,\n): CatchViolationInfo[] {\n const violations: CatchViolationInfo[] = [];\n const suffix = depth === 1 ? '' : String(depth);\n const expectedParam = 'err' + suffix;\n const expectedVar = 'error' + suffix;\n\n const catchLine = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;\n const catchContext = fileLines[catchLine - 1]?.trim() ?? '';\n const blockStart = node.block.getStart(sourceFile);\n const blockEnd = node.block.getEnd();\n const disabled = hasDisableComment(fileLines, catchLine) ||\n hasBlockLevelDisable(sourceFile.text, blockStart, blockEnd);\n\n const varDecl = node.variableDeclaration;\n if (!varDecl) {\n violations.push({\n line: catchLine, context: catchContext,\n message: `Catch clause must declare a parameter: catch (${expectedParam}: unknown)`,\n hasDisableComment: resolveDisable(disabled, disableAllowed),\n });\n return violations;\n }\n\n const actualParam = ts.isIdentifier(varDecl.name) ? varDecl.name.text : expectedParam;\n\n // Check parameter name\n if (ts.isIdentifier(varDecl.name) && varDecl.name.text !== expectedParam) {\n violations.push({\n line: catchLine, context: catchContext,\n message: `Catch parameter must be named \"${expectedParam}\" (or \"err2\", \"err3\" for nested), got \"${varDecl.name.text}\"`,\n hasDisableComment: resolveDisable(disabled, disableAllowed),\n });\n }\n\n // Check type annotation is : unknown\n if (!varDecl.type || varDecl.type.kind !== ts.SyntaxKind.UnknownKeyword) {\n violations.push({\n line: catchLine, context: catchContext,\n message: `Catch parameter must be typed as \"unknown\": catch (${actualParam}: unknown)`,\n hasDisableComment: resolveDisable(disabled, disableAllowed),\n });\n }\n\n // Check for commented-out ignore pattern\n if (hasIgnoreComment(sourceFile.text, blockStart, blockEnd, expectedVar, actualParam)) {\n return violations;\n }\n\n // Check first statement is const error = toError(err)\n if (node.block.statements.length === 0) {\n violations.push({\n line: catchLine, context: catchContext,\n message: `Catch block must call toError(${actualParam}) as first statement: const ${expectedVar} = toError(${actualParam});`,\n hasDisableComment: resolveDisable(disabled, disableAllowed),\n });\n return violations;\n }\n\n const firstStmt = node.block.statements[0];\n const toErrorViolation = validateToErrorStatement(firstStmt, sourceFile, fileLines, expectedParam, expectedVar, actualParam, disabled, disableAllowed);\n if (toErrorViolation) {\n violations.push(toErrorViolation);\n }\n\n return violations;\n}\n\nfunction resolveDisable(disabled: boolean, disableAllowed: boolean): boolean {\n if (!disableAllowed && disabled) {\n return false;\n }\n return disabled;\n}\n\n/**\n * Validate that the first statement is `const error = toError(err);`\n */\n// webpieces-disable max-lines-new-methods -- Deep AST check for variable declaration with toError call expression\nfunction validateToErrorStatement(\n stmt: ts.Statement,\n sourceFile: ts.SourceFile,\n fileLines: string[],\n expectedParam: string,\n expectedVar: string,\n actualParam: string,\n disabled: boolean,\n disableAllowed: boolean,\n): CatchViolationInfo | null {\n const stmtLine = sourceFile.getLineAndCharacterOfPosition(stmt.getStart(sourceFile)).line + 1;\n const stmtContext = fileLines[stmtLine - 1]?.trim() ?? '';\n\n if (!ts.isVariableStatement(stmt)) {\n return {\n line: stmtLine,\n message: `First statement in catch must be: const ${expectedVar} = toError(${actualParam});`,\n context: stmtContext,\n hasDisableComment: resolveDisable(disabled, disableAllowed),\n };\n }\n\n const declarations = stmt.declarationList.declarations;\n if (declarations.length === 0) {\n return {\n line: stmtLine,\n message: `First statement in catch must be: const ${expectedVar} = toError(${actualParam});`,\n context: stmtContext,\n hasDisableComment: resolveDisable(disabled, disableAllowed),\n };\n }\n\n const decl = declarations[0];\n\n // Check variable name\n if (ts.isIdentifier(decl.name) && decl.name.text !== expectedVar) {\n return {\n line: stmtLine,\n message: `Error variable must be named \"${expectedVar}\", got \"${decl.name.text}\"`,\n context: stmtContext,\n hasDisableComment: resolveDisable(disabled, disableAllowed),\n };\n }\n\n // Check initializer is toError(actualParam)\n const init = decl.initializer;\n if (!init || !ts.isCallExpression(init)) {\n return {\n line: stmtLine,\n message: `First statement in catch must be: const ${expectedVar} = toError(${actualParam});`,\n context: stmtContext,\n hasDisableComment: resolveDisable(disabled, disableAllowed),\n };\n }\n\n if (!ts.isIdentifier(init.expression) || init.expression.text !== 'toError') {\n return {\n line: stmtLine,\n message: `First statement in catch must call toError(), not \"${init.expression.getText(sourceFile)}\"`,\n context: stmtContext,\n hasDisableComment: resolveDisable(disabled, disableAllowed),\n };\n }\n\n // Check argument\n const args = init.arguments;\n if (args.length !== 1 || !ts.isIdentifier(args[0]) || args[0].text !== actualParam) {\n return {\n line: stmtLine,\n message: `toError() must be called with \"${actualParam}\"`,\n context: stmtContext,\n hasDisableComment: resolveDisable(disabled, disableAllowed),\n };\n }\n\n return null;\n}\n\n/**\n * Find all catch pattern violations in a file using AST.\n */\nfunction findCatchViolationsInFile(\n filePath: string,\n workspaceRoot: string,\n disableAllowed: boolean,\n): CatchViolationInfo[] {\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: CatchViolationInfo[] = [];\n let catchDepth = 0;\n\n function visit(node: ts.Node): void {\n if (ts.isCatchClause(node)) {\n catchDepth++;\n const clauseViolations = validateCatchClause(node, sourceFile, fileLines, catchDepth, disableAllowed);\n violations.push(...clauseViolations);\n ts.forEachChild(node, visit);\n catchDepth--;\n return;\n }\n ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return violations;\n}\n\n/**\n * NEW_AND_MODIFIED_CODE mode: Flag violations on changed lines.\n */\nfunction findViolationsForModifiedCode(\n workspaceRoot: string,\n changedFiles: string[],\n base: string,\n head: string | undefined,\n disableAllowed: boolean,\n): CatchViolation[] {\n const violations: CatchViolation[] = [];\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 = findCatchViolationsInFile(file, workspaceRoot, disableAllowed);\n\n for (const v of allViolations) {\n if (disableAllowed && v.hasDisableComment) continue;\n if (!changedLines.has(v.line)) continue;\n\n violations.push({ file, line: v.line, message: v.message, context: v.context });\n }\n }\n\n return violations;\n}\n\n/**\n * NEW_AND_MODIFIED_FILES mode: Flag ALL violations in modified files.\n */\nfunction findViolationsForModifiedFiles(\n workspaceRoot: string,\n changedFiles: string[],\n disableAllowed: boolean,\n): CatchViolation[] {\n const violations: CatchViolation[] = [];\n\n for (const file of changedFiles) {\n const allViolations = findCatchViolationsInFile(file, workspaceRoot, disableAllowed);\n\n for (const v of allViolations) {\n if (disableAllowed && v.hasDisableComment) continue;\n violations.push({ file, line: v.line, message: v.message, context: v.context });\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 pattern examples and escape hatch\nfunction reportViolations(violations: CatchViolation[], mode: ModifiedCodeMode, disableAllowed: boolean): void {\n console.error('');\n console.error('\\u274c Catch blocks must follow the standardized error handling pattern!');\n console.error('');\n console.error('\\ud83d\\udcda Required pattern:');\n console.error('');\n console.error(' catch (err: unknown) {');\n console.error(' const error = toError(err);');\n console.error(' // ... use error ...');\n console.error(' }');\n console.error('');\n console.error(' Or to explicitly ignore:');\n console.error(' catch (err: unknown) {');\n console.error(' //const error = toError(err);');\n console.error(' }');\n console.error('');\n console.error(' For nested catches: err2/error2, err3/error3, etc.');\n console.error('');\n\n for (const v of violations) {\n console.error(` \\u274c ${v.file}:${v.line}`);\n console.error(` ${v.message}`);\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 catch-error-pattern -- [your reason]');\n } else {\n console.error(' Escape hatch: DISABLED (disableAllowed: false)');\n console.error(' Disable comments are ignored. Fix the catch block directly.');\n }\n console.error('');\n console.error(` Current mode: ${mode}`);\n console.error('');\n}\n\nasync function runValidatorImpl(\n scan: ScanScope,\n options: CatchErrorPatternConfig,\n workspaceRoot: string\n): Promise<ExecutorResult> {\n const mode: ModifiedCodeMode = options.mode ?? 'OFF';\n const disableAllowed = options.disableAllowed ?? true;\n\n if (mode === 'OFF') {\n console.log('\\n\\u23ed\\ufe0f Skipping catch-error-pattern validation (mode: OFF)');\n console.log('');\n return { success: true };\n }\n\n console.log('\\n\\ud83d\\udccf Validating Catch Error Pattern\\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 catch-error-pattern 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 changedFiles = scan.files(workspaceRoot, mode, base, head);\n\n if (changedFiles.length === 0) {\n console.log('\\u2705 No TypeScript files changed');\n return { success: true };\n }\n\n console.log(`\\ud83d\\udcc2 Checking ${changedFiles.length} changed file(s)...`);\n\n let violations: CatchViolation[] = [];\n\n if (mode === 'NEW_AND_MODIFIED_CODE') {\n violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed);\n } else {\n // NEW_AND_MODIFIED_FILES and the whole-scope modes (#1027) all judge every site of every file.\n violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);\n }\n\n if (violations.length === 0) {\n console.log('\\u2705 No catch error pattern violations found');\n return { success: true };\n }\n\n scan.recordSites('catch-error-pattern', violations.map((v: CatchViolation) => v.file));\n reportViolations(violations, mode, disableAllowed);\n\n return { success: false };\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class CatchErrorPatternValidator extends CodeValidator<CatchErrorPatternConfig> {\n constructor(config: CatchErrorPatternConfig, private readonly scanScope: ScanScope) {\n super(config, 'catch-error-pattern', 'catch-error-pattern');\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runValidatorImpl(this.scanScope, this.config, workspaceRoot);\n }\n}\n"]}
1
+ {"version":3,"file":"validate-catch-error-pattern.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-catch-error-pattern.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,uDAAiC;AACjC,0DAAqG;AACrG,yDAAiE;AAEjE,qDAAiE;AACjE,yCAA2D;AAC3D,6CAAyC;AAgBzC;;;GAGG;AACH,SAAS,iBAAiB,CAAC,KAAe,EAAE,UAAkB;IAC1D,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,UAAU,GAAG,CAAC,CAAC,CAAC;IAC/C,KAAK,IAAI,CAAC,GAAG,UAAU,GAAG,CAAC,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,EAAE,EAAE,CAAC;QAChD,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;QACpC,IAAI,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;YAClF,MAAM;QACV,CAAC;QACD,IAAI,IAAA,yBAAU,EAAC,IAAI,EAAE,qBAAqB,CAAC,EAAE,CAAC;YAC1C,OAAO,IAAI,CAAC;QAChB,CAAC;QACD,IAAI,IAAI,CAAC,QAAQ,CAAC,gCAAgC,CAAC,EAAE,CAAC;YAClD,OAAO,IAAI,CAAC;QAChB,CAAC;IACL,CAAC;IACD,OAAO,KAAK,CAAC;AACjB,CAAC;AAED;;GAEG;AACH,SAAS,oBAAoB,CAAC,UAAkB,EAAE,UAAkB,EAAE,QAAgB;IAClF,MAAM,SAAS,GAAG,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C;QAC9D,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7B,CAAC;IAED,IAAI,CAAC,WAAW,CAAC,qBAAqB,EAAE,UAAU,CAAC,GAAG,CAAC,CAAC,CAAiB,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;IACvF,gBAAgB,CAAC,UAAU,EAAE,IAAI,EAAE,cAAc,CAAC,CAAC;IAEnD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC9B,CAAC;AAGM,IAAM,0BAA0B,GAAhC,MAAM,0BAA2B,SAAQ,8BAAsC;IACpB;IAA9D,YAAY,MAA+B,EAAmB,SAAoB;QAC9E,KAAK,CAAC,MAAM,EAAE,qBAAqB,EAAE,qBAAqB,CAAC,CAAC;QADF,cAAS,GAAT,SAAS,CAAW;IAElF,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,aAAqB;QAC3B,OAAO,gBAAgB,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IACxE,CAAC;CACJ,CAAA;AARY,gEAA0B;qCAA1B,0BAA0B;IADtC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEjB,sCAAuB,EAA8B,sBAAS;GADzE,0BAA0B,CAQtC","sourcesContent":["/**\n * Validate Catch Error Pattern Executor\n *\n * Validates that catch blocks follow the standardized error handling pattern.\n * Uses TypeScript AST for detection and LINE-BASED git diff filtering.\n *\n * ============================================================================\n * REQUIRED PATTERN\n * ============================================================================\n *\n * Standard: catch (err: unknown) { const error = toError(err); ... }\n * Ignored: catch (err: unknown) { //const error = toError(err); ... }\n * Nested: catch (err2: unknown) { const error2 = toError(err2); ... }\n *\n * ============================================================================\n * VIOLATIONS (BAD) - These patterns are flagged:\n * ============================================================================\n *\n * - catch (e) { ... } — wrong parameter name\n * - catch (err) { ... } — missing : unknown type annotation\n * - catch (err: unknown) { ... } — missing toError() as first statement\n * - catch (err: unknown) { const x = toError(err); } — wrong variable name\n *\n * ============================================================================\n * MODES (LINE-BASED)\n * ============================================================================\n * - OFF: Skip validation entirely\n * - NEW_AND_MODIFIED_CODE: Flag catch violations on changed lines (lines in diff hunks)\n * - NEW_AND_MODIFIED_FILES: Flag ALL catch violations in files that were modified\n *\n * ============================================================================\n * ESCAPE HATCH\n * ============================================================================\n * Add comment above the violation:\n * // webpieces-disable catch-error-pattern -- [your justification]\n * } catch (err: unknown) {\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as ts from 'typescript';\nimport { hasDisable, detectBase, getFileDiff, getChangedLineNumbers } from \"@webpieces/rules-config\";\nimport { CatchErrorPatternConfig } from \"./configs/rule-configs\";\nimport { ModifiedCodeMode } from '@webpieces/rules-sdk';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { ScanScope } from './scan-scope';\n\ninterface CatchViolation {\n file: string;\n line: number;\n message: string;\n context: string;\n}\n\ninterface CatchViolationInfo {\n line: number;\n message: string;\n context: string;\n hasDisableComment: boolean;\n}\n\n/**\n * Check if a line contains a disable comment for catch-error-pattern.\n * Recognizes both webpieces-disable and eslint-disable-next-line @webpieces/ formats.\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 (hasDisable(line, \"catch-error-pattern\")) {\n return true;\n }\n if (line.includes('@webpieces/catch-error-pattern')) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Check if the catch block contains a disable comment for catch-error-pattern.\n */\nfunction hasBlockLevelDisable(sourceText: string, blockStart: number, blockEnd: number): boolean {\n const blockText = sourceText.substring(blockStart, blockEnd);\n return hasDisable(blockText, \"catch-error-pattern\") ||\n blockText.includes('@webpieces/catch-error-pattern');\n}\n\n/**\n * Check if the catch block body text contains the commented-out ignore pattern.\n */\nfunction hasIgnoreComment(\n sourceText: string,\n blockStart: number,\n blockEnd: number,\n expectedVarName: string,\n actualParamName: string,\n): boolean {\n const blockText = sourceText.substring(blockStart, blockEnd);\n const ignorePattern = new RegExp(\n `//\\\\s*const\\\\s+${expectedVarName}\\\\s*=\\\\s*toError\\\\(${actualParamName}\\\\)`,\n );\n return ignorePattern.test(blockText);\n}\n\n/**\n * Validate a single CatchClause node.\n */\n// webpieces-disable max-lines-new-methods -- AST validation with multiple check paths for param name, type, and toError\nfunction validateCatchClause(\n node: ts.CatchClause,\n sourceFile: ts.SourceFile,\n fileLines: string[],\n depth: number,\n disableAllowed: boolean,\n): CatchViolationInfo[] {\n const violations: CatchViolationInfo[] = [];\n const suffix = depth === 1 ? '' : String(depth);\n const expectedParam = 'err' + suffix;\n const expectedVar = 'error' + suffix;\n\n const catchLine = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;\n const catchContext = fileLines[catchLine - 1]?.trim() ?? '';\n const blockStart = node.block.getStart(sourceFile);\n const blockEnd = node.block.getEnd();\n const disabled = hasDisableComment(fileLines, catchLine) ||\n hasBlockLevelDisable(sourceFile.text, blockStart, blockEnd);\n\n const varDecl = node.variableDeclaration;\n if (!varDecl) {\n violations.push({\n line: catchLine, context: catchContext,\n message: `Catch clause must declare a parameter: catch (${expectedParam}: unknown)`,\n hasDisableComment: resolveDisable(disabled, disableAllowed),\n });\n return violations;\n }\n\n const actualParam = ts.isIdentifier(varDecl.name) ? varDecl.name.text : expectedParam;\n\n // Check parameter name\n if (ts.isIdentifier(varDecl.name) && varDecl.name.text !== expectedParam) {\n violations.push({\n line: catchLine, context: catchContext,\n message: `Catch parameter must be named \"${expectedParam}\" (or \"err2\", \"err3\" for nested), got \"${varDecl.name.text}\"`,\n hasDisableComment: resolveDisable(disabled, disableAllowed),\n });\n }\n\n // Check type annotation is : unknown\n if (!varDecl.type || varDecl.type.kind !== ts.SyntaxKind.UnknownKeyword) {\n violations.push({\n line: catchLine, context: catchContext,\n message: `Catch parameter must be typed as \"unknown\": catch (${actualParam}: unknown)`,\n hasDisableComment: resolveDisable(disabled, disableAllowed),\n });\n }\n\n // Check for commented-out ignore pattern\n if (hasIgnoreComment(sourceFile.text, blockStart, blockEnd, expectedVar, actualParam)) {\n return violations;\n }\n\n // Check first statement is const error = toError(err)\n if (node.block.statements.length === 0) {\n violations.push({\n line: catchLine, context: catchContext,\n message: `Catch block must call toError(${actualParam}) as first statement: const ${expectedVar} = toError(${actualParam});`,\n hasDisableComment: resolveDisable(disabled, disableAllowed),\n });\n return violations;\n }\n\n const firstStmt = node.block.statements[0];\n const toErrorViolation = validateToErrorStatement(firstStmt, sourceFile, fileLines, expectedParam, expectedVar, actualParam, disabled, disableAllowed);\n if (toErrorViolation) {\n violations.push(toErrorViolation);\n }\n\n return violations;\n}\n\nfunction resolveDisable(disabled: boolean, disableAllowed: boolean): boolean {\n if (!disableAllowed && disabled) {\n return false;\n }\n return disabled;\n}\n\n/**\n * Validate that the first statement is `const error = toError(err);`\n */\n// webpieces-disable max-lines-new-methods -- Deep AST check for variable declaration with toError call expression\nfunction validateToErrorStatement(\n stmt: ts.Statement,\n sourceFile: ts.SourceFile,\n fileLines: string[],\n expectedParam: string,\n expectedVar: string,\n actualParam: string,\n disabled: boolean,\n disableAllowed: boolean,\n): CatchViolationInfo | null {\n const stmtLine = sourceFile.getLineAndCharacterOfPosition(stmt.getStart(sourceFile)).line + 1;\n const stmtContext = fileLines[stmtLine - 1]?.trim() ?? '';\n\n if (!ts.isVariableStatement(stmt)) {\n return {\n line: stmtLine,\n message: `First statement in catch must be: const ${expectedVar} = toError(${actualParam});`,\n context: stmtContext,\n hasDisableComment: resolveDisable(disabled, disableAllowed),\n };\n }\n\n const declarations = stmt.declarationList.declarations;\n if (declarations.length === 0) {\n return {\n line: stmtLine,\n message: `First statement in catch must be: const ${expectedVar} = toError(${actualParam});`,\n context: stmtContext,\n hasDisableComment: resolveDisable(disabled, disableAllowed),\n };\n }\n\n const decl = declarations[0];\n\n // Check variable name\n if (ts.isIdentifier(decl.name) && decl.name.text !== expectedVar) {\n return {\n line: stmtLine,\n message: `Error variable must be named \"${expectedVar}\", got \"${decl.name.text}\"`,\n context: stmtContext,\n hasDisableComment: resolveDisable(disabled, disableAllowed),\n };\n }\n\n // Check initializer is toError(actualParam)\n const init = decl.initializer;\n if (!init || !ts.isCallExpression(init)) {\n return {\n line: stmtLine,\n message: `First statement in catch must be: const ${expectedVar} = toError(${actualParam});`,\n context: stmtContext,\n hasDisableComment: resolveDisable(disabled, disableAllowed),\n };\n }\n\n if (!ts.isIdentifier(init.expression) || init.expression.text !== 'toError') {\n return {\n line: stmtLine,\n message: `First statement in catch must call toError(), not \"${init.expression.getText(sourceFile)}\"`,\n context: stmtContext,\n hasDisableComment: resolveDisable(disabled, disableAllowed),\n };\n }\n\n // Check argument\n const args = init.arguments;\n if (args.length !== 1 || !ts.isIdentifier(args[0]) || args[0].text !== actualParam) {\n return {\n line: stmtLine,\n message: `toError() must be called with \"${actualParam}\"`,\n context: stmtContext,\n hasDisableComment: resolveDisable(disabled, disableAllowed),\n };\n }\n\n return null;\n}\n\n/**\n * Find all catch pattern violations in a file using AST.\n */\nfunction findCatchViolationsInFile(\n filePath: string,\n workspaceRoot: string,\n disableAllowed: boolean,\n): CatchViolationInfo[] {\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: CatchViolationInfo[] = [];\n let catchDepth = 0;\n\n function visit(node: ts.Node): void {\n if (ts.isCatchClause(node)) {\n catchDepth++;\n const clauseViolations = validateCatchClause(node, sourceFile, fileLines, catchDepth, disableAllowed);\n violations.push(...clauseViolations);\n ts.forEachChild(node, visit);\n catchDepth--;\n return;\n }\n ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return violations;\n}\n\n/**\n * NEW_AND_MODIFIED_CODE mode: Flag violations on changed lines.\n */\n// webpieces-disable no-function-outside-class -- pre-existing module helper, made async only because DiffScope now reaches git through the injected process edge (#1381)\nasync function findViolationsForModifiedCode(\n workspaceRoot: string,\n changedFiles: string[],\n base: string,\n head: string | undefined,\n disableAllowed: boolean,\n): Promise<CatchViolation[]> {\n const violations: CatchViolation[] = [];\n\n for (const file of changedFiles) {\n const diff = await getFileDiff(workspaceRoot, file, base, head);\n const changedLines = getChangedLineNumbers(diff);\n\n if (changedLines.size === 0) continue;\n\n const allViolations = findCatchViolationsInFile(file, workspaceRoot, disableAllowed);\n\n for (const v of allViolations) {\n if (disableAllowed && v.hasDisableComment) continue;\n if (!changedLines.has(v.line)) continue;\n\n violations.push({ file, line: v.line, message: v.message, context: v.context });\n }\n }\n\n return violations;\n}\n\n/**\n * NEW_AND_MODIFIED_FILES mode: Flag ALL violations in modified files.\n */\nfunction findViolationsForModifiedFiles(\n workspaceRoot: string,\n changedFiles: string[],\n disableAllowed: boolean,\n): CatchViolation[] {\n const violations: CatchViolation[] = [];\n\n for (const file of changedFiles) {\n const allViolations = findCatchViolationsInFile(file, workspaceRoot, disableAllowed);\n\n for (const v of allViolations) {\n if (disableAllowed && v.hasDisableComment) continue;\n violations.push({ file, line: v.line, message: v.message, context: v.context });\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 pattern examples and escape hatch\nfunction reportViolations(violations: CatchViolation[], mode: ModifiedCodeMode, disableAllowed: boolean): void {\n console.error('');\n console.error('\\u274c Catch blocks must follow the standardized error handling pattern!');\n console.error('');\n console.error('\\ud83d\\udcda Required pattern:');\n console.error('');\n console.error(' catch (err: unknown) {');\n console.error(' const error = toError(err);');\n console.error(' // ... use error ...');\n console.error(' }');\n console.error('');\n console.error(' Or to explicitly ignore:');\n console.error(' catch (err: unknown) {');\n console.error(' //const error = toError(err);');\n console.error(' }');\n console.error('');\n console.error(' For nested catches: err2/error2, err3/error3, etc.');\n console.error('');\n\n for (const v of violations) {\n console.error(` \\u274c ${v.file}:${v.line}`);\n console.error(` ${v.message}`);\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 catch-error-pattern -- [your reason]');\n } else {\n console.error(' Escape hatch: DISABLED (disableAllowed: false)');\n console.error(' Disable comments are ignored. Fix the catch block directly.');\n }\n console.error('');\n console.error(` Current mode: ${mode}`);\n console.error('');\n}\n\nasync function runValidatorImpl(\n scan: ScanScope,\n options: CatchErrorPatternConfig,\n workspaceRoot: string\n): Promise<ExecutorResult> {\n const mode: ModifiedCodeMode = options.mode ?? 'OFF';\n const disableAllowed = options.disableAllowed ?? true;\n\n if (mode === 'OFF') {\n console.log('\\n\\u23ed\\ufe0f Skipping catch-error-pattern validation (mode: OFF)');\n console.log('');\n return { success: true };\n }\n\n console.log('\\n\\ud83d\\udccf Validating Catch Error Pattern\\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 = await detectBase(workspaceRoot) ?? undefined;\n\n if (!base) {\n console.log('\\n\\u23ed\\ufe0f Skipping catch-error-pattern 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 changedFiles = await scan.files(workspaceRoot, mode, base, head);\n\n if (changedFiles.length === 0) {\n console.log('\\u2705 No TypeScript files changed');\n return { success: true };\n }\n\n console.log(`\\ud83d\\udcc2 Checking ${changedFiles.length} changed file(s)...`);\n\n let violations: CatchViolation[] = [];\n\n if (mode === 'NEW_AND_MODIFIED_CODE') {\n violations = await findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed);\n } else {\n // NEW_AND_MODIFIED_FILES and the whole-scope modes (#1027) all judge every site of every file.\n violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);\n }\n\n if (violations.length === 0) {\n console.log('\\u2705 No catch error pattern violations found');\n return { success: true };\n }\n\n scan.recordSites('catch-error-pattern', violations.map((v: CatchViolation) => v.file));\n reportViolations(violations, mode, disableAllowed);\n\n return { success: false };\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class CatchErrorPatternValidator extends CodeValidator<CatchErrorPatternConfig> {\n constructor(config: CatchErrorPatternConfig, private readonly scanScope: ScanScope) {\n super(config, 'catch-error-pattern', 'catch-error-pattern');\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runValidatorImpl(this.scanScope, this.config, workspaceRoot);\n }\n}\n"]}
@@ -45,18 +45,18 @@ let CatchMustPropagateValidator = class CatchMustPropagateValidator extends code
45
45
  const mode = this.config.mode;
46
46
  if (mode === undefined || mode === 'OFF')
47
47
  return { success: true };
48
- const range = this.diffScope.resolveBase(workspaceRoot);
48
+ const range = await this.diffScope.resolveBase(workspaceRoot);
49
49
  if (range.base === undefined) {
50
50
  console.log(`\n⏭️ Skipping ${this.name} validation (could not detect base branch)\n`);
51
51
  return { success: true };
52
52
  }
53
53
  const analyzer = new catch_propagation_1.CatchPropagationAnalyzer(this.forwards());
54
54
  const found = [];
55
- for (const relFile of this.scanScope.files(workspaceRoot, mode, range.base, range.head)) {
55
+ for (const relFile of await this.scanScope.files(workspaceRoot, mode, range.base, range.head)) {
56
56
  if (!analyzer.judges(relFile) || !fs.existsSync(path.join(workspaceRoot, relFile)))
57
57
  continue;
58
58
  const changed = this.scanScope.isLineScoped(mode)
59
- ? this.diffScope.getChangedLineNumbers(this.diffScope.getFileDiff(workspaceRoot, relFile, range.base, range.head))
59
+ ? this.diffScope.getChangedLineNumbers(await this.diffScope.getFileDiff(workspaceRoot, relFile, range.base, range.head))
60
60
  : undefined;
61
61
  if (changed !== undefined && changed.size === 0)
62
62
  continue;
@@ -1 +1 @@
1
- {"version":3,"file":"validate-catch-must-propagate.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-catch-must-propagate.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;GAUG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,uDAAiC;AACjC,0DAA2E;AAE3E,8DAA0D;AAC1D,mFAOqD;AACrD,yCAA2D;AAC3D,uFAAiF;AACjF,qDAAiE;AACjE,6CAAyC;AAEzC,mEAAmE;AACnE,MAAa,mBAAmB;IAEf;IACA;IAFb,YACa,OAAe,EACf,OAAqB;QADrB,YAAO,GAAP,OAAO,CAAQ;QACf,YAAO,GAAP,OAAO,CAAc;IAC/B,CAAC;CACP;AALD,kDAKC;AAGM,IAAM,2BAA2B,GAAjC,MAAM,2BAA4B,SAAQ,8BAAuC;IAG/D;IACA;IAHrB,YACI,MAAgC,EACf,SAAoB,EACpB,SAAoB;QAErC,KAAK,CAAC,MAAM,EAAE,wCAAoB,EAAE,wCAAoB,CAAC,CAAC;QAHzC,cAAS,GAAT,SAAS,CAAW;QACpB,cAAS,GAAT,SAAS,CAAW;IAGzC,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,aAAqB;QAC3B,MAAM,IAAI,GAAiC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC;QAC5D,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,KAAK,KAAK;YAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;QACnE,MAAM,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,aAAa,CAAC,CAAC;QACxD,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YAC3B,OAAO,CAAC,GAAG,CAAC,kBAAkB,IAAI,CAAC,IAAI,8CAA8C,CAAC,CAAC;YACvF,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;QAC7B,CAAC;QACD,MAAM,QAAQ,GAAG,IAAI,4CAAwB,CAAC,IAAI,CAAC,QAAQ,E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AAI,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC,CAC7F,CAAC;IACN,CAAC;CACJ,CAAA;AAjEY,kEAA2B;sCAA3B,2BAA2B;IADvC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGzB,sDAAwB;QACJ,wBAAS;QACT,sBAAS;GAJhC,2BAA2B,CAiEvC","sourcesContent":["/**\n * `catch-must-propagate` at the build gate (#1313) — the backstop for repos that do not run the guard\n * hooks. It calls the SAME syntax-only `CatchPropagationAnalyzer` the Write/Edit guard calls, on the same\n * whole-file parse, so both runners report the same catches at the same lines (pinned by the conformance\n * spec in `@webpieces/webpieces-tooling`).\n *\n * Scoping follows the ApiLibSourceRule shape: NEW_AND_MODIFIED_CODE judges only a catch whose clause spans\n * a changed line (existing catches are grandfathered until someone touches them), NEW_AND_MODIFIED_FILES\n * every catch in a changed file, and the whole-scope modes (#1027) every catch of a touched project / the\n * repo. A failure is ONE thrown `RuleFailError` with one `Option` per site, which `RuleReporter` renders.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as ts from 'typescript';\nimport { DiffScope, Option, RuleFailError } from '@webpieces/rules-config';\nimport { ModifiedCodeMode } from '@webpieces/rules-sdk';\nimport { InformAiError } from '@webpieces/tooling-common';\nimport {\n CATCH_MUST_PROPAGATE,\n CATCH_MUST_PROPAGATE_CURES,\n CATCH_MUST_PROPAGATE_DISABLE,\n CatchCure,\n CatchFinding,\n CatchPropagationAnalyzer,\n} from '@webpieces/tooling-common/catch-propagation';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { CatchMustPropagateConfig } from './configs/catch-must-propagate-config';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { ScanScope } from './scan-scope';\n\n/** A finding located in its workspace-relative file. Data-only. */\nexport class LocatedCatchFinding {\n constructor(\n readonly relFile: string,\n readonly finding: CatchFinding,\n ) {}\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class CatchMustPropagateValidator extends CodeValidator<CatchMustPropagateConfig> {\n constructor(\n config: CatchMustPropagateConfig,\n private readonly diffScope: DiffScope,\n private readonly scanScope: ScanScope,\n ) {\n super(config, CATCH_MUST_PROPAGATE, CATCH_MUST_PROPAGATE);\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n const mode: ModifiedCodeMode | undefined = this.config.mode;\n if (mode === undefined || mode === 'OFF') return { success: true };\n const range = this.diffScope.resolveBase(workspaceRoot);\n if (range.base === undefined) {\n console.log(`\\n⏭️ Skipping ${this.name} validation (could not detect base branch)\\n`);\n return { success: true };\n }\n const analyzer = new CatchPropagationAnalyzer(this.forwards());\n const found: LocatedCatchFinding[] = [];\n for (const relFile of this.scanScope.files(workspaceRoot, mode, range.base, range.head)) {\n if (!analyzer.judges(relFile) || !fs.existsSync(path.join(workspaceRoot, relFile))) continue;\n const changed = this.scanScope.isLineScoped(mode)\n ? this.diffScope.getChangedLineNumbers(this.diffScope.getFileDiff(workspaceRoot, relFile, range.base, range.head))\n : undefined;\n if (changed !== undefined && changed.size === 0) continue;\n for (const finding of this.judge(analyzer, workspaceRoot, relFile, changed)) {\n found.push(new LocatedCatchFinding(relFile, finding));\n }\n }\n if (found.length === 0) return { success: true };\n this.scanScope.recordSites(this.name, found.map((each: LocatedCatchFinding) => each.relFile));\n throw this.failure(found);\n }\n\n /** One file's findings: the whole text parsed, exactly as the guard parses the proposed file. */\n judge(analyzer: CatchPropagationAnalyzer, workspaceRoot: string, relFile: string, changed?: ReadonlySet<number>): CatchFinding[] {\n const absFile = path.join(workspaceRoot, relFile);\n const source = ts.createSourceFile(absFile, fs.readFileSync(absFile, 'utf8'), ts.ScriptTarget.Latest, true);\n return analyzer.analyze(source, changed);\n }\n\n /** Required by the owner schema; the loader refuses a config without it, so its absence is plumbing. */\n private forwards(): readonly string[] {\n const forwards = this.config.forwards;\n if (forwards === undefined) {\n throw new InformAiError(`${CATCH_MUST_PROPAGATE} has no \"forwards\" list. Add the required \"forwards\" array to its config entry.`);\n }\n return forwards;\n }\n\n private failure(found: readonly LocatedCatchFinding[]): RuleFailError {\n const message =\n `${found.length} catch(es) let the caught error go — its stack, type and cause chain are lost for good, ` +\n `and a later refusal built from its text says nothing of WHY:\\n` +\n found.map((each: LocatedCatchFinding) =>\n ` ${each.relFile}:${each.finding.line} — ${each.finding.message}\\n ${each.finding.snippet}`).join('\\n') +\n `\\n Last resort, per site: ${CATCH_MUST_PROPAGATE_DISABLE}`;\n return new RuleFailError(\n this.name,\n message,\n undefined,\n undefined,\n CATCH_MUST_PROPAGATE_CURES.map((cure: CatchCure) => new Option(cure.text, cure.preferred)),\n );\n }\n}\n"]}
1
+ {"version":3,"file":"validate-catch-must-propagate.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-catch-must-propagate.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;GAUG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,uDAAiC;AACjC,0DAA2E;AAE3E,8DAA0D;AAC1D,mFAOqD;AACrD,yCAA2D;AAC3D,uFAAiF;AACjF,qDAAiE;AACjE,6CAAyC;AAEzC,mEAAmE;AACnE,MAAa,mBAAmB;IAEf;IACA;IAFb,YACa,OAAe,EACf,OAAqB;QADrB,YAAO,GAAP,OAAO,CAAQ;QACf,YAAO,GAAP,OAAO,CAAc;IAC/B,CAAC;CACP;AALD,kDAKC;AAGM,IAAM,2BAA2B,GAAjC,MAAM,2BAA4B,SAAQ,8BAAuC;IAG/D;IACA;IAHrB,YACI,MAAgC,EACf,SAAoB,EACpB,SAAoB;QAErC,KAAK,CAAC,MAAM,EAAE,wCAAoB,EAAE,wCAAoB,CAAC,CAAC;QAHzC,cAAS,GAAT,SAAS,CAAW;QACpB,cAAS,GAAT,SAAS,CAAW;IAGzC,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,aAAqB;QAC3B,MAAM,IAAI,GAAiC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC;QAC5D,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,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,CAAC,IAAyB,EAAE,EAAE,CACpC,KAAK,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,MAAM,IAAI,CAAC,OAAO,CAAC,OAAO,WAAW,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;YACjH,8BAA8B,gDAA4B,EAAE,CAAC;QACjE,OAAO,IAAI,4BAAa,CACpB,IAAI,CAAC,IAAI,EACT,OAAO,EACP,SAAS,EACT,SAAS,EACT,8CAA0B,CAAC,GAAG,CAAC,CAAC,IAAe,EAAE,EAAE,CAAC,IAAI,qBAAM,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC,CAC7F,CAAC;IACN,CAAC;CACJ,CAAA;AAjEY,kEAA2B;sCAA3B,2BAA2B;IADvC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGzB,sDAAwB;QACJ,wBAAS;QACT,sBAAS;GAJhC,2BAA2B,CAiEvC","sourcesContent":["/**\n * `catch-must-propagate` at the build gate (#1313) — the backstop for repos that do not run the guard\n * hooks. It calls the SAME syntax-only `CatchPropagationAnalyzer` the Write/Edit guard calls, on the same\n * whole-file parse, so both runners report the same catches at the same lines (pinned by the conformance\n * spec in `@webpieces/webpieces-tooling`).\n *\n * Scoping follows the ApiLibSourceRule shape: NEW_AND_MODIFIED_CODE judges only a catch whose clause spans\n * a changed line (existing catches are grandfathered until someone touches them), NEW_AND_MODIFIED_FILES\n * every catch in a changed file, and the whole-scope modes (#1027) every catch of a touched project / the\n * repo. A failure is ONE thrown `RuleFailError` with one `Option` per site, which `RuleReporter` renders.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as ts from 'typescript';\nimport { DiffScope, Option, RuleFailError } from '@webpieces/rules-config';\nimport { ModifiedCodeMode } from '@webpieces/rules-sdk';\nimport { InformAiError } from '@webpieces/tooling-common';\nimport {\n CATCH_MUST_PROPAGATE,\n CATCH_MUST_PROPAGATE_CURES,\n CATCH_MUST_PROPAGATE_DISABLE,\n CatchCure,\n CatchFinding,\n CatchPropagationAnalyzer,\n} from '@webpieces/tooling-common/catch-propagation';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { CatchMustPropagateConfig } from './configs/catch-must-propagate-config';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { ScanScope } from './scan-scope';\n\n/** A finding located in its workspace-relative file. Data-only. */\nexport class LocatedCatchFinding {\n constructor(\n readonly relFile: string,\n readonly finding: CatchFinding,\n ) {}\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class CatchMustPropagateValidator extends CodeValidator<CatchMustPropagateConfig> {\n constructor(\n config: CatchMustPropagateConfig,\n private readonly diffScope: DiffScope,\n private readonly scanScope: ScanScope,\n ) {\n super(config, CATCH_MUST_PROPAGATE, CATCH_MUST_PROPAGATE);\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n const mode: ModifiedCodeMode | undefined = this.config.mode;\n if (mode === undefined || mode === 'OFF') return { success: true };\n const range = await this.diffScope.resolveBase(workspaceRoot);\n if (range.base === undefined) {\n console.log(`\\n⏭️ Skipping ${this.name} validation (could not detect base branch)\\n`);\n return { success: true };\n }\n const analyzer = new CatchPropagationAnalyzer(this.forwards());\n const found: LocatedCatchFinding[] = [];\n for (const relFile of await this.scanScope.files(workspaceRoot, mode, range.base, range.head)) {\n if (!analyzer.judges(relFile) || !fs.existsSync(path.join(workspaceRoot, relFile))) continue;\n const changed = this.scanScope.isLineScoped(mode)\n ? this.diffScope.getChangedLineNumbers(await this.diffScope.getFileDiff(workspaceRoot, relFile, range.base, range.head))\n : undefined;\n if (changed !== undefined && changed.size === 0) continue;\n for (const finding of this.judge(analyzer, workspaceRoot, relFile, changed)) {\n found.push(new LocatedCatchFinding(relFile, finding));\n }\n }\n if (found.length === 0) return { success: true };\n this.scanScope.recordSites(this.name, found.map((each: LocatedCatchFinding) => each.relFile));\n throw this.failure(found);\n }\n\n /** One file's findings: the whole text parsed, exactly as the guard parses the proposed file. */\n judge(analyzer: CatchPropagationAnalyzer, workspaceRoot: string, relFile: string, changed?: ReadonlySet<number>): CatchFinding[] {\n const absFile = path.join(workspaceRoot, relFile);\n const source = ts.createSourceFile(absFile, fs.readFileSync(absFile, 'utf8'), ts.ScriptTarget.Latest, true);\n return analyzer.analyze(source, changed);\n }\n\n /** Required by the owner schema; the loader refuses a config without it, so its absence is plumbing. */\n private forwards(): readonly string[] {\n const forwards = this.config.forwards;\n if (forwards === undefined) {\n throw new InformAiError(`${CATCH_MUST_PROPAGATE} has no \"forwards\" list. Add the required \"forwards\" array to its config entry.`);\n }\n return forwards;\n }\n\n private failure(found: readonly LocatedCatchFinding[]): RuleFailError {\n const message =\n `${found.length} catch(es) let the caught error go — its stack, type and cause chain are lost for good, ` +\n `and a later refusal built from its text says nothing of WHY:\\n` +\n found.map((each: LocatedCatchFinding) =>\n ` ${each.relFile}:${each.finding.line} — ${each.finding.message}\\n ${each.finding.snippet}`).join('\\n') +\n `\\n Last resort, per site: ${CATCH_MUST_PROPAGATE_DISABLE}`;\n return new RuleFailError(\n this.name,\n message,\n undefined,\n undefined,\n CATCH_MUST_PROPAGATE_CURES.map((cure: CatchCure) => new Option(cure.text, cure.preferred)),\n );\n }\n}\n"]}