@webpieces/code-rules 0.3.312 → 0.3.314

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/code-rules",
3
- "version": "0.3.312",
3
+ "version": "0.3.314",
4
4
  "description": "Standalone code validation rules extracted from architecture-validators, no Nx dependency required",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -20,7 +20,7 @@
20
20
  "directory": "packages/tooling/code-rules"
21
21
  },
22
22
  "dependencies": {
23
- "@webpieces/rules-config": "0.3.312"
23
+ "@webpieces/rules-config": "0.3.314"
24
24
  },
25
25
  "publishConfig": {
26
26
  "access": "public"
@@ -19,15 +19,14 @@
19
19
  * - Non-function top-level consts: `const SCHEMA = z.object({})`, `const MAX = 5`, object/array literals.
20
20
  * - Ambient declarations (`declare function ...`) and whole `*.d.ts` files.
21
21
  * - Test files (*.test.ts, *.spec.ts, __tests__/**).
22
+ * - Files under a configured `allowedPaths` glob (e.g. React component/hook trees that legitimately use
23
+ * module-scope functions). Matched with the shared `isPathExcluded` glob/prefix/segment semantics.
22
24
  * - Lines with `// webpieces-disable no-function-outside-class -- <reason>` (when disableAllowed).
23
25
  *
24
26
  * MODES (AST + LINE-SCOPED)
25
27
  * - OFF: Skip.
26
28
  * - NEW_AND_MODIFIED_CODE: Flag only on changed lines (diff hunks).
27
29
  * - NEW_AND_MODIFIED_FILES: Flag every occurrence in any modified file.
28
- *
29
- * NOTE: intentionally NO allowedPaths — the only escapes are the inline `// webpieces-disable` comment
30
- * and the universal epoch/branch off-switches.
31
30
  */
32
31
  import { NoFunctionOutsideClassConfig } from '@webpieces/rules-config';
33
32
  import { CodeValidator, ExecutorResult } from './code-validator';
@@ -38,6 +37,7 @@ interface FnViolationInfo {
38
37
  hasDisableComment: boolean;
39
38
  }
40
39
  export declare function findFunctionsOutsideClassInSource(content: string, filePath: string, disableAllowed: boolean): FnViolationInfo[];
40
+ export declare function findFunctionsOutsideClassInFile(filePath: string, workspaceRoot: string, disableAllowed: boolean, allowedPaths: string[]): FnViolationInfo[];
41
41
  export declare class NoFunctionOutsideClassValidator extends CodeValidator<NoFunctionOutsideClassConfig> {
42
42
  constructor(config: NoFunctionOutsideClassConfig);
43
43
  run(workspaceRoot: string): Promise<ExecutorResult>;
@@ -20,19 +20,19 @@
20
20
  * - Non-function top-level consts: `const SCHEMA = z.object({})`, `const MAX = 5`, object/array literals.
21
21
  * - Ambient declarations (`declare function ...`) and whole `*.d.ts` files.
22
22
  * - Test files (*.test.ts, *.spec.ts, __tests__/**).
23
+ * - Files under a configured `allowedPaths` glob (e.g. React component/hook trees that legitimately use
24
+ * module-scope functions). Matched with the shared `isPathExcluded` glob/prefix/segment semantics.
23
25
  * - Lines with `// webpieces-disable no-function-outside-class -- <reason>` (when disableAllowed).
24
26
  *
25
27
  * MODES (AST + LINE-SCOPED)
26
28
  * - OFF: Skip.
27
29
  * - NEW_AND_MODIFIED_CODE: Flag only on changed lines (diff hunks).
28
30
  * - NEW_AND_MODIFIED_FILES: Flag every occurrence in any modified file.
29
- *
30
- * NOTE: intentionally NO allowedPaths — the only escapes are the inline `// webpieces-disable` comment
31
- * and the universal epoch/branch off-switches.
32
31
  */
33
32
  Object.defineProperty(exports, "__esModule", { value: true });
34
33
  exports.NoFunctionOutsideClassValidator = void 0;
35
34
  exports.findFunctionsOutsideClassInSource = findFunctionsOutsideClassInSource;
35
+ exports.findFunctionsOutsideClassInFile = findFunctionsOutsideClassInFile;
36
36
  const tslib_1 = require("tslib");
37
37
  const fs = tslib_1.__importStar(require("fs"));
38
38
  const path = tslib_1.__importStar(require("path"));
@@ -113,22 +113,26 @@ function findFunctionsOutsideClassInSource(content, filePath, disableAllowed) {
113
113
  visit(sourceFile);
114
114
  return violations;
115
115
  }
116
- function findFunctionsOutsideClassInFile(filePath, workspaceRoot, disableAllowed) {
116
+ // webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members
117
+ function findFunctionsOutsideClassInFile(filePath, workspaceRoot, disableAllowed, allowedPaths) {
117
118
  if (isTestFile(filePath))
118
119
  return [];
120
+ if ((0, rules_config_1.isPathExcluded)(filePath, allowedPaths))
121
+ return [];
119
122
  const fullPath = path.join(workspaceRoot, filePath);
120
123
  if (!fs.existsSync(fullPath))
121
124
  return [];
122
125
  const content = fs.readFileSync(fullPath, 'utf-8');
123
126
  return findFunctionsOutsideClassInSource(content, filePath, disableAllowed);
124
127
  }
125
- function findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed) {
128
+ // webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members
129
+ function findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed, allowedPaths) {
126
130
  const violations = [];
127
131
  for (const file of changedFiles) {
128
132
  const changedLines = (0, rules_config_1.getChangedLineNumbers)((0, rules_config_1.getFileDiff)(workspaceRoot, file, base, head));
129
133
  if (changedLines.size === 0)
130
134
  continue;
131
- for (const v of findFunctionsOutsideClassInFile(file, workspaceRoot, disableAllowed)) {
135
+ for (const v of findFunctionsOutsideClassInFile(file, workspaceRoot, disableAllowed, allowedPaths)) {
132
136
  if (disableAllowed && v.hasDisableComment)
133
137
  continue;
134
138
  if (!changedLines.has(v.line))
@@ -138,10 +142,11 @@ function findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head,
138
142
  }
139
143
  return violations;
140
144
  }
141
- function findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed) {
145
+ // webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members
146
+ function findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed, allowedPaths) {
142
147
  const violations = [];
143
148
  for (const file of changedFiles) {
144
- for (const v of findFunctionsOutsideClassInFile(file, workspaceRoot, disableAllowed)) {
149
+ for (const v of findFunctionsOutsideClassInFile(file, workspaceRoot, disableAllowed, allowedPaths)) {
145
150
  if (disableAllowed && v.hasDisableComment)
146
151
  continue;
147
152
  violations.push({ file, line: v.line, column: v.column, context: v.context });
@@ -163,6 +168,7 @@ function reportViolations(violations, mode, disableAllowed) {
163
168
  console.error(disableAllowed
164
169
  ? ' Escape hatch (use sparingly): // webpieces-disable no-function-outside-class -- <reason>'
165
170
  : ' Escape hatch: DISABLED (disableAllowed: false)');
171
+ console.error(' Whole-tree exemption (e.g. React): add a glob to no-function-outside-class.allowedPaths in webpieces.config.json');
166
172
  console.error(`\n Current mode: ${mode}\n`);
167
173
  }
168
174
  function resolveMode(normalMode, epoch, branchPattern) {
@@ -178,6 +184,7 @@ function resolveMode(normalMode, epoch, branchPattern) {
178
184
  async function runValidatorImpl(options, workspaceRoot) {
179
185
  const mode = resolveMode(options.mode ?? 'OFF', options.ignoreModifiedUntilEpoch, options.ignoreRuleWhileOnBranch);
180
186
  const disableAllowed = options.disableAllowed ?? true;
187
+ const allowedPaths = options.allowedPaths ?? [];
181
188
  if (mode === 'OFF') {
182
189
  console.log('\n⏭️ Skipping no-function-outside-class validation (mode: OFF)\n');
183
190
  return { success: true };
@@ -203,10 +210,10 @@ async function runValidatorImpl(options, workspaceRoot) {
203
210
  console.log(`📂 Checking ${changedFiles.length} changed file(s)...`);
204
211
  let violations = [];
205
212
  if (mode === 'NEW_AND_MODIFIED_CODE') {
206
- violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed);
213
+ violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed, allowedPaths);
207
214
  }
208
215
  else if (mode === 'NEW_AND_MODIFIED_FILES') {
209
- violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);
216
+ violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed, allowedPaths);
210
217
  }
211
218
  if (violations.length === 0) {
212
219
  console.log('✅ No function-outside-class violations found');
@@ -1 +1 @@
1
- {"version":3,"file":"validate-no-function-outside-class.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules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EAAE,CAAC;IAC7B,CAAC;IAED,gBAAgB,CAAC,UAAU,EAAE,IAAI,EAAE,cAAc,CAAC,CAAC;IACnD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC9B,CAAC;AAED,MAAa,+BAAgC,SAAQ,8BAA2C;IAC5F,YAAY,MAAoC;QAC5C,KAAK,CAAC,MAAM,EAAE,2BAA2B,CAAC,CAAC;IAC/C,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,aAAqB;QAC3B,OAAO,gBAAgB,CAAC,IAAI,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IACxD,CAAC;CACJ;AARD,0EAQC","sourcesContent":["/**\n * Validate No Function Outside Class\n *\n * Flags a function CREATED OUTSIDE A CLASS at module scope:\n * - a top-level `function foo()` / `export function foo()` declaration, and\n * - a top-level `const foo = () => {}` / `const foo = function(){}`.\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 * - 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 * NOTE: intentionally NO allowedPaths — the only escapes are the inline `// webpieces-disable` comment\n * and the universal epoch/branch off-switches.\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 } from '@webpieces/rules-config';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { shouldSkipRule } from './resolve-mode';\n\nconst SHARED_MESSAGE = `Functions must live inside a class — a function created at module scope can't be injected, so\nwebpieces DI + @DocumentDesign can't wire it into anything.\n BAD: export function computeTotal(cart: Cart): number { ... }\n GOOD: @provideSingleton()\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 and top-level\nconst-assigned 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// 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 ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return violations;\n}\n\nfunction findFunctionsOutsideClassInFile(filePath: string, workspaceRoot: string, disableAllowed: boolean): FnViolationInfo[] {\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 findFunctionsOutsideClassInSource(content, filePath, disableAllowed);\n}\n\nfunction findViolationsForModifiedCode(workspaceRoot: string, changedFiles: string[], base: string, head: string | undefined, disableAllowed: boolean): 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)) {\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\nfunction findViolationsForModifiedFiles(workspaceRoot: string, changedFiles: string[], disableAllowed: boolean): FnViolation[] {\n const violations: FnViolation[] = [];\n for (const file of changedFiles) {\n for (const v of findFunctionsOutsideClassInFile(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\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(`\\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.ignoreModifiedUntilEpoch, options.ignoreRuleWhileOnBranch);\n const disableAllowed = options.disableAllowed ?? true;\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);\n } else if (mode === 'NEW_AND_MODIFIED_FILES') {\n violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);\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\nexport class NoFunctionOutsideClassValidator extends CodeValidator<NoFunctionOutsideClassConfig> {\n constructor(config: NoFunctionOutsideClassConfig) {\n super(config, '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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;;;AA6FH,8EAmBC;AAGD,0EAOC;;AAxHD,+CAAyB;AACzB,mDAA6B;AAC7B,uDAAiC;AACjC,0DAAkM;AAClM,qDAAiE;AACjE,iDAAgD;AAEhD,MAAM,cAAc,GAAG;;;;;;;sCAOe,CAAC;AAgBvC,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,8EAA8E;AAC9E,SAAS,gBAAgB,CAAC,SAAmB,EAAE,UAAkB;IAC7D,MAAM,OAAO,GAAG,SAAS,CAAC,UAAU,GAAG,CAAC,CAAC,I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,GAAG,CAAC,eAAe,YAAY,CAAC,MAAM,qBAAqB,CAAC,CAAC;IAErE,IAAI,UAAU,GAAkB,EAAE,CAAC;IACnC,IAAI,IAAI,KAAK,uBAAuB,EAAE,CAAC;QACnC,UAAU,GAAG,6BAA6B,CAAC,aAAa,EAAE,YAAY,EAAE,IAAI,EAAE,IAAI,EAAE,cAAc,EAAE,YAAY,CAAC,CAAC;IACtH,CAAC;SAAM,IAAI,IAAI,KAAK,wBAAwB,EAAE,CAAC;QAC3C,UAAU,GAAG,8BAA8B,CAAC,aAAa,EAAE,YAAY,EAAE,cAAc,EAAE,YAAY,CAAC,CAAC;IAC3G,CAAC;IAED,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC1B,OAAO,CAAC,GAAG,CAAC,8CAA8C,CAAC,CAAC;QAC5D,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7B,CAAC;IAED,gBAAgB,CAAC,UAAU,EAAE,IAAI,EAAE,cAAc,CAAC,CAAC;IACnD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC9B,CAAC;AAED,MAAa,+BAAgC,SAAQ,8BAA2C;IAC5F,YAAY,MAAoC;QAC5C,KAAK,CAAC,MAAM,EAAE,2BAA2B,CAAC,CAAC;IAC/C,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,aAAqB;QAC3B,OAAO,gBAAgB,CAAC,IAAI,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IACxD,CAAC;CACJ;AARD,0EAQC","sourcesContent":["/**\n * Validate No Function Outside Class\n *\n * Flags a function CREATED OUTSIDE A CLASS at module scope:\n * - a top-level `function foo()` / `export function foo()` declaration, and\n * - a top-level `const foo = () => {}` / `const foo = function(){}`.\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 { shouldSkipRule } from './resolve-mode';\n\nconst SHARED_MESSAGE = `Functions must live inside a class — a function created at module scope can't be injected, so\nwebpieces DI + @DocumentDesign can't wire it into anything.\n BAD: export function computeTotal(cart: Cart): number { ... }\n GOOD: @provideSingleton()\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 and top-level\nconst-assigned 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// 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 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.ignoreModifiedUntilEpoch, options.ignoreRuleWhileOnBranch);\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\nexport class NoFunctionOutsideClassValidator extends CodeValidator<NoFunctionOutsideClassConfig> {\n constructor(config: NoFunctionOutsideClassConfig) {\n super(config, 'no-function-outside-class');\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runValidatorImpl(this.config, workspaceRoot);\n }\n}\n"]}