@webpieces/code-rules 0.4.976 → 0.4.978

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
@@ -1 +1 @@
1
- {"version":3,"file":"validate-framework-tsconfig.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-framework-tsconfig.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAkGH,wDAiBC;;AAjH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AAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;QAC7C,MAAM,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,YAAY,IAAI,EAAE,CAAC;QAC/C,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO;aACxB,QAAQ,CAAC,aAAa,EAAE,IAAI,EAAE,oBAAoB,CAAC;aACnD,MAAM,CAAC,CAAC,CAAiB,EAAE,EAAE,CAAC,CAAC,IAAA,6BAAc,EAAC,CAAC,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;QACpE,MAAM,UAAU,GAAG,IAAI,sBAAsB,EAAE,CAAC,KAAK,CAAC,aAAa,EAAE,QAAQ,CAAC,CAAC;QAC/E,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;QACtD,MAAM,sBAAsB,CAAC,UAAU,CAAC,CAAC;IAC7C,CAAC;CACJ,CAAA;AAnBY,gEAA0B;qCAA1B,0BAA0B;IADtC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGzB,2CAAuB;QACL,yCAAkB;GAHvC,0BAA0B,CAmBtC","sourcesContent":["/**\n * `framework-tsconfig` (#1064, D7) — the COMPILER enforces the runtime a library's `framework:` tags\n * promise.\n *\n * A tag used to be a promise only the dependency graph checked: nothing stopped a `browser+node`\n * library from importing `fs` or reading `window`. The cure is not a lint rule that greps for `window`;\n * it is the compiler, which already refuses a global its `lib` / `types` do not declare. So this rule\n * checks the one file that decides what compiles — the library's `tsconfig.lib.json`, with everything\n * it `extends` — against its tags:\n *\n * | tags | `lib` | `types` | effect |\n * |-----------------------------------------|---------------------|----------------|----------------------------------------------|\n * | browser only (browser / angular / react) | includes `dom` | no `node` | `fs`, `process`, `__dirname`, `Buffer` fail |\n * | node only (node / express) | no `dom` | includes `node`| `window`, `document`, `localStorage` fail |\n * | anything else — universal (browser + node + react-native), browser + react-native, react-native | no `dom` | no `node` | pure TypeScript |\n *\n * An unset `lib` resolves to TypeScript's default for the target, which INCLUDES `dom`; an unset\n * `types` loads every installed `@types/*`, which includes `node`. So a library whose runtime excludes\n * either must STATE both. Only `tsconfig.lib.json` is read — an app's own tsconfig (react-native types,\n * a server's) is the app's business.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as ts from 'typescript';\nimport { matchesAnyGlob, Option, RuleFailError } from \"@webpieces/rules-config\";\nimport { FrameworkTsconfigConfig } from \"./configs/tag-truth-configs\";\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { ProjectScanTargets, ScannedProject } from './project-scan-targets';\n\nconst LIB_TSCONFIG = 'tsconfig.lib.json';\n\n/** Envs whose every global is a browser's. */\nconst DOM_ENVS: readonly string[] = ['browser', 'angular', 'react'];\n/** Envs whose every global is node's. */\nconst NODE_ENVS: readonly string[] = ['node', 'express'];\n\n/** What a library's tsconfig must resolve to, given its framework set. Data-only. */\nexport class RuntimeCompilerOptions {\n constructor(\n /** `browser-only` | `node-only` | `pure` — which row of the table governs. */\n readonly row: string,\n readonly wantsDom: boolean,\n readonly wantsNodeTypes: boolean,\n /** The `compilerOptions` to paste. */\n readonly snippet: string,\n ) {}\n\n // webpieces-disable no-function-outside-class -- static factory of this class\n static forFrameworks(frameworks: readonly string[]): RuntimeCompilerOptions {\n if (frameworks.every((env: string) => DOM_ENVS.includes(env))) {\n return new RuntimeCompilerOptions('browser-only', true, false, '\"lib\": [\"es2022\", \"dom\"], \"types\": []');\n }\n if (frameworks.every((env: string) => NODE_ENVS.includes(env))) {\n return new RuntimeCompilerOptions('node-only', false, true, '\"lib\": [\"es2022\"], \"types\": [\"node\"]');\n }\n return new RuntimeCompilerOptions('pure', false, false, '\"lib\": [\"es2022\"], \"types\": []');\n }\n}\n\n/** ONE library whose tsconfig lets code compile that its runtime cannot run. Data-only. */\nexport class TsconfigRuntimeViolation {\n constructor(\n readonly project: string,\n /** Repo-relative path of the tsconfig.lib.json. */\n readonly tsconfig: string,\n readonly frameworks: readonly string[],\n readonly problems: readonly string[],\n readonly snippet: string,\n ) {}\n}\n\n/** The audit itself — no config, no git: a list of projects in, violations out. */\nexport class FrameworkTsconfigAudit {\n audit(workspaceRoot: string, projects: readonly ScannedProject[]): TsconfigRuntimeViolation[] {\n const out: TsconfigRuntimeViolation[] = [];\n for (const project of projects) {\n if (project.frameworks.length === 0) continue; // framework-tag's job\n const rel = `${project.dir}/${LIB_TSCONFIG}`;\n const abs = path.join(workspaceRoot, rel);\n if (!fs.existsSync(abs)) continue; // not a library\n const want = RuntimeCompilerOptions.forFrameworks(project.frameworks);\n const options = this.resolvedOptions(abs);\n const libs = options.lib?.map((each: string) => each.replace(/^lib\\./, '').replace(/\\.d\\.ts$/, '').toLowerCase());\n const hasDom = libs === undefined || libs.some((lib: string) => lib === 'dom' || lib.startsWith('dom.'));\n const hasNode = options.types === undefined || options.types.includes('node');\n const problems: string[] = [];\n if (want.wantsDom && !hasDom) problems.push('`lib` does not include \"dom\", so the browser globals its runtime has do not compile');\n if (!want.wantsDom && hasDom) {\n problems.push(\n libs === undefined\n ? '`lib` is unset, so TypeScript\\'s default — which includes \"dom\" — lets `window`/`document` compile'\n : '`lib` includes \"dom\", so `window`/`document`/`localStorage` compile where the runtime has none',\n );\n }\n if (want.wantsNodeTypes && !hasNode) problems.push('`types` does not include \"node\", so node\\'s globals do not compile');\n if (!want.wantsNodeTypes && hasNode) {\n problems.push(\n options.types === undefined\n ? '`types` is unset, so every installed @types/* — @types/node included — lets `fs`/`process`/`Buffer` compile'\n : '`types` includes \"node\", so `fs`/`process`/`__dirname`/`Buffer` compile where the runtime has none',\n );\n }\n if (problems.length > 0) out.push(new TsconfigRuntimeViolation(project.name, rel, project.frameworks, problems, want.snippet));\n }\n return out;\n }\n\n /** The compilerOptions the file resolves to, `extends` chain included. */\n private resolvedOptions(abs: string): ts.CompilerOptions {\n const host = Object.assign({}, ts.sys, { onUnRecoverableConfigFileDiagnostic: (): void => undefined }) as ts.ParseConfigFileHost;\n return ts.getParsedCommandLineOfConfigFile(abs, {}, host)?.options ?? {};\n }\n}\n\n/** The one structured failure for every violation, shared by the validator and its spec. */\n// webpieces-disable no-function-outside-class -- one structured rule failure shared by tests and runner\nexport function frameworkTsconfigError(violations: readonly TsconfigRuntimeViolation[]): RuleFailError {\n const details = violations\n .map((v: TsconfigRuntimeViolation) =>\n ` ${v.tsconfig} — ${v.project} [${v.frameworks.join(', ')}]\\n` +\n v.problems.map((p: string) => ` ${p}`).join('\\n') +\n `\\n set compilerOptions: { ${v.snippet} }`)\n .join('\\n');\n return new RuleFailError(\n \"framework-tsconfig\",\n 'A library\\'s tsconfig.lib.json lets code compile that the runtime its framework tags promise cannot run.\\n' + details,\n undefined,\n undefined,\n [\n new Option('Set each listed tsconfig.lib.json\\'s compilerOptions.lib and compilerOptions.types to the values printed beside it, then fix whatever stops compiling — that code was never runnable everywhere the tags promised.', true),\n new Option('If the code genuinely needs the other runtime, the TAGS are wrong: narrow the framework tags (and move the library to the folder for that runtime).'),\n ],\n );\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class FrameworkTsconfigValidator extends CodeValidator<FrameworkTsconfigConfig> {\n constructor(\n config: FrameworkTsconfigConfig,\n private readonly targets: ProjectScanTargets,\n ) {\n super(config, \"framework-tsconfig\", \"framework-tsconfig\");\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n const mode = this.config.mode ?? 'OFF';\n if (mode === 'OFF') return { success: true };\n const allowed = this.config.allowedPaths ?? [];\n const projects = this.targets\n .projects(workspaceRoot, mode, \"framework-tsconfig\")\n .filter((p: ScannedProject) => !matchesAnyGlob(p.dir, allowed));\n const violations = new FrameworkTsconfigAudit().audit(workspaceRoot, projects);\n if (violations.length === 0) return { success: true };\n throw frameworkTsconfigError(violations);\n }\n}\n"]}
1
+ {"version":3,"file":"validate-framework-tsconfig.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-framework-tscon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G,IAAI,CAAC,MAAM,CAAC,IAAI,IAAI,KAAK,CAAC;QACvC,IAAI,IAAI,KAAK,KAAK;YAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;QAC7C,MAAM,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,YAAY,IAAI,EAAE,CAAC;QAC/C,MAAM,QAAQ,GAAG,CAAC,MAAM,IAAI,CAAC,OAAO;aAC/B,QAAQ,CAAC,aAAa,EAAE,IAAI,EAAE,oBAAoB,CAAC,CAAC;aACpD,MAAM,CAAC,CAAC,CAAiB,EAAE,EAAE,CAAC,CAAC,IAAA,6BAAc,EAAC,CAAC,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;QACpE,MAAM,UAAU,GAAG,IAAI,sBAAsB,EAAE,CAAC,KAAK,CAAC,aAAa,EAAE,QAAQ,CAAC,CAAC;QAC/E,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;QACtD,MAAM,sBAAsB,CAAC,UAAU,CAAC,CAAC;IAC7C,CAAC;CACJ,CAAA;AAnBY,gEAA0B;qCAA1B,0BAA0B;IADtC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGzB,2CAAuB;QACL,yCAAkB;GAHvC,0BAA0B,CAmBtC","sourcesContent":["/**\n * `framework-tsconfig` (#1064, D7) — the COMPILER enforces the runtime a library's `framework:` tags\n * promise.\n *\n * A tag used to be a promise only the dependency graph checked: nothing stopped a `browser+node`\n * library from importing `fs` or reading `window`. The cure is not a lint rule that greps for `window`;\n * it is the compiler, which already refuses a global its `lib` / `types` do not declare. So this rule\n * checks the one file that decides what compiles — the library's `tsconfig.lib.json`, with everything\n * it `extends` — against its tags:\n *\n * | tags | `lib` | `types` | effect |\n * |-----------------------------------------|---------------------|----------------|----------------------------------------------|\n * | browser only (browser / angular / react) | includes `dom` | no `node` | `fs`, `process`, `__dirname`, `Buffer` fail |\n * | node only (node / express) | no `dom` | includes `node`| `window`, `document`, `localStorage` fail |\n * | anything else — universal (browser + node + react-native), browser + react-native, react-native | no `dom` | no `node` | pure TypeScript |\n *\n * An unset `lib` resolves to TypeScript's default for the target, which INCLUDES `dom`; an unset\n * `types` loads every installed `@types/*`, which includes `node`. So a library whose runtime excludes\n * either must STATE both. Only `tsconfig.lib.json` is read — an app's own tsconfig (react-native types,\n * a server's) is the app's business.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as ts from 'typescript';\nimport { matchesAnyGlob, Option, RuleFailError } from \"@webpieces/rules-config\";\nimport { FrameworkTsconfigConfig } from \"./configs/tag-truth-configs\";\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { ProjectScanTargets, ScannedProject } from './project-scan-targets';\n\nconst LIB_TSCONFIG = 'tsconfig.lib.json';\n\n/** Envs whose every global is a browser's. */\nconst DOM_ENVS: readonly string[] = ['browser', 'angular', 'react'];\n/** Envs whose every global is node's. */\nconst NODE_ENVS: readonly string[] = ['node', 'express'];\n\n/** What a library's tsconfig must resolve to, given its framework set. Data-only. */\nexport class RuntimeCompilerOptions {\n constructor(\n /** `browser-only` | `node-only` | `pure` — which row of the table governs. */\n readonly row: string,\n readonly wantsDom: boolean,\n readonly wantsNodeTypes: boolean,\n /** The `compilerOptions` to paste. */\n readonly snippet: string,\n ) {}\n\n // webpieces-disable no-function-outside-class -- static factory of this class\n static forFrameworks(frameworks: readonly string[]): RuntimeCompilerOptions {\n if (frameworks.every((env: string) => DOM_ENVS.includes(env))) {\n return new RuntimeCompilerOptions('browser-only', true, false, '\"lib\": [\"es2022\", \"dom\"], \"types\": []');\n }\n if (frameworks.every((env: string) => NODE_ENVS.includes(env))) {\n return new RuntimeCompilerOptions('node-only', false, true, '\"lib\": [\"es2022\"], \"types\": [\"node\"]');\n }\n return new RuntimeCompilerOptions('pure', false, false, '\"lib\": [\"es2022\"], \"types\": []');\n }\n}\n\n/** ONE library whose tsconfig lets code compile that its runtime cannot run. Data-only. */\nexport class TsconfigRuntimeViolation {\n constructor(\n readonly project: string,\n /** Repo-relative path of the tsconfig.lib.json. */\n readonly tsconfig: string,\n readonly frameworks: readonly string[],\n readonly problems: readonly string[],\n readonly snippet: string,\n ) {}\n}\n\n/** The audit itself — no config, no git: a list of projects in, violations out. */\nexport class FrameworkTsconfigAudit {\n audit(workspaceRoot: string, projects: readonly ScannedProject[]): TsconfigRuntimeViolation[] {\n const out: TsconfigRuntimeViolation[] = [];\n for (const project of projects) {\n if (project.frameworks.length === 0) continue; // framework-tag's job\n const rel = `${project.dir}/${LIB_TSCONFIG}`;\n const abs = path.join(workspaceRoot, rel);\n if (!fs.existsSync(abs)) continue; // not a library\n const want = RuntimeCompilerOptions.forFrameworks(project.frameworks);\n const options = this.resolvedOptions(abs);\n const libs = options.lib?.map((each: string) => each.replace(/^lib\\./, '').replace(/\\.d\\.ts$/, '').toLowerCase());\n const hasDom = libs === undefined || libs.some((lib: string) => lib === 'dom' || lib.startsWith('dom.'));\n const hasNode = options.types === undefined || options.types.includes('node');\n const problems: string[] = [];\n if (want.wantsDom && !hasDom) problems.push('`lib` does not include \"dom\", so the browser globals its runtime has do not compile');\n if (!want.wantsDom && hasDom) {\n problems.push(\n libs === undefined\n ? '`lib` is unset, so TypeScript\\'s default — which includes \"dom\" — lets `window`/`document` compile'\n : '`lib` includes \"dom\", so `window`/`document`/`localStorage` compile where the runtime has none',\n );\n }\n if (want.wantsNodeTypes && !hasNode) problems.push('`types` does not include \"node\", so node\\'s globals do not compile');\n if (!want.wantsNodeTypes && hasNode) {\n problems.push(\n options.types === undefined\n ? '`types` is unset, so every installed @types/* — @types/node included — lets `fs`/`process`/`Buffer` compile'\n : '`types` includes \"node\", so `fs`/`process`/`__dirname`/`Buffer` compile where the runtime has none',\n );\n }\n if (problems.length > 0) out.push(new TsconfigRuntimeViolation(project.name, rel, project.frameworks, problems, want.snippet));\n }\n return out;\n }\n\n /** The compilerOptions the file resolves to, `extends` chain included. */\n private resolvedOptions(abs: string): ts.CompilerOptions {\n const host = Object.assign({}, ts.sys, { onUnRecoverableConfigFileDiagnostic: (): void => undefined }) as ts.ParseConfigFileHost;\n return ts.getParsedCommandLineOfConfigFile(abs, {}, host)?.options ?? {};\n }\n}\n\n/** The one structured failure for every violation, shared by the validator and its spec. */\n// webpieces-disable no-function-outside-class -- one structured rule failure shared by tests and runner\nexport function frameworkTsconfigError(violations: readonly TsconfigRuntimeViolation[]): RuleFailError {\n const details = violations\n .map((v: TsconfigRuntimeViolation) =>\n ` ${v.tsconfig} — ${v.project} [${v.frameworks.join(', ')}]\\n` +\n v.problems.map((p: string) => ` ${p}`).join('\\n') +\n `\\n set compilerOptions: { ${v.snippet} }`)\n .join('\\n');\n return new RuleFailError(\n \"framework-tsconfig\",\n 'A library\\'s tsconfig.lib.json lets code compile that the runtime its framework tags promise cannot run.\\n' + details,\n undefined,\n undefined,\n [\n new Option('Set each listed tsconfig.lib.json\\'s compilerOptions.lib and compilerOptions.types to the values printed beside it, then fix whatever stops compiling — that code was never runnable everywhere the tags promised.', true),\n new Option('If the code genuinely needs the other runtime, the TAGS are wrong: narrow the framework tags (and move the library to the folder for that runtime).'),\n ],\n );\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class FrameworkTsconfigValidator extends CodeValidator<FrameworkTsconfigConfig> {\n constructor(\n config: FrameworkTsconfigConfig,\n private readonly targets: ProjectScanTargets,\n ) {\n super(config, \"framework-tsconfig\", \"framework-tsconfig\");\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n const mode = this.config.mode ?? 'OFF';\n if (mode === 'OFF') return { success: true };\n const allowed = this.config.allowedPaths ?? [];\n const projects = (await this.targets\n .projects(workspaceRoot, mode, \"framework-tsconfig\"))\n .filter((p: ScannedProject) => !matchesAnyGlob(p.dir, allowed));\n const violations = new FrameworkTsconfigAudit().audit(workspaceRoot, projects);\n if (violations.length === 0) return { success: true };\n throw frameworkTsconfigError(violations);\n }\n}\n"]}
@@ -158,10 +158,10 @@ function findRedundantInjectInFile(filePath, workspaceRoot, disableAllowed) {
158
158
  return findRedundantInjectInSource(content, filePath, disableAllowed);
159
159
  }
160
160
  // webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members
161
- function findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed) {
161
+ async function findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed) {
162
162
  const violations = [];
163
163
  for (const file of changedFiles) {
164
- const changedLines = (0, rules_config_1.getChangedLineNumbers)((0, rules_config_1.getFileDiff)(workspaceRoot, file, base, head));
164
+ const changedLines = (0, rules_config_1.getChangedLineNumbers)(await (0, rules_config_1.getFileDiff)(workspaceRoot, file, base, head));
165
165
  if (changedLines.size === 0)
166
166
  continue;
167
167
  for (const v of findRedundantInjectInFile(file, workspaceRoot, disableAllowed)) {
@@ -217,7 +217,7 @@ async function runValidatorImpl(scan, options, workspaceRoot) {
217
217
  let base = process.env['NX_BASE'];
218
218
  const head = process.env['NX_HEAD'];
219
219
  if (!base) {
220
- base = (0, rules_config_1.detectBase)(workspaceRoot) ?? undefined;
220
+ base = await (0, rules_config_1.detectBase)(workspaceRoot) ?? undefined;
221
221
  if (!base) {
222
222
  console.log(`\n⏭️ Skipping ${RULE_NAME} validation (could not detect base branch)\n`);
223
223
  return { success: true };
@@ -225,7 +225,7 @@ async function runValidatorImpl(scan, options, workspaceRoot) {
225
225
  }
226
226
  console.log(` Base: ${base}`);
227
227
  console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}\n`);
228
- const changedFiles = scan.files(workspaceRoot, mode, base, head);
228
+ const changedFiles = await scan.files(workspaceRoot, mode, base, head);
229
229
  if (changedFiles.length === 0) {
230
230
  console.log('✅ No TypeScript files changed');
231
231
  return { success: true };
@@ -233,7 +233,7 @@ async function runValidatorImpl(scan, options, workspaceRoot) {
233
233
  console.log(`📂 Checking ${changedFiles.length} changed file(s)...`);
234
234
  let violations = [];
235
235
  if (mode === 'NEW_AND_MODIFIED_CODE') {
236
- violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed);
236
+ violations = await findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed);
237
237
  }
238
238
  else {
239
239
  // NEW_AND_MODIFIED_FILES and the whole-scope modes (#1027) all judge every site of every file.
@@ -1 +1 @@
1
- {"version":3,"file":"validate-inject-annotation-not-needed-for-concrete-class.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-inject-annotation-not-needed-for-concrete-class.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;;;AAiFH,kEA4BC;;AA3GD,+CAAyB;AACzB,mDAA6B;AAC7B,uDAAiC;AACjC,0DAAqG;AACrG,yDAAyF;AAEzF,qDAAiE;AACjE,yCAA2D;AAC3D,6CAAyC;AAEzC,MAAM,SAAS,GAAG,iDAAiD,CAAC;AAEpE,MAAM,cAAc,GAAG;;;;;;;;sFAQ+D,CAAC;AAgBvF,6HAA6H;AAC7H,SAAS,UAAU,CAAC,QAAgB;IAChC,OAAO,QAAQ,CAAC,QAAQ,CAAC,UAAU,CAAC,IAAI,QAAQ,CAAC,QAAQ,CAAC,UAAU,CAAC,IAAI,QAAQ,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;AAC7G,CAAC;AAED,6HAA6H;AAC7H,SAAS,iBAAiB,CAAC,QAAgB;IACvC,OAAO,QAAQ,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;AACtC,CAAC;AAED,8EAA8E;AAC9E,6HAA6H;AAC7H,SAAS,gBAAgB,CAAC,SAAmB,EAAE,UAAkB;IAC7D,MAAM,OAAO,GAAG,SAAS,CAAC,UAAU,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;IAChD,MAAM,QAAQ,GAAG,UAAU,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,UAAU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Flags a REDUNDANT `@inject(X)` on a CONSTRUCTOR parameter whose token is textually identical to the\n * parameter's own declared type:\n *\n * BAD: constructor(@inject(RequestContextHeaders) private readonly h: RequestContextHeaders) {}\n * GOOD: constructor(private readonly h: RequestContextHeaders) {}\n *\n * WHY: in this inversify setup a constructor parameter is auto-resolved by its class TYPE via\n * reflect-metadata (`emitDecoratorMetadata` emits `design:paramtypes`). So `private readonly h: Foo`\n * already binds `Foo` — the `@inject(Foo)` adds nothing (see CLAUDE.md, and the sibling\n * no-symbol-di-tokens rule that pushes the same inject-by-type pattern). AI keeps carpet-bombing\n * `@inject`; this fails the build on the redundant form so it stops.\n *\n * Uses the TypeScript AST (not a regex) so \"token equals the parameter type\" is decided precisely.\n * That single rule is what makes every LEGITIMATE token pass untouched — a real token never equals the\n * type it resolves:\n * - `@inject(TASK_PROXY_CLIENT_PROVIDER) x: Provider<TaskProxyClient>` (Symbol token ≠ type)\n * - `@inject(WEBPIECES_CONFIG_TOKEN) c: WebpiecesConfig` (Symbol ≠ interface type)\n * - `@inject('some-string') x: Foo` (string token ≠ type)\n * - `@inject(Symbol.for('X')) x: Foo` (not a bare identifier)\n *\n * SCOPE: only CONSTRUCTOR parameters. Property injection (`@inject(Foo) private foo: Foo` on a class\n * field) genuinely REQUIRES `@inject` in inversify — there is no design:type auto-wiring for properties\n * — so it is left alone.\n *\n * ALLOWED (skip — NOT violations)\n * - Any `@inject(TOKEN)` whose token differs from the parameter's type (Symbols, string tokens,\n * provider tokens, interface tokens).\n * - Property/field injection, and any parameter without an `@inject` decorator.\n * - Test files (*.test.ts, *.spec.ts, __tests__/**).\n * - Files under the rule's `excludePaths` or the top-level one (dropped by the framework).\n * - Lines with `// webpieces-disable inject-annotation-not-needed-for-concrete-class -- <reason>`\n * (only when disableAllowed).\n *\n * MODES (AST + LINE-SCOPED)\n * - OFF: Skip.\n * - NEW_AND_MODIFIED_CODE: Flag only on changed lines (diff hunks).\n * - NEW_AND_MODIFIED_FILES: Flag every occurrence in any modified file.\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 { InjectAnnotationNotNeededForConcreteClassConfig } 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\nconst RULE_NAME = \"inject-annotation-not-needed-for-concrete-class\";\n\nconst SHARED_MESSAGE = `@inject(Foo) on a constructor parameter typed \\`: Foo\\` is noise — inversify resolves a constructor\nparameter by its class type via reflect-metadata, so \\`private readonly foo: Foo\\` already binds it\n(see CLAUDE.md). Pick one:\n Fix Option 1 (PREFERRED): delete the decorator — constructor(private readonly foo: Foo) {}\n Fix Option 2: if you actually need a DIFFERENT binding token (a Symbol for a generated\n http-client-node / cloud-tasks client, or an interface/config with multiple impls), inject that\n token so it DIFFERS from the type: @inject(FOO_TOKEN) foo: SomeInterface.\nProperty injection (@inject on a class field, not a constructor param) is NOT flagged — it genuinely\nneeds @inject. Only a constructor param whose token equals its own type is redundant.`;\n\ninterface InjectViolation {\n file: string;\n line: number;\n column: number;\n context: string;\n}\n\ninterface InjectViolationInfo {\n line: number;\n column: number;\n context: string;\n hasDisableComment: boolean;\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction isTestFile(filePath: string): boolean {\n return filePath.includes('.spec.ts') || filePath.includes('.test.ts') || filePath.includes('__tests__/');\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction isDeclarationFile(filePath: string): boolean {\n return filePath.endsWith('.d.ts');\n}\n\n// The violation line (or the line just above it) carries the disable comment.\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction hasDisableOnLine(fileLines: string[], lineNumber: number): boolean {\n const current = fileLines[lineNumber - 1] ?? '';\n const previous = lineNumber >= 2 ? (fileLines[lineNumber - 2] ?? '') : '';\n return hasDisable(current, RULE_NAME) || hasDisable(previous, RULE_NAME);\n}\n\n// The `@inject(X)` decorator's single argument, when it is a BARE identifier (a class/token name).\n// Returns null for Symbol.for(...), property-access (`Symbol.x`), string literals, or a non-inject\n// decorator — those can never equal the parameter type, so they are never redundant.\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction injectIdentifierArg(decorator: ts.Decorator): string | null {\n const expr = decorator.expression;\n if (!ts.isCallExpression(expr)) return null;\n if (!ts.isIdentifier(expr.expression) || expr.expression.text !== 'inject') return null;\n if (expr.arguments.length !== 1) return null;\n const arg = expr.arguments[0];\n return arg && ts.isIdentifier(arg) ? arg.text : null;\n}\n\n// The parameter's declared type when it is a simple `TypeReference` with an identifier name\n// (`Foo`, or `Foo<Bar>` → `Foo`). Qualified names (`ns.Foo`) and non-references return null.\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction paramTypeName(param: ts.ParameterDeclaration): string | null {\n const typeNode = param.type;\n if (!typeNode || !ts.isTypeReferenceNode(typeNode)) return null;\n return ts.isIdentifier(typeNode.typeName) ? typeNode.typeName.text : null;\n}\n\n// AST scan: a CONSTRUCTOR parameter is a violation when it carries `@inject(X)` and its declared type\n// is exactly `X`. Property injection and method params are ignored (only constructor params).\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nexport function findRedundantInjectInSource(content: string, filePath: string, disableAllowed: boolean): InjectViolationInfo[] {\n if (isDeclarationFile(filePath)) return [];\n const fileLines = content.split('\\n');\n const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);\n const violations: InjectViolationInfo[] = [];\n\n function checkParameter(param: ts.ParameterDeclaration): void {\n const decorators = ts.canHaveDecorators(param) ? ts.getDecorators(param) : undefined;\n if (!decorators) return;\n const typeName = paramTypeName(param);\n if (!typeName) return;\n for (const decorator of decorators) {\n if (injectIdentifierArg(decorator) === typeName) {\n recordViolation(param, `@inject(${typeName}) is redundant — the parameter is typed \\`: ${typeName}\\` and resolves by type`, fileLines, sourceFile, violations, disableAllowed);\n return;\n }\n }\n }\n\n function visit(node: ts.Node): void {\n if (ts.isConstructorDeclaration(node)) {\n for (const param of node.parameters) checkParameter(param);\n }\n ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return violations;\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction recordViolation(\n node: ts.Node,\n context: string,\n fileLines: string[],\n sourceFile: ts.SourceFile,\n violations: InjectViolationInfo[],\n disableAllowed: boolean,\n): void {\n const startPos = node.getStart(sourceFile);\n if (startPos < 0) return;\n const pos = sourceFile.getLineAndCharacterOfPosition(startPos);\n const line = pos.line + 1;\n const column = pos.character + 1;\n const disabled = hasDisableOnLine(fileLines, line);\n // When disableAllowed is false, a disable comment does NOT clear the violation.\n const effectiveDisabled = disableAllowed ? disabled : false;\n violations.push({ line, column, context, hasDisableComment: effectiveDisabled });\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction findRedundantInjectInFile(filePath: string, workspaceRoot: string, disableAllowed: boolean): InjectViolationInfo[] {\n if (isTestFile(filePath)) return [];\n const fullPath = path.join(workspaceRoot, filePath);\n if (!fs.existsSync(fullPath)) return [];\n const content = fs.readFileSync(fullPath, 'utf-8');\n return findRedundantInjectInSource(content, filePath, disableAllowed);\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction findViolationsForModifiedCode(workspaceRoot: string, changedFiles: string[], base: string, head: string | undefined, disableAllowed: boolean): InjectViolation[] {\n const violations: InjectViolation[] = [];\n for (const file of changedFiles) {\n const changedLines = getChangedLineNumbers(getFileDiff(workspaceRoot, file, base, head));\n if (changedLines.size === 0) continue;\n for (const v of findRedundantInjectInFile(file, workspaceRoot, disableAllowed)) {\n if (disableAllowed && v.hasDisableComment) continue;\n if (!changedLines.has(v.line)) continue;\n violations.push({ file, line: v.line, column: v.column, context: v.context });\n }\n }\n return violations;\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction findViolationsForModifiedFiles(workspaceRoot: string, changedFiles: string[], disableAllowed: boolean): InjectViolation[] {\n const violations: InjectViolation[] = [];\n for (const file of changedFiles) {\n for (const v of findRedundantInjectInFile(file, workspaceRoot, disableAllowed)) {\n if (disableAllowed && v.hasDisableComment) continue;\n violations.push({ file, line: v.line, column: v.column, context: v.context });\n }\n }\n return violations;\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction reportViolations(violations: InjectViolation[], mode: ModifiedCodeMode, disableAllowed: boolean): void {\n console.error('');\n console.error('❌ Redundant @inject — the parameter\\'s type already resolves it.');\n console.error('');\n console.error(SHARED_MESSAGE);\n console.error('');\n for (const v of violations) {\n console.error(` ❌ ${v.file}:${v.line}:${v.column}`);\n console.error(` ${v.context}`);\n }\n console.error('');\n console.error(disableAllowed\n ? ` Escape hatch (use sparingly): // webpieces-disable ${RULE_NAME} -- <reason>`\n : ' Escape hatch: DISABLED (disableAllowed: false)');\n console.error(` Whole-tree exemption: add a glob to ${RULE_NAME}.excludePaths in webpieces.config.json`);\n console.error(`\\n Current mode: ${mode}\\n`);\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nasync function runValidatorImpl(\n scan: ScanScope,\n options: InjectAnnotationNotNeededForConcreteClassConfig,\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⏭️ Skipping ${RULE_NAME} validation (mode: OFF)\\n`);\n return { success: true };\n }\n\n console.log(`\\n📏 Validating ${RULE_NAME}\\n`);\n console.log(` Mode: ${mode}`);\n\n let base = process.env['NX_BASE'];\n const head = process.env['NX_HEAD'];\n if (!base) {\n base = detectBase(workspaceRoot) ?? undefined;\n if (!base) {\n console.log(`\\n⏭️ Skipping ${RULE_NAME} validation (could not detect base branch)\\n`);\n return { success: true };\n }\n }\n\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}\\n`);\n\n const changedFiles = scan.files(workspaceRoot, mode, base, head);\n if (changedFiles.length === 0) {\n console.log('✅ No TypeScript files changed');\n return { success: true };\n }\n\n console.log(`📂 Checking ${changedFiles.length} changed file(s)...`);\n\n let violations: InjectViolation[] = [];\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('✅ No redundant-@inject violations found');\n return { success: true };\n }\n\n scan.recordSites(RULE_NAME, violations.map((v: InjectViolation) => v.file));\n reportViolations(violations, mode, disableAllowed);\n return { success: false };\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class InjectAnnotationNotNeededForConcreteClassValidator extends CodeValidator<InjectAnnotationNotNeededForConcreteClassConfig> {\n constructor(config: InjectAnnotationNotNeededForConcreteClassConfig, private readonly scanScope: ScanScope) {\n super(config, RULE_NAME, RULE_NAME);\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-inject-annotation-not-needed-for-concrete-class.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-inject-annotation-not-needed-for-concrete-class.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;;;AAiFH,kEA4BC;;AA3GD,+CAAyB;AACzB,mDAA6B;AAC7B,uDAAiC;AACjC,0DAAqG;AACrG,yD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CAAC,CAAkB,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;IAC5E,gBAAgB,CAAC,UAAU,EAAE,IAAI,EAAE,cAAc,CAAC,CAAC;IACnD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC9B,CAAC;AAGM,IAAM,kDAAkD,GAAxD,MAAM,kDAAmD,SAAQ,8BAA8D;IAC5C;IAAtF,YAAY,MAAuD,EAAmB,SAAoB;QACtG,KAAK,CAAC,MAAM,EAAE,SAAS,EAAE,SAAS,CAAC,CAAC;QAD8C,cAAS,GAAT,SAAS,CAAW;IAE1G,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,gHAAkD;6DAAlD,kDAAkD;IAD9D,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEjB,8DAA+C,EAA8B,sBAAS;GADjG,kDAAkD,CAQ9D","sourcesContent":["/**\n * Validate Inject Annotation Not Needed For Concrete Class\n *\n * Flags a REDUNDANT `@inject(X)` on a CONSTRUCTOR parameter whose token is textually identical to the\n * parameter's own declared type:\n *\n * BAD: constructor(@inject(RequestContextHeaders) private readonly h: RequestContextHeaders) {}\n * GOOD: constructor(private readonly h: RequestContextHeaders) {}\n *\n * WHY: in this inversify setup a constructor parameter is auto-resolved by its class TYPE via\n * reflect-metadata (`emitDecoratorMetadata` emits `design:paramtypes`). So `private readonly h: Foo`\n * already binds `Foo` — the `@inject(Foo)` adds nothing (see CLAUDE.md, and the sibling\n * no-symbol-di-tokens rule that pushes the same inject-by-type pattern). AI keeps carpet-bombing\n * `@inject`; this fails the build on the redundant form so it stops.\n *\n * Uses the TypeScript AST (not a regex) so \"token equals the parameter type\" is decided precisely.\n * That single rule is what makes every LEGITIMATE token pass untouched — a real token never equals the\n * type it resolves:\n * - `@inject(TASK_PROXY_CLIENT_PROVIDER) x: Provider<TaskProxyClient>` (Symbol token ≠ type)\n * - `@inject(WEBPIECES_CONFIG_TOKEN) c: WebpiecesConfig` (Symbol ≠ interface type)\n * - `@inject('some-string') x: Foo` (string token ≠ type)\n * - `@inject(Symbol.for('X')) x: Foo` (not a bare identifier)\n *\n * SCOPE: only CONSTRUCTOR parameters. Property injection (`@inject(Foo) private foo: Foo` on a class\n * field) genuinely REQUIRES `@inject` in inversify — there is no design:type auto-wiring for properties\n * — so it is left alone.\n *\n * ALLOWED (skip — NOT violations)\n * - Any `@inject(TOKEN)` whose token differs from the parameter's type (Symbols, string tokens,\n * provider tokens, interface tokens).\n * - Property/field injection, and any parameter without an `@inject` decorator.\n * - Test files (*.test.ts, *.spec.ts, __tests__/**).\n * - Files under the rule's `excludePaths` or the top-level one (dropped by the framework).\n * - Lines with `// webpieces-disable inject-annotation-not-needed-for-concrete-class -- <reason>`\n * (only when disableAllowed).\n *\n * MODES (AST + LINE-SCOPED)\n * - OFF: Skip.\n * - NEW_AND_MODIFIED_CODE: Flag only on changed lines (diff hunks).\n * - NEW_AND_MODIFIED_FILES: Flag every occurrence in any modified file.\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 { InjectAnnotationNotNeededForConcreteClassConfig } 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\nconst RULE_NAME = \"inject-annotation-not-needed-for-concrete-class\";\n\nconst SHARED_MESSAGE = `@inject(Foo) on a constructor parameter typed \\`: Foo\\` is noise — inversify resolves a constructor\nparameter by its class type via reflect-metadata, so \\`private readonly foo: Foo\\` already binds it\n(see CLAUDE.md). Pick one:\n Fix Option 1 (PREFERRED): delete the decorator — constructor(private readonly foo: Foo) {}\n Fix Option 2: if you actually need a DIFFERENT binding token (a Symbol for a generated\n http-client-node / cloud-tasks client, or an interface/config with multiple impls), inject that\n token so it DIFFERS from the type: @inject(FOO_TOKEN) foo: SomeInterface.\nProperty injection (@inject on a class field, not a constructor param) is NOT flagged — it genuinely\nneeds @inject. Only a constructor param whose token equals its own type is redundant.`;\n\ninterface InjectViolation {\n file: string;\n line: number;\n column: number;\n context: string;\n}\n\ninterface InjectViolationInfo {\n line: number;\n column: number;\n context: string;\n hasDisableComment: boolean;\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction isTestFile(filePath: string): boolean {\n return filePath.includes('.spec.ts') || filePath.includes('.test.ts') || filePath.includes('__tests__/');\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction isDeclarationFile(filePath: string): boolean {\n return filePath.endsWith('.d.ts');\n}\n\n// The violation line (or the line just above it) carries the disable comment.\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction hasDisableOnLine(fileLines: string[], lineNumber: number): boolean {\n const current = fileLines[lineNumber - 1] ?? '';\n const previous = lineNumber >= 2 ? (fileLines[lineNumber - 2] ?? '') : '';\n return hasDisable(current, RULE_NAME) || hasDisable(previous, RULE_NAME);\n}\n\n// The `@inject(X)` decorator's single argument, when it is a BARE identifier (a class/token name).\n// Returns null for Symbol.for(...), property-access (`Symbol.x`), string literals, or a non-inject\n// decorator — those can never equal the parameter type, so they are never redundant.\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction injectIdentifierArg(decorator: ts.Decorator): string | null {\n const expr = decorator.expression;\n if (!ts.isCallExpression(expr)) return null;\n if (!ts.isIdentifier(expr.expression) || expr.expression.text !== 'inject') return null;\n if (expr.arguments.length !== 1) return null;\n const arg = expr.arguments[0];\n return arg && ts.isIdentifier(arg) ? arg.text : null;\n}\n\n// The parameter's declared type when it is a simple `TypeReference` with an identifier name\n// (`Foo`, or `Foo<Bar>` → `Foo`). Qualified names (`ns.Foo`) and non-references return null.\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction paramTypeName(param: ts.ParameterDeclaration): string | null {\n const typeNode = param.type;\n if (!typeNode || !ts.isTypeReferenceNode(typeNode)) return null;\n return ts.isIdentifier(typeNode.typeName) ? typeNode.typeName.text : null;\n}\n\n// AST scan: a CONSTRUCTOR parameter is a violation when it carries `@inject(X)` and its declared type\n// is exactly `X`. Property injection and method params are ignored (only constructor params).\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nexport function findRedundantInjectInSource(content: string, filePath: string, disableAllowed: boolean): InjectViolationInfo[] {\n if (isDeclarationFile(filePath)) return [];\n const fileLines = content.split('\\n');\n const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);\n const violations: InjectViolationInfo[] = [];\n\n function checkParameter(param: ts.ParameterDeclaration): void {\n const decorators = ts.canHaveDecorators(param) ? ts.getDecorators(param) : undefined;\n if (!decorators) return;\n const typeName = paramTypeName(param);\n if (!typeName) return;\n for (const decorator of decorators) {\n if (injectIdentifierArg(decorator) === typeName) {\n recordViolation(param, `@inject(${typeName}) is redundant — the parameter is typed \\`: ${typeName}\\` and resolves by type`, fileLines, sourceFile, violations, disableAllowed);\n return;\n }\n }\n }\n\n function visit(node: ts.Node): void {\n if (ts.isConstructorDeclaration(node)) {\n for (const param of node.parameters) checkParameter(param);\n }\n ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return violations;\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction recordViolation(\n node: ts.Node,\n context: string,\n fileLines: string[],\n sourceFile: ts.SourceFile,\n violations: InjectViolationInfo[],\n disableAllowed: boolean,\n): void {\n const startPos = node.getStart(sourceFile);\n if (startPos < 0) return;\n const pos = sourceFile.getLineAndCharacterOfPosition(startPos);\n const line = pos.line + 1;\n const column = pos.character + 1;\n const disabled = hasDisableOnLine(fileLines, line);\n // When disableAllowed is false, a disable comment does NOT clear the violation.\n const effectiveDisabled = disableAllowed ? disabled : false;\n violations.push({ line, column, context, hasDisableComment: effectiveDisabled });\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction findRedundantInjectInFile(filePath: string, workspaceRoot: string, disableAllowed: boolean): InjectViolationInfo[] {\n if (isTestFile(filePath)) return [];\n const fullPath = path.join(workspaceRoot, filePath);\n if (!fs.existsSync(fullPath)) return [];\n const content = fs.readFileSync(fullPath, 'utf-8');\n return findRedundantInjectInSource(content, filePath, disableAllowed);\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nasync function findViolationsForModifiedCode(workspaceRoot: string, changedFiles: string[], base: string, head: string | undefined, disableAllowed: boolean): Promise<InjectViolation[]> {\n const violations: InjectViolation[] = [];\n for (const file of changedFiles) {\n const changedLines = getChangedLineNumbers(await getFileDiff(workspaceRoot, file, base, head));\n if (changedLines.size === 0) continue;\n for (const v of findRedundantInjectInFile(file, workspaceRoot, disableAllowed)) {\n if (disableAllowed && v.hasDisableComment) continue;\n if (!changedLines.has(v.line)) continue;\n violations.push({ file, line: v.line, column: v.column, context: v.context });\n }\n }\n return violations;\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction findViolationsForModifiedFiles(workspaceRoot: string, changedFiles: string[], disableAllowed: boolean): InjectViolation[] {\n const violations: InjectViolation[] = [];\n for (const file of changedFiles) {\n for (const v of findRedundantInjectInFile(file, workspaceRoot, disableAllowed)) {\n if (disableAllowed && v.hasDisableComment) continue;\n violations.push({ file, line: v.line, column: v.column, context: v.context });\n }\n }\n return violations;\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction reportViolations(violations: InjectViolation[], mode: ModifiedCodeMode, disableAllowed: boolean): void {\n console.error('');\n console.error('❌ Redundant @inject — the parameter\\'s type already resolves it.');\n console.error('');\n console.error(SHARED_MESSAGE);\n console.error('');\n for (const v of violations) {\n console.error(` ❌ ${v.file}:${v.line}:${v.column}`);\n console.error(` ${v.context}`);\n }\n console.error('');\n console.error(disableAllowed\n ? ` Escape hatch (use sparingly): // webpieces-disable ${RULE_NAME} -- <reason>`\n : ' Escape hatch: DISABLED (disableAllowed: false)');\n console.error(` Whole-tree exemption: add a glob to ${RULE_NAME}.excludePaths in webpieces.config.json`);\n console.error(`\\n Current mode: ${mode}\\n`);\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nasync function runValidatorImpl(\n scan: ScanScope,\n options: InjectAnnotationNotNeededForConcreteClassConfig,\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⏭️ Skipping ${RULE_NAME} validation (mode: OFF)\\n`);\n return { success: true };\n }\n\n console.log(`\\n📏 Validating ${RULE_NAME}\\n`);\n console.log(` Mode: ${mode}`);\n\n let base = process.env['NX_BASE'];\n const head = process.env['NX_HEAD'];\n if (!base) {\n base = await detectBase(workspaceRoot) ?? undefined;\n if (!base) {\n console.log(`\\n⏭️ Skipping ${RULE_NAME} validation (could not detect base branch)\\n`);\n return { success: true };\n }\n }\n\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}\\n`);\n\n const changedFiles = await scan.files(workspaceRoot, mode, base, head);\n if (changedFiles.length === 0) {\n console.log('✅ No TypeScript files changed');\n return { success: true };\n }\n\n console.log(`📂 Checking ${changedFiles.length} changed file(s)...`);\n\n let violations: InjectViolation[] = [];\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('✅ No redundant-@inject violations found');\n return { success: true };\n }\n\n scan.recordSites(RULE_NAME, violations.map((v: InjectViolation) => v.file));\n reportViolations(violations, mode, disableAllowed);\n return { success: false };\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class InjectAnnotationNotNeededForConcreteClassValidator extends CodeValidator<InjectAnnotationNotNeededForConcreteClassConfig> {\n constructor(config: InjectAnnotationNotNeededForConcreteClassConfig, private readonly scanScope: ScanScope) {\n super(config, RULE_NAME, RULE_NAME);\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runValidatorImpl(this.scanScope, this.config, workspaceRoot);\n }\n}\n"]}
@@ -60,7 +60,7 @@ let MatchRulesChecker = class MatchRulesChecker {
60
60
  let base = process.env['NX_BASE'];
61
61
  const head = process.env['NX_HEAD'];
62
62
  if (!base) {
63
- base = (0, rules_config_1.detectBase)(workspaceRoot) ?? undefined;
63
+ base = await (0, rules_config_1.detectBase)(workspaceRoot) ?? undefined;
64
64
  if (!base) {
65
65
  console.log(`\n⏭️ Skipping ${config.name} validation (could not detect base branch)\n`);
66
66
  return { success: true };
@@ -68,14 +68,14 @@ let MatchRulesChecker = class MatchRulesChecker {
68
68
  }
69
69
  console.log(` Base: ${base}`);
70
70
  console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}\n`);
71
- const changedFiles = this.scanScope.files(workspaceRoot, mode, base, head);
71
+ const changedFiles = await this.scanScope.files(workspaceRoot, mode, base, head);
72
72
  if (changedFiles.length === 0) {
73
73
  console.log('✅ No TypeScript files changed');
74
74
  return { success: true };
75
75
  }
76
76
  console.log(`📂 Checking ${changedFiles.length} changed file(s)...`);
77
77
  const violations = this.scanScope.isLineScoped(mode)
78
- ? this.findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, config)
78
+ ? await this.findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, config)
79
79
  : this.findViolationsForModifiedFiles(workspaceRoot, changedFiles, config);
80
80
  if (violations.length === 0) {
81
81
  console.log(`✅ No ${config.name} violations found`);
@@ -101,10 +101,10 @@ let MatchRulesChecker = class MatchRulesChecker {
101
101
  return new MatchViolationInfo(hit.line, hit.context, disableAllowed && disabled);
102
102
  });
103
103
  }
104
- findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, config) {
104
+ async findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, config) {
105
105
  const violations = [];
106
106
  for (const file of changedFiles) {
107
- const diff = (0, rules_config_1.getFileDiff)(workspaceRoot, file, base, head);
107
+ const diff = await (0, rules_config_1.getFileDiff)(workspaceRoot, file, base, head);
108
108
  const changedLines = (0, rules_config_1.getChangedLineNumbers)(diff);
109
109
  if (changedLines.size === 0)
110
110
  continue;
@@ -1 +1 @@
1
- {"version":3,"file":"validate-match-rules.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-match-rules.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA2M;AAE3M,yCAA2D;AAE3D,6CAAyC;AAEzC,MAAM,cAAc;IACP,IAAI,CAAS;IACb,IAAI,CAAS;IACb,OAAO,CAAS;IAEzB,YAAY,IAAY,EAAE,IAAY,EAAE,OAAe;QACnD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IAC3B,CAAC;CACJ;AAED,MAAa,kBAAkB;IAClB,IAAI,CAAS;IACb,OAAO,CAAS;IAChB,iBAAiB,CAAU;IAEpC,YAAY,IAAY,EAAE,OAAe,EAAE,iBAA0B;QACjE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;IAC/C,C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AC,MAAuB,EAAE,UAA4B,EAAE,IAAsB;QAClG,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAClB,OAAO,CAAC,KAAK,CAAC,MAAM,MAAM,CAAC,IAAI,kCAAkC,CAAC,CAAC;QACnE,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAClB,OAAO,CAAC,KAAK,CAAC,IAAA,qCAAsB,EAAC,MAAM,CAAC,CAAC,CAAC;QAC9C,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAClB,KAAK,MAAM,CAAC,IAAI,UAAU,EAAE,CAAC;YACzB,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;YACzC,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;QACvC,CAAC;QACD,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAClB,OAAO,CAAC,KAAK,CAAC,oBAAoB,IAAI,EAAE,CAAC,CAAC;QAC1C,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IACtB,CAAC;CAEJ,CAAA;AA7HY,8CAAiB;4BAAjB,iBAAiB;IAD7B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEG,sBAAS;GADxC,iBAAiB,CA6H7B","sourcesContent":["/**\n * Validate `match-rules` entries (client-authored content guards) at build time.\n *\n * A config-free, injected checker: the {@link CodeRulesEngine} injects ONE MatchRulesChecker and runs\n * it once per `match-rules` entry (config passed to the method), so there is no `new` of a DAG member.\n * `shouldRun` / mode / epoch apply per entry and the report shows the entry name. The regex matching +\n * allowedPath/test-file exemption is shared with the ai-hook engine via findMatchRuleViolations; this\n * adds diff-scoping (mode), the `// webpieces-disable <name>` filter, and the console report.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { hasDisable, MatchRuleConfig, MatchRuleViolation, findMatchRuleViolations, renderMatchRuleMessage, detectBase, getFileDiff, getChangedLineNumbers, shouldSkipRule } from \"@webpieces/rules-config\";\nimport { ModifiedCodeMode } from '@webpieces/rules-sdk';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { ExecutorResult } from './code-validator';\nimport { ScanScope } from './scan-scope';\n\nclass MatchViolation {\n readonly file: string;\n readonly line: number;\n readonly context: string;\n\n constructor(file: string, line: number, context: string) {\n this.file = file;\n this.line = line;\n this.context = context;\n }\n}\n\nexport class MatchViolationInfo {\n readonly line: number;\n readonly context: string;\n readonly hasDisableComment: boolean;\n\n constructor(line: number, context: string, hasDisableComment: boolean) {\n this.line = line;\n this.context = context;\n this.hasDisableComment = hasDisableComment;\n }\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class MatchRulesChecker {\n constructor(private readonly scanScope: ScanScope) {}\n\n /** True unless this entry is `mode: \"OFF\"` or skipped by a branch/epoch escape hatch. */\n shouldRun(config: MatchRuleConfig): boolean {\n if ((config.mode ?? 'OFF') === 'OFF') return false;\n return !shouldSkipRule(config.turnOffRuleUntilEpoch, config.turnOffRuleWhileOnBranch).skip;\n }\n\n /** Run one `match-rules` entry against the workspace (per-entry mode/diff-scoping/report). */\n async runForConfig(config: MatchRuleConfig, workspaceRoot: string): Promise<ExecutorResult> {\n const mode: ModifiedCodeMode = config.mode ?? 'OFF';\n if (mode === 'OFF') {\n console.log(`\\n⏭️ Skipping ${config.name} validation (mode: OFF)\\n`);\n return { success: true };\n }\n\n console.log(`\\n📏 Validating match-rule: ${config.name}\\n`);\n console.log(` Mode: ${mode}`);\n\n let base = process.env['NX_BASE'];\n const head = process.env['NX_HEAD'];\n if (!base) {\n base = detectBase(workspaceRoot) ?? undefined;\n if (!base) {\n console.log(`\\n⏭️ Skipping ${config.name} validation (could not detect base branch)\\n`);\n return { success: true };\n }\n }\n\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}\\n`);\n\n const changedFiles = this.scanScope.files(workspaceRoot, mode, base, head);\n if (changedFiles.length === 0) {\n console.log('✅ No TypeScript files changed');\n return { success: true };\n }\n\n console.log(`📂 Checking ${changedFiles.length} changed file(s)...`);\n const violations = this.scanScope.isLineScoped(mode)\n ? this.findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, config)\n : this.findViolationsForModifiedFiles(workspaceRoot, changedFiles, config);\n\n if (violations.length === 0) {\n console.log(`✅ No ${config.name} violations found`);\n return { success: true };\n }\n\n this.scanScope.recordSites(config.name, violations.map((v: MatchViolation) => v.file));\n this.reportViolations(config, violations, mode);\n return { success: false };\n }\n\n findViolationsInFile(filePath: string, workspaceRoot: string, config: MatchRuleConfig): MatchViolationInfo[] {\n const fullPath = path.join(workspaceRoot, filePath);\n if (!fs.existsSync(fullPath)) return [];\n\n const content = fs.readFileSync(fullPath, 'utf-8');\n const lines = content.split('\\n');\n\n // Shared engine applies allowedPaths + test-file exemption and regex matching.\n const hits = findMatchRuleViolations(lines, filePath, config);\n const disableAllowed = config.disableAllowed ?? true;\n\n return hits.map((hit: MatchRuleViolation) => {\n const line = lines[hit.line - 1] ?? '';\n const prevLine = hit.line > 1 ? (lines[hit.line - 2] ?? '') : '';\n const disabled = hasDisable(line, config.name) || hasDisable(prevLine, config.name);\n return new MatchViolationInfo(hit.line, hit.context, disableAllowed && disabled);\n });\n }\n\n private findViolationsForModifiedCode(\n workspaceRoot: string,\n changedFiles: string[],\n base: string,\n head: string | undefined,\n config: MatchRuleConfig,\n ): MatchViolation[] {\n const violations: MatchViolation[] = [];\n for (const file of changedFiles) {\n const diff = getFileDiff(workspaceRoot, file, base, head);\n const changedLines = getChangedLineNumbers(diff);\n if (changedLines.size === 0) continue;\n\n for (const v of this.findViolationsInFile(file, workspaceRoot, config)) {\n if (v.hasDisableComment) continue;\n if (!changedLines.has(v.line)) continue;\n violations.push(new MatchViolation(file, v.line, v.context));\n }\n }\n return violations;\n }\n\n private findViolationsForModifiedFiles(\n workspaceRoot: string,\n changedFiles: string[],\n config: MatchRuleConfig,\n ): MatchViolation[] {\n const violations: MatchViolation[] = [];\n for (const file of changedFiles) {\n for (const v of this.findViolationsInFile(file, workspaceRoot, config)) {\n if (v.hasDisableComment) continue;\n violations.push(new MatchViolation(file, v.line, v.context));\n }\n }\n return violations;\n }\n\n private reportViolations(config: MatchRuleConfig, violations: MatchViolation[], mode: ModifiedCodeMode): void {\n console.error('');\n console.error(`❌ [${config.name}] matched disallowed pattern(s)!`);\n console.error('');\n console.error(renderMatchRuleMessage(config));\n console.error('');\n for (const v of violations) {\n console.error(` ❌ ${v.file}:${v.line}`);\n console.error(` ${v.context}`);\n }\n console.error('');\n console.error(` Current mode: ${mode}`);\n console.error('');\n }\n\n}\n"]}
1
+ {"version":3,"file":"validate-match-rules.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-match-rules.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA2M;AAE3M,yCAA2D;AAE3D,6CAAyC;AAEzC,MAAM,cAAc;IACP,IAAI,CAAS;IACb,IAAI,CAAS;IACb,OAAO,CAAS;IAEzB,YAAY,IAAY,EAAE,IAAY,EAAE,OAAe;QACnD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IAC3B,CAAC;CACJ;AAED,MAAa,kBAAkB;IAClB,IAAI,CAAS;IACb,OAAO,CAAS;IAChB,iBAAiB,CAAU;IAEpC,YAAY,IAAY,EAAE,OAAe,EAAE,iBAA0B;QACjE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;IAC/C,CAAC;CACJ;AAVD,gDAUC;AAGM,IAAM,iBAAiB,GAAvB,MAAM,iBAAiB;IACG;I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AClG,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAClB,OAAO,CAAC,KAAK,CAAC,MAAM,MAAM,CAAC,IAAI,kCAAkC,CAAC,CAAC;QACnE,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAClB,OAAO,CAAC,KAAK,CAAC,IAAA,qCAAsB,EAAC,MAAM,CAAC,CAAC,CAAC;QAC9C,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAClB,KAAK,MAAM,CAAC,IAAI,UAAU,EAAE,CAAC;YACzB,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;YACzC,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;QACvC,CAAC;QACD,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAClB,OAAO,CAAC,KAAK,CAAC,oBAAoB,IAAI,EAAE,CAAC,CAAC;QAC1C,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IACtB,CAAC;CAEJ,CAAA;AA7HY,8CAAiB;4BAAjB,iBAAiB;IAD7B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEG,sBAAS;GADxC,iBAAiB,CA6H7B","sourcesContent":["/**\n * Validate `match-rules` entries (client-authored content guards) at build time.\n *\n * A config-free, injected checker: the {@link CodeRulesEngine} injects ONE MatchRulesChecker and runs\n * it once per `match-rules` entry (config passed to the method), so there is no `new` of a DAG member.\n * `shouldRun` / mode / epoch apply per entry and the report shows the entry name. The regex matching +\n * allowedPath/test-file exemption is shared with the ai-hook engine via findMatchRuleViolations; this\n * adds diff-scoping (mode), the `// webpieces-disable <name>` filter, and the console report.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { hasDisable, MatchRuleConfig, MatchRuleViolation, findMatchRuleViolations, renderMatchRuleMessage, detectBase, getFileDiff, getChangedLineNumbers, shouldSkipRule } from \"@webpieces/rules-config\";\nimport { ModifiedCodeMode } from '@webpieces/rules-sdk';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { ExecutorResult } from './code-validator';\nimport { ScanScope } from './scan-scope';\n\nclass MatchViolation {\n readonly file: string;\n readonly line: number;\n readonly context: string;\n\n constructor(file: string, line: number, context: string) {\n this.file = file;\n this.line = line;\n this.context = context;\n }\n}\n\nexport class MatchViolationInfo {\n readonly line: number;\n readonly context: string;\n readonly hasDisableComment: boolean;\n\n constructor(line: number, context: string, hasDisableComment: boolean) {\n this.line = line;\n this.context = context;\n this.hasDisableComment = hasDisableComment;\n }\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class MatchRulesChecker {\n constructor(private readonly scanScope: ScanScope) {}\n\n /** True unless this entry is `mode: \"OFF\"` or skipped by a branch/epoch escape hatch. */\n shouldRun(config: MatchRuleConfig): boolean {\n if ((config.mode ?? 'OFF') === 'OFF') return false;\n return !shouldSkipRule(config.turnOffRuleUntilEpoch, config.turnOffRuleWhileOnBranch).skip;\n }\n\n /** Run one `match-rules` entry against the workspace (per-entry mode/diff-scoping/report). */\n async runForConfig(config: MatchRuleConfig, workspaceRoot: string): Promise<ExecutorResult> {\n const mode: ModifiedCodeMode = config.mode ?? 'OFF';\n if (mode === 'OFF') {\n console.log(`\\n⏭️ Skipping ${config.name} validation (mode: OFF)\\n`);\n return { success: true };\n }\n\n console.log(`\\n📏 Validating match-rule: ${config.name}\\n`);\n console.log(` Mode: ${mode}`);\n\n let base = process.env['NX_BASE'];\n const head = process.env['NX_HEAD'];\n if (!base) {\n base = await detectBase(workspaceRoot) ?? undefined;\n if (!base) {\n console.log(`\\n⏭️ Skipping ${config.name} validation (could not detect base branch)\\n`);\n return { success: true };\n }\n }\n\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}\\n`);\n\n const changedFiles = await this.scanScope.files(workspaceRoot, mode, base, head);\n if (changedFiles.length === 0) {\n console.log('✅ No TypeScript files changed');\n return { success: true };\n }\n\n console.log(`📂 Checking ${changedFiles.length} changed file(s)...`);\n const violations = this.scanScope.isLineScoped(mode)\n ? await this.findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, config)\n : this.findViolationsForModifiedFiles(workspaceRoot, changedFiles, config);\n\n if (violations.length === 0) {\n console.log(`✅ No ${config.name} violations found`);\n return { success: true };\n }\n\n this.scanScope.recordSites(config.name, violations.map((v: MatchViolation) => v.file));\n this.reportViolations(config, violations, mode);\n return { success: false };\n }\n\n findViolationsInFile(filePath: string, workspaceRoot: string, config: MatchRuleConfig): MatchViolationInfo[] {\n const fullPath = path.join(workspaceRoot, filePath);\n if (!fs.existsSync(fullPath)) return [];\n\n const content = fs.readFileSync(fullPath, 'utf-8');\n const lines = content.split('\\n');\n\n // Shared engine applies allowedPaths + test-file exemption and regex matching.\n const hits = findMatchRuleViolations(lines, filePath, config);\n const disableAllowed = config.disableAllowed ?? true;\n\n return hits.map((hit: MatchRuleViolation) => {\n const line = lines[hit.line - 1] ?? '';\n const prevLine = hit.line > 1 ? (lines[hit.line - 2] ?? '') : '';\n const disabled = hasDisable(line, config.name) || hasDisable(prevLine, config.name);\n return new MatchViolationInfo(hit.line, hit.context, disableAllowed && disabled);\n });\n }\n\n private async findViolationsForModifiedCode(\n workspaceRoot: string,\n changedFiles: string[],\n base: string,\n head: string | undefined,\n config: MatchRuleConfig,\n ): Promise<MatchViolation[]> {\n const violations: MatchViolation[] = [];\n for (const file of changedFiles) {\n const diff = await getFileDiff(workspaceRoot, file, base, head);\n const changedLines = getChangedLineNumbers(diff);\n if (changedLines.size === 0) continue;\n\n for (const v of this.findViolationsInFile(file, workspaceRoot, config)) {\n if (v.hasDisableComment) continue;\n if (!changedLines.has(v.line)) continue;\n violations.push(new MatchViolation(file, v.line, v.context));\n }\n }\n return violations;\n }\n\n private findViolationsForModifiedFiles(\n workspaceRoot: string,\n changedFiles: string[],\n config: MatchRuleConfig,\n ): MatchViolation[] {\n const violations: MatchViolation[] = [];\n for (const file of changedFiles) {\n for (const v of this.findViolationsInFile(file, workspaceRoot, config)) {\n if (v.hasDisableComment) continue;\n violations.push(new MatchViolation(file, v.line, v.context));\n }\n }\n return violations;\n }\n\n private reportViolations(config: MatchRuleConfig, violations: MatchViolation[], mode: ModifiedCodeMode): void {\n console.error('');\n console.error(`❌ [${config.name}] matched disallowed pattern(s)!`);\n console.error('');\n console.error(renderMatchRuleMessage(config));\n console.error('');\n for (const v of violations) {\n console.error(` ❌ ${v.file}:${v.line}`);\n console.error(` ${v.context}`);\n }\n console.error('');\n console.error(` Current mode: ${mode}`);\n console.error('');\n }\n\n}\n"]}
@@ -219,7 +219,7 @@ async function runValidatorImpl(options, workspaceRoot) {
219
219
  let base = process.env['NX_BASE'];
220
220
  const head = process.env['NX_HEAD'];
221
221
  if (!base) {
222
- base = (0, rules_config_1.detectBase)(workspaceRoot) ?? undefined;
222
+ base = await (0, rules_config_1.detectBase)(workspaceRoot) ?? undefined;
223
223
  if (!base) {
224
224
  console.log('\n\u23ed\ufe0f Skipping modified files validation (could not detect base branch)');
225
225
  console.log(' To run explicitly: nx affected --target=validate-modified-files --base=origin/main');
@@ -241,7 +241,7 @@ async function runValidatorImpl(options, workspaceRoot) {
241
241
  let violations;
242
242
  // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
243
243
  try {
244
- const changedFiles = (0, rules_config_1.getChangedFiles)(workspaceRoot, base, head);
244
+ const changedFiles = await (0, rules_config_1.getChangedFiles)(workspaceRoot, base, head);
245
245
  if (changedFiles.length === 0) {
246
246
  console.log('\u2705 No TypeScript files changed');
247
247
  return { success: true };
@@ -1 +1 @@
1
- {"version":3,"file":"validate-modified-files.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-modified-files.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;GAaG;;;AA6HH,wCA8CC;AAsBD,0CAgCC;;AA/ND,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA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,CAAC;QAE/E,UAAU,GAAG,cAAc,CAAC,aAAa,EAAE,YAAY,EAAE,KAAK,EAAE,cAAc,EAAE,WAAW,CAAC,CAAC;IACjG,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,6BAA6B;QAC7B,MAAM,KAAK,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;QAClE,OAAO,CAAC,KAAK,CAAC,0CAA0C,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QACzE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;IAED,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC1B,OAAO,CAAC,GAAG,CAAC,sCAAsC,GAAG,KAAK,GAAG,QAAQ,CAAC,CAAC;QACvE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7B,CAAC;IAED,oGAAoG;IACpG,oBAAoB,CAAC,aAAa,CAAC,CAAC;IACpC,MAAM,eAAe,CAAC,UAAU,EAAE,KAAK,EAAE,cAAc,CAAC,CAAC;AAC7D,CAAC;AAGM,IAAM,qBAAqB,GAA3B,MAAM,qBAAsB,SAAQ,8BAAiC;IACxE,YAAY,MAA0B;QAClC,KAAK,CAAC,MAAM,EAAE,gBAAgB,EAAE,gBAAgB,CAAC,CAAC;IACtD,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,aAAqB;QAC3B,OAAO,gBAAgB,CAAC,IAAI,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IACxD,CAAC;CACJ,CAAA;AARY,sDAAqB;gCAArB,qBAAqB;IADjC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEjB,iCAAkB;GAD7B,qBAAqB,CAQjC","sourcesContent":["/**\n * Validate Modified Files Executor\n *\n * Validates that modified files don't exceed a maximum line count (default 900).\n * This encourages keeping files small and focused - when you touch a file,\n * you must bring it under the limit.\n *\n * Usage:\n * nx affected --target=validate-modified-files --base=origin/main\n *\n * Escape hatch: Add webpieces-disable max-lines-modified-files comment with date and justification\n * Format: // webpieces-disable max-lines-modified-files 2025/01/15 -- [reason]\n * The disable expires after 1 month from the date specified.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { writeTemplate, hasDisable, detectBase, getChangedFiles, isPathExcluded, GENERATED_CODE_PATHS, RuleFailError, Option, TurnOffRuleCure } from \"@webpieces/rules-config\";\nimport { MaxFileLinesConfig } from \"./configs/rule-configs\";\nimport { FileLimitMode } from '@webpieces/rules-sdk';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { injectable, bindingScopeValues } from 'inversify';\n\n/** One over-limit file. A class, not an interface — findViolations is exported for its tests. */\nexport class FileViolation {\n readonly file: string;\n readonly lines: number;\n readonly expiredDisable: boolean;\n readonly expiredDate: string | undefined;\n\n constructor(file: string, lines: number, expiredDisable = false, expiredDate?: string) {\n this.file = file;\n this.lines = lines;\n this.expiredDisable = expiredDisable;\n this.expiredDate = expiredDate;\n }\n}\n\nconst TMP_MD_FILE = 'webpieces.filesize.md';\n\n\n/**\n * Write the instructions documentation to .webpieces/instruct-ai/.\n * Sourced from @webpieces/rules-config.\n */\nfunction writeTmpInstructions(workspaceRoot: string): string {\n return writeTemplate(workspaceRoot, TMP_MD_FILE);\n}\n\n/**\n * Parse a date string in yyyy/mm/dd format and return a Date object.\n * Returns null if the format is invalid.\n */\nfunction parseDisableDate(dateStr: string): Date | null {\n // Match yyyy/mm/dd format\n const match = dateStr.match(/^(\\d{4})\\/(\\d{2})\\/(\\d{2})$/);\n if (!match) return null;\n\n const year = parseInt(match[1], 10);\n const month = parseInt(match[2], 10) - 1; // JS months are 0-indexed\n const day = parseInt(match[3], 10);\n\n const date = new Date(year, month, day);\n\n // Validate the date is valid (e.g., not Feb 30)\n if (date.getFullYear() !== year || date.getMonth() !== month || date.getDate() !== day) {\n return null;\n }\n\n return date;\n}\n\n/**\n * Check if a date is within the last month (not expired).\n */\nfunction isDateWithinMonth(date: Date): boolean {\n const now = new Date();\n const oneMonthAgo = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());\n return date >= oneMonthAgo;\n}\n\ninterface DisableStatus {\n hasDisable: boolean;\n isValid: boolean;\n isExpired: boolean;\n date?: string;\n}\n\n/**\n * Check if a file has a valid, non-expired disable comment at the top (within first 5 lines).\n * Returns status object with details about the disable comment.\n */\n// webpieces-disable max-lines-new-methods -- Date validation logic requires checking multiple conditions\nfunction checkDisableComment(content: string): DisableStatus {\n const lines = content.split('\\n').slice(0, 5);\n\n for (const line of lines) {\n if (hasDisable(line, \"max-lines-modified-files\")) {\n // Found disable comment, now check for date\n // Format: // webpieces-disable max-lines-modified-files yyyy/mm/dd -- reason\n const dateMatch = line.match(/max-lines-modified-files\\s+(\\d{4}\\/\\d{2}\\/\\d{2}|XXXX\\/XX\\/XX)/);\n\n if (!dateMatch) {\n // No date found - invalid disable comment\n return { hasDisable: true, isValid: false, isExpired: false };\n }\n\n const dateStr = dateMatch[1];\n\n // Secret permanent disable\n if (dateStr === 'XXXX/XX/XX') {\n return { hasDisable: true, isValid: true, isExpired: false, date: dateStr };\n }\n\n const date = parseDisableDate(dateStr);\n if (!date) {\n // Invalid date format\n return { hasDisable: true, isValid: false, isExpired: false, date: dateStr };\n }\n\n if (!isDateWithinMonth(date)) {\n // Date is expired (older than 1 month)\n return { hasDisable: true, isValid: true, isExpired: true, date: dateStr };\n }\n\n // Valid and not expired\n return { hasDisable: true, isValid: true, isExpired: false, date: dateStr };\n }\n }\n\n return { hasDisable: false, isValid: false, isExpired: false };\n}\n\n/**\n * Count lines in a file and check for violations\n */\n// webpieces-disable max-lines-new-methods -- File iteration with disable checking logic\n// webpieces-disable no-function-outside-class -- pure scan over (files, limit, exemptPaths), sibling of the file-scoped helpers here\nexport function findViolations(workspaceRoot: string, changedFiles: string[], limit: number, disableAllowed: boolean, exemptPaths: readonly string[]): FileViolation[] {\n const violations: FileViolation[] = [];\n\n for (const file of changedFiles) {\n const fullPath = path.join(workspaceRoot, file);\n\n // Machine-generated trees: the file's size is not the repo's to fix. (A tree the repo lists in\n // excludePaths never reaches this list at all — the framework drops it from the file listing.)\n if (isPathExcluded(file, exemptPaths)) continue;\n\n if (!fs.existsSync(fullPath)) continue;\n\n const content = fs.readFileSync(fullPath, 'utf-8');\n const lineCount = content.split('\\n').length;\n\n // Skip files under the limit\n if (lineCount <= limit) continue;\n\n // When disableAllowed is false, ignore all disable comments\n if (!disableAllowed) {\n violations.push(new FileViolation(file, lineCount));\n continue;\n }\n\n // Check for disable comment\n const disableStatus = checkDisableComment(content);\n\n if (disableStatus.hasDisable) {\n if (disableStatus.isValid && !disableStatus.isExpired) {\n // Valid, non-expired disable - skip this file\n continue;\n }\n\n if (disableStatus.isExpired) {\n // Expired disable - report as violation with expired info\n violations.push(new FileViolation(file, lineCount, true, disableStatus.date));\n continue;\n }\n\n // Invalid disable (missing/bad date) - fall through to report as violation\n }\n\n violations.push(new FileViolation(file, lineCount));\n }\n\n return violations;\n}\n\n/**\n * Get today's date in yyyy/mm/dd format for error messages\n */\nfunction getTodayDateString(): string {\n const now = new Date();\n const year = now.getFullYear();\n const month = String(now.getMonth() + 1).padStart(2, '0');\n const day = String(now.getDate()).padStart(2, '0');\n return `${year}/${month}/${day}`;\n}\n\n/**\n * The ONE failure value for this rule: a `RuleFailError` carrying the prose for a human and the cures\n * as `Option[]`, which {@link RuleReporter} renders (it owns the \"Fix Option N:\" / \"(preferred)\"\n * labels, so nothing here hand-numbers a cure). This used to be a `console.error` paragraph beside a\n * `{ success: false }` return — a second spelling of \"this validator failed\" that the edit-time half of\n * the SAME rule never used.\n */\n// webpieces-disable max-lines-new-methods -- one message value assembled from several sections\n// webpieces-disable no-function-outside-class -- pure value builder, sibling of the file-scoped helpers here\nexport function violationsError(violations: readonly FileViolation[], limit: number, disableAllowed: boolean): RuleFailError {\n const listed = violations.map((v: FileViolation): string => v.expiredDisable\n ? ` ${v.file} (${v.lines} lines, max: ${limit})\\n EXPIRED DISABLE: the disable comment dated ${v.expiredDate ?? '?'} is over a month old — FIX the file or update the date for another month.`\n : ` ${v.file} (${v.lines} lines, max: ${limit})`).join('\\n');\n\n const message = [\n `YOU MUST FIX THIS AND NOT be more than ${limit} lines of code per file — it slows down IDEs and is VERY VERY EASY to refactor.`,\n '',\n 'With stateless systems + dependency injection, refactor is trivial: pick a method or a few and',\n 'move them to a new class XXXXX, inject XXXXX into all users of those methods via the constructor,',\n `then delete those methods from the original class. 99% of files can be less than ${limit} lines.`,\n '',\n listed,\n '',\n `disableAllowed is ${disableAllowed}${disableAllowed ? '' : ' — inline disable comments are IGNORED for this rule'}.`,\n ].join('\\n');\n\n const cures: Option[] = [\n new Option(`Refactor the file under ${limit} lines — READ .webpieces/instruct-ai/${TMP_MD_FILE} for step-by-step guidance.`, true),\n new Option('Is the file MACHINE-GENERATED (codegen output, a schema dump)? Its size is not yours to fix, and turning the rule off is the wrong cure — that stops it on hand-written files too. Add its tree to \"excludePaths\" in the max-file-lines entry (that rule only) or to the top-level \"excludePaths\" of webpieces.config.json (every rule), e.g. \"excludePaths\": [\"**/__generated__/**\"]. Never list hand-written code there.'),\n ];\n if (disableAllowed) {\n cures.push(new Option(`Put this on the FIRST 5 lines of the file (it expires in 1 month): // webpieces-disable max-lines-modified-files ${getTodayDateString()} -- [your reason]`));\n } else {\n // A HUMAN decision (never an AI agent's), and the branch hatch LEADS: a future epoch is REPO-WIDE (#1318).\n const entry = 'the \"max-file-lines\" entry in its owner rule file (the @webpieces/code-rules entry of \"rulePacks\" in webpieces.config.json, conventionally .webpieces-config/rules/code-rules.json)';\n const turnOff = new TurnOffRuleCure();\n cures.push(new Option(`For a major refactor a HUMAN — never an AI agent — may let files expand while each PR shrinks them as it touches them (e.g. porting legacy code into the repo). ${turnOff.byBranchText(entry)}`));\n cures.push(new Option(`(HUMAN only) ${turnOff.byEpochText(entry)}`));\n }\n\n return new RuleFailError('max-file-lines', message, undefined, undefined, cures);\n}\n\nasync function runValidatorImpl(\n options: MaxFileLinesConfig,\n workspaceRoot: string\n): Promise<ExecutorResult> {\n const limit = options.limit ?? 900;\n const disableAllowed = options.disableAllowed ?? true;\n // Machine-generated trees: a line-count rule firing on a file nobody authored is never a useful\n // signal, so this floor needs no configuration. The repo's own excludePaths are applied upstream.\n const exemptPaths = GENERATED_CODE_PATHS;\n\n const mode: FileLimitMode = options.mode ?? 'NEW_AND_MODIFIED_FILES';\n\n // Skip validation entirely if mode is OFF\n if (mode === 'OFF') {\n console.log(`\\n\\u23ed\\ufe0f Skipping modified files validation (mode: OFF)`);\n console.log('');\n return { success: true };\n }\n\n // If NX_HEAD is set (via nx affected --head=X), use it; otherwise compare to working tree\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 modified files validation (could not detect base branch)');\n console.log(' To run explicitly: nx affected --target=validate-modified-files --base=origin/main');\n console.log('');\n return { success: true };\n }\n\n console.log('\\n\\ud83d\\udccf Validating Modified File Sizes (auto-detected base)\\n');\n } else {\n console.log('\\n\\ud83d\\udccf Validating Modified File Sizes\\n');\n }\n\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);\n console.log(` Mode: ${mode}`);\n console.log(` Max lines for modified files: ${limit}`);\n console.log(` Disable allowed: ${disableAllowed}${!disableAllowed ? ' (no escape hatch)' : ''}`);\n console.log(` Exempt paths: ${exemptPaths.join(', ')}`);\n console.log('');\n\n let violations: FileViolation[];\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const changedFiles = getChangedFiles(workspaceRoot, 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 violations = findViolations(workspaceRoot, changedFiles, limit, disableAllowed, exemptPaths);\n } catch (err: unknown) {\n //const error = toError(err);\n const error = err instanceof Error ? err : new Error(String(err));\n console.error('\\u274c Modified files validation failed:', error.message);\n return { success: false };\n }\n\n if (violations.length === 0) {\n console.log('\\u2705 All modified files are under ' + limit + ' lines');\n return { success: true };\n }\n\n // The ONE failure path: throw, so RuleReporter renders the message and its cures for this audience.\n writeTmpInstructions(workspaceRoot);\n throw violationsError(violations, limit, disableAllowed);\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class MaxFileLinesValidator extends CodeValidator<MaxFileLinesConfig> {\n constructor(config: MaxFileLinesConfig) {\n super(config, 'max-file-lines', 'max-file-lines');\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runValidatorImpl(this.config, workspaceRoot);\n }\n}\n"]}
1
+ {"version":3,"file":"validate-modified-files.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-modified-files.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;GAaG;;;AA6HH,wCA8CC;AAsBD,0CAgCC;;AA/ND,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA+K;AAC/K,yDAA4D;AAE5D,qDAAiE;AACjE,yCAA2D;AAE3D,iGAAiG;AACjG,MAAa,aAAa;IACb,IAAI,CAAS;IACb,KAAK,CAAS;IACd,cAAc,CAAU;IACxB,WAAW,CAAqB;IAEzC,YAAY,IAAY,EAAE,KAAa,EAAE,cAAc,GAAG,KAAK,EAAE,WAAoB;QACjF,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;QACrC,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACnC,CAAC;CACJ;AAZD,sCAYC;AAED,MAAM,WAAW,GAAG,uBAAuB,CAAC;AAG5C;;;GAGG;AACH,SAAS,oBAAoB,CAAC,aAAq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C1B,OAAO,CAAC,GAAG,CAAC,sCAAsC,GAAG,KAAK,GAAG,QAAQ,CAAC,CAAC;QACvE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7B,CAAC;IAED,oGAAoG;IACpG,oBAAoB,CAAC,aAAa,CAAC,CAAC;IACpC,MAAM,eAAe,CAAC,UAAU,EAAE,KAAK,EAAE,cAAc,CAAC,CAAC;AAC7D,CAAC;AAGM,IAAM,qBAAqB,GAA3B,MAAM,qBAAsB,SAAQ,8BAAiC;IACxE,YAAY,MAA0B;QAClC,KAAK,CAAC,MAAM,EAAE,gBAAgB,EAAE,gBAAgB,CAAC,CAAC;IACtD,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,aAAqB;QAC3B,OAAO,gBAAgB,CAAC,IAAI,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IACxD,CAAC;CACJ,CAAA;AARY,sDAAqB;gCAArB,qBAAqB;IADjC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEjB,iCAAkB;GAD7B,qBAAqB,CAQjC","sourcesContent":["/**\n * Validate Modified Files Executor\n *\n * Validates that modified files don't exceed a maximum line count (default 900).\n * This encourages keeping files small and focused - when you touch a file,\n * you must bring it under the limit.\n *\n * Usage:\n * nx affected --target=validate-modified-files --base=origin/main\n *\n * Escape hatch: Add webpieces-disable max-lines-modified-files comment with date and justification\n * Format: // webpieces-disable max-lines-modified-files 2025/01/15 -- [reason]\n * The disable expires after 1 month from the date specified.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { writeTemplate, hasDisable, detectBase, getChangedFiles, isPathExcluded, GENERATED_CODE_PATHS, RuleFailError, Option, TurnOffRuleCure } from \"@webpieces/rules-config\";\nimport { MaxFileLinesConfig } from \"./configs/rule-configs\";\nimport { FileLimitMode } from '@webpieces/rules-sdk';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { injectable, bindingScopeValues } from 'inversify';\n\n/** One over-limit file. A class, not an interface — findViolations is exported for its tests. */\nexport class FileViolation {\n readonly file: string;\n readonly lines: number;\n readonly expiredDisable: boolean;\n readonly expiredDate: string | undefined;\n\n constructor(file: string, lines: number, expiredDisable = false, expiredDate?: string) {\n this.file = file;\n this.lines = lines;\n this.expiredDisable = expiredDisable;\n this.expiredDate = expiredDate;\n }\n}\n\nconst TMP_MD_FILE = 'webpieces.filesize.md';\n\n\n/**\n * Write the instructions documentation to .webpieces/instruct-ai/.\n * Sourced from @webpieces/rules-config.\n */\nfunction writeTmpInstructions(workspaceRoot: string): string {\n return writeTemplate(workspaceRoot, TMP_MD_FILE);\n}\n\n/**\n * Parse a date string in yyyy/mm/dd format and return a Date object.\n * Returns null if the format is invalid.\n */\nfunction parseDisableDate(dateStr: string): Date | null {\n // Match yyyy/mm/dd format\n const match = dateStr.match(/^(\\d{4})\\/(\\d{2})\\/(\\d{2})$/);\n if (!match) return null;\n\n const year = parseInt(match[1], 10);\n const month = parseInt(match[2], 10) - 1; // JS months are 0-indexed\n const day = parseInt(match[3], 10);\n\n const date = new Date(year, month, day);\n\n // Validate the date is valid (e.g., not Feb 30)\n if (date.getFullYear() !== year || date.getMonth() !== month || date.getDate() !== day) {\n return null;\n }\n\n return date;\n}\n\n/**\n * Check if a date is within the last month (not expired).\n */\nfunction isDateWithinMonth(date: Date): boolean {\n const now = new Date();\n const oneMonthAgo = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());\n return date >= oneMonthAgo;\n}\n\ninterface DisableStatus {\n hasDisable: boolean;\n isValid: boolean;\n isExpired: boolean;\n date?: string;\n}\n\n/**\n * Check if a file has a valid, non-expired disable comment at the top (within first 5 lines).\n * Returns status object with details about the disable comment.\n */\n// webpieces-disable max-lines-new-methods -- Date validation logic requires checking multiple conditions\nfunction checkDisableComment(content: string): DisableStatus {\n const lines = content.split('\\n').slice(0, 5);\n\n for (const line of lines) {\n if (hasDisable(line, \"max-lines-modified-files\")) {\n // Found disable comment, now check for date\n // Format: // webpieces-disable max-lines-modified-files yyyy/mm/dd -- reason\n const dateMatch = line.match(/max-lines-modified-files\\s+(\\d{4}\\/\\d{2}\\/\\d{2}|XXXX\\/XX\\/XX)/);\n\n if (!dateMatch) {\n // No date found - invalid disable comment\n return { hasDisable: true, isValid: false, isExpired: false };\n }\n\n const dateStr = dateMatch[1];\n\n // Secret permanent disable\n if (dateStr === 'XXXX/XX/XX') {\n return { hasDisable: true, isValid: true, isExpired: false, date: dateStr };\n }\n\n const date = parseDisableDate(dateStr);\n if (!date) {\n // Invalid date format\n return { hasDisable: true, isValid: false, isExpired: false, date: dateStr };\n }\n\n if (!isDateWithinMonth(date)) {\n // Date is expired (older than 1 month)\n return { hasDisable: true, isValid: true, isExpired: true, date: dateStr };\n }\n\n // Valid and not expired\n return { hasDisable: true, isValid: true, isExpired: false, date: dateStr };\n }\n }\n\n return { hasDisable: false, isValid: false, isExpired: false };\n}\n\n/**\n * Count lines in a file and check for violations\n */\n// webpieces-disable max-lines-new-methods -- File iteration with disable checking logic\n// webpieces-disable no-function-outside-class -- pure scan over (files, limit, exemptPaths), sibling of the file-scoped helpers here\nexport function findViolations(workspaceRoot: string, changedFiles: string[], limit: number, disableAllowed: boolean, exemptPaths: readonly string[]): FileViolation[] {\n const violations: FileViolation[] = [];\n\n for (const file of changedFiles) {\n const fullPath = path.join(workspaceRoot, file);\n\n // Machine-generated trees: the file's size is not the repo's to fix. (A tree the repo lists in\n // excludePaths never reaches this list at all — the framework drops it from the file listing.)\n if (isPathExcluded(file, exemptPaths)) continue;\n\n if (!fs.existsSync(fullPath)) continue;\n\n const content = fs.readFileSync(fullPath, 'utf-8');\n const lineCount = content.split('\\n').length;\n\n // Skip files under the limit\n if (lineCount <= limit) continue;\n\n // When disableAllowed is false, ignore all disable comments\n if (!disableAllowed) {\n violations.push(new FileViolation(file, lineCount));\n continue;\n }\n\n // Check for disable comment\n const disableStatus = checkDisableComment(content);\n\n if (disableStatus.hasDisable) {\n if (disableStatus.isValid && !disableStatus.isExpired) {\n // Valid, non-expired disable - skip this file\n continue;\n }\n\n if (disableStatus.isExpired) {\n // Expired disable - report as violation with expired info\n violations.push(new FileViolation(file, lineCount, true, disableStatus.date));\n continue;\n }\n\n // Invalid disable (missing/bad date) - fall through to report as violation\n }\n\n violations.push(new FileViolation(file, lineCount));\n }\n\n return violations;\n}\n\n/**\n * Get today's date in yyyy/mm/dd format for error messages\n */\nfunction getTodayDateString(): string {\n const now = new Date();\n const year = now.getFullYear();\n const month = String(now.getMonth() + 1).padStart(2, '0');\n const day = String(now.getDate()).padStart(2, '0');\n return `${year}/${month}/${day}`;\n}\n\n/**\n * The ONE failure value for this rule: a `RuleFailError` carrying the prose for a human and the cures\n * as `Option[]`, which {@link RuleReporter} renders (it owns the \"Fix Option N:\" / \"(preferred)\"\n * labels, so nothing here hand-numbers a cure). This used to be a `console.error` paragraph beside a\n * `{ success: false }` return — a second spelling of \"this validator failed\" that the edit-time half of\n * the SAME rule never used.\n */\n// webpieces-disable max-lines-new-methods -- one message value assembled from several sections\n// webpieces-disable no-function-outside-class -- pure value builder, sibling of the file-scoped helpers here\nexport function violationsError(violations: readonly FileViolation[], limit: number, disableAllowed: boolean): RuleFailError {\n const listed = violations.map((v: FileViolation): string => v.expiredDisable\n ? ` ${v.file} (${v.lines} lines, max: ${limit})\\n EXPIRED DISABLE: the disable comment dated ${v.expiredDate ?? '?'} is over a month old — FIX the file or update the date for another month.`\n : ` ${v.file} (${v.lines} lines, max: ${limit})`).join('\\n');\n\n const message = [\n `YOU MUST FIX THIS AND NOT be more than ${limit} lines of code per file — it slows down IDEs and is VERY VERY EASY to refactor.`,\n '',\n 'With stateless systems + dependency injection, refactor is trivial: pick a method or a few and',\n 'move them to a new class XXXXX, inject XXXXX into all users of those methods via the constructor,',\n `then delete those methods from the original class. 99% of files can be less than ${limit} lines.`,\n '',\n listed,\n '',\n `disableAllowed is ${disableAllowed}${disableAllowed ? '' : ' — inline disable comments are IGNORED for this rule'}.`,\n ].join('\\n');\n\n const cures: Option[] = [\n new Option(`Refactor the file under ${limit} lines — READ .webpieces/instruct-ai/${TMP_MD_FILE} for step-by-step guidance.`, true),\n new Option('Is the file MACHINE-GENERATED (codegen output, a schema dump)? Its size is not yours to fix, and turning the rule off is the wrong cure — that stops it on hand-written files too. Add its tree to \"excludePaths\" in the max-file-lines entry (that rule only) or to the top-level \"excludePaths\" of webpieces.config.json (every rule), e.g. \"excludePaths\": [\"**/__generated__/**\"]. Never list hand-written code there.'),\n ];\n if (disableAllowed) {\n cures.push(new Option(`Put this on the FIRST 5 lines of the file (it expires in 1 month): // webpieces-disable max-lines-modified-files ${getTodayDateString()} -- [your reason]`));\n } else {\n // A HUMAN decision (never an AI agent's), and the branch hatch LEADS: a future epoch is REPO-WIDE (#1318).\n const entry = 'the \"max-file-lines\" entry in its owner rule file (the @webpieces/code-rules entry of \"rulePacks\" in webpieces.config.json, conventionally .webpieces-config/rules/code-rules.json)';\n const turnOff = new TurnOffRuleCure();\n cures.push(new Option(`For a major refactor a HUMAN — never an AI agent — may let files expand while each PR shrinks them as it touches them (e.g. porting legacy code into the repo). ${turnOff.byBranchText(entry)}`));\n cures.push(new Option(`(HUMAN only) ${turnOff.byEpochText(entry)}`));\n }\n\n return new RuleFailError('max-file-lines', message, undefined, undefined, cures);\n}\n\nasync function runValidatorImpl(\n options: MaxFileLinesConfig,\n workspaceRoot: string\n): Promise<ExecutorResult> {\n const limit = options.limit ?? 900;\n const disableAllowed = options.disableAllowed ?? true;\n // Machine-generated trees: a line-count rule firing on a file nobody authored is never a useful\n // signal, so this floor needs no configuration. The repo's own excludePaths are applied upstream.\n const exemptPaths = GENERATED_CODE_PATHS;\n\n const mode: FileLimitMode = options.mode ?? 'NEW_AND_MODIFIED_FILES';\n\n // Skip validation entirely if mode is OFF\n if (mode === 'OFF') {\n console.log(`\\n\\u23ed\\ufe0f Skipping modified files validation (mode: OFF)`);\n console.log('');\n return { success: true };\n }\n\n // If NX_HEAD is set (via nx affected --head=X), use it; otherwise compare to working tree\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 modified files validation (could not detect base branch)');\n console.log(' To run explicitly: nx affected --target=validate-modified-files --base=origin/main');\n console.log('');\n return { success: true };\n }\n\n console.log('\\n\\ud83d\\udccf Validating Modified File Sizes (auto-detected base)\\n');\n } else {\n console.log('\\n\\ud83d\\udccf Validating Modified File Sizes\\n');\n }\n\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);\n console.log(` Mode: ${mode}`);\n console.log(` Max lines for modified files: ${limit}`);\n console.log(` Disable allowed: ${disableAllowed}${!disableAllowed ? ' (no escape hatch)' : ''}`);\n console.log(` Exempt paths: ${exemptPaths.join(', ')}`);\n console.log('');\n\n let violations: FileViolation[];\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const changedFiles = await getChangedFiles(workspaceRoot, 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 violations = findViolations(workspaceRoot, changedFiles, limit, disableAllowed, exemptPaths);\n } catch (err: unknown) {\n //const error = toError(err);\n const error = err instanceof Error ? err : new Error(String(err));\n console.error('\\u274c Modified files validation failed:', error.message);\n return { success: false };\n }\n\n if (violations.length === 0) {\n console.log('\\u2705 All modified files are under ' + limit + ' lines');\n return { success: true };\n }\n\n // The ONE failure path: throw, so RuleReporter renders the message and its cures for this audience.\n writeTmpInstructions(workspaceRoot);\n throw violationsError(violations, limit, disableAllowed);\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class MaxFileLinesValidator extends CodeValidator<MaxFileLinesConfig> {\n constructor(config: MaxFileLinesConfig) {\n super(config, 'max-file-lines', 'max-file-lines');\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runValidatorImpl(this.config, workspaceRoot);\n }\n}\n"]}
@@ -255,10 +255,11 @@ function checkModifiedMethodViolation(file, method, disableAllowed) {
255
255
  * Find methods that exceed the limit.
256
256
  * Checks NEW methods with escape hatches and MODIFIED methods.
257
257
  */
258
- function findViolations(workspaceRoot, changedFiles, base, limit, disableAllowed, head) {
258
+ // webpieces-disable no-function-outside-class -- pre-existing module helper, made async only because DiffScope now reaches git through the injected process edge (#1381)
259
+ async function findViolations(workspaceRoot, changedFiles, base, limit, disableAllowed, head) {
259
260
  const violations = [];
260
261
  for (const file of changedFiles) {
261
- const diff = (0, rules_config_1.getFileDiff)(workspaceRoot, file, base, head);
262
+ const diff = await (0, rules_config_1.getFileDiff)(workspaceRoot, file, base, head);
262
263
  if (!diff)
263
264
  continue;
264
265
  const newMethodNames = (0, rules_config_1.findNewMethodSignaturesInDiff)(diff);
@@ -368,7 +369,7 @@ async function runModifiedMethods(options, workspaceRoot) {
368
369
  let base = process.env['NX_BASE'];
369
370
  const head = process.env['NX_HEAD'];
370
371
  if (!base) {
371
- base = (0, rules_config_1.detectBase)(workspaceRoot) ?? undefined;
372
+ base = await (0, rules_config_1.detectBase)(workspaceRoot) ?? undefined;
372
373
  if (!base) {
373
374
  console.log('\n\u23ed\ufe0f Skipping modified method validation (could not detect base branch)');
374
375
  console.log(' To run explicitly: nx affected --target=validate-modified-methods --base=origin/main');
@@ -388,13 +389,13 @@ async function runModifiedMethods(options, workspaceRoot) {
388
389
  console.log('');
389
390
  // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
390
391
  try {
391
- const changedFiles = (0, rules_config_1.getChangedFiles)(workspaceRoot, base, head);
392
+ const changedFiles = await (0, rules_config_1.getChangedFiles)(workspaceRoot, base, head);
392
393
  if (changedFiles.length === 0) {
393
394
  console.log('\u2705 No TypeScript files changed');
394
395
  return { success: true };
395
396
  }
396
397
  console.log(`\ud83d\udcc2 Checking ${changedFiles.length} changed file(s)...`);
397
- const violations = findViolations(workspaceRoot, changedFiles, base, limit, disableAllowed, head);
398
+ const violations = await findViolations(workspaceRoot, changedFiles, base, limit, disableAllowed, head);
398
399
  if (violations.length === 0) {
399
400
  console.log('\u2705 All modified methods are under ' + limit + ' lines');
400
401
  return { success: true };