@webpieces/code-rules 0.4.927 → 0.4.929
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.
- package/package.json +6 -6
- package/src/api-lib-source-rule.d.ts +1 -1
- package/src/api-lib-source-rule.js +1 -3
- package/src/api-lib-source-rule.js.map +1 -1
- package/src/code-policy-composition.js +10 -1
- package/src/code-policy-composition.js.map +1 -1
- package/src/code-rules-bootstrap.js +1 -1
- package/src/code-rules-bootstrap.js.map +1 -1
- package/src/code-rules-engine.d.ts +3 -1
- package/src/code-rules-engine.js +13 -4
- package/src/code-rules-engine.js.map +1 -1
- package/src/configs/api-lib-spelling-configs.d.ts +2 -4
- package/src/configs/api-lib-spelling-configs.js +2 -8
- package/src/configs/api-lib-spelling-configs.js.map +1 -1
- package/src/configs/no-client-creation-config.d.ts +0 -1
- package/src/configs/no-client-creation-config.js +1 -4
- package/src/configs/no-client-creation-config.js.map +1 -1
- package/src/configs/no-state-paths-config.js +0 -1
- package/src/configs/no-state-paths-config.js.map +1 -1
- package/src/configs/no-utility-types-config.d.ts +1 -2
- package/src/configs/no-utility-types-config.js +1 -4
- package/src/configs/no-utility-types-config.js.map +1 -1
- package/src/configs/required-type-suffix-config.d.ts +1 -2
- package/src/configs/required-type-suffix-config.js +1 -4
- package/src/configs/required-type-suffix-config.js.map +1 -1
- package/src/configs/rule-configs.d.ts +0 -5
- package/src/configs/rule-configs.js +13 -44
- package/src/configs/rule-configs.js.map +1 -1
- package/src/configs/tag-truth-configs.d.ts +4 -2
- package/src/configs/tag-truth-configs.js +4 -4
- package/src/configs/tag-truth-configs.js.map +1 -1
- package/src/index.d.ts +1 -0
- package/src/index.js +7 -2
- package/src/index.js.map +1 -1
- package/src/rule-dispatch.d.ts +30 -0
- package/src/rule-dispatch.js +49 -0
- package/src/rule-dispatch.js.map +1 -0
- package/src/rule-migrations.d.ts +17 -0
- package/src/rule-migrations.js +40 -0
- package/src/rule-migrations.js.map +1 -0
- package/src/rule-pack.js +2 -1
- package/src/rule-pack.js.map +1 -1
- package/src/scan-scope.js +4 -1
- package/src/scan-scope.js.map +1 -1
- package/src/tag-rule.js +1 -14
- package/src/tag-rule.js.map +1 -1
- package/src/validate-catch-error-pattern.js +1 -17
- package/src/validate-catch-error-pattern.js.map +1 -1
- package/src/validate-dtos.js +1 -18
- package/src/validate-dtos.js.map +1 -1
- package/src/validate-ensure-we-are-secure.js +3 -0
- package/src/validate-ensure-we-are-secure.js.map +1 -1
- package/src/validate-framework-packages.js +3 -1
- package/src/validate-framework-packages.js.map +1 -1
- package/src/validate-inject-annotation-not-needed-for-concrete-class.d.ts +1 -1
- package/src/validate-inject-annotation-not-needed-for-concrete-class.js +10 -25
- package/src/validate-inject-annotation-not-needed-for-concrete-class.js.map +1 -1
- package/src/validate-match-rules.d.ts +0 -1
- package/src/validate-match-rules.js +1 -12
- package/src/validate-match-rules.js.map +1 -1
- package/src/validate-modified-files.d.ts +0 -7
- package/src/validate-modified-files.js +8 -22
- package/src/validate-modified-files.js.map +1 -1
- package/src/validate-modified-methods.js +2 -6
- package/src/validate-modified-methods.js.map +1 -1
- package/src/validate-new-methods.js +2 -6
- package/src/validate-new-methods.js.map +1 -1
- package/src/validate-no-any-unknown.js +1 -18
- package/src/validate-no-any-unknown.js.map +1 -1
- package/src/validate-no-client-creation-outside-server-or-client.d.ts +2 -3
- package/src/validate-no-client-creation-outside-server-or-client.js +4 -18
- package/src/validate-no-client-creation-outside-server-or-client.js.map +1 -1
- package/src/validate-no-custom-css.d.ts +0 -1
- package/src/validate-no-custom-css.js +1 -12
- package/src/validate-no-custom-css.js.map +1 -1
- package/src/validate-no-destructure.d.ts +3 -3
- package/src/validate-no-destructure.js +11 -31
- package/src/validate-no-destructure.js.map +1 -1
- package/src/validate-no-direct-api-resolver.js +1 -18
- package/src/validate-no-direct-api-resolver.js.map +1 -1
- package/src/validate-no-function-outside-class.d.ts +3 -3
- package/src/validate-no-function-outside-class.js +11 -25
- package/src/validate-no-function-outside-class.js.map +1 -1
- package/src/validate-no-implicit-any.js +1 -14
- package/src/validate-no-implicit-any.js.map +1 -1
- package/src/validate-no-inline-types.js +1 -18
- package/src/validate-no-inline-types.js.map +1 -1
- package/src/validate-no-process-exit-outside-main.js +1 -12
- package/src/validate-no-process-exit-outside-main.js.map +1 -1
- package/src/validate-no-state-paths-in-templates.d.ts +0 -1
- package/src/validate-no-state-paths-in-templates.js +1 -12
- package/src/validate-no-state-paths-in-templates.js.map +1 -1
- package/src/validate-no-symbol-di-tokens.d.ts +2 -2
- package/src/validate-no-symbol-di-tokens.js +9 -65
- package/src/validate-no-symbol-di-tokens.js.map +1 -1
- package/src/validate-no-unmanaged-exceptions.js +1 -17
- package/src/validate-no-unmanaged-exceptions.js.map +1 -1
- package/src/validate-prisma-converters.js +1 -18
- package/src/validate-prisma-converters.js.map +1 -1
- package/src/validate-return-types.js +1 -18
- package/src/validate-return-types.js.map +1 -1
- package/src/resolve-mode.d.ts +0 -2
- package/src/resolve-mode.js +0 -11
- package/src/resolve-mode.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validate-framework-packages.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-framework-packages.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAmHH,wDAiBC;;AAlID,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA4F;AAC5F,mEAA8F;AAC9F,yCAA2D;AAC3D,qDAAiE;AACjE,iEAA4E;AAE5E,2DAA2D;AAC3D,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,CAAC,cAAc,EAAE,MAAM,EAAE,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC;AAC1G,+DAA+D;AAC/D,MAAM,SAAS,GAAG,+EAA+E,CAAC;AAElG,mFAAmF;AACnF,MAAa,yBAAyB;IAErB;IACA;IACA;IAEA;IAEA;IAPb,Y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AI,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,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,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,CAAC,aAAa,EAAE,QAAQ,CAAC,CAAC;QAClG,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-packages` (#1064, D8) — a framework package is imported only by a project whose EVERY\n * `framework:` tag is one its config entry allows: `@angular/*` only in angular projects, `react` /\n * `react-native` / `expo*` only in react / react-native projects, `express` and the node-only SDKs\n * (`firebase-admin`, `googleapis`, `@google-cloud/*`) only in node / express projects, the browser\n * `firebase` SDK only in browser projects.\n *\n * \"Every\" is the point: a `browser+node` library importing `firebase-admin` is refused, because its\n * browser half cannot run it — the same reading `library-types-match-client` gives an env SET.\n *\n * The package list is the CONSUMER's (required, no default — `.claude/rules/no-rule-defaults.md`);\n * webpieces seeds and documents the recommended one (`.claude/rules/framework-tags.md`). Only\n * production source is read: a spec importing `express` to stand up a fake server is not the runtime.\n * A package no entry names is not judged. The per-site hatch is\n * `// webpieces-disable framework-packages -- <reason>` on the import line or the line above it.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { hasDisable, matchesAnyGlob, Option, RuleFailError } from \"@webpieces/rules-config\";\nimport { FrameworkPackagesConfig, FrameworkPackagesEntry } from \"./configs/tag-truth-configs\";\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { ProjectScanTargets, ScannedProject } from './project-scan-targets';\n\n/** Directories never read: build output, vendored code. */\nconst SKIP_DIRS = new Set(['node_modules', 'dist', 'build', 'out-tsc', 'coverage', '.nx', '.git', 'tmp']);\n/** `from '…'`, `import '…'`, `require('…')`, `import('…')`. */\nconst IMPORT_RE = /(?:\\bfrom\\s*|\\bimport\\s*|\\brequire\\s*\\(\\s*|\\bimport\\s*\\(\\s*)['\"]([^'\"]+)['\"]/g;\n\n/** ONE project importing a framework package its runtime cannot run. Data-only. */\nexport class FrameworkPackageViolation {\n constructor(\n readonly project: string,\n readonly frameworks: readonly string[],\n readonly packageName: string,\n /** `path/to/File.ts:LINE`, repo-relative — the first import found. */\n readonly at: string,\n /** The framework tags an entry allows for that package. */\n readonly allowed: readonly string[],\n ) {}\n}\n\n/** The audit itself — no config, no git: projects and entries in, violations out. */\nexport class FrameworkPackagesAudit {\n constructor(private readonly entries: readonly FrameworkPackagesEntry[]) {}\n\n audit(workspaceRoot: string, projects: readonly ScannedProject[]): FrameworkPackageViolation[] {\n const out: FrameworkPackageViolation[] = [];\n const nestedRoots = new Set(projects.map((p: ScannedProject) => p.dir));\n for (const project of projects) {\n if (project.frameworks.length === 0) continue; // framework-tag's job\n const seen = new Set<string>();\n for (const site of this.importsOf(workspaceRoot, project.dir, nestedRoots)) {\n if (seen.has(site.packageName)) continue;\n const matching = this.entries.filter((e: FrameworkPackagesEntry) => matchesAnyGlob(site.packageName, e.packages));\n if (matching.length === 0) continue;\n const ok = matching.some((e: FrameworkPackagesEntry) =>\n project.frameworks.every((env: string) => e.frameworks.includes(env)));\n if (ok) continue;\n seen.add(site.packageName);\n const allowed = Array.from(new Set(matching.flatMap((e: FrameworkPackagesEntry) => e.frameworks)));\n out.push(new FrameworkPackageViolation(project.name, project.frameworks, site.packageName, site.at, allowed));\n }\n }\n return out;\n }\n\n /** Every bare-package import in a project's production source, nested projects excluded. */\n private importsOf(workspaceRoot: string, dir: string, projectDirs: ReadonlySet<string>): ImportSite[] {\n const sites: ImportSite[] = [];\n const walk = (absDir: string): void => {\n for (const entry of fs.readdirSync(absDir, { withFileTypes: true })) {\n const abs = path.join(absDir, entry.name);\n const rel = path.relative(workspaceRoot, abs).split(path.sep).join('/');\n if (entry.isDirectory()) {\n if (SKIP_DIRS.has(entry.name) || entry.name === '__tests__' || projectDirs.has(rel)) continue;\n if (fs.existsSync(path.join(abs, 'project.json'))) continue; // a nested project is judged on its own\n walk(abs);\n } else if (/\\.(ts|tsx|mts|cts)$/.test(entry.name) && !/\\.d\\.ts$/.test(entry.name) && !this.isTestFile(entry.name)) {\n sites.push(...this.sitesIn(abs, rel));\n }\n }\n };\n const root = path.join(workspaceRoot, dir);\n if (fs.existsSync(root)) walk(root);\n return sites;\n }\n\n private isTestFile(name: string): boolean {\n return /\\.(spec|test)\\.[cm]?tsx?$/.test(name) || /^test-setup\\./.test(name) || /\\.config\\.[cm]?ts$/.test(name);\n }\n\n private sitesIn(abs: string, rel: string): ImportSite[] {\n const lines = fs.readFileSync(abs, 'utf-8').split('\\n');\n const sites: ImportSite[] = [];\n lines.forEach((line: string, index: number) => {\n IMPORT_RE.lastIndex = 0;\n let match = IMPORT_RE.exec(line);\n while (match !== null) {\n const pkg = this.packageNameOf(match[1]);\n const disabled =\n hasDisable(line, \"framework-packages\") ||\n (index > 0 && hasDisable(lines[index - 1], \"framework-packages\"));\n if (pkg !== null && !disabled) sites.push(new ImportSite(pkg, `${rel}:${index + 1}`));\n match = IMPORT_RE.exec(line);\n }\n });\n return sites;\n }\n\n /** `@scope/pkg/sub` → `@scope/pkg`; `pkg/sub` → `pkg`; relative paths and `node:` builtins → null. */\n private packageNameOf(specifier: string): string | null {\n if (specifier === '' || specifier.startsWith('.') || specifier.startsWith('/') || specifier.startsWith('node:')) return null;\n const parts = specifier.split('/');\n if (specifier.startsWith('@')) return parts.length < 2 ? null : `${parts[0]}/${parts[1]}`;\n return parts[0];\n }\n}\n\n/** One import of a bare package. Data-only. */\nclass ImportSite {\n constructor(\n readonly packageName: string,\n readonly at: string,\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 frameworkPackagesError(violations: readonly FrameworkPackageViolation[]): RuleFailError {\n const details = violations\n .map((v: FrameworkPackageViolation) =>\n ` ${v.at} — ${v.project} [${v.frameworks.join(', ')}] imports '${v.packageName}', ` +\n `which only [${v.allowed.join(', ')}] projects may import`)\n .join('\\n');\n return new RuleFailError(\n \"framework-packages\",\n 'A project imports a framework package that one of the runtimes its framework tags promise cannot run.\\n' + details,\n undefined,\n undefined,\n [\n new Option('Move the code that needs the package into a project whose framework tags are all ones the package runs on, and depend on that project behind an api-lib contract.', true),\n new Option('If the project really runs only where the package does, the TAGS are wrong: narrow its framework tags (and move it to that runtime\\'s folder).'),\n new Option('For one import that is genuinely safe, put `// webpieces-disable framework-packages -- <reason>` on the line above it.'),\n ],\n );\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class FrameworkPackagesValidator extends CodeValidator<FrameworkPackagesConfig> {\n constructor(\n config: FrameworkPackagesConfig,\n private readonly targets: ProjectScanTargets,\n ) {\n super(config, \"framework-packages\", \"framework-packages\");\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-packages\")\n .filter((p: ScannedProject) => !matchesAnyGlob(p.dir, allowed));\n const violations = new FrameworkPackagesAudit(this.config.entries).audit(workspaceRoot, projects);\n if (violations.length === 0) return { success: true };\n throw frameworkPackagesError(violations);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"validate-framework-packages.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-framework-packages.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAqHH,wDAiBC;;AApID,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA2G;AAC3G,mEAA8F;AAC9F,yCAA2D;AAC3D,qDAAiE;AACjE,iEAA4E;AAE5E,2DAA2D;AAC3D,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,CAAC,cAAc,EAAE,MAAM,EAAE,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC;AAC1G,+DAA+D;AAC/D,MAAM,SAAS,GAAG,+EAA+E,CAAC;AAElG,mFAAmF;AACnF,MAAa,yBAAyB;IAErB;IACA;IACA;IAEA;IAEA;IAPb,YACa,OAAe,EACf,UAA6B,EAC7B,WAAmB;IAC5B,sEAAsE;IAC7D,EAAU;IACnB,2DAA2D;IAClD,OAA0B;QAN1B,YAAO,GAAP,OAAO,CAAQ;QACf,eAAU,GAAV,UAAU,CAAmB;QAC7B,gBAAW,GAAX,WAAW,CAAQ;QAEnB,OAAE,GAAF,EAAE,CAAQ;QAEV,YAAO,GAAP,OAAO,CAAmB;IACpC,CAAC;CACP;AAVD,8DAUC;AAED,qFAAqF;AACrF,MAAa,sBAAsB;IACF;IAA7B,YAA6B,OAA0C;QAA1C,YAAO,GAAP,OAAO,CAAmC;IAAG,CAAC;IAE3E,KAAK,CAAC,aAAqB,EAAE,QAAmC;QAC5D,MAAM,GAAG,GAAgC,EAAE,CAAC;QAC5C,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAA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CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,CAAC,aAAa,EAAE,QAAQ,CAAC,CAAC;QAClG,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-packages` (#1064, D8) — a framework package is imported only by a project whose EVERY\n * `framework:` tag is one its config entry allows: `@angular/*` only in angular projects, `react` /\n * `react-native` / `expo*` only in react / react-native projects, `express` and the node-only SDKs\n * (`firebase-admin`, `googleapis`, `@google-cloud/*`) only in node / express projects, the browser\n * `firebase` SDK only in browser projects.\n *\n * \"Every\" is the point: a `browser+node` library importing `firebase-admin` is refused, because its\n * browser half cannot run it — the same reading `library-types-match-client` gives an env SET.\n *\n * The package list is the CONSUMER's (required, no default — `.claude/rules/no-rule-defaults.md`);\n * webpieces seeds and documents the recommended one (`.claude/rules/framework-tags.md`). Only\n * production source is read: a spec importing `express` to stand up a fake server is not the runtime.\n * A package no entry names is not judged. The per-site hatch is\n * `// webpieces-disable framework-packages -- <reason>` on the import line or the line above it.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { hasDisable, matchesAnyGlob, Option, RuleFailError, RuleFileScope } from \"@webpieces/rules-config\";\nimport { FrameworkPackagesConfig, FrameworkPackagesEntry } from \"./configs/tag-truth-configs\";\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { ProjectScanTargets, ScannedProject } from './project-scan-targets';\n\n/** Directories never read: build output, vendored code. */\nconst SKIP_DIRS = new Set(['node_modules', 'dist', 'build', 'out-tsc', 'coverage', '.nx', '.git', 'tmp']);\n/** `from '…'`, `import '…'`, `require('…')`, `import('…')`. */\nconst IMPORT_RE = /(?:\\bfrom\\s*|\\bimport\\s*|\\brequire\\s*\\(\\s*|\\bimport\\s*\\(\\s*)['\"]([^'\"]+)['\"]/g;\n\n/** ONE project importing a framework package its runtime cannot run. Data-only. */\nexport class FrameworkPackageViolation {\n constructor(\n readonly project: string,\n readonly frameworks: readonly string[],\n readonly packageName: string,\n /** `path/to/File.ts:LINE`, repo-relative — the first import found. */\n readonly at: string,\n /** The framework tags an entry allows for that package. */\n readonly allowed: readonly string[],\n ) {}\n}\n\n/** The audit itself — no config, no git: projects and entries in, violations out. */\nexport class FrameworkPackagesAudit {\n constructor(private readonly entries: readonly FrameworkPackagesEntry[]) {}\n\n audit(workspaceRoot: string, projects: readonly ScannedProject[]): FrameworkPackageViolation[] {\n const out: FrameworkPackageViolation[] = [];\n const nestedRoots = new Set(projects.map((p: ScannedProject) => p.dir));\n for (const project of projects) {\n if (project.frameworks.length === 0) continue; // framework-tag's job\n const seen = new Set<string>();\n for (const site of this.importsOf(workspaceRoot, project.dir, nestedRoots)) {\n if (seen.has(site.packageName)) continue;\n const matching = this.entries.filter((e: FrameworkPackagesEntry) => matchesAnyGlob(site.packageName, e.packages));\n if (matching.length === 0) continue;\n const ok = matching.some((e: FrameworkPackagesEntry) =>\n project.frameworks.every((env: string) => e.frameworks.includes(env)));\n if (ok) continue;\n seen.add(site.packageName);\n const allowed = Array.from(new Set(matching.flatMap((e: FrameworkPackagesEntry) => e.frameworks)));\n out.push(new FrameworkPackageViolation(project.name, project.frameworks, site.packageName, site.at, allowed));\n }\n }\n return out;\n }\n\n /** Every bare-package import in a project's production source, nested projects excluded. */\n private importsOf(workspaceRoot: string, dir: string, projectDirs: ReadonlySet<string>): ImportSite[] {\n const sites: ImportSite[] = [];\n // A directory walk bypasses DiffScope, so the framework's path exclusions (#1253) are asked here.\n const scope = new RuleFileScope();\n const walk = (absDir: string): void => {\n for (const entry of fs.readdirSync(absDir, { withFileTypes: true })) {\n const abs = path.join(absDir, entry.name);\n const rel = path.relative(workspaceRoot, abs).split(path.sep).join('/');\n if (entry.isDirectory()) {\n if (SKIP_DIRS.has(entry.name) || entry.name === '__tests__' || projectDirs.has(rel)) continue;\n if (fs.existsSync(path.join(abs, 'project.json'))) continue; // a nested project is judged on its own\n walk(abs);\n } else if (/\\.(ts|tsx|mts|cts)$/.test(entry.name) && !/\\.d\\.ts$/.test(entry.name) && !this.isTestFile(entry.name) && !scope.isExcluded(rel)) {\n sites.push(...this.sitesIn(abs, rel));\n }\n }\n };\n const root = path.join(workspaceRoot, dir);\n if (fs.existsSync(root)) walk(root);\n return sites;\n }\n\n private isTestFile(name: string): boolean {\n return /\\.(spec|test)\\.[cm]?tsx?$/.test(name) || /^test-setup\\./.test(name) || /\\.config\\.[cm]?ts$/.test(name);\n }\n\n private sitesIn(abs: string, rel: string): ImportSite[] {\n const lines = fs.readFileSync(abs, 'utf-8').split('\\n');\n const sites: ImportSite[] = [];\n lines.forEach((line: string, index: number) => {\n IMPORT_RE.lastIndex = 0;\n let match = IMPORT_RE.exec(line);\n while (match !== null) {\n const pkg = this.packageNameOf(match[1]);\n const disabled =\n hasDisable(line, \"framework-packages\") ||\n (index > 0 && hasDisable(lines[index - 1], \"framework-packages\"));\n if (pkg !== null && !disabled) sites.push(new ImportSite(pkg, `${rel}:${index + 1}`));\n match = IMPORT_RE.exec(line);\n }\n });\n return sites;\n }\n\n /** `@scope/pkg/sub` → `@scope/pkg`; `pkg/sub` → `pkg`; relative paths and `node:` builtins → null. */\n private packageNameOf(specifier: string): string | null {\n if (specifier === '' || specifier.startsWith('.') || specifier.startsWith('/') || specifier.startsWith('node:')) return null;\n const parts = specifier.split('/');\n if (specifier.startsWith('@')) return parts.length < 2 ? null : `${parts[0]}/${parts[1]}`;\n return parts[0];\n }\n}\n\n/** One import of a bare package. Data-only. */\nclass ImportSite {\n constructor(\n readonly packageName: string,\n readonly at: string,\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 frameworkPackagesError(violations: readonly FrameworkPackageViolation[]): RuleFailError {\n const details = violations\n .map((v: FrameworkPackageViolation) =>\n ` ${v.at} — ${v.project} [${v.frameworks.join(', ')}] imports '${v.packageName}', ` +\n `which only [${v.allowed.join(', ')}] projects may import`)\n .join('\\n');\n return new RuleFailError(\n \"framework-packages\",\n 'A project imports a framework package that one of the runtimes its framework tags promise cannot run.\\n' + details,\n undefined,\n undefined,\n [\n new Option('Move the code that needs the package into a project whose framework tags are all ones the package runs on, and depend on that project behind an api-lib contract.', true),\n new Option('If the project really runs only where the package does, the TAGS are wrong: narrow its framework tags (and move it to that runtime\\'s folder).'),\n new Option('For one import that is genuinely safe, put `// webpieces-disable framework-packages -- <reason>` on the line above it.'),\n ],\n );\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class FrameworkPackagesValidator extends CodeValidator<FrameworkPackagesConfig> {\n constructor(\n config: FrameworkPackagesConfig,\n private readonly targets: ProjectScanTargets,\n ) {\n super(config, \"framework-packages\", \"framework-packages\");\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-packages\")\n .filter((p: ScannedProject) => !matchesAnyGlob(p.dir, allowed));\n const violations = new FrameworkPackagesAudit(this.config.entries).audit(workspaceRoot, projects);\n if (violations.length === 0) return { success: true };\n throw frameworkPackagesError(violations);\n }\n}\n"]}
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
* provider tokens, interface tokens).
|
|
31
31
|
* - Property/field injection, and any parameter without an `@inject` decorator.
|
|
32
32
|
* - Test files (*.test.ts, *.spec.ts, __tests__/**).
|
|
33
|
-
* - Files under
|
|
33
|
+
* - Files under the rule's `excludePaths` or the top-level one (dropped by the framework).
|
|
34
34
|
* - Lines with `// webpieces-disable inject-annotation-not-needed-for-concrete-class -- <reason>`
|
|
35
35
|
* (only when disableAllowed).
|
|
36
36
|
*
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
* provider tokens, interface tokens).
|
|
32
32
|
* - Property/field injection, and any parameter without an `@inject` decorator.
|
|
33
33
|
* - Test files (*.test.ts, *.spec.ts, __tests__/**).
|
|
34
|
-
* - Files under
|
|
34
|
+
* - Files under the rule's `excludePaths` or the top-level one (dropped by the framework).
|
|
35
35
|
* - Lines with `// webpieces-disable inject-annotation-not-needed-for-concrete-class -- <reason>`
|
|
36
36
|
* (only when disableAllowed).
|
|
37
37
|
*
|
|
@@ -51,7 +51,6 @@ const rules_config_1 = require("@webpieces/rules-config");
|
|
|
51
51
|
const rule_configs_1 = require("./configs/rule-configs");
|
|
52
52
|
const code_validator_1 = require("./code-validator");
|
|
53
53
|
const inversify_1 = require("inversify");
|
|
54
|
-
const resolve_mode_1 = require("./resolve-mode");
|
|
55
54
|
const scan_scope_1 = require("./scan-scope");
|
|
56
55
|
const RULE_NAME = "inject-annotation-not-needed-for-concrete-class";
|
|
57
56
|
const SHARED_MESSAGE = `@inject(Foo) on a constructor parameter typed \`: Foo\` is noise — inversify resolves a constructor
|
|
@@ -149,11 +148,9 @@ function recordViolation(node, context, fileLines, sourceFile, violations, disab
|
|
|
149
148
|
violations.push({ line, column, context, hasDisableComment: effectiveDisabled });
|
|
150
149
|
}
|
|
151
150
|
// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members
|
|
152
|
-
function findRedundantInjectInFile(filePath, workspaceRoot, disableAllowed
|
|
151
|
+
function findRedundantInjectInFile(filePath, workspaceRoot, disableAllowed) {
|
|
153
152
|
if (isTestFile(filePath))
|
|
154
153
|
return [];
|
|
155
|
-
if ((0, rules_config_1.isPathExcluded)(filePath, allowedPaths))
|
|
156
|
-
return [];
|
|
157
154
|
const fullPath = path.join(workspaceRoot, filePath);
|
|
158
155
|
if (!fs.existsSync(fullPath))
|
|
159
156
|
return [];
|
|
@@ -161,13 +158,13 @@ function findRedundantInjectInFile(filePath, workspaceRoot, disableAllowed, allo
|
|
|
161
158
|
return findRedundantInjectInSource(content, filePath, disableAllowed);
|
|
162
159
|
}
|
|
163
160
|
// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members
|
|
164
|
-
function findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed
|
|
161
|
+
function findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed) {
|
|
165
162
|
const violations = [];
|
|
166
163
|
for (const file of changedFiles) {
|
|
167
164
|
const changedLines = (0, rules_config_1.getChangedLineNumbers)((0, rules_config_1.getFileDiff)(workspaceRoot, file, base, head));
|
|
168
165
|
if (changedLines.size === 0)
|
|
169
166
|
continue;
|
|
170
|
-
for (const v of findRedundantInjectInFile(file, workspaceRoot, disableAllowed
|
|
167
|
+
for (const v of findRedundantInjectInFile(file, workspaceRoot, disableAllowed)) {
|
|
171
168
|
if (disableAllowed && v.hasDisableComment)
|
|
172
169
|
continue;
|
|
173
170
|
if (!changedLines.has(v.line))
|
|
@@ -178,10 +175,10 @@ function findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head,
|
|
|
178
175
|
return violations;
|
|
179
176
|
}
|
|
180
177
|
// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members
|
|
181
|
-
function findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed
|
|
178
|
+
function findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed) {
|
|
182
179
|
const violations = [];
|
|
183
180
|
for (const file of changedFiles) {
|
|
184
|
-
for (const v of findRedundantInjectInFile(file, workspaceRoot, disableAllowed
|
|
181
|
+
for (const v of findRedundantInjectInFile(file, workspaceRoot, disableAllowed)) {
|
|
185
182
|
if (disableAllowed && v.hasDisableComment)
|
|
186
183
|
continue;
|
|
187
184
|
violations.push({ file, line: v.line, column: v.column, context: v.context });
|
|
@@ -204,25 +201,13 @@ function reportViolations(violations, mode, disableAllowed) {
|
|
|
204
201
|
console.error(disableAllowed
|
|
205
202
|
? ` Escape hatch (use sparingly): // webpieces-disable ${RULE_NAME} -- <reason>`
|
|
206
203
|
: ' Escape hatch: DISABLED (disableAllowed: false)');
|
|
207
|
-
console.error(` Whole-tree exemption: add a glob to ${RULE_NAME}.
|
|
204
|
+
console.error(` Whole-tree exemption: add a glob to ${RULE_NAME}.excludePaths in webpieces.config.json`);
|
|
208
205
|
console.error(`\n Current mode: ${mode}\n`);
|
|
209
206
|
}
|
|
210
207
|
// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members
|
|
211
|
-
function resolveMode(normalMode, epoch, branchPattern) {
|
|
212
|
-
if (normalMode === 'OFF')
|
|
213
|
-
return normalMode;
|
|
214
|
-
const skip = (0, resolve_mode_1.shouldSkipRule)(epoch, branchPattern);
|
|
215
|
-
if (skip.skip) {
|
|
216
|
-
console.log(`\n⏭️ Skipping ${RULE_NAME} validation (${skip.reason})\n`);
|
|
217
|
-
return 'OFF';
|
|
218
|
-
}
|
|
219
|
-
return normalMode;
|
|
220
|
-
}
|
|
221
|
-
// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members
|
|
222
208
|
async function runValidatorImpl(scan, options, workspaceRoot) {
|
|
223
|
-
const mode =
|
|
209
|
+
const mode = options.mode ?? 'OFF';
|
|
224
210
|
const disableAllowed = options.disableAllowed ?? true;
|
|
225
|
-
const allowedPaths = options.allowedPaths ?? [];
|
|
226
211
|
if (mode === 'OFF') {
|
|
227
212
|
console.log(`\n⏭️ Skipping ${RULE_NAME} validation (mode: OFF)\n`);
|
|
228
213
|
return { success: true };
|
|
@@ -248,11 +233,11 @@ async function runValidatorImpl(scan, options, workspaceRoot) {
|
|
|
248
233
|
console.log(`📂 Checking ${changedFiles.length} changed file(s)...`);
|
|
249
234
|
let violations = [];
|
|
250
235
|
if (mode === 'NEW_AND_MODIFIED_CODE') {
|
|
251
|
-
violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed
|
|
236
|
+
violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed);
|
|
252
237
|
}
|
|
253
238
|
else {
|
|
254
239
|
// NEW_AND_MODIFIED_FILES and the whole-scope modes (#1027) all judge every site of every file.
|
|
255
|
-
violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed
|
|
240
|
+
violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);
|
|
256
241
|
}
|
|
257
242
|
if (violations.length === 0) {
|
|
258
243
|
console.log('✅ No redundant-@inject violations found');
|
|
@@ -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;;;AAkFH,kEA4BC;;AA5GD,+CAAyB;AACzB,mDAA6B;AAC7B,uDAAiC;AACjC,0DAAqH;AACrH,yDAAyF;AAEzF,qDAAiE;AACjE,yCAA2D;AAC3D,iDAAgD;AAChD,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,6HA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M,KAAK,CAAC,EAAE,CAAC;QAC1B,OAAO,CAAC,GAAG,CAAC,yCAAyC,CAAC,CAAC;QACvD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7B,CAAC;IAED,IAAI,CAAC,WAAW,CAAC,SAAS,EAAE,UAAU,CAAC,GAAG,CAAC,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 a configured `allowedPaths` glob (shared isPathExcluded glob/prefix/segment semantics).\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, isPathExcluded } 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 { shouldSkipRule } from './resolve-mode';\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, allowedPaths: string[]): InjectViolationInfo[] {\n if (isTestFile(filePath)) return [];\n if (isPathExcluded(filePath, allowedPaths)) 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, allowedPaths: string[]): 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, allowedPaths)) {\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, allowedPaths: string[]): InjectViolation[] {\n const violations: InjectViolation[] = [];\n for (const file of changedFiles) {\n for (const v of findRedundantInjectInFile(file, workspaceRoot, disableAllowed, allowedPaths)) {\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}.allowedPaths 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\nfunction resolveMode(normalMode: ModifiedCodeMode, epoch: number | undefined, branchPattern: string | undefined): ModifiedCodeMode {\n if (normalMode === 'OFF') return normalMode;\n const skip = shouldSkipRule(epoch, branchPattern);\n if (skip.skip) {\n console.log(`\\n⏭️ Skipping ${RULE_NAME} validation (${skip.reason})\\n`);\n return 'OFF';\n }\n return normalMode;\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 = resolveMode(options.mode ?? 'OFF', options.turnOffRuleUntilEpoch, (options.turnOffRuleWhileOnBranch ?? undefined));\n const disableAllowed = options.disableAllowed ?? true;\n const allowedPaths = options.allowedPaths ?? [];\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, allowedPaths);\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, allowedPaths);\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","sour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K,CAAC,EAAE,CAAC;QAC1B,OAAO,CAAC,GAAG,CAAC,yCAAyC,CAAC,CAAC;QACvD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7B,CAAC;IAED,IAAI,CAAC,WAAW,CAAC,SAAS,EAAE,UAAU,CAAC,GAAG,CAAC,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\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"]}
|
|
@@ -50,7 +50,7 @@ let MatchRulesChecker = class MatchRulesChecker {
|
|
|
50
50
|
}
|
|
51
51
|
/** Run one `match-rules` entry against the workspace (per-entry mode/diff-scoping/report). */
|
|
52
52
|
async runForConfig(config, workspaceRoot) {
|
|
53
|
-
const mode =
|
|
53
|
+
const mode = config.mode ?? 'OFF';
|
|
54
54
|
if (mode === 'OFF') {
|
|
55
55
|
console.log(`\n⏭️ Skipping ${config.name} validation (mode: OFF)\n`);
|
|
56
56
|
return { success: true };
|
|
@@ -143,17 +143,6 @@ let MatchRulesChecker = class MatchRulesChecker {
|
|
|
143
143
|
console.error(` Current mode: ${mode}`);
|
|
144
144
|
console.error('');
|
|
145
145
|
}
|
|
146
|
-
resolveMode(config) {
|
|
147
|
-
const normalMode = config.mode ?? 'OFF';
|
|
148
|
-
if (normalMode === 'OFF')
|
|
149
|
-
return normalMode;
|
|
150
|
-
const skip = (0, rules_config_1.shouldSkipRule)(config.turnOffRuleUntilEpoch, config.turnOffRuleWhileOnBranch);
|
|
151
|
-
if (skip.skip) {
|
|
152
|
-
console.log(`\n⏭️ Skipping ${config.name} validation (${skip.reason})\n`);
|
|
153
|
-
return 'OFF';
|
|
154
|
-
}
|
|
155
|
-
return normalMode;
|
|
156
|
-
}
|
|
157
146
|
};
|
|
158
147
|
exports.MatchRulesChecker = MatchRulesChecker;
|
|
159
148
|
exports.MatchRulesChecker = MatchRulesChecker = tslib_1.__decorate([
|
|
@@ -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,CAAC;CACJ;AAVD,gDAUC;AAGM,IAAM,iBAAiB,GAAvB,MAAM,iBAAiB;IACG;IAA7B,YAA6B,SAAoB;QAApB,cAAS,GAAT,SAAS,CAAW;IAAG,CAAC;IAErD,yFAAyF;IACzF,SAAS,CAAC,MAAu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AAO,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;IAEO,WAAW,CAAC,MAAuB;QACvC,MAAM,UAAU,GAAqB,MAAM,CAAC,IAAI,IAAI,KAAK,CAAC;QAC1D,IAAI,UAAU,KAAK,KAAK;YAAE,OAAO,UAAU,CAAC;QAC5C,MAAM,IAAI,GAAG,IAAA,6BAAc,EAAC,MAAM,CAAC,qBAAqB,EAAE,MAAM,CAAC,wBAAwB,CAAC,CAAC;QAC3F,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;YACZ,OAAO,CAAC,GAAG,CAAC,kBAAkB,MAAM,CAAC,IAAI,gBAAgB,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC;YAC3E,OAAO,KAAK,CAAC;QACjB,CAAC;QACD,OAAO,UAAU,CAAC;IACtB,CAAC;CACJ,CAAA;AAvIY,8CAAiB;4BAAjB,iBAAiB;IAD7B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEG,sBAAS;GADxC,iBAAiB,CAuI7B","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 = this.resolveMode(config);\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 private resolveMode(config: MatchRuleConfig): ModifiedCodeMode {\n const normalMode: ModifiedCodeMode = config.mode ?? 'OFF';\n if (normalMode === 'OFF') return normalMode;\n const skip = shouldSkipRule(config.turnOffRuleUntilEpoch, config.turnOffRuleWhileOnBranch);\n if (skip.skip) {\n console.log(`\\n⏭️ Skipping ${config.name} validation (${skip.reason})\\n`);\n return 'OFF';\n }\n return normalMode;\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;IAC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,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"]}
|
|
@@ -23,13 +23,6 @@ export declare class FileViolation {
|
|
|
23
23
|
readonly expiredDate: string | undefined;
|
|
24
24
|
constructor(file: string, lines: number, expiredDisable?: boolean, expiredDate?: string);
|
|
25
25
|
}
|
|
26
|
-
/**
|
|
27
|
-
* The complete exempt-path list for one run: the machine-generated trees that are exempt with no
|
|
28
|
-
* configuration at all, PLUS whatever the repo listed in `max-file-lines.allowedPaths`. The config
|
|
29
|
-
* ADDS to the floor rather than replacing it, so exempting one of your own trees can never silently
|
|
30
|
-
* cost you the generated-code exemption (see GENERATED_CODE_PATHS for why that matters).
|
|
31
|
-
*/
|
|
32
|
-
export declare function exemptPathsFor(config: MaxFileLinesConfig): readonly string[];
|
|
33
26
|
/**
|
|
34
27
|
* Count lines in a file and check for violations
|
|
35
28
|
*/
|
|
@@ -15,7 +15,6 @@
|
|
|
15
15
|
*/
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
17
|
exports.MaxFileLinesValidator = exports.FileViolation = void 0;
|
|
18
|
-
exports.exemptPathsFor = exemptPathsFor;
|
|
19
18
|
exports.findViolations = findViolations;
|
|
20
19
|
exports.violationsError = violationsError;
|
|
21
20
|
const tslib_1 = require("tslib");
|
|
@@ -25,7 +24,6 @@ const rules_config_1 = require("@webpieces/rules-config");
|
|
|
25
24
|
const rule_configs_1 = require("./configs/rule-configs");
|
|
26
25
|
const code_validator_1 = require("./code-validator");
|
|
27
26
|
const inversify_1 = require("inversify");
|
|
28
|
-
const resolve_mode_1 = require("./resolve-mode");
|
|
29
27
|
/** One over-limit file. A class, not an interface — findViolations is exported for its tests. */
|
|
30
28
|
class FileViolation {
|
|
31
29
|
file;
|
|
@@ -111,16 +109,6 @@ function checkDisableComment(content) {
|
|
|
111
109
|
}
|
|
112
110
|
return { hasDisable: false, isValid: false, isExpired: false };
|
|
113
111
|
}
|
|
114
|
-
/**
|
|
115
|
-
* The complete exempt-path list for one run: the machine-generated trees that are exempt with no
|
|
116
|
-
* configuration at all, PLUS whatever the repo listed in `max-file-lines.allowedPaths`. The config
|
|
117
|
-
* ADDS to the floor rather than replacing it, so exempting one of your own trees can never silently
|
|
118
|
-
* cost you the generated-code exemption (see GENERATED_CODE_PATHS for why that matters).
|
|
119
|
-
*/
|
|
120
|
-
// webpieces-disable no-function-outside-class -- pure list join, sibling of the file-scoped helpers here
|
|
121
|
-
function exemptPathsFor(config) {
|
|
122
|
-
return [...rules_config_1.GENERATED_CODE_PATHS, ...(config.allowedPaths ?? [])];
|
|
123
|
-
}
|
|
124
112
|
/**
|
|
125
113
|
* Count lines in a file and check for violations
|
|
126
114
|
*/
|
|
@@ -130,7 +118,8 @@ function findViolations(workspaceRoot, changedFiles, limit, disableAllowed, exem
|
|
|
130
118
|
const violations = [];
|
|
131
119
|
for (const file of changedFiles) {
|
|
132
120
|
const fullPath = path.join(workspaceRoot, file);
|
|
133
|
-
// Machine-generated
|
|
121
|
+
// Machine-generated trees: the file's size is not the repo's to fix. (A tree the repo lists in
|
|
122
|
+
// excludePaths never reaches this list at all — the framework drops it from the file listing.)
|
|
134
123
|
if ((0, rules_config_1.isPathExcluded)(file, exemptPaths))
|
|
135
124
|
continue;
|
|
136
125
|
if (!fs.existsSync(fullPath))
|
|
@@ -199,7 +188,7 @@ function violationsError(violations, limit, disableAllowed) {
|
|
|
199
188
|
].join('\n');
|
|
200
189
|
const cures = [
|
|
201
190
|
new rules_config_1.Option(`Refactor the file under ${limit} lines — READ .webpieces/instruct-ai/${TMP_MD_FILE} for step-by-step guidance.`, true),
|
|
202
|
-
new rules_config_1.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
|
|
191
|
+
new rules_config_1.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.'),
|
|
203
192
|
];
|
|
204
193
|
if (disableAllowed) {
|
|
205
194
|
cures.push(new rules_config_1.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]`));
|
|
@@ -212,16 +201,13 @@ function violationsError(violations, limit, disableAllowed) {
|
|
|
212
201
|
async function runValidatorImpl(options, workspaceRoot) {
|
|
213
202
|
const limit = options.limit ?? 900;
|
|
214
203
|
const disableAllowed = options.disableAllowed ?? true;
|
|
215
|
-
// Machine-generated trees
|
|
216
|
-
//
|
|
217
|
-
const exemptPaths =
|
|
218
|
-
const
|
|
219
|
-
const skip = rawMode !== 'OFF' ? (0, resolve_mode_1.shouldSkipRule)(options.turnOffRuleUntilEpoch, (options.turnOffRuleWhileOnBranch ?? undefined)) : new resolve_mode_1.SkipRuleResult(false);
|
|
220
|
-
const mode = skip.skip ? 'OFF' : rawMode;
|
|
204
|
+
// Machine-generated trees: a line-count rule firing on a file nobody authored is never a useful
|
|
205
|
+
// signal, so this floor needs no configuration. The repo's own excludePaths are applied upstream.
|
|
206
|
+
const exemptPaths = rules_config_1.GENERATED_CODE_PATHS;
|
|
207
|
+
const mode = options.mode ?? 'NEW_AND_MODIFIED_FILES';
|
|
221
208
|
// Skip validation entirely if mode is OFF
|
|
222
209
|
if (mode === 'OFF') {
|
|
223
|
-
|
|
224
|
-
console.log(`\n\u23ed\ufe0f Skipping modified files validation (${reason})`);
|
|
210
|
+
console.log(`\n\u23ed\ufe0f Skipping modified files validation (mode: OFF)`);
|
|
225
211
|
console.log('');
|
|
226
212
|
return { success: true };
|
|
227
213
|
}
|