@webpieces/code-rules 0.4.819 → 0.4.820

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 (84) hide show
  1. package/package.json +2 -2
  2. package/src/api-lib-source-rule.d.ts +5 -2
  3. package/src/api-lib-source-rule.js +8 -4
  4. package/src/api-lib-source-rule.js.map +1 -1
  5. package/src/cli.js +13 -14
  6. package/src/cli.js.map +1 -1
  7. package/src/code-rules-bootstrap.d.ts +31 -8
  8. package/src/code-rules-bootstrap.js +136 -18
  9. package/src/code-rules-bootstrap.js.map +1 -1
  10. package/src/code-rules-config-table.d.ts +3 -1
  11. package/src/code-rules-config-table.js +0 -6
  12. package/src/code-rules-config-table.js.map +1 -1
  13. package/src/code-rules-engine.d.ts +4 -13
  14. package/src/code-rules-engine.js +9 -31
  15. package/src/code-rules-engine.js.map +1 -1
  16. package/src/code-rules-run-request.d.ts +30 -34
  17. package/src/code-rules-run-request.js +43 -80
  18. package/src/code-rules-run-request.js.map +1 -1
  19. package/src/index.d.ts +3 -1
  20. package/src/index.js +13 -2
  21. package/src/index.js.map +1 -1
  22. package/src/scan-scope.d.ts +82 -0
  23. package/src/scan-scope.js +200 -0
  24. package/src/scan-scope.js.map +1 -0
  25. package/src/validate-catch-error-pattern.d.ts +3 -1
  26. package/src/validate-catch-error-pattern.js +11 -6
  27. package/src/validate-catch-error-pattern.js.map +1 -1
  28. package/src/validate-code.d.ts +4 -5
  29. package/src/validate-code.js +6 -17
  30. package/src/validate-code.js.map +1 -1
  31. package/src/validate-inject-annotation-not-needed-for-concrete-class.d.ts +3 -1
  32. package/src/validate-inject-annotation-not-needed-for-concrete-class.js +11 -6
  33. package/src/validate-inject-annotation-not-needed-for-concrete-class.js.map +1 -1
  34. package/src/validate-match-rules.d.ts +3 -0
  35. package/src/validate-match-rules.js +10 -3
  36. package/src/validate-match-rules.js.map +1 -1
  37. package/src/validate-no-any-unknown.d.ts +3 -1
  38. package/src/validate-no-any-unknown.js +11 -6
  39. package/src/validate-no-any-unknown.js.map +1 -1
  40. package/src/validate-no-client-creation-outside-server-or-client.d.ts +4 -2
  41. package/src/validate-no-client-creation-outside-server-or-client.js +10 -5
  42. package/src/validate-no-client-creation-outside-server-or-client.js.map +1 -1
  43. package/src/validate-no-custom-css.d.ts +4 -2
  44. package/src/validate-no-custom-css.js +9 -5
  45. package/src/validate-no-custom-css.js.map +1 -1
  46. package/src/validate-no-destructure.d.ts +3 -1
  47. package/src/validate-no-destructure.js +11 -6
  48. package/src/validate-no-destructure.js.map +1 -1
  49. package/src/validate-no-function-outside-class.d.ts +3 -1
  50. package/src/validate-no-function-outside-class.js +12 -6
  51. package/src/validate-no-function-outside-class.js.map +1 -1
  52. package/src/validate-no-implicit-any.d.ts +3 -1
  53. package/src/validate-no-implicit-any.js +13 -8
  54. package/src/validate-no-implicit-any.js.map +1 -1
  55. package/src/validate-no-inline-import-in-api-lib.d.ts +2 -1
  56. package/src/validate-no-inline-import-in-api-lib.js +4 -3
  57. package/src/validate-no-inline-import-in-api-lib.js.map +1 -1
  58. package/src/validate-no-process-exit-outside-main.d.ts +3 -1
  59. package/src/validate-no-process-exit-outside-main.js +12 -6
  60. package/src/validate-no-process-exit-outside-main.js.map +1 -1
  61. package/src/validate-no-state-paths-in-templates.d.ts +4 -2
  62. package/src/validate-no-state-paths-in-templates.js +9 -5
  63. package/src/validate-no-state-paths-in-templates.js.map +1 -1
  64. package/src/validate-no-symbol-di-tokens.d.ts +3 -1
  65. package/src/validate-no-symbol-di-tokens.js +11 -6
  66. package/src/validate-no-symbol-di-tokens.js.map +1 -1
  67. package/src/validate-no-unmanaged-exceptions.d.ts +3 -1
  68. package/src/validate-no-unmanaged-exceptions.js +11 -6
  69. package/src/validate-no-unmanaged-exceptions.js.map +1 -1
  70. package/src/validate-no-utility-types-in-api-lib.d.ts +2 -1
  71. package/src/validate-no-utility-types-in-api-lib.js +4 -3
  72. package/src/validate-no-utility-types-in-api-lib.js.map +1 -1
  73. package/src/validate-one-enum-spelling-in-api-lib.d.ts +2 -1
  74. package/src/validate-one-enum-spelling-in-api-lib.js +4 -3
  75. package/src/validate-one-enum-spelling-in-api-lib.js.map +1 -1
  76. package/src/validate-required-type-suffix.d.ts +2 -1
  77. package/src/validate-required-type-suffix.js +7 -3
  78. package/src/validate-required-type-suffix.js.map +1 -1
  79. package/src/debug-run-report.d.ts +0 -22
  80. package/src/debug-run-report.js +0 -127
  81. package/src/debug-run-report.js.map +0 -1
  82. package/src/rule-scope-plan.d.ts +0 -72
  83. package/src/rule-scope-plan.js +0 -132
  84. package/src/rule-scope-plan.js.map +0 -1
@@ -43,6 +43,7 @@ const rules_config_1 = require("@webpieces/rules-config");
43
43
  const code_validator_1 = require("./code-validator");
44
44
  const inversify_1 = require("inversify");
45
45
  const resolve_mode_1 = require("./resolve-mode");
46
+ const scan_scope_1 = require("./scan-scope");
46
47
  const SHARED_MESSAGE = `Functions must live inside a class as INSTANCE methods — a function created at module scope, OR a
47
48
  static method, can't be injected, so webpieces DI + @DocumentDesign can't wire it into anything. A
48
49
  static method is just a module-scope function wearing a class as a namespace.
@@ -216,7 +217,8 @@ function resolveMode(normalMode, epoch, branchPattern) {
216
217
  }
217
218
  return normalMode;
218
219
  }
219
- async function runValidatorImpl(options, workspaceRoot) {
220
+ // webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members
221
+ async function runValidatorImpl(scan, options, workspaceRoot) {
220
222
  const mode = resolveMode(options.mode ?? 'OFF', options.turnOffRuleUntilEpoch, (options.turnOffRuleWhileOnBranch ?? undefined));
221
223
  const disableAllowed = options.disableAllowed ?? true;
222
224
  const allowedPaths = options.allowedPaths ?? [];
@@ -237,7 +239,7 @@ async function runValidatorImpl(options, workspaceRoot) {
237
239
  }
238
240
  console.log(` Base: ${base}`);
239
241
  console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}\n`);
240
- const changedFiles = (0, rules_config_1.getChangedFiles)(workspaceRoot, base, head);
242
+ const changedFiles = scan.files(workspaceRoot, mode, base, head);
241
243
  if (changedFiles.length === 0) {
242
244
  console.log('✅ No TypeScript files changed');
243
245
  return { success: true };
@@ -247,27 +249,31 @@ async function runValidatorImpl(options, workspaceRoot) {
247
249
  if (mode === 'NEW_AND_MODIFIED_CODE') {
248
250
  violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed, allowedPaths);
249
251
  }
250
- else if (mode === 'NEW_AND_MODIFIED_FILES') {
252
+ else {
253
+ // NEW_AND_MODIFIED_FILES and the whole-scope modes (#1027) all judge every site of every file.
251
254
  violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed, allowedPaths);
252
255
  }
253
256
  if (violations.length === 0) {
254
257
  console.log('✅ No function-outside-class violations found');
255
258
  return { success: true };
256
259
  }
260
+ scan.recordSites('no-function-outside-class', violations.map((v) => v.file));
257
261
  reportViolations(violations, mode, disableAllowed);
258
262
  return { success: false };
259
263
  }
260
264
  let NoFunctionOutsideClassValidator = class NoFunctionOutsideClassValidator extends code_validator_1.CodeValidator {
261
- constructor(config) {
265
+ scanScope;
266
+ constructor(config, scanScope) {
262
267
  super(config, 'no-function-outside-class', 'no-function-outside-class');
268
+ this.scanScope = scanScope;
263
269
  }
264
270
  async run(workspaceRoot) {
265
- return runValidatorImpl(this.config, workspaceRoot);
271
+ return runValidatorImpl(this.scanScope, this.config, workspaceRoot);
266
272
  }
267
273
  };
268
274
  exports.NoFunctionOutsideClassValidator = NoFunctionOutsideClassValidator;
269
275
  exports.NoFunctionOutsideClassValidator = NoFunctionOutsideClassValidator = tslib_1.__decorate([
270
276
  (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
271
- tslib_1.__metadata("design:paramtypes", [rules_config_1.NoFunctionOutsideClassConfig])
277
+ tslib_1.__metadata("design:paramtypes", [rules_config_1.NoFunctionOutsideClassConfig, scan_scope_1.ScanScope])
272
278
  ], NoFunctionOutsideClassValidator);
273
279
  //# sourceMappingURL=validate-no-function-outside-class.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"validate-no-function-outside-class.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-function-outside-class.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;;;AA2HH,8EAuBC;AAGD,0EAOC;;AA1JD,+CAAyB;AACzB,mDAA6B;AAC7B,uDAAiC;AACjC,0DAAkM;AAClM,qDAAiE;AACjE,yCAA2D;AAC3D,iDAAgD;AAEhD,MAAM,cAAc,GAAG;;;;;;;;;0EASmD,CAAC;AAgB3E,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,SAAS,iBAAiB,CAAC,QAAgB;IACvC,OAAO,QAAQ,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;AACtC,CAAC;AAED,6FAA6F;AAC7F,SAAS,kBAAkB,CAAC,IAAa;IACrC,IAAI,CAAC,EAAE,CAAC,gBAAgB,CAAC,IAAI,CAAC;QAAE,OAAO,KAAK,CAAC;IAC7C,MAAM,IAAI,GAAG,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;IACnC,OAAO,IAAI,EAAE,IAAI,CAAC,CAAC,CAAc,EAAW,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,EAAE,CAAC,UAAU,CAAC,cAAc,CAAC,IAAI,KAAK,CAAC;AACrG,CAAC;AAED,iGAAiG;AACjG,kGAAkG;AAClG,4EAA4E;AAC5E,6HAA6H;AAC7H,SAAS,iBAAiB,CAAC,IAAa;IACpC,IAAI,CAAC,EAAE,CAAC,gBAAgB,CAAC,IAAI,CAAC;QAAE,OAAO,KAAK,CAAC;IAC7C,MAAM,IAAI,GAAG,EAAE,CAAC,YAAY,CAAC,IAAI,CA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C class member:\n * - a top-level `function foo()` / `export function foo()` declaration,\n * - a top-level `const foo = () => {}` / `const foo = function(){}`, and\n * - a `static foo() {}` method or `static foo = () => {}` field-function (a static member\n * belongs to the class object, not an instance, so it can't be injected either).\n *\n * WHY: webpieces DI + @DocumentDesign only work when behavior lives in injectable classes that can be\n * wired into each other. A module-scope function is a dead-end the DI graph can't reach — move the\n * logic onto a `@provideSingleton()` class and inject it instead.\n *\n * Uses the TypeScript AST so class-membership is checked precisely (not a regex heuristic): a node is a\n * violation only when its parent is the SourceFile (module scope). That automatically EXEMPTS inline\n * callbacks (`arr.map(x => x)`), promise handlers, nested functions inside methods, and functions\n * nested in other functions — their parent is a Block/CallExpression, never the SourceFile.\n *\n * ALLOWED (skip — NOT violations)\n * - Any function/arrow nested inside a class method, another function, or a callback.\n * - Non-function top-level consts: `const SCHEMA = z.object({})`, `const MAX = 5`, object/array literals.\n * - Ambient declarations (`declare function ...`) and whole `*.d.ts` files.\n * - Test files (*.test.ts, *.spec.ts, __tests__/**).\n * - Files under a configured `allowedPaths` glob (e.g. React component/hook trees that legitimately use\n * module-scope functions). Matched with the shared `isPathExcluded` glob/prefix/segment semantics.\n * - Lines with `// webpieces-disable no-function-outside-class -- <reason>` (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, RULE_NAMES, NoFunctionOutsideClassConfig, ModifiedCodeMode, detectBase, getChangedFiles, getFileDiff, getChangedLineNumbers, isPathExcluded } from '@webpieces/rules-config';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { shouldSkipRule } from './resolve-mode';\n\nconst SHARED_MESSAGE = `Functions must live inside a class as INSTANCE methods — a function created at module scope, OR a\nstatic method, can't be injected, so webpieces DI + @DocumentDesign can't wire it into anything. A\nstatic method is just a module-scope function wearing a class as a namespace.\n BAD: export function computeTotal(cart: Cart): number { ... }\n BAD: export class CartMath { static computeTotal(cart: Cart): number { ... } } // static = not injectable\n GOOD: @injectable(bindingScopeValues.Singleton)\n export class CartService { computeTotal(cart: Cart): number { ... } }\nThen inject CartService where you need it. Inline callbacks (arr.map(x => x)), promise handlers, and\nfunctions nested inside a method are fine — only MODULE-SCOPE function declarations, top-level\nconst-assigned functions, and STATIC methods/field-functions are flagged.`;\n\ninterface FnViolation {\n file: string;\n line: number;\n column: number;\n context: string;\n}\n\ninterface FnViolationInfo {\n line: number;\n column: number;\n context: string;\n hasDisableComment: boolean;\n}\n\nfunction isTestFile(filePath: string): boolean {\n return filePath.includes('.spec.ts') || filePath.includes('.test.ts') || filePath.includes('__tests__/');\n}\n\nfunction isDeclarationFile(filePath: string): boolean {\n return filePath.endsWith('.d.ts');\n}\n\n// True for a node carrying a `declare` modifier (ambient signature — not a real definition).\nfunction hasDeclareModifier(node: ts.Node): boolean {\n if (!ts.canHaveModifiers(node)) return false;\n const mods = ts.getModifiers(node);\n return mods?.some((m: ts.Modifier): boolean => m.kind === ts.SyntaxKind.DeclareKeyword) ?? false;\n}\n\n// True for a class member carrying the `static` modifier. A static method/field-function belongs\n// to the class object, not an instance, so it can't be injected — it is procedural code wearing a\n// class as a namespace, and is flagged the same as a module-scope function.\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction hasStaticModifier(node: ts.Node): boolean {\n if (!ts.canHaveModifiers(node)) return false;\n const mods = ts.getModifiers(node);\n return mods?.some((m: ts.Modifier): boolean => m.kind === ts.SyntaxKind.StaticKeyword) ?? false;\n}\n\n// A `static` method, or a `static` field initialized to an arrow/function-expression, on a class.\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction isStaticFunctionMember(node: ts.Node): boolean {\n if (ts.isMethodDeclaration(node)) return hasStaticModifier(node);\n if (ts.isPropertyDeclaration(node) && hasStaticModifier(node)) {\n const init = node.initializer;\n return init !== undefined && (ts.isArrowFunction(init) || ts.isFunctionExpression(init));\n }\n return false;\n}\n\n// Display name of a static member for the violation message.\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction staticMemberName(node: ts.MethodDeclaration | ts.PropertyDeclaration): string {\n return ts.isIdentifier(node.name) ? node.name.text : '<static>';\n}\n\n// The violation line (or the line just above it) carries the disable comment.\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_NAMES.NO_FUNCTION_OUTSIDE_CLASS)\n || hasDisable(previous, RULE_NAMES.NO_FUNCTION_OUTSIDE_CLASS);\n}\n\nfunction recordViolation(\n node: ts.Node,\n context: string,\n fileLines: string[],\n sourceFile: ts.SourceFile,\n violations: FnViolationInfo[],\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// Report a module-scope const whose initializer is an arrow / function-expression (a function\n// assigned to a top-level const). Non-function consts are left alone.\nfunction checkTopLevelConst(\n node: ts.VariableStatement,\n fileLines: string[],\n sourceFile: ts.SourceFile,\n violations: FnViolationInfo[],\n disableAllowed: boolean,\n): void {\n for (const decl of node.declarationList.declarations) {\n const init = decl.initializer;\n if (!init) continue;\n if (!ts.isArrowFunction(init) && !ts.isFunctionExpression(init)) continue;\n const name = ts.isIdentifier(decl.name) ? decl.name.text : '<fn>';\n recordViolation(decl, `const ${name} = <function> at module scope (outside any class)`, fileLines, sourceFile, violations, disableAllowed);\n }\n}\n\n// AST scan: a node is a violation only when its parent is the SourceFile (module scope).\nexport function findFunctionsOutsideClassInSource(content: string, filePath: string, disableAllowed: boolean): FnViolationInfo[] {\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: FnViolationInfo[] = [];\n\n function visit(node: ts.Node): void {\n if (ts.isFunctionDeclaration(node) && ts.isSourceFile(node.parent) && !hasDeclareModifier(node)) {\n const name = node.name?.text ?? '<anonymous>';\n recordViolation(node, `function ${name}() declared at module scope (outside any class)`, fileLines, sourceFile, violations, disableAllowed);\n }\n if (ts.isVariableStatement(node) && ts.isSourceFile(node.parent) && !hasDeclareModifier(node)) {\n checkTopLevelConst(node, fileLines, sourceFile, violations, disableAllowed);\n }\n if (isStaticFunctionMember(node) && !hasDeclareModifier(node)) {\n const name = staticMemberName(node as ts.MethodDeclaration | ts.PropertyDeclaration);\n recordViolation(node, `static ${name}() — a static method can't be injected; make it an instance method and inject the class`, fileLines, sourceFile, violations, disableAllowed);\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\nexport function findFunctionsOutsideClassInFile(filePath: string, workspaceRoot: string, disableAllowed: boolean, allowedPaths: string[]): FnViolationInfo[] {\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 findFunctionsOutsideClassInSource(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[]): FnViolation[] {\n const violations: FnViolation[] = [];\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 findFunctionsOutsideClassInFile(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[]): FnViolation[] {\n const violations: FnViolation[] = [];\n for (const file of changedFiles) {\n for (const v of findFunctionsOutsideClassInFile(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\nfunction reportViolations(violations: FnViolation[], mode: ModifiedCodeMode, disableAllowed: boolean): void {\n console.error('');\n console.error('❌ Function(s) created outside a class!');\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 no-function-outside-class -- <reason>'\n : ' Escape hatch: DISABLED (disableAllowed: false)');\n console.error(' Whole-tree exemption (e.g. React): add a glob to no-function-outside-class.allowedPaths in webpieces.config.json');\n console.error(`\\n Current mode: ${mode}\\n`);\n}\n\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 no-function-outside-class validation (${skip.reason})\\n`);\n return 'OFF';\n }\n return normalMode;\n}\n\nasync function runValidatorImpl(options: NoFunctionOutsideClassConfig, workspaceRoot: string): 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 no-function-outside-class validation (mode: OFF)\\n');\n return { success: true };\n }\n\n console.log('\\n📏 Validating No Function Outside Class\\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 no-function-outside-class 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 = getChangedFiles(workspaceRoot, 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: FnViolation[] = [];\n if (mode === 'NEW_AND_MODIFIED_CODE') {\n violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed, allowedPaths);\n } else if (mode === 'NEW_AND_MODIFIED_FILES') {\n violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed, allowedPaths);\n }\n\n if (violations.length === 0) {\n console.log('✅ No function-outside-class violations found');\n return { success: true };\n }\n\n reportViolations(violations, mode, disableAllowed);\n return { success: false };\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoFunctionOutsideClassValidator extends CodeValidator<NoFunctionOutsideClassConfig> {\n constructor(config: NoFunctionOutsideClassConfig) {\n super(config, 'no-function-outside-class', 'no-function-outside-class');\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runValidatorImpl(this.config, workspaceRoot);\n }\n}\n"]}
1
+ {"version":3,"file":"validate-no-function-outside-class.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-function-outside-class.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;;;AA4HH,8EAuBC;AAGD,0EAOC;;AA3JD,+CAAyB;AACzB,mDAA6B;AAC7B,uDAAiC;AACjC,0DAAiL;AACjL,qDAAiE;AACjE,yCAA2D;AAC3D,iDAAgD;AAChD,6CAAyC;AAEzC,MAAM,cAAc,GAAG;;;;;;;;;0EASmD,CAAC;AAgB3E,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,SAAS,iBAAiB,CAAC,QAAgB;IACvC,OAAO,QAAQ,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;AACtC,CAAC;AAED,6FAA6F;AAC7F,SAAS,kBAAkB,CAAC,IAAa;IACrC,IAAI,CAAC,EAAE,CAAC,gBAAgB,CAAC,IAAI,CAAC;QAAE,OAAO,KAAK,CAAC;IAC7C,MAAM,IAAI,GAAG,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;IACnC,OAAO,IAAI,EAAE,IAAI,CAAC,CAAC,CAAc,EAAW,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,EAAE,CAAC,UAAU,CAAC,cAAc,CAAC,IAAI,KAAK,CAAC;AACrG,CAAC;AAED,iGAAiG;AACjG,kGAAkG;AAClG,4EAA4E;AAC5E,6HAA6H;AAC7H,SAAS,iBAAiB,CAAC,IAAa;IACpC,IAAI,CAAC,EAAE,CAAC,gBAAgB,CAAC,IAAI,CAAC;QAAE,OAAO,KAAK,CAAC;IAC7C,MAAM,IAAI,GAAG,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;IACnC,OAAO,IAAI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CACJ,CAAA;AARY,0EAA+B;0CAA/B,+BAA+B;IAD3C,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEjB,2CAA4B,EAA8B,sBAAS;GAD9E,+BAA+B,CAQ3C","sourcesContent":["/**\n * Validate No Function Outside Class\n *\n * Flags a function CREATED OUTSIDE A CLASS at module scope, or a STATIC class member:\n * - a top-level `function foo()` / `export function foo()` declaration,\n * - a top-level `const foo = () => {}` / `const foo = function(){}`, and\n * - a `static foo() {}` method or `static foo = () => {}` field-function (a static member\n * belongs to the class object, not an instance, so it can't be injected either).\n *\n * WHY: webpieces DI + @DocumentDesign only work when behavior lives in injectable classes that can be\n * wired into each other. A module-scope function is a dead-end the DI graph can't reach — move the\n * logic onto a `@provideSingleton()` class and inject it instead.\n *\n * Uses the TypeScript AST so class-membership is checked precisely (not a regex heuristic): a node is a\n * violation only when its parent is the SourceFile (module scope). That automatically EXEMPTS inline\n * callbacks (`arr.map(x => x)`), promise handlers, nested functions inside methods, and functions\n * nested in other functions — their parent is a Block/CallExpression, never the SourceFile.\n *\n * ALLOWED (skip — NOT violations)\n * - Any function/arrow nested inside a class method, another function, or a callback.\n * - Non-function top-level consts: `const SCHEMA = z.object({})`, `const MAX = 5`, object/array literals.\n * - Ambient declarations (`declare function ...`) and whole `*.d.ts` files.\n * - Test files (*.test.ts, *.spec.ts, __tests__/**).\n * - Files under a configured `allowedPaths` glob (e.g. React component/hook trees that legitimately use\n * module-scope functions). Matched with the shared `isPathExcluded` glob/prefix/segment semantics.\n * - Lines with `// webpieces-disable no-function-outside-class -- <reason>` (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, RULE_NAMES, NoFunctionOutsideClassConfig, ModifiedCodeMode, detectBase, getFileDiff, getChangedLineNumbers, isPathExcluded } from '@webpieces/rules-config';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { shouldSkipRule } from './resolve-mode';\nimport { ScanScope } from './scan-scope';\n\nconst SHARED_MESSAGE = `Functions must live inside a class as INSTANCE methods — a function created at module scope, OR a\nstatic method, can't be injected, so webpieces DI + @DocumentDesign can't wire it into anything. A\nstatic method is just a module-scope function wearing a class as a namespace.\n BAD: export function computeTotal(cart: Cart): number { ... }\n BAD: export class CartMath { static computeTotal(cart: Cart): number { ... } } // static = not injectable\n GOOD: @injectable(bindingScopeValues.Singleton)\n export class CartService { computeTotal(cart: Cart): number { ... } }\nThen inject CartService where you need it. Inline callbacks (arr.map(x => x)), promise handlers, and\nfunctions nested inside a method are fine — only MODULE-SCOPE function declarations, top-level\nconst-assigned functions, and STATIC methods/field-functions are flagged.`;\n\ninterface FnViolation {\n file: string;\n line: number;\n column: number;\n context: string;\n}\n\ninterface FnViolationInfo {\n line: number;\n column: number;\n context: string;\n hasDisableComment: boolean;\n}\n\nfunction isTestFile(filePath: string): boolean {\n return filePath.includes('.spec.ts') || filePath.includes('.test.ts') || filePath.includes('__tests__/');\n}\n\nfunction isDeclarationFile(filePath: string): boolean {\n return filePath.endsWith('.d.ts');\n}\n\n// True for a node carrying a `declare` modifier (ambient signature — not a real definition).\nfunction hasDeclareModifier(node: ts.Node): boolean {\n if (!ts.canHaveModifiers(node)) return false;\n const mods = ts.getModifiers(node);\n return mods?.some((m: ts.Modifier): boolean => m.kind === ts.SyntaxKind.DeclareKeyword) ?? false;\n}\n\n// True for a class member carrying the `static` modifier. A static method/field-function belongs\n// to the class object, not an instance, so it can't be injected — it is procedural code wearing a\n// class as a namespace, and is flagged the same as a module-scope function.\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction hasStaticModifier(node: ts.Node): boolean {\n if (!ts.canHaveModifiers(node)) return false;\n const mods = ts.getModifiers(node);\n return mods?.some((m: ts.Modifier): boolean => m.kind === ts.SyntaxKind.StaticKeyword) ?? false;\n}\n\n// A `static` method, or a `static` field initialized to an arrow/function-expression, on a class.\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction isStaticFunctionMember(node: ts.Node): boolean {\n if (ts.isMethodDeclaration(node)) return hasStaticModifier(node);\n if (ts.isPropertyDeclaration(node) && hasStaticModifier(node)) {\n const init = node.initializer;\n return init !== undefined && (ts.isArrowFunction(init) || ts.isFunctionExpression(init));\n }\n return false;\n}\n\n// Display name of a static member for the violation message.\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction staticMemberName(node: ts.MethodDeclaration | ts.PropertyDeclaration): string {\n return ts.isIdentifier(node.name) ? node.name.text : '<static>';\n}\n\n// The violation line (or the line just above it) carries the disable comment.\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_NAMES.NO_FUNCTION_OUTSIDE_CLASS)\n || hasDisable(previous, RULE_NAMES.NO_FUNCTION_OUTSIDE_CLASS);\n}\n\nfunction recordViolation(\n node: ts.Node,\n context: string,\n fileLines: string[],\n sourceFile: ts.SourceFile,\n violations: FnViolationInfo[],\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// Report a module-scope const whose initializer is an arrow / function-expression (a function\n// assigned to a top-level const). Non-function consts are left alone.\nfunction checkTopLevelConst(\n node: ts.VariableStatement,\n fileLines: string[],\n sourceFile: ts.SourceFile,\n violations: FnViolationInfo[],\n disableAllowed: boolean,\n): void {\n for (const decl of node.declarationList.declarations) {\n const init = decl.initializer;\n if (!init) continue;\n if (!ts.isArrowFunction(init) && !ts.isFunctionExpression(init)) continue;\n const name = ts.isIdentifier(decl.name) ? decl.name.text : '<fn>';\n recordViolation(decl, `const ${name} = <function> at module scope (outside any class)`, fileLines, sourceFile, violations, disableAllowed);\n }\n}\n\n// AST scan: a node is a violation only when its parent is the SourceFile (module scope).\nexport function findFunctionsOutsideClassInSource(content: string, filePath: string, disableAllowed: boolean): FnViolationInfo[] {\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: FnViolationInfo[] = [];\n\n function visit(node: ts.Node): void {\n if (ts.isFunctionDeclaration(node) && ts.isSourceFile(node.parent) && !hasDeclareModifier(node)) {\n const name = node.name?.text ?? '<anonymous>';\n recordViolation(node, `function ${name}() declared at module scope (outside any class)`, fileLines, sourceFile, violations, disableAllowed);\n }\n if (ts.isVariableStatement(node) && ts.isSourceFile(node.parent) && !hasDeclareModifier(node)) {\n checkTopLevelConst(node, fileLines, sourceFile, violations, disableAllowed);\n }\n if (isStaticFunctionMember(node) && !hasDeclareModifier(node)) {\n const name = staticMemberName(node as ts.MethodDeclaration | ts.PropertyDeclaration);\n recordViolation(node, `static ${name}() — a static method can't be injected; make it an instance method and inject the class`, fileLines, sourceFile, violations, disableAllowed);\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\nexport function findFunctionsOutsideClassInFile(filePath: string, workspaceRoot: string, disableAllowed: boolean, allowedPaths: string[]): FnViolationInfo[] {\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 findFunctionsOutsideClassInSource(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[]): FnViolation[] {\n const violations: FnViolation[] = [];\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 findFunctionsOutsideClassInFile(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[]): FnViolation[] {\n const violations: FnViolation[] = [];\n for (const file of changedFiles) {\n for (const v of findFunctionsOutsideClassInFile(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\nfunction reportViolations(violations: FnViolation[], mode: ModifiedCodeMode, disableAllowed: boolean): void {\n console.error('');\n console.error('❌ Function(s) created outside a class!');\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 no-function-outside-class -- <reason>'\n : ' Escape hatch: DISABLED (disableAllowed: false)');\n console.error(' Whole-tree exemption (e.g. React): add a glob to no-function-outside-class.allowedPaths in webpieces.config.json');\n console.error(`\\n Current mode: ${mode}\\n`);\n}\n\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 no-function-outside-class 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: NoFunctionOutsideClassConfig,\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 no-function-outside-class validation (mode: OFF)\\n');\n return { success: true };\n }\n\n console.log('\\n📏 Validating No Function Outside Class\\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 no-function-outside-class 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: FnViolation[] = [];\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 function-outside-class violations found');\n return { success: true };\n }\n\n scan.recordSites('no-function-outside-class', violations.map((v: FnViolation) => v.file));\n reportViolations(violations, mode, disableAllowed);\n return { success: false };\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoFunctionOutsideClassValidator extends CodeValidator<NoFunctionOutsideClassConfig> {\n constructor(config: NoFunctionOutsideClassConfig, private readonly scanScope: ScanScope) {\n super(config, 'no-function-outside-class', 'no-function-outside-class');\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runValidatorImpl(this.scanScope, this.config, workspaceRoot);\n }\n}\n"]}
@@ -26,7 +26,9 @@
26
26
  */
27
27
  import { NoImplicitAnyConfig } from '@webpieces/rules-config';
28
28
  import { CodeValidator, ExecutorResult } from './code-validator';
29
+ import { ScanScope } from './scan-scope';
29
30
  export declare class NoImplicitAnyValidator extends CodeValidator<NoImplicitAnyConfig> {
30
- constructor(config: NoImplicitAnyConfig);
31
+ private readonly scanScope;
32
+ constructor(config: NoImplicitAnyConfig, scanScope: ScanScope);
31
33
  run(workspaceRoot: string): Promise<ExecutorResult>;
32
34
  }
@@ -35,6 +35,7 @@ const rules_config_1 = require("@webpieces/rules-config");
35
35
  const code_validator_1 = require("./code-validator");
36
36
  const inversify_1 = require("inversify");
37
37
  const resolve_mode_1 = require("./resolve-mode");
38
+ const scan_scope_1 = require("./scan-scope");
38
39
  // TS diagnostic codes that describe an implicit-any inference. TS7010 (missing
39
40
  // return-type annotation) is intentionally omitted because it is already
40
41
  // covered by the sibling `require-return-type` validator.
@@ -189,7 +190,7 @@ function resolveMode(normalMode, epoch, branchPattern) {
189
190
  }
190
191
  return normalMode;
191
192
  }
192
- async function runInternal(options, workspaceRoot) {
193
+ async function runInternal(scan, options, workspaceRoot) {
193
194
  const mode = resolveMode(options.mode ?? 'OFF', options.turnOffRuleUntilEpoch, (options.turnOffRuleWhileOnBranch ?? undefined));
194
195
  const disableAllowed = options.disableAllowed ?? true;
195
196
  if (mode === 'OFF') {
@@ -212,7 +213,7 @@ async function runInternal(options, workspaceRoot) {
212
213
  console.log(` Base: ${base}`);
213
214
  console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);
214
215
  console.log('');
215
- const changedFiles = (0, rules_config_1.getChangedFiles)(workspaceRoot, base, head);
216
+ const changedFiles = scan.files(workspaceRoot, mode, base, head);
216
217
  if (changedFiles.length === 0) {
217
218
  console.log('\u2705 No TypeScript files changed');
218
219
  return { success: true };
@@ -222,20 +223,22 @@ async function runInternal(options, workspaceRoot) {
222
223
  if (mode === 'NEW_AND_MODIFIED_CODE') {
223
224
  violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed);
224
225
  }
225
- else if (mode === 'NEW_AND_MODIFIED_FILES') {
226
+ else {
227
+ // NEW_AND_MODIFIED_FILES and the whole-scope modes (#1027) all judge every site of every file.
226
228
  violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);
227
229
  }
228
230
  if (violations.length === 0) {
229
231
  console.log('\u2705 No implicit-any inferences found');
230
232
  return { success: true };
231
233
  }
234
+ scan.recordSites('no-implicit-any', violations.map((v) => v.file));
232
235
  reportViolations(violations, mode);
233
236
  return { success: false };
234
237
  }
235
- async function runValidatorImpl(options, workspaceRoot) {
238
+ async function runValidatorImpl(scan, options, workspaceRoot) {
236
239
  // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
237
240
  try {
238
- return await runInternal(options, workspaceRoot);
241
+ return await runInternal(scan, options, workspaceRoot);
239
242
  }
240
243
  catch (err) {
241
244
  //const error = toError(err);
@@ -244,16 +247,18 @@ async function runValidatorImpl(options, workspaceRoot) {
244
247
  }
245
248
  }
246
249
  let NoImplicitAnyValidator = class NoImplicitAnyValidator extends code_validator_1.CodeValidator {
247
- constructor(config) {
250
+ scanScope;
251
+ constructor(config, scanScope) {
248
252
  super(config, 'no-implicit-any', 'no-implicit-any');
253
+ this.scanScope = scanScope;
249
254
  }
250
255
  async run(workspaceRoot) {
251
- return runValidatorImpl(this.config, workspaceRoot);
256
+ return runValidatorImpl(this.scanScope, this.config, workspaceRoot);
252
257
  }
253
258
  };
254
259
  exports.NoImplicitAnyValidator = NoImplicitAnyValidator;
255
260
  exports.NoImplicitAnyValidator = NoImplicitAnyValidator = tslib_1.__decorate([
256
261
  (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
257
- tslib_1.__metadata("design:paramtypes", [rules_config_1.NoImplicitAnyConfig])
262
+ tslib_1.__metadata("design:paramtypes", [rules_config_1.NoImplicitAnyConfig, scan_scope_1.ScanScope])
258
263
  ], NoImplicitAnyValidator);
259
264
  //# sourceMappingURL=validate-no-implicit-any.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"validate-no-implicit-any.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-implicit-any.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,uDAAiC;AACjC,0DAAyK;AACzK,qDAAiE;AACjE,yCAA2D;AAC3D,iDAAgD;AAWhD,+EAA+E;AAC/E,yEAAyE;AACzE,0DAA0D;AAC1D,MAAM,kBAAkB,GAAwB,IAAI,GAAG,CAAS;IAC5D,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI;CACvD,CAAC,CAAC;AAEH,SAAS,iBAAiB,CAAC,KAAe,EAAE,UAAkB;IAC1D,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,UAAU,GAAG,CAAC,CAAC,CAAC;IAC/C,KAAK,IAAI,CAAC,GAAG,UAAU,GAAG,CAAC,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,EAAE,EAAE,CAAC;QAChD,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;QACpC,IAAI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AC,OAAO,EAAE,aAAa,CAAC,CAAC;IACrD,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,6BAA6B;QAC7B,OAAO,CAAC,IAAI,CAAC,+EAA+E,CAAC,CAAC;QAC9F,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7B,CAAC;AACL,CAAC;AAGM,IAAM,sBAAsB,GAA5B,MAAM,sBAAuB,SAAQ,8BAAkC;IAC1E,YAAY,MAA2B;QACnC,KAAK,CAAC,MAAM,EAAE,iBAAiB,EAAE,iBAAiB,CAAC,CAAC;IACxD,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,aAAqB;QAC3B,OAAO,gBAAgB,CAAC,IAAI,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IACxD,CAAC;CACJ,CAAA;AARY,wDAAsB;iCAAtB,sBAAsB;IADlC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEjB,kCAAmB;GAD9B,sBAAsB,CAQlC","sourcesContent":["/**\n * Validate No Implicit Any Executor\n *\n * Flags function parameters, variables, and object-literal properties whose\n * types collapse to the implicit `any` produced by TypeScript inference when\n * an annotation is missing. Pairs with validate-no-any-unknown (which bans\n * the literal keyword) so together they force developers to write real types.\n *\n * Detection leverages the TypeScript compiler directly: we build a ts.Program\n * from the project's tsconfig.json with `noImplicitAny: true` overridden, then\n * filter pre-emit diagnostics to the set of codes that describe implicit-any\n * inferences (TS7006, TS7005, TS7018, etc.) and map them back to changed lines.\n *\n * ============================================================================\n * MODES (LINE-BASED)\n * ============================================================================\n * - OFF: Skip validation entirely.\n * - NEW_AND_MODIFIED_CODE: Flag implicit-any on changed lines (lines in diff hunks).\n * - NEW_AND_MODIFIED_FILES: Flag ALL implicit-any in files that were modified.\n *\n * ============================================================================\n * ESCAPE HATCH\n * ============================================================================\n * // webpieces-disable no-implicit-any -- [your justification]\n * function handler(x) { ... }\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as ts from 'typescript';\nimport { hasDisable, RULE_NAMES, NoImplicitAnyConfig, ModifiedCodeMode, detectBase, getChangedFiles, getFileDiff, getChangedLineNumbers } from '@webpieces/rules-config';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { shouldSkipRule } from './resolve-mode';\n\ninterface ImplicitAnyViolation {\n file: string;\n line: number;\n column: number;\n code: number;\n message: string;\n hasDisableComment: boolean;\n}\n\n// TS diagnostic codes that describe an implicit-any inference. TS7010 (missing\n// return-type annotation) is intentionally omitted because it is already\n// covered by the sibling `require-return-type` validator.\nconst IMPLICIT_ANY_CODES: ReadonlySet<number> = new Set<number>([\n 7005, 7006, 7008, 7015, 7018, 7019, 7031, 7034, 7053,\n]);\n\nfunction hasDisableComment(lines: string[], lineNumber: number): boolean {\n const startCheck = Math.max(0, lineNumber - 5);\n for (let i = lineNumber - 2; i >= startCheck; i--) {\n const line = lines[i]?.trim() ?? '';\n if (line.startsWith('function ') || line.startsWith('class ') || line.endsWith('}')) {\n break;\n }\n if (hasDisable(line, RULE_NAMES.NO_IMPLICIT_ANY)) {\n return true;\n }\n }\n return false;\n}\n\n// Cache one ts.Program per tsconfig.json so multiple changed files in the\n// same project share parse/binding cost.\nconst programCache = new Map<string, ts.Program | null>();\n\nfunction findTsConfigForFile(absoluteFilePath: string, workspaceRoot: string): string | null {\n const root = path.resolve(workspaceRoot);\n let dir = path.dirname(absoluteFilePath);\n while (dir.startsWith(root)) {\n const candidate = path.join(dir, 'tsconfig.json');\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\nfunction buildProgram(tsconfigPath: string): ts.Program | null {\n const configFile = ts.readConfigFile(tsconfigPath, (p: string) => ts.sys.readFile(p));\n if (configFile.error) return null;\n const parsed = ts.parseJsonConfigFileContent(configFile.config, ts.sys, path.dirname(tsconfigPath));\n if (parsed.errors.length > 0 || parsed.fileNames.length === 0) return null;\n const options: ts.CompilerOptions = { ...parsed.options, noImplicitAny: true, noEmit: true, skipLibCheck: true };\n return ts.createProgram({ rootNames: parsed.fileNames, options });\n}\n\nfunction getProgramForFile(absoluteFilePath: string, workspaceRoot: string): ts.Program | null {\n const tsconfigPath = findTsConfigForFile(absoluteFilePath, workspaceRoot);\n if (!tsconfigPath) return null;\n if (programCache.has(tsconfigPath)) {\n return programCache.get(tsconfigPath) ?? null;\n }\n const program = buildProgram(tsconfigPath);\n programCache.set(tsconfigPath, program);\n return program;\n}\n\nfunction flattenMessage(message: string | ts.DiagnosticMessageChain): string {\n return ts.flattenDiagnosticMessageText(message, ' ');\n}\n\nfunction findImplicitAnyInFile(filePath: string, workspaceRoot: string): ImplicitAnyViolation[] {\n const absolute = path.resolve(workspaceRoot, filePath);\n if (!fs.existsSync(absolute)) return [];\n\n const program = getProgramForFile(absolute, workspaceRoot);\n if (!program) return [];\n\n const sourceFile = program.getSourceFile(absolute);\n if (!sourceFile) return [];\n\n const fileLines = fs.readFileSync(absolute, 'utf-8').split('\\n');\n const diagnostics = ts.getPreEmitDiagnostics(program, sourceFile);\n const violations: ImplicitAnyViolation[] = [];\n\n for (const diag of diagnostics) {\n if (!IMPLICIT_ANY_CODES.has(diag.code)) continue;\n if (!diag.file || diag.start === undefined) continue;\n const pos = diag.file.getLineAndCharacterOfPosition(diag.start);\n const line = pos.line + 1;\n const column = pos.character + 1;\n violations.push({\n file: filePath,\n line,\n column,\n code: diag.code,\n message: flattenMessage(diag.messageText),\n hasDisableComment: hasDisableComment(fileLines, line),\n });\n }\n\n return violations;\n}\n\nfunction findViolationsForModifiedCode(\n workspaceRoot: string,\n changedFiles: string[],\n base: string,\n head: string | undefined,\n disableAllowed: boolean,\n): ImplicitAnyViolation[] {\n const results: ImplicitAnyViolation[] = [];\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 const all = findImplicitAnyInFile(file, workspaceRoot);\n for (const v of all) {\n if (disableAllowed && v.hasDisableComment) continue;\n if (!changedLines.has(v.line)) continue;\n results.push(v);\n }\n }\n return results;\n}\n\nfunction findViolationsForModifiedFiles(\n workspaceRoot: string,\n changedFiles: string[],\n disableAllowed: boolean,\n): ImplicitAnyViolation[] {\n const results: ImplicitAnyViolation[] = [];\n for (const file of changedFiles) {\n const all = findImplicitAnyInFile(file, workspaceRoot);\n for (const v of all) {\n if (disableAllowed && v.hasDisableComment) continue;\n results.push(v);\n }\n }\n return results;\n}\n\nfunction reportViolations(violations: ImplicitAnyViolation[], mode: ModifiedCodeMode): void {\n console.error('');\n console.error('\\u274c Implicit-any inferences found! Add explicit type annotations.');\n console.error('');\n console.error('\\ud83d\\udcda Why: an untyped parameter or variable erases type safety silently.');\n console.error('');\n console.error(' BAD: function process(input) { return input.length; }');\n console.error(' GOOD: function process(input: string): number { return input.length; }');\n console.error('');\n\n for (const v of violations) {\n console.error(` \\u274c ${v.file}:${v.line}:${v.column}`);\n console.error(` TS${v.code}: ${v.message}`);\n }\n console.error('');\n console.error(' Escape hatch (use sparingly):');\n console.error(' // webpieces-disable no-implicit-any -- [your reason]');\n console.error('');\n console.error(` Current mode: ${mode}`);\n console.error('');\n}\n\nfunction resolveMode(normalMode: ModifiedCodeMode, epoch: number | undefined, branchPattern: string | undefined): ModifiedCodeMode {\n if (normalMode === 'OFF') {\n return normalMode;\n }\n const skip = shouldSkipRule(epoch, branchPattern);\n if (skip.skip) {\n console.log(`\\n\\u23ed\\ufe0f Skipping no-implicit-any validation (${skip.reason})`);\n console.log('');\n return 'OFF';\n }\n return normalMode;\n}\n\nasync function runInternal(\n options: NoImplicitAnyConfig,\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\n if (mode === 'OFF') {\n console.log('\\n\\u23ed\\ufe0f Skipping no-implicit-any validation (mode: OFF)');\n console.log('');\n return { success: true };\n }\n\n console.log('\\n\\ud83d\\udccf Validating No Implicit Any\\n');\n console.log(` Mode: ${mode}`);\n\n let base = process.env['NX_BASE'];\n const head = process.env['NX_HEAD'];\n\n if (!base) {\n base = detectBase(workspaceRoot) ?? undefined;\n if (!base) {\n console.log('\\n\\u23ed\\ufe0f Skipping no-implicit-any validation (could not detect base branch)');\n console.log('');\n return { success: true };\n }\n }\n\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);\n console.log('');\n\n const changedFiles = getChangedFiles(workspaceRoot, base, head);\n if (changedFiles.length === 0) {\n console.log('\\u2705 No TypeScript files changed');\n return { success: true };\n }\n\n console.log(`\\ud83d\\udcc2 Checking ${changedFiles.length} changed file(s)...`);\n\n let violations: ImplicitAnyViolation[] = [];\n if (mode === 'NEW_AND_MODIFIED_CODE') {\n violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed);\n } else if (mode === 'NEW_AND_MODIFIED_FILES') {\n violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);\n }\n\n if (violations.length === 0) {\n console.log('\\u2705 No implicit-any inferences found');\n return { success: true };\n }\n\n reportViolations(violations, mode);\n return { success: false };\n}\n\nasync function runValidatorImpl(\n options: NoImplicitAnyConfig,\n workspaceRoot: string\n): Promise<ExecutorResult> {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return await runInternal(options, workspaceRoot);\n } catch (err: unknown) {\n //const error = toError(err);\n console.warn('\\n\\u23ed\\ufe0f Skipping no-implicit-any validation due to unexpected error\\n');\n return { success: true };\n }\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoImplicitAnyValidator extends CodeValidator<NoImplicitAnyConfig> {\n constructor(config: NoImplicitAnyConfig) {\n super(config, 'no-implicit-any', 'no-implicit-any');\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runValidatorImpl(this.config, workspaceRoot);\n }\n}\n"]}
1
+ {"version":3,"file":"validate-no-implicit-any.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-implicit-any.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,uDAAiC;AACjC,0DAAwJ;AACxJ,qDAAiE;AACjE,yCAA2D;AAC3D,iDAAgD;AAChD,6CAAyC;AAWzC,+EAA+E;AAC/E,yEAAyE;AACzE,0DAA0D;AAC1D,MAAM,kBAAkB,GAAwB,IAAI,GAAG,CAAS;IAC5D,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI;CACvD,CAAC,CAAC;AAEH,SAAS,iBAAiB,CAAC,KAAe,EAAE,UAAkB;IAC1D,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,UAAU,GAAG,CAAC,CAAC,CAAC;IAC/C,KAAK,IAAI,CAAC,GAAG,UAAU,GAAG,CAAC,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,EAAE,EAAE,CAAC;QAChD,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;QACpC,IAAI,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;YAClF,MAAM;QACV,CAAC;QACD,IAAI,IAAA,yBAAU,EAAC,IAAI,EAAE,yBAAU,CAAC,eAAe,CAAC,EAAE,CAAC;YAC/C,OAAO,IAAI,CAAC;QAChB,CAAC;IACL,CAAC;IACD,OAAO,KAAK,CAAC;AACjB,CAAC;AAED,0EAA0E;AAC1E,yCAAyC;AACzC,MAAM,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AC7B,CAAC;AACL,CAAC;AAGM,IAAM,sBAAsB,GAA5B,MAAM,sBAAuB,SAAQ,8BAAkC;IAChB;IAA1D,YAAY,MAA2B,EAAmB,SAAoB;QAC1E,KAAK,CAAC,MAAM,EAAE,iBAAiB,EAAE,iBAAiB,CAAC,CAAC;QADE,cAAS,GAAT,SAAS,CAAW;IAE9E,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,wDAAsB;iCAAtB,sBAAsB;IADlC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEjB,kCAAmB,EAA8B,sBAAS;GADrE,sBAAsB,CAQlC","sourcesContent":["/**\n * Validate No Implicit Any Executor\n *\n * Flags function parameters, variables, and object-literal properties whose\n * types collapse to the implicit `any` produced by TypeScript inference when\n * an annotation is missing. Pairs with validate-no-any-unknown (which bans\n * the literal keyword) so together they force developers to write real types.\n *\n * Detection leverages the TypeScript compiler directly: we build a ts.Program\n * from the project's tsconfig.json with `noImplicitAny: true` overridden, then\n * filter pre-emit diagnostics to the set of codes that describe implicit-any\n * inferences (TS7006, TS7005, TS7018, etc.) and map them back to changed lines.\n *\n * ============================================================================\n * MODES (LINE-BASED)\n * ============================================================================\n * - OFF: Skip validation entirely.\n * - NEW_AND_MODIFIED_CODE: Flag implicit-any on changed lines (lines in diff hunks).\n * - NEW_AND_MODIFIED_FILES: Flag ALL implicit-any in files that were modified.\n *\n * ============================================================================\n * ESCAPE HATCH\n * ============================================================================\n * // webpieces-disable no-implicit-any -- [your justification]\n * function handler(x) { ... }\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as ts from 'typescript';\nimport { hasDisable, RULE_NAMES, NoImplicitAnyConfig, ModifiedCodeMode, detectBase, getFileDiff, getChangedLineNumbers } from '@webpieces/rules-config';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { shouldSkipRule } from './resolve-mode';\nimport { ScanScope } from './scan-scope';\n\ninterface ImplicitAnyViolation {\n file: string;\n line: number;\n column: number;\n code: number;\n message: string;\n hasDisableComment: boolean;\n}\n\n// TS diagnostic codes that describe an implicit-any inference. TS7010 (missing\n// return-type annotation) is intentionally omitted because it is already\n// covered by the sibling `require-return-type` validator.\nconst IMPLICIT_ANY_CODES: ReadonlySet<number> = new Set<number>([\n 7005, 7006, 7008, 7015, 7018, 7019, 7031, 7034, 7053,\n]);\n\nfunction hasDisableComment(lines: string[], lineNumber: number): boolean {\n const startCheck = Math.max(0, lineNumber - 5);\n for (let i = lineNumber - 2; i >= startCheck; i--) {\n const line = lines[i]?.trim() ?? '';\n if (line.startsWith('function ') || line.startsWith('class ') || line.endsWith('}')) {\n break;\n }\n if (hasDisable(line, RULE_NAMES.NO_IMPLICIT_ANY)) {\n return true;\n }\n }\n return false;\n}\n\n// Cache one ts.Program per tsconfig.json so multiple changed files in the\n// same project share parse/binding cost.\nconst programCache = new Map<string, ts.Program | null>();\n\nfunction findTsConfigForFile(absoluteFilePath: string, workspaceRoot: string): string | null {\n const root = path.resolve(workspaceRoot);\n let dir = path.dirname(absoluteFilePath);\n while (dir.startsWith(root)) {\n const candidate = path.join(dir, 'tsconfig.json');\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\nfunction buildProgram(tsconfigPath: string): ts.Program | null {\n const configFile = ts.readConfigFile(tsconfigPath, (p: string) => ts.sys.readFile(p));\n if (configFile.error) return null;\n const parsed = ts.parseJsonConfigFileContent(configFile.config, ts.sys, path.dirname(tsconfigPath));\n if (parsed.errors.length > 0 || parsed.fileNames.length === 0) return null;\n const options: ts.CompilerOptions = { ...parsed.options, noImplicitAny: true, noEmit: true, skipLibCheck: true };\n return ts.createProgram({ rootNames: parsed.fileNames, options });\n}\n\nfunction getProgramForFile(absoluteFilePath: string, workspaceRoot: string): ts.Program | null {\n const tsconfigPath = findTsConfigForFile(absoluteFilePath, workspaceRoot);\n if (!tsconfigPath) return null;\n if (programCache.has(tsconfigPath)) {\n return programCache.get(tsconfigPath) ?? null;\n }\n const program = buildProgram(tsconfigPath);\n programCache.set(tsconfigPath, program);\n return program;\n}\n\nfunction flattenMessage(message: string | ts.DiagnosticMessageChain): string {\n return ts.flattenDiagnosticMessageText(message, ' ');\n}\n\nfunction findImplicitAnyInFile(filePath: string, workspaceRoot: string): ImplicitAnyViolation[] {\n const absolute = path.resolve(workspaceRoot, filePath);\n if (!fs.existsSync(absolute)) return [];\n\n const program = getProgramForFile(absolute, workspaceRoot);\n if (!program) return [];\n\n const sourceFile = program.getSourceFile(absolute);\n if (!sourceFile) return [];\n\n const fileLines = fs.readFileSync(absolute, 'utf-8').split('\\n');\n const diagnostics = ts.getPreEmitDiagnostics(program, sourceFile);\n const violations: ImplicitAnyViolation[] = [];\n\n for (const diag of diagnostics) {\n if (!IMPLICIT_ANY_CODES.has(diag.code)) continue;\n if (!diag.file || diag.start === undefined) continue;\n const pos = diag.file.getLineAndCharacterOfPosition(diag.start);\n const line = pos.line + 1;\n const column = pos.character + 1;\n violations.push({\n file: filePath,\n line,\n column,\n code: diag.code,\n message: flattenMessage(diag.messageText),\n hasDisableComment: hasDisableComment(fileLines, line),\n });\n }\n\n return violations;\n}\n\nfunction findViolationsForModifiedCode(\n workspaceRoot: string,\n changedFiles: string[],\n base: string,\n head: string | undefined,\n disableAllowed: boolean,\n): ImplicitAnyViolation[] {\n const results: ImplicitAnyViolation[] = [];\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 const all = findImplicitAnyInFile(file, workspaceRoot);\n for (const v of all) {\n if (disableAllowed && v.hasDisableComment) continue;\n if (!changedLines.has(v.line)) continue;\n results.push(v);\n }\n }\n return results;\n}\n\nfunction findViolationsForModifiedFiles(\n workspaceRoot: string,\n changedFiles: string[],\n disableAllowed: boolean,\n): ImplicitAnyViolation[] {\n const results: ImplicitAnyViolation[] = [];\n for (const file of changedFiles) {\n const all = findImplicitAnyInFile(file, workspaceRoot);\n for (const v of all) {\n if (disableAllowed && v.hasDisableComment) continue;\n results.push(v);\n }\n }\n return results;\n}\n\nfunction reportViolations(violations: ImplicitAnyViolation[], mode: ModifiedCodeMode): void {\n console.error('');\n console.error('\\u274c Implicit-any inferences found! Add explicit type annotations.');\n console.error('');\n console.error('\\ud83d\\udcda Why: an untyped parameter or variable erases type safety silently.');\n console.error('');\n console.error(' BAD: function process(input) { return input.length; }');\n console.error(' GOOD: function process(input: string): number { return input.length; }');\n console.error('');\n\n for (const v of violations) {\n console.error(` \\u274c ${v.file}:${v.line}:${v.column}`);\n console.error(` TS${v.code}: ${v.message}`);\n }\n console.error('');\n console.error(' Escape hatch (use sparingly):');\n console.error(' // webpieces-disable no-implicit-any -- [your reason]');\n console.error('');\n console.error(` Current mode: ${mode}`);\n console.error('');\n}\n\nfunction resolveMode(normalMode: ModifiedCodeMode, epoch: number | undefined, branchPattern: string | undefined): ModifiedCodeMode {\n if (normalMode === 'OFF') {\n return normalMode;\n }\n const skip = shouldSkipRule(epoch, branchPattern);\n if (skip.skip) {\n console.log(`\\n\\u23ed\\ufe0f Skipping no-implicit-any validation (${skip.reason})`);\n console.log('');\n return 'OFF';\n }\n return normalMode;\n}\n\nasync function runInternal(\n scan: ScanScope,\n options: NoImplicitAnyConfig,\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\n if (mode === 'OFF') {\n console.log('\\n\\u23ed\\ufe0f Skipping no-implicit-any validation (mode: OFF)');\n console.log('');\n return { success: true };\n }\n\n console.log('\\n\\ud83d\\udccf Validating No Implicit Any\\n');\n console.log(` Mode: ${mode}`);\n\n let base = process.env['NX_BASE'];\n const head = process.env['NX_HEAD'];\n\n if (!base) {\n base = detectBase(workspaceRoot) ?? undefined;\n if (!base) {\n console.log('\\n\\u23ed\\ufe0f Skipping no-implicit-any validation (could not detect base branch)');\n console.log('');\n return { success: true };\n }\n }\n\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);\n console.log('');\n\n const changedFiles = scan.files(workspaceRoot, mode, base, head);\n if (changedFiles.length === 0) {\n console.log('\\u2705 No TypeScript files changed');\n return { success: true };\n }\n\n console.log(`\\ud83d\\udcc2 Checking ${changedFiles.length} changed file(s)...`);\n\n let violations: ImplicitAnyViolation[] = [];\n if (mode === 'NEW_AND_MODIFIED_CODE') {\n violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed);\n } else {\n // NEW_AND_MODIFIED_FILES and the whole-scope modes (#1027) all judge every site of every file.\n violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);\n }\n\n if (violations.length === 0) {\n console.log('\\u2705 No implicit-any inferences found');\n return { success: true };\n }\n\n scan.recordSites('no-implicit-any', violations.map((v: ImplicitAnyViolation) => v.file));\n reportViolations(violations, mode);\n return { success: false };\n}\n\nasync function runValidatorImpl(\n scan: ScanScope,\n options: NoImplicitAnyConfig,\n workspaceRoot: string\n): Promise<ExecutorResult> {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return await runInternal(scan, options, workspaceRoot);\n } catch (err: unknown) {\n //const error = toError(err);\n console.warn('\\n\\u23ed\\ufe0f Skipping no-implicit-any validation due to unexpected error\\n');\n return { success: true };\n }\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoImplicitAnyValidator extends CodeValidator<NoImplicitAnyConfig> {\n constructor(config: NoImplicitAnyConfig, private readonly scanScope: ScanScope) {\n super(config, 'no-implicit-any', 'no-implicit-any');\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runValidatorImpl(this.scanScope, this.config, workspaceRoot);\n }\n}\n"]}
@@ -19,6 +19,7 @@
19
19
  import { DiffScope, NoInlineImportInApiLibConfig } from '@webpieces/rules-config';
20
20
  import { ApiLibFile, ApiLibSite, ApiLibSourceRule } from './api-lib-source-rule';
21
21
  import { ProjectRoleResolver } from './project-role-resolver';
22
+ import { ScanScope } from './scan-scope';
22
23
  /** Finds every inline `import()` in one parsed file. */
23
24
  export declare class InlineImportScanner {
24
25
  scan(file: ApiLibFile): ApiLibSite[];
@@ -32,7 +33,7 @@ export declare class InlineImportScanner {
32
33
  }
33
34
  export declare class NoInlineImportInApiLibValidator extends ApiLibSourceRule<NoInlineImportInApiLibConfig> {
34
35
  private readonly scanner;
35
- constructor(config: NoInlineImportInApiLibConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope);
36
+ constructor(config: NoInlineImportInApiLibConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope, scanScope: ScanScope);
36
37
  protected sitesIn(file: ApiLibFile): ApiLibSite[];
37
38
  protected why(): string;
38
39
  }
@@ -25,6 +25,7 @@ const inversify_1 = require("inversify");
25
25
  const ts = tslib_1.__importStar(require("typescript"));
26
26
  const api_lib_source_rule_1 = require("./api-lib-source-rule");
27
27
  const project_role_resolver_1 = require("./project-role-resolver");
28
+ const scan_scope_1 = require("./scan-scope");
28
29
  /** Finds every inline `import()` in one parsed file. */
29
30
  class InlineImportScanner {
30
31
  scan(file) {
@@ -77,8 +78,8 @@ class InlineImportScanner {
77
78
  exports.InlineImportScanner = InlineImportScanner;
78
79
  let NoInlineImportInApiLibValidator = class NoInlineImportInApiLibValidator extends api_lib_source_rule_1.ApiLibSourceRule {
79
80
  scanner = new InlineImportScanner();
80
- constructor(config, roleResolver, diffScope) {
81
- super(config, rules_config_1.RULE_NAMES.NO_INLINE_IMPORT_IN_API_LIB, roleResolver, diffScope);
81
+ constructor(config, roleResolver, diffScope, scanScope) {
82
+ super(config, rules_config_1.RULE_NAMES.NO_INLINE_IMPORT_IN_API_LIB, roleResolver, diffScope, scanScope);
82
83
  }
83
84
  sitesIn(file) {
84
85
  return this.scanner.scan(file);
@@ -91,6 +92,6 @@ let NoInlineImportInApiLibValidator = class NoInlineImportInApiLibValidator exte
91
92
  exports.NoInlineImportInApiLibValidator = NoInlineImportInApiLibValidator;
92
93
  exports.NoInlineImportInApiLibValidator = NoInlineImportInApiLibValidator = tslib_1.__decorate([
93
94
  (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
94
- tslib_1.__metadata("design:paramtypes", [rules_config_1.NoInlineImportInApiLibConfig, project_role_resolver_1.ProjectRoleResolver, rules_config_1.DiffScope])
95
+ tslib_1.__metadata("design:paramtypes", [rules_config_1.NoInlineImportInApiLibConfig, project_role_resolver_1.ProjectRoleResolver, rules_config_1.DiffScope, scan_scope_1.ScanScope])
95
96
  ], NoInlineImportInApiLibValidator);
96
97
  //# sourceMappingURL=validate-no-inline-import-in-api-lib.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"validate-no-inline-import-in-api-lib.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-inline-import-in-api-lib.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;GAiBG;;;;AAEH,0DAA8F;AAC9F,yCAA2D;AAC3D,uDAAiC;AACjC,+DAAiF;AACjF,mEAA8D;AAE9D,wDAAwD;AACxD,MAAa,mBAAmB;IAC5B,IAAI,CAAC,IAAgB;QACjB,MAAM,KAAK,GAAiB,EAAE,CAAC;QAC/B,MAAM,KAAK,GAAG,CAAC,IAAa,EAAQ,EAAE;YAClC,IAAI,EAAE,CAAC,gBAAgB,CAAC,IAAI,CAAC;gBAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;iBAChE,IAAI,EAAE,CAAC,gBAAgB,CAAC,IAAI,CAAC,IAAI,IAAI,C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KAAK,EAAE,CAAC;aACnE,GAAG,CAAC,CAAC,IAAY,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC,CAAE,CAAC,WAAW,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,QAAQ,CAAC;IAC5F,CAAC;CACJ;AArDD,kDAqDC;AAGM,IAAM,+BAA+B,GAArC,MAAM,+BAAgC,SAAQ,sCAA8C;IAC9E,OAAO,GAAG,IAAI,mBAAmB,EAAE,CAAC;IAErD,YAAY,MAAoC,EAAE,YAAiC,EAAE,SAAoB;QACrG,KAAK,CAAC,MAAM,EAAE,yBAAU,CAAC,2BAA2B,EAAE,YAAY,EAAE,SAAS,CAAC,CAAC;IACnF,CAAC;IAES,OAAO,CAAC,IAAgB;QAC9B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACnC,CAAC;IAES,GAAG;QACT,OAAO,oGAAoG;YACvG,qGAAqG,CAAC;IAC9G,CAAC;CACJ,CAAA;AAfY,0EAA+B;0CAA/B,+BAA+B;IAD3C,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAIjB,2CAA4B,EAAgB,2CAAmB,EAAa,wBAAS;GAHhG,+BAA+B,CAe3C","sourcesContent":["/**\n * `no-inline-import-in-api-lib` (#1023) — an API imports at the top of the file, only.\n *\n * In every `role:api-lib` project this refuses:\n *\n * activeAiProvider?: import('@myorg/company-core').AiProvider; // an import() TYPE node\n * const mod = await import('./heavy'); // a dynamic import() EXPRESSION\n *\n * and prints the replacement:\n *\n * import { AiProvider } from '@myorg/company-core';\n * activeAiProvider?: AiProvider;\n *\n * Why: an api library is the contract every client, server and document generator reads. An inline\n * `import()` hides a cross-library dependency inside a field's type, where no reader of the file's\n * imports — human, architecture graph or generator — sees it, and a dynamic import in a contract is\n * runtime behaviour in a file that should carry none.\n */\n\nimport { DiffScope, NoInlineImportInApiLibConfig, RULE_NAMES } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport * as ts from 'typescript';\nimport { ApiLibFile, ApiLibSite, ApiLibSourceRule } from './api-lib-source-rule';\nimport { ProjectRoleResolver } from './project-role-resolver';\n\n/** Finds every inline `import()` in one parsed file. */\nexport class InlineImportScanner {\n scan(file: ApiLibFile): ApiLibSite[] {\n const sites: ApiLibSite[] = [];\n const visit = (node: ts.Node): void => {\n if (ts.isImportTypeNode(node)) sites.push(this.typeSite(file, node));\n else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {\n sites.push(this.expressionSite(file, node));\n }\n ts.forEachChild(node, visit);\n };\n visit(file.source);\n return sites;\n }\n\n /** `import('m').A.B` → `import { A } from 'm';` and `A.B` in its place. */\n private typeSite(file: ApiLibFile, node: ts.ImportTypeNode): ApiLibSite {\n const specifier = this.specifierOf(node);\n const qualifier = node.qualifier === undefined ? undefined : this.entityText(node.qualifier);\n const first = qualifier?.split('.')[0];\n const what = 'an import() TYPE — an API imports at the top of the file, only';\n if (first === undefined) {\n return file.site(node, what,\n `add \\`import * as ${this.namespaceFor(specifier)} from '${specifier}';\\` at the top of the file and ` +\n `write \\`${node.isTypeOf ? 'typeof ' : ''}${this.namespaceFor(specifier)}\\` here.`);\n }\n return file.site(node, what,\n `add \\`import { ${first} } from '${specifier}';\\` at the top of the file and write ` +\n `\\`${node.isTypeOf ? 'typeof ' : ''}${qualifier}\\` here instead of \\`${node.getText(file.source)}\\`.`);\n }\n\n private expressionSite(file: ApiLibFile, node: ts.CallExpression): ApiLibSite {\n const argument = node.arguments[0];\n const specifier = argument !== undefined && ts.isStringLiteralLike(argument) ? argument.text : '<module>';\n return file.site(node, 'a dynamic import() EXPRESSION — an API loads nothing lazily; it imports at the top of the file, only',\n `replace it with a static \\`import { … } from '${specifier}';\\` at the top of the file, naming what is used.`);\n }\n\n private specifierOf(node: ts.ImportTypeNode): string {\n const argument = node.argument;\n if (ts.isLiteralTypeNode(argument) && ts.isStringLiteral(argument.literal)) return argument.literal.text;\n return argument.getText();\n }\n\n private entityText(name: ts.EntityName): string {\n return ts.isIdentifier(name) ? name.text : `${this.entityText(name.left)}.${name.right.text}`;\n }\n\n /** A PascalCase namespace name for a module specifier: `@myorg/company-core` → `CompanyCore`. */\n private namespaceFor(specifier: string): string {\n const last = specifier.split('/').pop() ?? specifier;\n return last.split(/[^A-Za-z0-9]+/).filter((part: string) => part !== '')\n .map((part: string) => part[0]!.toUpperCase() + part.slice(1)).join('') || 'Module';\n }\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoInlineImportInApiLibValidator extends ApiLibSourceRule<NoInlineImportInApiLibConfig> {\n private readonly scanner = new InlineImportScanner();\n\n constructor(config: NoInlineImportInApiLibConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope) {\n super(config, RULE_NAMES.NO_INLINE_IMPORT_IN_API_LIB, roleResolver, diffScope);\n }\n\n protected sitesIn(file: ApiLibFile): ApiLibSite[] {\n return this.scanner.scan(file);\n }\n\n protected why(): string {\n return 'an API imports at the top of the file, only — an inline import() hides a cross-library dependency ' +\n 'from every reader of the contract\\'s imports, and a dynamic one is runtime behaviour in a contract.';\n }\n}\n"]}
1
+ {"version":3,"file":"validate-no-inline-import-in-api-lib.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-inline-import-in-api-lib.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;GAiBG;;;;AAEH,0DAA8F;AAC9F,yCAA2D;AAC3D,uDAAiC;AACjC,+DAAiF;AACjF,mEAA8D;AAC9D,6CAAyC;AAEzC,wDAAwD;AACxD,MAAa,mBAAmB;IAC5B,IAAI,CAAC,IAAgB;QACjB,MAAM,KAAK,GAAiB,EAAE,CAAC;QAC/B,MAAM,KAAK,GAAG,CAAC,IAAa,EAAQ,EAAE;YAClC,IAAI,EAAE,CAAC,gBAAgB,CAAC,IAAI,CAAC;gBAAE,KAAK,CAAC,IAAI,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GAAG,EAAE,IAAI,SAAS,CAAC;QACrD,OAAO,IAAI,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC,MAAM,CAAC,CAAC,IAAY,EAAE,EAAE,CAAC,IAAI,KAAK,EAAE,CAAC;aACnE,GAAG,CAAC,CAAC,IAAY,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC,CAAE,CAAC,WAAW,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,QAAQ,CAAC;IAC5F,CAAC;CACJ;AArDD,kDAqDC;AAGM,IAAM,+BAA+B,GAArC,MAAM,+BAAgC,SAAQ,sCAA8C;IAC9E,OAAO,GAAG,IAAI,mBAAmB,EAAE,CAAC;IAErD,YAAY,MAAoC,EAAE,YAAiC,EAAE,SAAoB,EAAE,SAAoB;QAC3H,KAAK,CAAC,MAAM,EAAE,yBAAU,CAAC,2BAA2B,EAAE,YAAY,EAAE,SAAS,EAAE,SAAS,CAAC,CAAC;IAC9F,CAAC;IAES,OAAO,CAAC,IAAgB;QAC9B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACnC,CAAC;IAES,GAAG;QACT,OAAO,oGAAoG;YACvG,qGAAqG,CAAC;IAC9G,CAAC;CACJ,CAAA;AAfY,0EAA+B;0CAA/B,+BAA+B;IAD3C,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAIjB,2CAA4B,EAAgB,2CAAmB,EAAa,wBAAS,EAAa,sBAAS;GAHtH,+BAA+B,CAe3C","sourcesContent":["/**\n * `no-inline-import-in-api-lib` (#1023) — an API imports at the top of the file, only.\n *\n * In every `role:api-lib` project this refuses:\n *\n * activeAiProvider?: import('@myorg/company-core').AiProvider; // an import() TYPE node\n * const mod = await import('./heavy'); // a dynamic import() EXPRESSION\n *\n * and prints the replacement:\n *\n * import { AiProvider } from '@myorg/company-core';\n * activeAiProvider?: AiProvider;\n *\n * Why: an api library is the contract every client, server and document generator reads. An inline\n * `import()` hides a cross-library dependency inside a field's type, where no reader of the file's\n * imports — human, architecture graph or generator — sees it, and a dynamic import in a contract is\n * runtime behaviour in a file that should carry none.\n */\n\nimport { DiffScope, NoInlineImportInApiLibConfig, RULE_NAMES } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport * as ts from 'typescript';\nimport { ApiLibFile, ApiLibSite, ApiLibSourceRule } from './api-lib-source-rule';\nimport { ProjectRoleResolver } from './project-role-resolver';\nimport { ScanScope } from './scan-scope';\n\n/** Finds every inline `import()` in one parsed file. */\nexport class InlineImportScanner {\n scan(file: ApiLibFile): ApiLibSite[] {\n const sites: ApiLibSite[] = [];\n const visit = (node: ts.Node): void => {\n if (ts.isImportTypeNode(node)) sites.push(this.typeSite(file, node));\n else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {\n sites.push(this.expressionSite(file, node));\n }\n ts.forEachChild(node, visit);\n };\n visit(file.source);\n return sites;\n }\n\n /** `import('m').A.B` → `import { A } from 'm';` and `A.B` in its place. */\n private typeSite(file: ApiLibFile, node: ts.ImportTypeNode): ApiLibSite {\n const specifier = this.specifierOf(node);\n const qualifier = node.qualifier === undefined ? undefined : this.entityText(node.qualifier);\n const first = qualifier?.split('.')[0];\n const what = 'an import() TYPE — an API imports at the top of the file, only';\n if (first === undefined) {\n return file.site(node, what,\n `add \\`import * as ${this.namespaceFor(specifier)} from '${specifier}';\\` at the top of the file and ` +\n `write \\`${node.isTypeOf ? 'typeof ' : ''}${this.namespaceFor(specifier)}\\` here.`);\n }\n return file.site(node, what,\n `add \\`import { ${first} } from '${specifier}';\\` at the top of the file and write ` +\n `\\`${node.isTypeOf ? 'typeof ' : ''}${qualifier}\\` here instead of \\`${node.getText(file.source)}\\`.`);\n }\n\n private expressionSite(file: ApiLibFile, node: ts.CallExpression): ApiLibSite {\n const argument = node.arguments[0];\n const specifier = argument !== undefined && ts.isStringLiteralLike(argument) ? argument.text : '<module>';\n return file.site(node, 'a dynamic import() EXPRESSION — an API loads nothing lazily; it imports at the top of the file, only',\n `replace it with a static \\`import { … } from '${specifier}';\\` at the top of the file, naming what is used.`);\n }\n\n private specifierOf(node: ts.ImportTypeNode): string {\n const argument = node.argument;\n if (ts.isLiteralTypeNode(argument) && ts.isStringLiteral(argument.literal)) return argument.literal.text;\n return argument.getText();\n }\n\n private entityText(name: ts.EntityName): string {\n return ts.isIdentifier(name) ? name.text : `${this.entityText(name.left)}.${name.right.text}`;\n }\n\n /** A PascalCase namespace name for a module specifier: `@myorg/company-core` → `CompanyCore`. */\n private namespaceFor(specifier: string): string {\n const last = specifier.split('/').pop() ?? specifier;\n return last.split(/[^A-Za-z0-9]+/).filter((part: string) => part !== '')\n .map((part: string) => part[0]!.toUpperCase() + part.slice(1)).join('') || 'Module';\n }\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoInlineImportInApiLibValidator extends ApiLibSourceRule<NoInlineImportInApiLibConfig> {\n private readonly scanner = new InlineImportScanner();\n\n constructor(config: NoInlineImportInApiLibConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope, scanScope: ScanScope) {\n super(config, RULE_NAMES.NO_INLINE_IMPORT_IN_API_LIB, roleResolver, diffScope, scanScope);\n }\n\n protected sitesIn(file: ApiLibFile): ApiLibSite[] {\n return this.scanner.scan(file);\n }\n\n protected why(): string {\n return 'an API imports at the top of the file, only — an inline import() hides a cross-library dependency ' +\n 'from every reader of the contract\\'s imports, and a dynamic one is runtime behaviour in a contract.';\n }\n}\n"]}
@@ -20,6 +20,7 @@
20
20
  */
21
21
  import { NoProcessExitOutsideMainConfig } from '@webpieces/rules-config';
22
22
  import { CodeValidator, ExecutorResult } from './code-validator';
23
+ import { ScanScope } from './scan-scope';
23
24
  interface ExitViolationInfo {
24
25
  line: number;
25
26
  context: string;
@@ -27,7 +28,8 @@ interface ExitViolationInfo {
27
28
  }
28
29
  export declare function findExitViolationsInFile(filePath: string, workspaceRoot: string, disableAllowed: boolean): ExitViolationInfo[];
29
30
  export declare class NoProcessExitOutsideMainValidator extends CodeValidator<NoProcessExitOutsideMainConfig> {
30
- constructor(config: NoProcessExitOutsideMainConfig);
31
+ private readonly scanScope;
32
+ constructor(config: NoProcessExitOutsideMainConfig, scanScope: ScanScope);
31
33
  run(workspaceRoot: string): Promise<ExecutorResult>;
32
34
  }
33
35
  export {};
@@ -29,6 +29,7 @@ const rules_config_1 = require("@webpieces/rules-config");
29
29
  const code_validator_1 = require("./code-validator");
30
30
  const inversify_1 = require("inversify");
31
31
  const resolve_mode_1 = require("./resolve-mode");
32
+ const scan_scope_1 = require("./scan-scope");
32
33
  const INSTRUCT_FILE = 'webpieces.noexitinmain.md';
33
34
  const EXIT_REGEX = /\bprocess\.exit\s*\(/;
34
35
  const IMPORT_MAIN_REGEX = /^\s*import\b[^;]*\{[^}]*\bmain\b[^}]*\}[^;]*\bfrom\b/;
@@ -148,7 +149,8 @@ function resolveMode(normalMode, epoch, branchPattern) {
148
149
  }
149
150
  return normalMode;
150
151
  }
151
- async function runValidatorImpl(options, workspaceRoot) {
152
+ // webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members
153
+ async function runValidatorImpl(scan, options, workspaceRoot) {
152
154
  const mode = resolveMode(options.mode ?? 'OFF', options.turnOffRuleUntilEpoch, (options.turnOffRuleWhileOnBranch ?? undefined));
153
155
  const disableAllowed = options.disableAllowed ?? true;
154
156
  if (mode === 'OFF') {
@@ -168,7 +170,7 @@ async function runValidatorImpl(options, workspaceRoot) {
168
170
  }
169
171
  console.log(` Base: ${base}`);
170
172
  console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}\n`);
171
- const changedFiles = (0, rules_config_1.getChangedFiles)(workspaceRoot, base, head);
173
+ const changedFiles = scan.files(workspaceRoot, mode, base, head);
172
174
  if (changedFiles.length === 0) {
173
175
  console.log('✅ No TypeScript files changed');
174
176
  return { success: true };
@@ -178,27 +180,31 @@ async function runValidatorImpl(options, workspaceRoot) {
178
180
  if (mode === 'NEW_AND_MODIFIED_CODE') {
179
181
  violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed);
180
182
  }
181
- else if (mode === 'NEW_AND_MODIFIED_FILES') {
183
+ else {
184
+ // NEW_AND_MODIFIED_FILES and the whole-scope modes (#1027) all judge every site of every file.
182
185
  violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);
183
186
  }
184
187
  if (violations.length === 0) {
185
188
  console.log('✅ No process.exit-outside-main violations found');
186
189
  return { success: true };
187
190
  }
191
+ scan.recordSites('no-process-exit-outside-main', violations.map((v) => v.file));
188
192
  reportViolations(workspaceRoot, violations, mode, disableAllowed);
189
193
  return { success: false };
190
194
  }
191
195
  let NoProcessExitOutsideMainValidator = class NoProcessExitOutsideMainValidator extends code_validator_1.CodeValidator {
192
- constructor(config) {
196
+ scanScope;
197
+ constructor(config, scanScope) {
193
198
  super(config, 'no-process-exit-outside-main', 'no-process-exit-outside-main');
199
+ this.scanScope = scanScope;
194
200
  }
195
201
  async run(workspaceRoot) {
196
- return runValidatorImpl(this.config, workspaceRoot);
202
+ return runValidatorImpl(this.scanScope, this.config, workspaceRoot);
197
203
  }
198
204
  };
199
205
  exports.NoProcessExitOutsideMainValidator = NoProcessExitOutsideMainValidator;
200
206
  exports.NoProcessExitOutsideMainValidator = NoProcessExitOutsideMainValidator = tslib_1.__decorate([
201
207
  (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
202
- tslib_1.__metadata("design:paramtypes", [rules_config_1.NoProcessExitOutsideMainConfig])
208
+ tslib_1.__metadata("design:paramtypes", [rules_config_1.NoProcessExitOutsideMainConfig, scan_scope_1.ScanScope])
203
209
  ], NoProcessExitOutsideMainValidator);
204
210
  //# sourceMappingURL=validate-no-process-exit-outside-main.js.map