@webpieces/code-rules 0.4.819 → 0.4.821
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 +2 -2
- package/src/api-lib-source-rule.d.ts +5 -2
- package/src/api-lib-source-rule.js +8 -4
- package/src/api-lib-source-rule.js.map +1 -1
- package/src/cli.js +13 -14
- package/src/cli.js.map +1 -1
- package/src/code-rules-bootstrap.d.ts +31 -8
- package/src/code-rules-bootstrap.js +136 -18
- package/src/code-rules-bootstrap.js.map +1 -1
- package/src/code-rules-config-table.d.ts +3 -1
- package/src/code-rules-config-table.js +0 -6
- package/src/code-rules-config-table.js.map +1 -1
- package/src/code-rules-engine.d.ts +4 -13
- package/src/code-rules-engine.js +9 -31
- package/src/code-rules-engine.js.map +1 -1
- package/src/code-rules-run-request.d.ts +30 -34
- package/src/code-rules-run-request.js +43 -80
- package/src/code-rules-run-request.js.map +1 -1
- package/src/index.d.ts +3 -1
- package/src/index.js +13 -2
- package/src/index.js.map +1 -1
- package/src/resolve-mode.d.ts +1 -1
- package/src/resolve-mode.js +2 -3
- package/src/resolve-mode.js.map +1 -1
- package/src/scan-scope.d.ts +82 -0
- package/src/scan-scope.js +200 -0
- package/src/scan-scope.js.map +1 -0
- package/src/validate-catch-error-pattern.d.ts +3 -1
- package/src/validate-catch-error-pattern.js +11 -6
- package/src/validate-catch-error-pattern.js.map +1 -1
- package/src/validate-code.d.ts +4 -5
- package/src/validate-code.js +6 -17
- package/src/validate-code.js.map +1 -1
- package/src/validate-inject-annotation-not-needed-for-concrete-class.d.ts +3 -1
- package/src/validate-inject-annotation-not-needed-for-concrete-class.js +11 -6
- package/src/validate-inject-annotation-not-needed-for-concrete-class.js.map +1 -1
- package/src/validate-match-rules.d.ts +3 -0
- package/src/validate-match-rules.js +10 -3
- package/src/validate-match-rules.js.map +1 -1
- package/src/validate-no-any-unknown.d.ts +3 -1
- package/src/validate-no-any-unknown.js +11 -6
- package/src/validate-no-any-unknown.js.map +1 -1
- package/src/validate-no-client-creation-outside-server-or-client.d.ts +4 -2
- package/src/validate-no-client-creation-outside-server-or-client.js +10 -5
- package/src/validate-no-client-creation-outside-server-or-client.js.map +1 -1
- package/src/validate-no-custom-css.d.ts +4 -2
- package/src/validate-no-custom-css.js +9 -5
- package/src/validate-no-custom-css.js.map +1 -1
- package/src/validate-no-destructure.d.ts +3 -1
- package/src/validate-no-destructure.js +11 -6
- package/src/validate-no-destructure.js.map +1 -1
- package/src/validate-no-function-outside-class.d.ts +3 -1
- package/src/validate-no-function-outside-class.js +12 -6
- package/src/validate-no-function-outside-class.js.map +1 -1
- package/src/validate-no-implicit-any.d.ts +3 -1
- package/src/validate-no-implicit-any.js +13 -8
- package/src/validate-no-implicit-any.js.map +1 -1
- package/src/validate-no-inline-import-in-api-lib.d.ts +2 -1
- package/src/validate-no-inline-import-in-api-lib.js +4 -3
- package/src/validate-no-inline-import-in-api-lib.js.map +1 -1
- package/src/validate-no-process-exit-outside-main.d.ts +3 -1
- package/src/validate-no-process-exit-outside-main.js +12 -6
- package/src/validate-no-process-exit-outside-main.js.map +1 -1
- package/src/validate-no-state-paths-in-templates.d.ts +4 -2
- package/src/validate-no-state-paths-in-templates.js +9 -5
- package/src/validate-no-state-paths-in-templates.js.map +1 -1
- package/src/validate-no-symbol-di-tokens.d.ts +3 -1
- package/src/validate-no-symbol-di-tokens.js +11 -6
- package/src/validate-no-symbol-di-tokens.js.map +1 -1
- package/src/validate-no-unmanaged-exceptions.d.ts +3 -1
- package/src/validate-no-unmanaged-exceptions.js +11 -6
- package/src/validate-no-unmanaged-exceptions.js.map +1 -1
- package/src/validate-no-utility-types-in-api-lib.d.ts +2 -1
- package/src/validate-no-utility-types-in-api-lib.js +4 -3
- package/src/validate-no-utility-types-in-api-lib.js.map +1 -1
- package/src/validate-one-enum-spelling-in-api-lib.d.ts +2 -1
- package/src/validate-one-enum-spelling-in-api-lib.js +4 -3
- package/src/validate-one-enum-spelling-in-api-lib.js.map +1 -1
- package/src/validate-required-type-suffix.d.ts +2 -1
- package/src/validate-required-type-suffix.js +7 -3
- package/src/validate-required-type-suffix.js.map +1 -1
- package/src/wp-ci.d.ts +2 -2
- package/src/wp-ci.js +11 -5
- package/src/wp-ci.js.map +1 -1
- package/src/debug-run-report.d.ts +0 -22
- package/src/debug-run-report.js +0 -127
- package/src/debug-run-report.js.map +0 -1
- package/src/rule-scope-plan.d.ts +0 -72
- package/src/rule-scope-plan.js +0 -132
- package/src/rule-scope-plan.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validate-no-process-exit-outside-main.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-process-exit-outside-main.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;GAmBG;;;AAgEH,4DAuBC;;AArFD,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA4N;AAC5N,qDAAiE;AACjE,yCAA2D;AAC3D,iDAAgD;AAEhD,MAAM,aAAa,GAAG,2BAA2B,CAAC;AAClD,MAAM,UAAU,GAAG,sBAAsB,CAAC;AAC1C,MAAM,iBAAiB,GAAG,sDAAsD,CAAC;AACjF,iGAAiG;AACjG,iDAAiD;AACjD,MAAM,cAAc,GAAG,2HAA2H,CAAC;AACnJ,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;AAEhD,MAAM,cAAc,GAAG;;;;;;;;kHAQ2F,CAAC;AAcnH,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,IAAY;IACnC,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IAC/B,IAAI,GAAG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Content":["/**\n * Validate No Process Exit Outside Main\n *\n * Flags `process.exit(...)` outside a `main()`/`runMain` wrapper, and `import { main }` from another\n * module. A `process.exit` deep in a reused call stack crashes a server or command far too early and\n * unexpectedly — and with exit 0 it masquerades as success. Throw a semantic error instead and let\n * the ONE top-level `main()`/`runMain` try-catch pick the exit code.\n *\n * See .webpieces/instruct-ai/webpieces.noexitinmain.md (generated on violation) for the full pattern.\n *\n * ALLOWED\n * - A `process.exit` whose nearest enclosing function is named `main` or `runMain`.\n * - Test files (*.test.ts, *.spec.ts, __tests__/**).\n * - Lines with `// webpieces-disable no-process-exit-outside-main -- <reason>` (when disableAllowed).\n *\n * MODES (LINE-BASED)\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 { hasDisable, RULE_NAMES, NoProcessExitOutsideMainConfig, ModifiedCodeMode, detectBase, getChangedFiles, getFileDiff, getChangedLineNumbers, writeTemplateIfMissing, RepoRootFinder } from '@webpieces/rules-config';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { shouldSkipRule } from './resolve-mode';\n\nconst INSTRUCT_FILE = 'webpieces.noexitinmain.md';\nconst EXIT_REGEX = /\\bprocess\\.exit\\s*\\(/;\nconst IMPORT_MAIN_REGEX = /^\\s*import\\b[^;]*\\{[^}]*\\bmain\\b[^}]*\\}[^;]*\\bfrom\\b/;\n// Named function / arrow-const DEFINITION openers (never a call like `main()`), used to find the\n// enclosing function's name via a backward scan.\nconst FUNC_DEF_REGEX = /(?:export\\s+)?(?:async\\s+)?function\\s+(\\w+)\\s*\\(|(?:export\\s+)?(?:const|let)\\s+(\\w+)\\s*=\\s*(?:async\\s*)?(?:\\(|function\\b)/;\nconst ALLOWED_FN = new Set(['main', 'runMain']);\n\nconst SHARED_MESSAGE = `Do not call process.exit() deep in the stack — any code may be reused, and a deep exit crashes a\nserver or command far too early (exit 0 even masquerades as success). Throw a semantic error instead:\n - Expected/normal failure → your domain's failure error (in the rules engine: RuleFailError).\n - A bug / broken precondition (should-never-happen, missing required var) → an ordinary Error.\nLet the ONE top-level main()/runMain try-catch pick the exit code (non-zero on failure, 0 on success):\n if (require.main === module) runMain(main)\nNeed a specific exit code deep down? throw new CliExitError(code, message) — runMain maps it.\nAlso: do NOT import another module's main — call a named function; only a thin wrapper calls main.\nLast resort: append // webpieces-disable no-process-exit-outside-main -- <reason> at a genuine terminal boundary.`;\n\ninterface ExitViolation {\n file: string;\n line: number;\n context: string;\n}\n\ninterface ExitViolationInfo {\n line: 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 stripLineComments(line: string): string {\n const idx = line.indexOf('//');\n if (idx === -1) return line;\n return line.substring(0, idx);\n}\n\n// Walk backward from `idx` for the nearest NAMED function/arrow definition and return its name.\n// Line-based heuristic (no AST): recognises a `main`/`runMain` wrapper enclosing the exit.\nfunction enclosingFunctionName(strippedLines: string[], idx: number): string | null {\n for (let j = idx; j >= 0; j -= 1) {\n const m = FUNC_DEF_REGEX.exec(strippedLines[j] ?? '');\n if (m) return m[1] ?? m[2] ?? null;\n }\n return null;\n}\n\nfunction resolveDisable(disabled: boolean, disableAllowed: boolean): boolean {\n if (!disableAllowed && disabled) return false;\n return disabled;\n}\n\nexport function findExitViolationsInFile(filePath: string, workspaceRoot: string, disableAllowed: boolean): ExitViolationInfo[] {\n if (isTestFile(filePath)) return [];\n const fullPath = path.join(workspaceRoot, filePath);\n if (!fs.existsSync(fullPath)) return [];\n\n const content = fs.readFileSync(fullPath, 'utf-8');\n const lines = content.split('\\n');\n const stripped = lines.map((l: string): string => stripLineComments(l));\n const violations: ExitViolationInfo[] = [];\n\n for (let i = 0; i < lines.length; i += 1) {\n const line = lines[i] ?? '';\n const strippedLine = stripped[i] ?? '';\n const isExit = EXIT_REGEX.test(strippedLine) && !ALLOWED_FN.has(enclosingFunctionName(stripped, i) ?? '');\n const isImportMain = IMPORT_MAIN_REGEX.test(strippedLine);\n if (!isExit && !isImportMain) continue;\n\n const lineNum = i + 1;\n const prevLine = i > 0 ? (lines[i - 1] ?? '') : '';\n const disabled = hasDisable(line, RULE_NAMES.NO_PROCESS_EXIT_OUTSIDE_MAIN) || hasDisable(prevLine, RULE_NAMES.NO_PROCESS_EXIT_OUTSIDE_MAIN);\n violations.push({ line: lineNum, context: line.trim(), hasDisableComment: resolveDisable(disabled, disableAllowed) });\n }\n return violations;\n}\n\nfunction findViolationsForModifiedCode(workspaceRoot: string, changedFiles: string[], base: string, head: string | undefined, disableAllowed: boolean): ExitViolation[] {\n const violations: ExitViolation[] = [];\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 findExitViolationsInFile(file, workspaceRoot, disableAllowed)) {\n if (disableAllowed && v.hasDisableComment) continue;\n if (!changedLines.has(v.line)) continue;\n violations.push({ file, line: v.line, context: v.context });\n }\n }\n return violations;\n}\n\nfunction findViolationsForModifiedFiles(workspaceRoot: string, changedFiles: string[], disableAllowed: boolean): ExitViolation[] {\n const violations: ExitViolation[] = [];\n for (const file of changedFiles) {\n for (const v of findExitViolationsInFile(file, workspaceRoot, disableAllowed)) {\n if (disableAllowed && v.hasDisableComment) continue;\n violations.push({ file, line: v.line, context: v.context });\n }\n }\n return violations;\n}\n\nfunction reportViolations(workspaceRoot: string, violations: ExitViolation[], mode: ModifiedCodeMode, disableAllowed: boolean): void {\n writeTemplateIfMissing(workspaceRoot, INSTRUCT_FILE);\n console.error('');\n console.error('❌ process.exit() outside main()/runMain (or an import of another module\\'s main)!');\n console.error('');\n console.error(SHARED_MESSAGE);\n console.error(`READ ${new RepoRootFinder().instructAiDocPath(workspaceRoot, INSTRUCT_FILE)} for the full pattern.`);\n console.error('');\n for (const v of violations) {\n console.error(` ❌ ${v.file}:${v.line}`);\n console.error(` ${v.context}`);\n }\n console.error('');\n console.error(disableAllowed\n ? ' Escape hatch (genuine terminal boundary only): // webpieces-disable no-process-exit-outside-main -- <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-process-exit-outside-main validation (${skip.reason})\\n`);\n return 'OFF';\n }\n return normalMode;\n}\n\nasync function runValidatorImpl(options: NoProcessExitOutsideMainConfig, workspaceRoot: string): 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⏭️ Skipping no-process-exit-outside-main validation (mode: OFF)\\n');\n return { success: true };\n }\n\n console.log('\\n📏 Validating No Process Exit Outside Main\\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-process-exit-outside-main 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: ExitViolation[] = [];\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 process.exit-outside-main violations found');\n return { success: true };\n }\n\n reportViolations(workspaceRoot, violations, mode, disableAllowed);\n return { success: false };\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoProcessExitOutsideMainValidator extends CodeValidator<NoProcessExitOutsideMainConfig> {\n constructor(config: NoProcessExitOutsideMainConfig) {\n super(config, 'no-process-exit-outside-main', 'no-process-exit-outside-main');\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runValidatorImpl(this.config, workspaceRoot);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"validate-no-process-exit-outside-main.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-process-exit-outside-main.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;GAmBG;;;AAiEH,4DAuBC;;AAtFD,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA2M;AAC3M,qDAAiE;AACjE,yCAA2D;AAC3D,iDAAgD;AAChD,6CAAyC;AAEzC,MAAM,aAAa,GAAG,2BAA2B,CAAC;AAClD,MAAM,UAAU,GAAG,sBAAsB,CAAC;AAC1C,MAAM,iBAAiB,GAAG,sDAAsD,CAAC;AACjF,iGAAiG;AACjG,iDAAiD;AACjD,MAAM,cAAc,GAAG,2HAA2H,CAAC;AACnJ,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;AAEhD,MAAM,cAAc,GAAG;;;;;;;;kHAQ2F,CAAC;AAcnH,SAAS,UAAU,CAAC,QAAgB;IAChC,OAAO,QAAQ,CAAC,QAAQ,CAAC,UAAU,CAAC,IAAI,QAAQ,CAAC,QAAQ,CAAC,UAAU,CAAC,IAAI,QAAQ,CAAC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B,SAAoB;QACrF,KAAK,CAAC,MAAM,EAAE,8BAA8B,EAAE,8BAA8B,CAAC,CAAC;QADb,cAAS,GAAT,SAAS,CAAW;IAEzF,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,8EAAiC;4CAAjC,iCAAiC;IAD7C,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEjB,6CAA8B,EAA8B,sBAAS;GADhF,iCAAiC,CAQ7C","sourcesContent":["/**\n * Validate No Process Exit Outside Main\n *\n * Flags `process.exit(...)` outside a `main()`/`runMain` wrapper, and `import { main }` from another\n * module. A `process.exit` deep in a reused call stack crashes a server or command far too early and\n * unexpectedly — and with exit 0 it masquerades as success. Throw a semantic error instead and let\n * the ONE top-level `main()`/`runMain` try-catch pick the exit code.\n *\n * See .webpieces/instruct-ai/webpieces.noexitinmain.md (generated on violation) for the full pattern.\n *\n * ALLOWED\n * - A `process.exit` whose nearest enclosing function is named `main` or `runMain`.\n * - Test files (*.test.ts, *.spec.ts, __tests__/**).\n * - Lines with `// webpieces-disable no-process-exit-outside-main -- <reason>` (when disableAllowed).\n *\n * MODES (LINE-BASED)\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 { hasDisable, RULE_NAMES, NoProcessExitOutsideMainConfig, ModifiedCodeMode, detectBase, getFileDiff, getChangedLineNumbers, writeTemplateIfMissing, RepoRootFinder } 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 INSTRUCT_FILE = 'webpieces.noexitinmain.md';\nconst EXIT_REGEX = /\\bprocess\\.exit\\s*\\(/;\nconst IMPORT_MAIN_REGEX = /^\\s*import\\b[^;]*\\{[^}]*\\bmain\\b[^}]*\\}[^;]*\\bfrom\\b/;\n// Named function / arrow-const DEFINITION openers (never a call like `main()`), used to find the\n// enclosing function's name via a backward scan.\nconst FUNC_DEF_REGEX = /(?:export\\s+)?(?:async\\s+)?function\\s+(\\w+)\\s*\\(|(?:export\\s+)?(?:const|let)\\s+(\\w+)\\s*=\\s*(?:async\\s*)?(?:\\(|function\\b)/;\nconst ALLOWED_FN = new Set(['main', 'runMain']);\n\nconst SHARED_MESSAGE = `Do not call process.exit() deep in the stack — any code may be reused, and a deep exit crashes a\nserver or command far too early (exit 0 even masquerades as success). Throw a semantic error instead:\n - Expected/normal failure → your domain's failure error (in the rules engine: RuleFailError).\n - A bug / broken precondition (should-never-happen, missing required var) → an ordinary Error.\nLet the ONE top-level main()/runMain try-catch pick the exit code (non-zero on failure, 0 on success):\n if (require.main === module) runMain(main)\nNeed a specific exit code deep down? throw new CliExitError(code, message) — runMain maps it.\nAlso: do NOT import another module's main — call a named function; only a thin wrapper calls main.\nLast resort: append // webpieces-disable no-process-exit-outside-main -- <reason> at a genuine terminal boundary.`;\n\ninterface ExitViolation {\n file: string;\n line: number;\n context: string;\n}\n\ninterface ExitViolationInfo {\n line: 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 stripLineComments(line: string): string {\n const idx = line.indexOf('//');\n if (idx === -1) return line;\n return line.substring(0, idx);\n}\n\n// Walk backward from `idx` for the nearest NAMED function/arrow definition and return its name.\n// Line-based heuristic (no AST): recognises a `main`/`runMain` wrapper enclosing the exit.\nfunction enclosingFunctionName(strippedLines: string[], idx: number): string | null {\n for (let j = idx; j >= 0; j -= 1) {\n const m = FUNC_DEF_REGEX.exec(strippedLines[j] ?? '');\n if (m) return m[1] ?? m[2] ?? null;\n }\n return null;\n}\n\nfunction resolveDisable(disabled: boolean, disableAllowed: boolean): boolean {\n if (!disableAllowed && disabled) return false;\n return disabled;\n}\n\nexport function findExitViolationsInFile(filePath: string, workspaceRoot: string, disableAllowed: boolean): ExitViolationInfo[] {\n if (isTestFile(filePath)) return [];\n const fullPath = path.join(workspaceRoot, filePath);\n if (!fs.existsSync(fullPath)) return [];\n\n const content = fs.readFileSync(fullPath, 'utf-8');\n const lines = content.split('\\n');\n const stripped = lines.map((l: string): string => stripLineComments(l));\n const violations: ExitViolationInfo[] = [];\n\n for (let i = 0; i < lines.length; i += 1) {\n const line = lines[i] ?? '';\n const strippedLine = stripped[i] ?? '';\n const isExit = EXIT_REGEX.test(strippedLine) && !ALLOWED_FN.has(enclosingFunctionName(stripped, i) ?? '');\n const isImportMain = IMPORT_MAIN_REGEX.test(strippedLine);\n if (!isExit && !isImportMain) continue;\n\n const lineNum = i + 1;\n const prevLine = i > 0 ? (lines[i - 1] ?? '') : '';\n const disabled = hasDisable(line, RULE_NAMES.NO_PROCESS_EXIT_OUTSIDE_MAIN) || hasDisable(prevLine, RULE_NAMES.NO_PROCESS_EXIT_OUTSIDE_MAIN);\n violations.push({ line: lineNum, context: line.trim(), hasDisableComment: resolveDisable(disabled, disableAllowed) });\n }\n return violations;\n}\n\nfunction findViolationsForModifiedCode(workspaceRoot: string, changedFiles: string[], base: string, head: string | undefined, disableAllowed: boolean): ExitViolation[] {\n const violations: ExitViolation[] = [];\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 findExitViolationsInFile(file, workspaceRoot, disableAllowed)) {\n if (disableAllowed && v.hasDisableComment) continue;\n if (!changedLines.has(v.line)) continue;\n violations.push({ file, line: v.line, context: v.context });\n }\n }\n return violations;\n}\n\nfunction findViolationsForModifiedFiles(workspaceRoot: string, changedFiles: string[], disableAllowed: boolean): ExitViolation[] {\n const violations: ExitViolation[] = [];\n for (const file of changedFiles) {\n for (const v of findExitViolationsInFile(file, workspaceRoot, disableAllowed)) {\n if (disableAllowed && v.hasDisableComment) continue;\n violations.push({ file, line: v.line, context: v.context });\n }\n }\n return violations;\n}\n\nfunction reportViolations(workspaceRoot: string, violations: ExitViolation[], mode: ModifiedCodeMode, disableAllowed: boolean): void {\n writeTemplateIfMissing(workspaceRoot, INSTRUCT_FILE);\n console.error('');\n console.error('❌ process.exit() outside main()/runMain (or an import of another module\\'s main)!');\n console.error('');\n console.error(SHARED_MESSAGE);\n console.error(`READ ${new RepoRootFinder().instructAiDocPath(workspaceRoot, INSTRUCT_FILE)} for the full pattern.`);\n console.error('');\n for (const v of violations) {\n console.error(` ❌ ${v.file}:${v.line}`);\n console.error(` ${v.context}`);\n }\n console.error('');\n console.error(disableAllowed\n ? ' Escape hatch (genuine terminal boundary only): // webpieces-disable no-process-exit-outside-main -- <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-process-exit-outside-main 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: NoProcessExitOutsideMainConfig,\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⏭️ Skipping no-process-exit-outside-main validation (mode: OFF)\\n');\n return { success: true };\n }\n\n console.log('\\n📏 Validating No Process Exit Outside Main\\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-process-exit-outside-main 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: ExitViolation[] = [];\n if (mode === 'NEW_AND_MODIFIED_CODE') {\n violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed);\n } else {\n // NEW_AND_MODIFIED_FILES and the whole-scope modes (#1027) all judge every site of every file.\n violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);\n }\n\n if (violations.length === 0) {\n console.log('✅ No process.exit-outside-main violations found');\n return { success: true };\n }\n\n scan.recordSites('no-process-exit-outside-main', violations.map((v: ExitViolation) => v.file));\n reportViolations(workspaceRoot, violations, mode, disableAllowed);\n return { success: false };\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoProcessExitOutsideMainValidator extends CodeValidator<NoProcessExitOutsideMainConfig> {\n constructor(config: NoProcessExitOutsideMainConfig, private readonly scanScope: ScanScope) {\n super(config, 'no-process-exit-outside-main', 'no-process-exit-outside-main');\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runValidatorImpl(this.scanScope, this.config, workspaceRoot);\n }\n}\n"]}
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
* them falsifies the record) or to hand-written docs that name a FILE rather than a path.
|
|
31
31
|
*
|
|
32
32
|
* MODES: OFF | NEW_AND_MODIFIED_CODE (changed lines only) | NEW_AND_MODIFIED_FILES (whole changed file)
|
|
33
|
-
*
|
|
33
|
+
* | MODIFIED_PROJECTS / RUN_EVERY_TIME (whole files of every touched project / of the repo — #1027).
|
|
34
34
|
* Diff-scoped by default, so the docs whose SUBJECT is the layout (they print both rows on purpose)
|
|
35
35
|
* are not retroactively flooded — the rule bites when a template is next edited.
|
|
36
36
|
*
|
|
@@ -42,6 +42,7 @@
|
|
|
42
42
|
*/
|
|
43
43
|
import { NoStatePathsInTemplatesConfig } from '@webpieces/rules-config';
|
|
44
44
|
import { CodeValidator, ExecutorResult } from './code-validator';
|
|
45
|
+
import { ScanScope } from './scan-scope';
|
|
45
46
|
/** One restated state path, located in a template. */
|
|
46
47
|
export declare class StatePathViolation {
|
|
47
48
|
readonly file: string;
|
|
@@ -59,7 +60,8 @@ export declare class StatePathHit {
|
|
|
59
60
|
constructor(line: number, column: number, detail: string, hasDisableComment: boolean);
|
|
60
61
|
}
|
|
61
62
|
export declare class NoStatePathsInTemplatesValidator extends CodeValidator<NoStatePathsInTemplatesConfig> {
|
|
62
|
-
|
|
63
|
+
private readonly scanScope;
|
|
64
|
+
constructor(config: NoStatePathsInTemplatesConfig, scanScope: ScanScope);
|
|
63
65
|
run(workspaceRoot: string): Promise<ExecutorResult>;
|
|
64
66
|
/**
|
|
65
67
|
* The ONE spelling of "this validator failed": a thrown {@link RuleFailError} carrying its cures as
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
* them falsifies the record) or to hand-written docs that name a FILE rather than a path.
|
|
32
32
|
*
|
|
33
33
|
* MODES: OFF | NEW_AND_MODIFIED_CODE (changed lines only) | NEW_AND_MODIFIED_FILES (whole changed file)
|
|
34
|
-
*
|
|
34
|
+
* | MODIFIED_PROJECTS / RUN_EVERY_TIME (whole files of every touched project / of the repo — #1027).
|
|
35
35
|
* Diff-scoped by default, so the docs whose SUBJECT is the layout (they print both rows on purpose)
|
|
36
36
|
* are not retroactively flooded — the rule bites when a template is next edited.
|
|
37
37
|
*
|
|
@@ -50,6 +50,7 @@ const rules_config_1 = require("@webpieces/rules-config");
|
|
|
50
50
|
const inversify_1 = require("inversify");
|
|
51
51
|
const code_validator_1 = require("./code-validator");
|
|
52
52
|
const resolve_mode_1 = require("./resolve-mode");
|
|
53
|
+
const scan_scope_1 = require("./scan-scope");
|
|
53
54
|
/** One restated state path, located in a template. */
|
|
54
55
|
class StatePathViolation {
|
|
55
56
|
file;
|
|
@@ -79,8 +80,10 @@ class StatePathHit {
|
|
|
79
80
|
}
|
|
80
81
|
exports.StatePathHit = StatePathHit;
|
|
81
82
|
let NoStatePathsInTemplatesValidator = class NoStatePathsInTemplatesValidator extends code_validator_1.CodeValidator {
|
|
82
|
-
|
|
83
|
+
scanScope;
|
|
84
|
+
constructor(config, scanScope) {
|
|
83
85
|
super(config, rules_config_1.RULE_NAMES.NO_STATE_PATHS_IN_TEMPLATES, rules_config_1.RULE_NAMES.NO_STATE_PATHS_IN_TEMPLATES);
|
|
86
|
+
this.scanScope = scanScope;
|
|
84
87
|
}
|
|
85
88
|
async run(workspaceRoot) {
|
|
86
89
|
const opts = this.config;
|
|
@@ -103,20 +106,21 @@ let NoStatePathsInTemplatesValidator = class NoStatePathsInTemplatesValidator ex
|
|
|
103
106
|
}
|
|
104
107
|
console.log(` Base: ${base}`);
|
|
105
108
|
console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}\n`);
|
|
106
|
-
const changedFiles =
|
|
109
|
+
const changedFiles = this.scanScope.files(workspaceRoot, mode, base, head, { tsOnly: false })
|
|
107
110
|
.filter((file) => this.isRelevantFile(file));
|
|
108
111
|
if (changedFiles.length === 0) {
|
|
109
112
|
console.log('✅ No generated-doc templates changed');
|
|
110
113
|
return { success: true };
|
|
111
114
|
}
|
|
112
115
|
console.log(`📂 Checking ${String(changedFiles.length)} changed template(s)...`);
|
|
113
|
-
const violations = mode
|
|
116
|
+
const violations = this.scanScope.isLineScoped(mode)
|
|
114
117
|
? this.violationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed)
|
|
115
118
|
: this.violationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);
|
|
116
119
|
if (violations.length === 0) {
|
|
117
120
|
console.log('✅ No hard-coded state paths in generated-doc templates');
|
|
118
121
|
return { success: true };
|
|
119
122
|
}
|
|
123
|
+
this.scanScope.recordSites(this.name, violations.map((v) => v.file));
|
|
120
124
|
throw this.failure(violations, mode);
|
|
121
125
|
}
|
|
122
126
|
/**
|
|
@@ -255,6 +259,6 @@ let NoStatePathsInTemplatesValidator = class NoStatePathsInTemplatesValidator ex
|
|
|
255
259
|
exports.NoStatePathsInTemplatesValidator = NoStatePathsInTemplatesValidator;
|
|
256
260
|
exports.NoStatePathsInTemplatesValidator = NoStatePathsInTemplatesValidator = tslib_1.__decorate([
|
|
257
261
|
(0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
|
|
258
|
-
tslib_1.__metadata("design:paramtypes", [rules_config_1.NoStatePathsInTemplatesConfig])
|
|
262
|
+
tslib_1.__metadata("design:paramtypes", [rules_config_1.NoStatePathsInTemplatesConfig, scan_scope_1.ScanScope])
|
|
259
263
|
], NoStatePathsInTemplatesValidator);
|
|
260
264
|
//# sourceMappingURL=validate-no-state-paths-in-templates.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validate-no-state-paths-in-templates.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-state-paths-in-templates.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,0DAaiC;AACjC,yCAA2D;AAE3D,qDAAiE;AACjE,iDAAgD;AAEhD,sDAAsD;AACtD,MAAa,kBAAkB;IAEd;IACA;IACA;IACA;IAJb,YACa,IAAY,EACZ,IAAY,EACZ,MAAc,EACd,MAAc;QAHd,SAAI,GAAJ,IAAI,CAAQ;QACZ,SAAI,GAAJ,IAAI,CAAQ;QACZ,W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,UAA4B,EAC5B,KAAyB,EACzB,aAAiC;QAEjC,IAAI,UAAU,KAAK,KAAK;YAAE,OAAO,UAAU,CAAC;QAC5C,MAAM,IAAI,GAAG,IAAA,6BAAc,EAAC,KAAK,EAAE,aAAa,CAAC,CAAC;QAClD,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;YACZ,OAAO,CAAC,GAAG,CAAC,0DAA0D,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC;YACxF,OAAO,KAAK,CAAC;QACjB,CAAC;QACD,OAAO,UAAU,CAAC;IACtB,CAAC;CACJ,CAAA;AA5MY,4EAAgC;2CAAhC,gCAAgC;IAD5C,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEjB,4CAA6B;GADxC,gCAAgC,CA4M5C","sourcesContent":["/**\n * Validate No State Paths In Templates\n *\n * FAILS when a GENERATED-doc template restates a webpieces state path (`.webpieces/…`) as a literal\n * instead of rendering it from the resolver that already computes it.\n *\n * ## The incident this exists for\n *\n * `webpieces.git-workflow.md` — an AI-instruction doc regenerated into `.webpieces/instruct-ai/` of\n * every governed repo on every `wp-*` command — carried the literal\n * `.webpieces/logs/branch-mutations.log`. That log is deliberately PER-WORKTREE (one appender each):\n *\n * primary clone → `<primary>/.webpieces/logs/branch-mutations.log`\n * linked worktree → `<primary>/.webpieces/worktrees/<name>/logs/branch-mutations.log`\n *\n * So in a linked worktree the doc named a file that DOES NOT EXIST. The reader greps nothing, and the\n * silence reads as \"no deletions were logged\" — the opposite of the truth, from the one file whose\n * entire job is to prove every deletion is recoverable.\n *\n * The cure is not \"fix that line\". Every one of these paths already has a resolver, and the template\n * engine already substitutes (`{{MERGE_DIR}}`, `{{RUN_STATE}}`, `{{BRANCH_MUTATION_LOG}}` …). This\n * rule makes RESTATING the thing that fails and RENDERING the thing that passes, so the next one\n * cannot land.\n *\n * ## Scope\n *\n * `templateDirs` (workspace-relative dirs, recursive, `.md` only) — default\n * `packages/tooling/rules-config/templates`. A repo that generates no AI docs matches no files and the\n * rule is a no-op. Deliberately NOT widened to `backlog/**` (frozen records of past requests — editing\n * them falsifies the record) or to hand-written docs that name a FILE rather than a path.\n *\n * MODES: OFF | NEW_AND_MODIFIED_CODE (changed lines only) | NEW_AND_MODIFIED_FILES (whole changed file)\n * | MODIFIED_PROJECTS / RUN_EVERY_TIME (whole-scope, #1027 — widened centrally by DiffScope).\n * Diff-scoped by default, so the docs whose SUBJECT is the layout (they print both rows on purpose)\n * are not retroactively flooded — the rule bites when a template is next edited.\n *\n * ESCAPE HATCH (this table IS the layout, and printing it is the point):\n * <!-- webpieces-disable no-state-paths-in-templates -- <reason> -->\n *\n * `~/.webpieces/…` is NOT a violation: the machine-local tier has no per-tree resolver and no\n * per-tree answer, so the literal is the correct and only spelling of it.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport {\n hasDisable,\n RULE_NAMES,\n NoStatePathsInTemplatesConfig,\n Option,\n RuleFailError,\n DEFAULT_TEMPLATE_DIRS,\n DEFAULT_BANNED_STATE_PATH_PREFIXES,\n ModifiedCodeMode,\n detectBase,\n getChangedFiles,\n getFileDiff,\n getChangedLineNumbers,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { shouldSkipRule } from './resolve-mode';\n\n/** One restated state path, located in a template. */\nexport class StatePathViolation {\n constructor(\n readonly file: string,\n readonly line: number,\n readonly column: number,\n readonly detail: string,\n ) {}\n}\n\n/** One restated state path within a single file, plus whether its line carries a disable. */\nexport class StatePathHit {\n constructor(\n readonly line: number,\n readonly column: number,\n readonly detail: string,\n readonly hasDisableComment: boolean,\n ) {}\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoStatePathsInTemplatesValidator extends CodeValidator<NoStatePathsInTemplatesConfig> {\n constructor(config: NoStatePathsInTemplatesConfig) {\n super(config, RULE_NAMES.NO_STATE_PATHS_IN_TEMPLATES, RULE_NAMES.NO_STATE_PATHS_IN_TEMPLATES);\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n const opts = this.config;\n const mode = this.resolveMode(\n opts.mode ?? 'NEW_AND_MODIFIED_CODE', opts.turnOffRuleUntilEpoch, opts.turnOffRuleWhileOnBranch ?? undefined);\n const disableAllowed = opts.disableAllowed ?? true;\n if (mode === 'OFF') {\n console.log('\\n⏭️ Skipping no-state-paths-in-templates validation (mode: OFF)\\n');\n return { success: true };\n }\n\n console.log('\\n📏 Validating No State Paths In Templates\\n');\n console.log(` Mode: ${mode}`);\n\n let base = process.env['NX_BASE'];\n const head = process.env['NX_HEAD'];\n if (base === undefined || base === '') {\n base = detectBase(workspaceRoot) ?? undefined;\n if (base === undefined || base === '') {\n console.log('\\n⏭️ Skipping no-state-paths-in-templates validation (could not detect base branch)\\n');\n return { success: true };\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, { tsOnly: false })\n .filter((file: string): boolean => this.isRelevantFile(file));\n if (changedFiles.length === 0) {\n console.log('✅ No generated-doc templates changed');\n return { success: true };\n }\n console.log(`📂 Checking ${String(changedFiles.length)} changed template(s)...`);\n\n const violations = mode === 'NEW_AND_MODIFIED_CODE'\n ? this.violationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed)\n : this.violationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);\n\n if (violations.length === 0) {\n console.log('✅ No hard-coded state paths in generated-doc templates');\n return { success: true };\n }\n throw this.failure(violations, mode);\n }\n\n /**\n * The ONE spelling of \"this validator failed\": a thrown {@link RuleFailError} carrying its cures as\n * `Option[]`, which {@link RuleReporter} catches and renders.\n *\n * NOT `console.error` + `{ success: false }`. That pair is a second spelling of the same fact (see\n * RuleReporter.runValidators, which calls it a back-compat shim scheduled for deletion), and\n * hand-written \"To fix: … / Escape hatch: …\" prose is a second spelling of `Option[]` — the\n * framework owns the `Fix Option N:` numbering and the `(preferred)` tag, so a rule never writes them.\n */\n private failure(violations: StatePathViolation[], mode: ModifiedCodeMode): RuleFailError {\n const detail = violations.map((violation: StatePathViolation): string =>\n ` ${violation.file}:${String(violation.line)}:${String(violation.column)} restates \\`${violation.detail}…\\``)\n .join('\\n');\n const first = violations[0];\n return new RuleFailError(\n RULE_NAMES.NO_STATE_PATHS_IN_TEMPLATES,\n 'A generated-doc template RESTATES a webpieces state path instead of computing it. These docs are '\n + 'regenerated into every governed repo and handed to an agent by absolute path AS INSTRUCTION, and '\n + 'every .webpieces/ path is per-tree — a linked worktree keeps its state under '\n + `<primary>/.webpieces/worktrees/<name>/ — so the relative spelling names a file that DOES NOT EXIST `\n + `in half the trees that read it. Current mode: ${mode}.\\n${detail}`,\n first?.line,\n first?.detail,\n [\n new Option(\n 'Put a {{PLACEHOLDER}} in the template and render it from the resolver that already computes '\n + 'that path, the way {{BRANCH_MUTATION_LOG}} is rendered from '\n + 'BranchMutationLog.branchMutationLogPath(root) in GitWorkflowDoc.render',\n true),\n new Option(\n 'If the doc\\'s SUBJECT is the layout and printing the literal is the point, say so out loud:\\n'\n + '<!-- webpieces-disable no-state-paths-in-templates -- <reason> -->'),\n ],\n );\n }\n\n /**\n * A changed file this rule looks at: a `.md` under one of the configured template dirs.\n *\n * The ONE place the file set is narrowed, so both modes run over the same list and a scope change\n * cannot be applied in one and forgotten in the other.\n */\n isRelevantFile(file: string): boolean {\n const norm = file.replace(/\\\\/g, '/');\n if (!norm.endsWith('.md')) return false;\n return this.templateDirs().some((dir: string): boolean => norm.startsWith(`${dir}/`));\n }\n\n /** Every restated state path in `text`, one hit per line (the first match on that line). */\n findHits(text: string): StatePathHit[] {\n const lines = text.split('\\n');\n const hits: StatePathHit[] = [];\n for (let i = 0; i < lines.length; i++) {\n const raw = lines[i] ?? '';\n for (const prefix of this.bannedPrefixes()) {\n const column = this.columnOf(raw, prefix);\n if (column < 0) continue;\n hits.push(new StatePathHit(i + 1, column + 1, prefix, this.hasDisableComment(lines, i + 1)));\n break;\n }\n }\n return hits;\n }\n\n /**\n * Where `prefix` is restated in `raw`, or -1.\n *\n * `~/.webpieces/…` is skipped: the machine-local tier is the same absolute path from every tree, so\n * there is no resolver to call and the literal is the only spelling there is. Everything else —\n * including the bare relative form that started this — is a restatement of a per-tree path.\n */\n private columnOf(raw: string, prefix: string): number {\n let from = 0;\n for (;;) {\n const at = raw.indexOf(prefix, from);\n if (at < 0) return -1;\n if (raw.slice(Math.max(0, at - 2), at) !== '~/') return at;\n from = at + 1;\n }\n }\n\n /** NEW_AND_MODIFIED_CODE: only hits whose line is in the diff hunks. */\n private violationsForModifiedCode(\n workspaceRoot: string,\n changedFiles: string[],\n base: string,\n head: string | undefined,\n disableAllowed: boolean,\n ): StatePathViolation[] {\n const violations: StatePathViolation[] = [];\n for (const file of changedFiles) {\n const changedLines = getChangedLineNumbers(getFileDiff(workspaceRoot, file, base, head));\n if (changedLines.size === 0) continue;\n for (const hit of this.hitsForFile(file, workspaceRoot)) {\n if (disableAllowed && hit.hasDisableComment) continue;\n if (!changedLines.has(hit.line)) continue;\n violations.push(new StatePathViolation(file, hit.line, hit.column, hit.detail));\n }\n }\n return violations;\n }\n\n /** NEW_AND_MODIFIED_FILES: every hit in any changed template. */\n private violationsForModifiedFiles(\n workspaceRoot: string,\n changedFiles: string[],\n disableAllowed: boolean,\n ): StatePathViolation[] {\n const violations: StatePathViolation[] = [];\n for (const file of changedFiles) {\n for (const hit of this.hitsForFile(file, workspaceRoot)) {\n if (disableAllowed && hit.hasDisableComment) continue;\n violations.push(new StatePathViolation(file, hit.line, hit.column, hit.detail));\n }\n }\n return violations;\n }\n\n private hitsForFile(file: string, workspaceRoot: string): StatePathHit[] {\n const fullPath = path.join(workspaceRoot, file);\n if (!fs.existsSync(fullPath)) return [];\n return this.findHits(fs.readFileSync(fullPath, 'utf-8'));\n }\n\n private templateDirs(): readonly string[] {\n const dirs = this.config.templateDirs ?? DEFAULT_TEMPLATE_DIRS;\n return dirs.map((dir: string): string => dir.replace(/\\\\/g, '/').replace(/\\/+$/, ''));\n }\n\n private bannedPrefixes(): readonly string[] {\n return this.config.bannedPathPrefixes ?? DEFAULT_BANNED_STATE_PATH_PREFIXES;\n }\n\n /** True if a `webpieces-disable no-state-paths-in-templates` sits on this line or up to 3 above. */\n private hasDisableComment(lines: string[], lineNumber: number): boolean {\n const start = Math.max(0, lineNumber - 4);\n for (let i = lineNumber - 1; i >= start; i--) {\n if (hasDisable(lines[i] ?? '', RULE_NAMES.NO_STATE_PATHS_IN_TEMPLATES)) return true;\n }\n return false;\n }\n\n private resolveMode(\n normalMode: ModifiedCodeMode,\n epoch: number | undefined,\n branchPattern: string | undefined,\n ): ModifiedCodeMode {\n if (normalMode === 'OFF') return normalMode;\n const skip = shouldSkipRule(epoch, branchPattern);\n if (skip.skip) {\n console.log(`\\n⏭️ Skipping no-state-paths-in-templates validation (${skip.reason})\\n`);\n return 'OFF';\n }\n return normalMode;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"validate-no-state-paths-in-templates.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-state-paths-in-templates.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,0DAYiC;AACjC,yCAA2D;AAE3D,qDAAiE;AACjE,iDAAgD;AAChD,6CAAyC;AAEzC,sDAAsD;AACtD,MAAa,kBAAkB;IAEd;IACA;IACA;IACA;IAJb,YACa,IAAY,EACZ,IAAY,EACZ,MAAc,EACd,MAAc;QAHd,SAAI,GAAJ,IAAI,CAAQ;QACZ,SAAI,GAAJ,IAAI,CAAQ;QACZ,WAAM,GAAN,MAAM,CAAQ;QACd,WAAM,GAAN,MAAM,CAAQ;IACxB,CAAC;CACP;AAPD,gDAOC;AAED,6FAA6F;AAC7F,MAAa,YAAY;IAER;IACA;IACA;IACA;IAJb,YACa,IAAY,EAC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AAC,2BAA2B,CAAC;gBAAE,OAAO,IAAI,CAAC;QACxF,CAAC;QACD,OAAO,KAAK,CAAC;IACjB,CAAC;IAEO,WAAW,CACf,UAA4B,EAC5B,KAAyB,EACzB,aAAiC;QAEjC,IAAI,UAAU,KAAK,KAAK;YAAE,OAAO,UAAU,CAAC;QAC5C,MAAM,IAAI,GAAG,IAAA,6BAAc,EAAC,KAAK,EAAE,aAAa,CAAC,CAAC;QAClD,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;YACZ,OAAO,CAAC,GAAG,CAAC,0DAA0D,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC;YACxF,OAAO,KAAK,CAAC;QACjB,CAAC;QACD,OAAO,UAAU,CAAC;IACtB,CAAC;CACJ,CAAA;AA7MY,4EAAgC;2CAAhC,gCAAgC;IAD5C,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEjB,4CAA6B,EAA8B,sBAAS;GAD/E,gCAAgC,CA6M5C","sourcesContent":["/**\n * Validate No State Paths In Templates\n *\n * FAILS when a GENERATED-doc template restates a webpieces state path (`.webpieces/…`) as a literal\n * instead of rendering it from the resolver that already computes it.\n *\n * ## The incident this exists for\n *\n * `webpieces.git-workflow.md` — an AI-instruction doc regenerated into `.webpieces/instruct-ai/` of\n * every governed repo on every `wp-*` command — carried the literal\n * `.webpieces/logs/branch-mutations.log`. That log is deliberately PER-WORKTREE (one appender each):\n *\n * primary clone → `<primary>/.webpieces/logs/branch-mutations.log`\n * linked worktree → `<primary>/.webpieces/worktrees/<name>/logs/branch-mutations.log`\n *\n * So in a linked worktree the doc named a file that DOES NOT EXIST. The reader greps nothing, and the\n * silence reads as \"no deletions were logged\" — the opposite of the truth, from the one file whose\n * entire job is to prove every deletion is recoverable.\n *\n * The cure is not \"fix that line\". Every one of these paths already has a resolver, and the template\n * engine already substitutes (`{{MERGE_DIR}}`, `{{RUN_STATE}}`, `{{BRANCH_MUTATION_LOG}}` …). This\n * rule makes RESTATING the thing that fails and RENDERING the thing that passes, so the next one\n * cannot land.\n *\n * ## Scope\n *\n * `templateDirs` (workspace-relative dirs, recursive, `.md` only) — default\n * `packages/tooling/rules-config/templates`. A repo that generates no AI docs matches no files and the\n * rule is a no-op. Deliberately NOT widened to `backlog/**` (frozen records of past requests — editing\n * them falsifies the record) or to hand-written docs that name a FILE rather than a path.\n *\n * MODES: OFF | NEW_AND_MODIFIED_CODE (changed lines only) | NEW_AND_MODIFIED_FILES (whole changed file)\n * | MODIFIED_PROJECTS / RUN_EVERY_TIME (whole files of every touched project / of the repo — #1027).\n * Diff-scoped by default, so the docs whose SUBJECT is the layout (they print both rows on purpose)\n * are not retroactively flooded — the rule bites when a template is next edited.\n *\n * ESCAPE HATCH (this table IS the layout, and printing it is the point):\n * <!-- webpieces-disable no-state-paths-in-templates -- <reason> -->\n *\n * `~/.webpieces/…` is NOT a violation: the machine-local tier has no per-tree resolver and no\n * per-tree answer, so the literal is the correct and only spelling of it.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport {\n hasDisable,\n RULE_NAMES,\n NoStatePathsInTemplatesConfig,\n Option,\n RuleFailError,\n DEFAULT_TEMPLATE_DIRS,\n DEFAULT_BANNED_STATE_PATH_PREFIXES,\n ModifiedCodeMode,\n detectBase,\n getFileDiff,\n getChangedLineNumbers,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { shouldSkipRule } from './resolve-mode';\nimport { ScanScope } from './scan-scope';\n\n/** One restated state path, located in a template. */\nexport class StatePathViolation {\n constructor(\n readonly file: string,\n readonly line: number,\n readonly column: number,\n readonly detail: string,\n ) {}\n}\n\n/** One restated state path within a single file, plus whether its line carries a disable. */\nexport class StatePathHit {\n constructor(\n readonly line: number,\n readonly column: number,\n readonly detail: string,\n readonly hasDisableComment: boolean,\n ) {}\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoStatePathsInTemplatesValidator extends CodeValidator<NoStatePathsInTemplatesConfig> {\n constructor(config: NoStatePathsInTemplatesConfig, private readonly scanScope: ScanScope) {\n super(config, RULE_NAMES.NO_STATE_PATHS_IN_TEMPLATES, RULE_NAMES.NO_STATE_PATHS_IN_TEMPLATES);\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n const opts = this.config;\n const mode = this.resolveMode(\n opts.mode ?? 'NEW_AND_MODIFIED_CODE', opts.turnOffRuleUntilEpoch, opts.turnOffRuleWhileOnBranch ?? undefined);\n const disableAllowed = opts.disableAllowed ?? true;\n if (mode === 'OFF') {\n console.log('\\n⏭️ Skipping no-state-paths-in-templates validation (mode: OFF)\\n');\n return { success: true };\n }\n\n console.log('\\n📏 Validating No State Paths In Templates\\n');\n console.log(` Mode: ${mode}`);\n\n let base = process.env['NX_BASE'];\n const head = process.env['NX_HEAD'];\n if (base === undefined || base === '') {\n base = detectBase(workspaceRoot) ?? undefined;\n if (base === undefined || base === '') {\n console.log('\\n⏭️ Skipping no-state-paths-in-templates validation (could not detect base branch)\\n');\n return { success: true };\n }\n }\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}\\n`);\n\n const changedFiles = this.scanScope.files(workspaceRoot, mode, base, head, { tsOnly: false })\n .filter((file: string): boolean => this.isRelevantFile(file));\n if (changedFiles.length === 0) {\n console.log('✅ No generated-doc templates changed');\n return { success: true };\n }\n console.log(`📂 Checking ${String(changedFiles.length)} changed template(s)...`);\n\n const violations = this.scanScope.isLineScoped(mode)\n ? this.violationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed)\n : this.violationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);\n\n if (violations.length === 0) {\n console.log('✅ No hard-coded state paths in generated-doc templates');\n return { success: true };\n }\n this.scanScope.recordSites(this.name, violations.map((v: StatePathViolation) => v.file));\n throw this.failure(violations, mode);\n }\n\n /**\n * The ONE spelling of \"this validator failed\": a thrown {@link RuleFailError} carrying its cures as\n * `Option[]`, which {@link RuleReporter} catches and renders.\n *\n * NOT `console.error` + `{ success: false }`. That pair is a second spelling of the same fact (see\n * RuleReporter.runValidators, which calls it a back-compat shim scheduled for deletion), and\n * hand-written \"To fix: … / Escape hatch: …\" prose is a second spelling of `Option[]` — the\n * framework owns the `Fix Option N:` numbering and the `(preferred)` tag, so a rule never writes them.\n */\n private failure(violations: StatePathViolation[], mode: ModifiedCodeMode): RuleFailError {\n const detail = violations.map((violation: StatePathViolation): string =>\n ` ${violation.file}:${String(violation.line)}:${String(violation.column)} restates \\`${violation.detail}…\\``)\n .join('\\n');\n const first = violations[0];\n return new RuleFailError(\n RULE_NAMES.NO_STATE_PATHS_IN_TEMPLATES,\n 'A generated-doc template RESTATES a webpieces state path instead of computing it. These docs are '\n + 'regenerated into every governed repo and handed to an agent by absolute path AS INSTRUCTION, and '\n + 'every .webpieces/ path is per-tree — a linked worktree keeps its state under '\n + `<primary>/.webpieces/worktrees/<name>/ — so the relative spelling names a file that DOES NOT EXIST `\n + `in half the trees that read it. Current mode: ${mode}.\\n${detail}`,\n first?.line,\n first?.detail,\n [\n new Option(\n 'Put a {{PLACEHOLDER}} in the template and render it from the resolver that already computes '\n + 'that path, the way {{BRANCH_MUTATION_LOG}} is rendered from '\n + 'BranchMutationLog.branchMutationLogPath(root) in GitWorkflowDoc.render',\n true),\n new Option(\n 'If the doc\\'s SUBJECT is the layout and printing the literal is the point, say so out loud:\\n'\n + '<!-- webpieces-disable no-state-paths-in-templates -- <reason> -->'),\n ],\n );\n }\n\n /**\n * A changed file this rule looks at: a `.md` under one of the configured template dirs.\n *\n * The ONE place the file set is narrowed, so both modes run over the same list and a scope change\n * cannot be applied in one and forgotten in the other.\n */\n isRelevantFile(file: string): boolean {\n const norm = file.replace(/\\\\/g, '/');\n if (!norm.endsWith('.md')) return false;\n return this.templateDirs().some((dir: string): boolean => norm.startsWith(`${dir}/`));\n }\n\n /** Every restated state path in `text`, one hit per line (the first match on that line). */\n findHits(text: string): StatePathHit[] {\n const lines = text.split('\\n');\n const hits: StatePathHit[] = [];\n for (let i = 0; i < lines.length; i++) {\n const raw = lines[i] ?? '';\n for (const prefix of this.bannedPrefixes()) {\n const column = this.columnOf(raw, prefix);\n if (column < 0) continue;\n hits.push(new StatePathHit(i + 1, column + 1, prefix, this.hasDisableComment(lines, i + 1)));\n break;\n }\n }\n return hits;\n }\n\n /**\n * Where `prefix` is restated in `raw`, or -1.\n *\n * `~/.webpieces/…` is skipped: the machine-local tier is the same absolute path from every tree, so\n * there is no resolver to call and the literal is the only spelling there is. Everything else —\n * including the bare relative form that started this — is a restatement of a per-tree path.\n */\n private columnOf(raw: string, prefix: string): number {\n let from = 0;\n for (;;) {\n const at = raw.indexOf(prefix, from);\n if (at < 0) return -1;\n if (raw.slice(Math.max(0, at - 2), at) !== '~/') return at;\n from = at + 1;\n }\n }\n\n /** NEW_AND_MODIFIED_CODE: only hits whose line is in the diff hunks. */\n private violationsForModifiedCode(\n workspaceRoot: string,\n changedFiles: string[],\n base: string,\n head: string | undefined,\n disableAllowed: boolean,\n ): StatePathViolation[] {\n const violations: StatePathViolation[] = [];\n for (const file of changedFiles) {\n const changedLines = getChangedLineNumbers(getFileDiff(workspaceRoot, file, base, head));\n if (changedLines.size === 0) continue;\n for (const hit of this.hitsForFile(file, workspaceRoot)) {\n if (disableAllowed && hit.hasDisableComment) continue;\n if (!changedLines.has(hit.line)) continue;\n violations.push(new StatePathViolation(file, hit.line, hit.column, hit.detail));\n }\n }\n return violations;\n }\n\n /** NEW_AND_MODIFIED_FILES: every hit in any changed template. */\n private violationsForModifiedFiles(\n workspaceRoot: string,\n changedFiles: string[],\n disableAllowed: boolean,\n ): StatePathViolation[] {\n const violations: StatePathViolation[] = [];\n for (const file of changedFiles) {\n for (const hit of this.hitsForFile(file, workspaceRoot)) {\n if (disableAllowed && hit.hasDisableComment) continue;\n violations.push(new StatePathViolation(file, hit.line, hit.column, hit.detail));\n }\n }\n return violations;\n }\n\n private hitsForFile(file: string, workspaceRoot: string): StatePathHit[] {\n const fullPath = path.join(workspaceRoot, file);\n if (!fs.existsSync(fullPath)) return [];\n return this.findHits(fs.readFileSync(fullPath, 'utf-8'));\n }\n\n private templateDirs(): readonly string[] {\n const dirs = this.config.templateDirs ?? DEFAULT_TEMPLATE_DIRS;\n return dirs.map((dir: string): string => dir.replace(/\\\\/g, '/').replace(/\\/+$/, ''));\n }\n\n private bannedPrefixes(): readonly string[] {\n return this.config.bannedPathPrefixes ?? DEFAULT_BANNED_STATE_PATH_PREFIXES;\n }\n\n /** True if a `webpieces-disable no-state-paths-in-templates` sits on this line or up to 3 above. */\n private hasDisableComment(lines: string[], lineNumber: number): boolean {\n const start = Math.max(0, lineNumber - 4);\n for (let i = lineNumber - 1; i >= start; i--) {\n if (hasDisable(lines[i] ?? '', RULE_NAMES.NO_STATE_PATHS_IN_TEMPLATES)) return true;\n }\n return false;\n }\n\n private resolveMode(\n normalMode: ModifiedCodeMode,\n epoch: number | undefined,\n branchPattern: string | undefined,\n ): ModifiedCodeMode {\n if (normalMode === 'OFF') return normalMode;\n const skip = shouldSkipRule(epoch, branchPattern);\n if (skip.skip) {\n console.log(`\\n⏭️ Skipping no-state-paths-in-templates validation (${skip.reason})\\n`);\n return 'OFF';\n }\n return normalMode;\n }\n}\n"]}
|
|
@@ -36,6 +36,7 @@
|
|
|
36
36
|
*/
|
|
37
37
|
import { NoSymbolDiTokensConfig } from '@webpieces/rules-config';
|
|
38
38
|
import { CodeValidator, ExecutorResult } from './code-validator';
|
|
39
|
+
import { ScanScope } from './scan-scope';
|
|
39
40
|
interface SymbolViolationInfo {
|
|
40
41
|
line: number;
|
|
41
42
|
context: string;
|
|
@@ -43,7 +44,8 @@ interface SymbolViolationInfo {
|
|
|
43
44
|
}
|
|
44
45
|
export declare function findSymbolViolationsInFile(filePath: string, workspaceRoot: string, disableAllowed: boolean, allowedPaths: string[]): SymbolViolationInfo[];
|
|
45
46
|
export declare class NoSymbolDiTokensValidator extends CodeValidator<NoSymbolDiTokensConfig> {
|
|
46
|
-
|
|
47
|
+
private readonly scanScope;
|
|
48
|
+
constructor(config: NoSymbolDiTokensConfig, scanScope: ScanScope);
|
|
47
49
|
run(workspaceRoot: string): Promise<ExecutorResult>;
|
|
48
50
|
}
|
|
49
51
|
export {};
|
|
@@ -45,6 +45,7 @@ const rules_config_1 = require("@webpieces/rules-config");
|
|
|
45
45
|
const code_validator_1 = require("./code-validator");
|
|
46
46
|
const inversify_1 = require("inversify");
|
|
47
47
|
const resolve_mode_1 = require("./resolve-mode");
|
|
48
|
+
const scan_scope_1 = require("./scan-scope");
|
|
48
49
|
const SYMBOL_DI_REGEX = /=\s*Symbol(?:\.for)?\(/;
|
|
49
50
|
const SHARED_MESSAGE = `Do not create a dependency-injection token with Symbol(). Choose the right pattern:
|
|
50
51
|
Option 1: OWN class — annotate it with @injectable(bindingScopeValues.Singleton) and inject by concrete class TYPE — no Symbol, no @inject.
|
|
@@ -209,7 +210,7 @@ function resolveMode(normalMode, epoch, branchPattern) {
|
|
|
209
210
|
}
|
|
210
211
|
return normalMode;
|
|
211
212
|
}
|
|
212
|
-
async function runValidatorImpl(options, workspaceRoot) {
|
|
213
|
+
async function runValidatorImpl(scan, options, workspaceRoot) {
|
|
213
214
|
const mode = resolveMode(options.mode ?? 'OFF', options.turnOffRuleUntilEpoch, (options.turnOffRuleWhileOnBranch ?? undefined));
|
|
214
215
|
const disableAllowed = options.disableAllowed ?? true;
|
|
215
216
|
const allowedPaths = options.allowedPaths ?? [];
|
|
@@ -233,7 +234,7 @@ async function runValidatorImpl(options, workspaceRoot) {
|
|
|
233
234
|
console.log(` Base: ${base}`);
|
|
234
235
|
console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);
|
|
235
236
|
console.log('');
|
|
236
|
-
const changedFiles =
|
|
237
|
+
const changedFiles = scan.files(workspaceRoot, mode, base, head);
|
|
237
238
|
if (changedFiles.length === 0) {
|
|
238
239
|
console.log('✅ No TypeScript files changed');
|
|
239
240
|
return { success: true };
|
|
@@ -243,27 +244,31 @@ async function runValidatorImpl(options, workspaceRoot) {
|
|
|
243
244
|
if (mode === 'NEW_AND_MODIFIED_CODE') {
|
|
244
245
|
violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed, allowedPaths);
|
|
245
246
|
}
|
|
246
|
-
else
|
|
247
|
+
else {
|
|
248
|
+
// NEW_AND_MODIFIED_FILES and the whole-scope modes (#1027) all judge every site of every file.
|
|
247
249
|
violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed, allowedPaths);
|
|
248
250
|
}
|
|
249
251
|
if (violations.length === 0) {
|
|
250
252
|
console.log('✅ No Symbol DI token violations found');
|
|
251
253
|
return { success: true };
|
|
252
254
|
}
|
|
255
|
+
scan.recordSites('no-symbol-di-tokens', violations.map((v) => v.file));
|
|
253
256
|
reportViolations(violations, mode, disableAllowed);
|
|
254
257
|
return { success: false };
|
|
255
258
|
}
|
|
256
259
|
let NoSymbolDiTokensValidator = class NoSymbolDiTokensValidator extends code_validator_1.CodeValidator {
|
|
257
|
-
|
|
260
|
+
scanScope;
|
|
261
|
+
constructor(config, scanScope) {
|
|
258
262
|
super(config, 'no-symbol-di-tokens', 'no-symbol-di-tokens');
|
|
263
|
+
this.scanScope = scanScope;
|
|
259
264
|
}
|
|
260
265
|
async run(workspaceRoot) {
|
|
261
|
-
return runValidatorImpl(this.config, workspaceRoot);
|
|
266
|
+
return runValidatorImpl(this.scanScope, this.config, workspaceRoot);
|
|
262
267
|
}
|
|
263
268
|
};
|
|
264
269
|
exports.NoSymbolDiTokensValidator = NoSymbolDiTokensValidator;
|
|
265
270
|
exports.NoSymbolDiTokensValidator = NoSymbolDiTokensValidator = tslib_1.__decorate([
|
|
266
271
|
(0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
|
|
267
|
-
tslib_1.__metadata("design:paramtypes", [rules_config_1.NoSymbolDiTokensConfig])
|
|
272
|
+
tslib_1.__metadata("design:paramtypes", [rules_config_1.NoSymbolDiTokensConfig, scan_scope_1.ScanScope])
|
|
268
273
|
], NoSymbolDiTokensValidator);
|
|
269
274
|
//# sourceMappingURL=validate-no-symbol-di-tokens.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validate-no-symbol-di-tokens.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-symbol-di-tokens.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;;;AAmGH,gEAkCC;;AAnID,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA4K;AAC5K,qDAAiE;AACjE,yCAA2D;AAC3D,iDAAgD;AAEhD,MAAM,eAAe,GAAG,wBAAwB,CAAC;AAEjD,MAAM,cAAc,GAAG;;;;;;;;;;mHAU4F,CAAC;AAcpH,SAAS,UAAU,CAAC,QAAgB;IAChC,OAAO,QAAQ,CAAC,QAAQ,CAAC,UAAU,CAAC;QAChC,QAAQ,CAAC,QAAQ,CAAC,UAAU,CAAC;QAC7B,QAAQ,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;AACxC,CAAC;AAED,SAAS,WAAW,CAAC,OAAe;IAChC,IAAI,EAAE,GAAG,EAAE,CAAC;IACZ,IAAI,CAAC,GAAG,CAAC,CAAC;IACV,OAAO,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;QACxB,MAAM,EAAE,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;QACtB,IAAI,EAAE,KAAK,GAAG,EAAE,CAAC;YACb,IAAI,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,GAAG,EAAE,CAAC;gBACzB,EAAE,IAAI,IAAI,CAAC;gBACX,CAAC,IAAI,CAAC,CAAC;gBACP,IAAI,OAAO,CAAC,CAAC,CAAC,KAAK,GAAG;oBAAE,CAAC,IAAI,CAAC,CAAC;gBAC/B,SAAS;YACb,CAAC;YACD,EAAE,IAAI,OAAO,CAAC;YACd,CAAC,I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AAC,CAAC;IAC3G,CAAC;IAED,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC1B,OAAO,CAAC,GAAG,CAAC,uCAAuC,CAAC,CAAC;QACrD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7B,CAAC;IAED,gBAAgB,CAAC,UAAU,EAAE,IAAI,EAAE,cAAc,CAAC,CAAC;IAEnD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC9B,CAAC;AAGM,IAAM,yBAAyB,GAA/B,MAAM,yBAA0B,SAAQ,8BAAqC;IAChF,YAAY,MAA8B;QACtC,KAAK,CAAC,MAAM,EAAE,qBAAqB,EAAE,qBAAqB,CAAC,CAAC;IAChE,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,aAAqB;QAC3B,OAAO,gBAAgB,CAAC,IAAI,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IACxD,CAAC;CACJ,CAAA;AARY,8DAAyB;oCAAzB,yBAAyB;IADrC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEjB,qCAAsB;GADjC,yBAAyB,CAQrC","sourcesContent":["/**\n * Validate No Symbol DI Tokens Executor\n *\n * Validates that Symbol() / Symbol.for() are not used to create DI tokens\n * outside of the designated API-binding packages.\n *\n * ============================================================================\n * VIOLATIONS (BAD) - These patterns are flagged:\n * ============================================================================\n *\n * - export const MY_TOKEN = Symbol('MY_TOKEN')\n * - export const MY_TOKEN = Symbol.for('MY_TOKEN')\n * - const TOKEN: symbol = Symbol('TOKEN')\n *\n * ============================================================================\n * ALLOWED\n * ============================================================================\n *\n * - Files under allowedPaths (configured in webpieces.config.json, defaults to [])\n * - Test files (*.test.ts, *.spec.ts, __tests__/**)\n * - Lines with // webpieces-disable no-symbol-di-tokens -- <reason> (when disableAllowed: true)\n *\n * ============================================================================\n * MODES (LINE-BASED)\n * ============================================================================\n * - OFF: Skip validation entirely\n * - NEW_AND_MODIFIED_CODE: Flag Symbol DI tokens on changed lines (lines in diff hunks)\n * - NEW_AND_MODIFIED_FILES: Flag ALL Symbol DI tokens in files that were modified\n *\n * ============================================================================\n * ESCAPE HATCH\n * ============================================================================\n * Add comment on the same line or line above the violation:\n * // webpieces-disable no-symbol-di-tokens -- [your justification]\n * export const MY_TOKEN = Symbol('MY_TOKEN');\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { hasDisable, RULE_NAMES, NoSymbolDiTokensConfig, 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\nconst SYMBOL_DI_REGEX = /=\\s*Symbol(?:\\.for)?\\(/;\n\nconst SHARED_MESSAGE = `Do not create a dependency-injection token with Symbol(). Choose the right pattern:\nOption 1: OWN class — annotate it with @injectable(bindingScopeValues.Singleton) and inject by concrete class TYPE — no Symbol, no @inject.\n constructor(private readonly myService: MyService) {}\nOption 2: API IMPLEMENTATION — import the Symbol from the API definition file and use:\n @provideSingletonDefaultForApi(SOME_API_TOKEN)\n export class SomeApiImpl implements SomeApi { ... }\nOption 3: External lib class you cannot decorate (DataSource, Anthropic, etc.):\n bind in a ContainerModule using the class itself as token — no Symbol needed:\n bind<Anthropic>(Anthropic).toDynamicValue(() => new Anthropic({ apiKey: ... })).inSingletonScope()\n Then inject by type — no Symbol, no @inject.\nOption 4 (last resort): append // webpieces-disable no-symbol-di-tokens -- <reason> to justify this specific line.`;\n\ninterface SymbolViolation {\n file: string;\n line: number;\n context: string;\n}\n\ninterface SymbolViolationInfo {\n line: number;\n context: string;\n hasDisableComment: boolean;\n}\n\nfunction isTestFile(filePath: string): boolean {\n return filePath.includes('.spec.ts') ||\n filePath.includes('.test.ts') ||\n filePath.includes('__tests__/');\n}\n\nfunction globToRegex(pattern: string): RegExp {\n let re = '';\n let i = 0;\n while (i < pattern.length) {\n const ch = pattern[i];\n if (ch === '*') {\n if (pattern[i + 1] === '*') {\n re += '.*';\n i += 2;\n if (pattern[i] === '/') i += 1;\n continue;\n }\n re += '[^/]*';\n i += 1;\n continue;\n }\n if (ch === '?') {\n re += '[^/]';\n i += 1;\n continue;\n }\n if ('.+^$(){}|[]\\\\'.includes(ch)) {\n re += '\\\\' + ch;\n i += 1;\n continue;\n }\n re += ch;\n i += 1;\n }\n return new RegExp('^' + re + '$');\n}\n\nfunction isAllowedPath(filePath: string, allowedPaths: string[]): boolean {\n for (const pattern of allowedPaths) {\n if (globToRegex(pattern).test(filePath)) {\n return true;\n }\n }\n return false;\n}\n\nfunction stripLineComments(line: string): string {\n const idx = line.indexOf('//');\n if (idx === -1) return line;\n return line.substring(0, idx);\n}\n\nfunction hasDisableOnLine(line: string): boolean {\n return hasDisable(line, RULE_NAMES.NO_SYMBOL_DI_TOKENS);\n}\n\nfunction resolveDisable(disabled: boolean, disableAllowed: boolean): boolean {\n if (!disableAllowed && disabled) {\n return false;\n }\n return disabled;\n}\n\nexport function findSymbolViolationsInFile(\n filePath: string,\n workspaceRoot: string,\n disableAllowed: boolean,\n allowedPaths: string[],\n): SymbolViolationInfo[] {\n if (isTestFile(filePath)) return [];\n if (isAllowedPath(filePath, allowedPaths)) return [];\n\n const fullPath = path.join(workspaceRoot, filePath);\n if (!fs.existsSync(fullPath)) return [];\n\n const content = fs.readFileSync(fullPath, 'utf-8');\n const lines = content.split('\\n');\n const violations: SymbolViolationInfo[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? '';\n const stripped = stripLineComments(line);\n\n if (!SYMBOL_DI_REGEX.test(stripped)) continue;\n\n const lineNum = i + 1;\n const prevLine = i > 0 ? (lines[i - 1] ?? '') : '';\n const disabled = hasDisableOnLine(line) || hasDisableOnLine(prevLine);\n\n violations.push({\n line: lineNum,\n context: line.trim(),\n hasDisableComment: resolveDisable(disabled, disableAllowed),\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 allowedPaths: string[],\n): SymbolViolation[] {\n const violations: SymbolViolation[] = [];\n\n for (const file of changedFiles) {\n const diff = getFileDiff(workspaceRoot, file, base, head);\n const changedLines = getChangedLineNumbers(diff);\n\n if (changedLines.size === 0) continue;\n\n const allViolations = findSymbolViolationsInFile(file, workspaceRoot, disableAllowed, allowedPaths);\n\n for (const v of allViolations) {\n if (disableAllowed && v.hasDisableComment) continue;\n if (!changedLines.has(v.line)) continue;\n\n violations.push({ file, line: v.line, context: v.context });\n }\n }\n\n return violations;\n}\n\nfunction findViolationsForModifiedFiles(\n workspaceRoot: string,\n changedFiles: string[],\n disableAllowed: boolean,\n allowedPaths: string[],\n): SymbolViolation[] {\n const violations: SymbolViolation[] = [];\n\n for (const file of changedFiles) {\n const allViolations = findSymbolViolationsInFile(file, workspaceRoot, disableAllowed, allowedPaths);\n\n for (const v of allViolations) {\n if (disableAllowed && v.hasDisableComment) continue;\n violations.push({ file, line: v.line, context: v.context });\n }\n }\n\n return violations;\n}\n\n// webpieces-disable max-lines-new-methods -- Console output with guidance message and violation list\nfunction reportViolations(violations: SymbolViolation[], mode: ModifiedCodeMode, disableAllowed: boolean): void {\n console.error('');\n console.error('❌ Symbol() DI tokens are not allowed outside api(-external) packages!');\n console.error('');\n console.error(SHARED_MESSAGE);\n console.error('');\n\n for (const v of violations) {\n console.error(` ❌ ${v.file}:${v.line}`);\n console.error(` ${v.context}`);\n }\n console.error('');\n\n if (disableAllowed) {\n console.error(' Escape hatch (use sparingly):');\n console.error(' // webpieces-disable no-symbol-di-tokens -- <reason>');\n } else {\n console.error(' Escape hatch: DISABLED (disableAllowed: false)');\n }\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⏭️ Skipping no-symbol-di-tokens validation (${skip.reason})`);\n console.log('');\n return 'OFF';\n }\n return normalMode;\n}\n\nasync function runValidatorImpl(\n options: NoSymbolDiTokensConfig,\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-symbol-di-tokens validation (mode: OFF)');\n console.log('');\n return { success: true };\n }\n\n console.log('\\n📏 Validating No Symbol DI Tokens\\n');\n console.log(` Mode: ${mode}`);\n\n let base = process.env['NX_BASE'];\n const head = process.env['NX_HEAD'];\n\n if (!base) {\n base = detectBase(workspaceRoot) ?? undefined;\n\n if (!base) {\n console.log('\\n⏭️ Skipping no-symbol-di-tokens 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\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: SymbolViolation[] = [];\n\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 Symbol DI token violations found');\n return { success: true };\n }\n\n reportViolations(violations, mode, disableAllowed);\n\n return { success: false };\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoSymbolDiTokensValidator extends CodeValidator<NoSymbolDiTokensConfig> {\n constructor(config: NoSymbolDiTokensConfig) {\n super(config, 'no-symbol-di-tokens', 'no-symbol-di-tokens');\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runValidatorImpl(this.config, workspaceRoot);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"validate-no-symbol-di-tokens.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-symbol-di-tokens.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;;;AAoGH,gEAkCC;;AApID,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA2J;AAC3J,qDAAiE;AACjE,yCAA2D;AAC3D,iDAAgD;AAChD,6CAAyC;AAEzC,MAAM,eAAe,GAAG,wBAAwB,CAAC;AAEjD,MAAM,cAAc,GAAG;;;;;;;;;;mHAU4F,CAAC;AAcpH,SAAS,UAAU,CAAC,QAAgB;IAChC,OAAO,QAAQ,CAAC,QAAQ,CAAC,UAAU,CAAC;QAChC,QAAQ,CAAC,QAAQ,CAAC,UAAU,CAAC;QAC7B,QAAQ,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;AACxC,CAAC;AAED,SAAS,WAAW,CAAC,OAAe;IAChC,IAAI,EAAE,GAAG,EAAE,CAAC;IACZ,IAAI,CAAC,GAAG,CAAC,CAAC;IACV,OAAO,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;QACxB,MAAM,EAAE,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;QACtB,IAAI,EAAE,KAAK,GAAG,EAAE,CAAC;YACb,IAAI,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,GAAG,EAAE,CAAC;gBACzB,EAAE,IAAI,IAAI,CAAC;gBACX,CAAC,IAAI,CAAC,CAAC;gBACP,IAAI,OAAO,CAAC,CAAC,CAAC,KAAK,GAAG;oBAAE,CA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CAAC;QACJ,+FAA+F;QAC/F,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,uCAAuC,CAAC,CAAC;QACrD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7B,CAAC;IAED,IAAI,CAAC,WAAW,CAAC,qBAAqB,EAAE,UAAU,CAAC,GAAG,CAAC,CAAC,CAAkB,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;IACxF,gBAAgB,CAAC,UAAU,EAAE,IAAI,EAAE,cAAc,CAAC,CAAC;IAEnD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC9B,CAAC;AAGM,IAAM,yBAAyB,GAA/B,MAAM,yBAA0B,SAAQ,8BAAqC;IACnB;IAA7D,YAAY,MAA8B,EAAmB,SAAoB;QAC7E,KAAK,CAAC,MAAM,EAAE,qBAAqB,EAAE,qBAAqB,CAAC,CAAC;QADH,cAAS,GAAT,SAAS,CAAW;IAEjF,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,8DAAyB;oCAAzB,yBAAyB;IADrC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEjB,qCAAsB,EAA8B,sBAAS;GADxE,yBAAyB,CAQrC","sourcesContent":["/**\n * Validate No Symbol DI Tokens Executor\n *\n * Validates that Symbol() / Symbol.for() are not used to create DI tokens\n * outside of the designated API-binding packages.\n *\n * ============================================================================\n * VIOLATIONS (BAD) - These patterns are flagged:\n * ============================================================================\n *\n * - export const MY_TOKEN = Symbol('MY_TOKEN')\n * - export const MY_TOKEN = Symbol.for('MY_TOKEN')\n * - const TOKEN: symbol = Symbol('TOKEN')\n *\n * ============================================================================\n * ALLOWED\n * ============================================================================\n *\n * - Files under allowedPaths (configured in webpieces.config.json, defaults to [])\n * - Test files (*.test.ts, *.spec.ts, __tests__/**)\n * - Lines with // webpieces-disable no-symbol-di-tokens -- <reason> (when disableAllowed: true)\n *\n * ============================================================================\n * MODES (LINE-BASED)\n * ============================================================================\n * - OFF: Skip validation entirely\n * - NEW_AND_MODIFIED_CODE: Flag Symbol DI tokens on changed lines (lines in diff hunks)\n * - NEW_AND_MODIFIED_FILES: Flag ALL Symbol DI tokens in files that were modified\n *\n * ============================================================================\n * ESCAPE HATCH\n * ============================================================================\n * Add comment on the same line or line above the violation:\n * // webpieces-disable no-symbol-di-tokens -- [your justification]\n * export const MY_TOKEN = Symbol('MY_TOKEN');\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { hasDisable, RULE_NAMES, NoSymbolDiTokensConfig, 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\nconst SYMBOL_DI_REGEX = /=\\s*Symbol(?:\\.for)?\\(/;\n\nconst SHARED_MESSAGE = `Do not create a dependency-injection token with Symbol(). Choose the right pattern:\nOption 1: OWN class — annotate it with @injectable(bindingScopeValues.Singleton) and inject by concrete class TYPE — no Symbol, no @inject.\n constructor(private readonly myService: MyService) {}\nOption 2: API IMPLEMENTATION — import the Symbol from the API definition file and use:\n @provideSingletonDefaultForApi(SOME_API_TOKEN)\n export class SomeApiImpl implements SomeApi { ... }\nOption 3: External lib class you cannot decorate (DataSource, Anthropic, etc.):\n bind in a ContainerModule using the class itself as token — no Symbol needed:\n bind<Anthropic>(Anthropic).toDynamicValue(() => new Anthropic({ apiKey: ... })).inSingletonScope()\n Then inject by type — no Symbol, no @inject.\nOption 4 (last resort): append // webpieces-disable no-symbol-di-tokens -- <reason> to justify this specific line.`;\n\ninterface SymbolViolation {\n file: string;\n line: number;\n context: string;\n}\n\ninterface SymbolViolationInfo {\n line: number;\n context: string;\n hasDisableComment: boolean;\n}\n\nfunction isTestFile(filePath: string): boolean {\n return filePath.includes('.spec.ts') ||\n filePath.includes('.test.ts') ||\n filePath.includes('__tests__/');\n}\n\nfunction globToRegex(pattern: string): RegExp {\n let re = '';\n let i = 0;\n while (i < pattern.length) {\n const ch = pattern[i];\n if (ch === '*') {\n if (pattern[i + 1] === '*') {\n re += '.*';\n i += 2;\n if (pattern[i] === '/') i += 1;\n continue;\n }\n re += '[^/]*';\n i += 1;\n continue;\n }\n if (ch === '?') {\n re += '[^/]';\n i += 1;\n continue;\n }\n if ('.+^$(){}|[]\\\\'.includes(ch)) {\n re += '\\\\' + ch;\n i += 1;\n continue;\n }\n re += ch;\n i += 1;\n }\n return new RegExp('^' + re + '$');\n}\n\nfunction isAllowedPath(filePath: string, allowedPaths: string[]): boolean {\n for (const pattern of allowedPaths) {\n if (globToRegex(pattern).test(filePath)) {\n return true;\n }\n }\n return false;\n}\n\nfunction stripLineComments(line: string): string {\n const idx = line.indexOf('//');\n if (idx === -1) return line;\n return line.substring(0, idx);\n}\n\nfunction hasDisableOnLine(line: string): boolean {\n return hasDisable(line, RULE_NAMES.NO_SYMBOL_DI_TOKENS);\n}\n\nfunction resolveDisable(disabled: boolean, disableAllowed: boolean): boolean {\n if (!disableAllowed && disabled) {\n return false;\n }\n return disabled;\n}\n\nexport function findSymbolViolationsInFile(\n filePath: string,\n workspaceRoot: string,\n disableAllowed: boolean,\n allowedPaths: string[],\n): SymbolViolationInfo[] {\n if (isTestFile(filePath)) return [];\n if (isAllowedPath(filePath, allowedPaths)) return [];\n\n const fullPath = path.join(workspaceRoot, filePath);\n if (!fs.existsSync(fullPath)) return [];\n\n const content = fs.readFileSync(fullPath, 'utf-8');\n const lines = content.split('\\n');\n const violations: SymbolViolationInfo[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? '';\n const stripped = stripLineComments(line);\n\n if (!SYMBOL_DI_REGEX.test(stripped)) continue;\n\n const lineNum = i + 1;\n const prevLine = i > 0 ? (lines[i - 1] ?? '') : '';\n const disabled = hasDisableOnLine(line) || hasDisableOnLine(prevLine);\n\n violations.push({\n line: lineNum,\n context: line.trim(),\n hasDisableComment: resolveDisable(disabled, disableAllowed),\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 allowedPaths: string[],\n): SymbolViolation[] {\n const violations: SymbolViolation[] = [];\n\n for (const file of changedFiles) {\n const diff = getFileDiff(workspaceRoot, file, base, head);\n const changedLines = getChangedLineNumbers(diff);\n\n if (changedLines.size === 0) continue;\n\n const allViolations = findSymbolViolationsInFile(file, workspaceRoot, disableAllowed, allowedPaths);\n\n for (const v of allViolations) {\n if (disableAllowed && v.hasDisableComment) continue;\n if (!changedLines.has(v.line)) continue;\n\n violations.push({ file, line: v.line, context: v.context });\n }\n }\n\n return violations;\n}\n\nfunction findViolationsForModifiedFiles(\n workspaceRoot: string,\n changedFiles: string[],\n disableAllowed: boolean,\n allowedPaths: string[],\n): SymbolViolation[] {\n const violations: SymbolViolation[] = [];\n\n for (const file of changedFiles) {\n const allViolations = findSymbolViolationsInFile(file, workspaceRoot, disableAllowed, allowedPaths);\n\n for (const v of allViolations) {\n if (disableAllowed && v.hasDisableComment) continue;\n violations.push({ file, line: v.line, context: v.context });\n }\n }\n\n return violations;\n}\n\n// webpieces-disable max-lines-new-methods -- Console output with guidance message and violation list\nfunction reportViolations(violations: SymbolViolation[], mode: ModifiedCodeMode, disableAllowed: boolean): void {\n console.error('');\n console.error('❌ Symbol() DI tokens are not allowed outside api(-external) packages!');\n console.error('');\n console.error(SHARED_MESSAGE);\n console.error('');\n\n for (const v of violations) {\n console.error(` ❌ ${v.file}:${v.line}`);\n console.error(` ${v.context}`);\n }\n console.error('');\n\n if (disableAllowed) {\n console.error(' Escape hatch (use sparingly):');\n console.error(' // webpieces-disable no-symbol-di-tokens -- <reason>');\n } else {\n console.error(' Escape hatch: DISABLED (disableAllowed: false)');\n }\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⏭️ Skipping no-symbol-di-tokens validation (${skip.reason})`);\n console.log('');\n return 'OFF';\n }\n return normalMode;\n}\n\nasync function runValidatorImpl(\n scan: ScanScope,\n options: NoSymbolDiTokensConfig,\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-symbol-di-tokens validation (mode: OFF)');\n console.log('');\n return { success: true };\n }\n\n console.log('\\n📏 Validating No Symbol DI Tokens\\n');\n console.log(` Mode: ${mode}`);\n\n let base = process.env['NX_BASE'];\n const head = process.env['NX_HEAD'];\n\n if (!base) {\n base = detectBase(workspaceRoot) ?? undefined;\n\n if (!base) {\n console.log('\\n⏭️ Skipping no-symbol-di-tokens validation (could not detect base branch)');\n console.log('');\n return { success: true };\n }\n }\n\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);\n console.log('');\n\n const changedFiles = scan.files(workspaceRoot, mode, base, head);\n\n if (changedFiles.length === 0) {\n console.log('✅ No TypeScript files changed');\n return { success: true };\n }\n\n console.log(`📂 Checking ${changedFiles.length} changed file(s)...`);\n\n let violations: SymbolViolation[] = [];\n\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 Symbol DI token violations found');\n return { success: true };\n }\n\n scan.recordSites('no-symbol-di-tokens', violations.map((v: SymbolViolation) => v.file));\n reportViolations(violations, mode, disableAllowed);\n\n return { success: false };\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoSymbolDiTokensValidator extends CodeValidator<NoSymbolDiTokensConfig> {\n constructor(config: NoSymbolDiTokensConfig, private readonly scanScope: ScanScope) {\n super(config, 'no-symbol-di-tokens', 'no-symbol-di-tokens');\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runValidatorImpl(this.scanScope, this.config, workspaceRoot);\n }\n}\n"]}
|
|
@@ -33,7 +33,9 @@
|
|
|
33
33
|
*/
|
|
34
34
|
import { NoUnmanagedExceptionsConfig } from '@webpieces/rules-config';
|
|
35
35
|
import { CodeValidator, ExecutorResult } from './code-validator';
|
|
36
|
+
import { ScanScope } from './scan-scope';
|
|
36
37
|
export declare class NoUnmanagedExceptionsValidator extends CodeValidator<NoUnmanagedExceptionsConfig> {
|
|
37
|
-
|
|
38
|
+
private readonly scanScope;
|
|
39
|
+
constructor(config: NoUnmanagedExceptionsConfig, scanScope: ScanScope);
|
|
38
40
|
run(workspaceRoot: string): Promise<ExecutorResult>;
|
|
39
41
|
}
|
|
@@ -41,6 +41,7 @@ const rules_config_1 = require("@webpieces/rules-config");
|
|
|
41
41
|
const code_validator_1 = require("./code-validator");
|
|
42
42
|
const inversify_1 = require("inversify");
|
|
43
43
|
const resolve_mode_1 = require("./resolve-mode");
|
|
44
|
+
const scan_scope_1 = require("./scan-scope");
|
|
44
45
|
/**
|
|
45
46
|
* Check if a line contains a disable comment for no-unmanaged-exceptions.
|
|
46
47
|
* Recognizes both webpieces-disable and eslint-disable-next-line @webpieces/ formats.
|
|
@@ -174,7 +175,7 @@ function resolveMode(normalMode, epoch, branchPattern) {
|
|
|
174
175
|
}
|
|
175
176
|
return normalMode;
|
|
176
177
|
}
|
|
177
|
-
async function runValidatorImpl(options, workspaceRoot) {
|
|
178
|
+
async function runValidatorImpl(scan, options, workspaceRoot) {
|
|
178
179
|
const mode = resolveMode(options.mode ?? 'OFF', options.turnOffRuleUntilEpoch, (options.turnOffRuleWhileOnBranch ?? undefined));
|
|
179
180
|
const disableAllowed = options.disableAllowed ?? true;
|
|
180
181
|
if (mode === 'OFF') {
|
|
@@ -197,7 +198,7 @@ async function runValidatorImpl(options, workspaceRoot) {
|
|
|
197
198
|
console.log(` Base: ${base}`);
|
|
198
199
|
console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);
|
|
199
200
|
console.log('');
|
|
200
|
-
const changedFiles =
|
|
201
|
+
const changedFiles = scan.files(workspaceRoot, mode, base, head);
|
|
201
202
|
if (changedFiles.length === 0) {
|
|
202
203
|
console.log('\u2705 No TypeScript files changed');
|
|
203
204
|
return { success: true };
|
|
@@ -207,27 +208,31 @@ async function runValidatorImpl(options, workspaceRoot) {
|
|
|
207
208
|
if (mode === 'NEW_AND_MODIFIED_CODE') {
|
|
208
209
|
violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed);
|
|
209
210
|
}
|
|
210
|
-
else
|
|
211
|
+
else {
|
|
212
|
+
// NEW_AND_MODIFIED_FILES and the whole-scope modes (#1027) all judge every site of every file.
|
|
211
213
|
violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);
|
|
212
214
|
}
|
|
213
215
|
if (violations.length === 0) {
|
|
214
216
|
console.log('\u2705 No unmanaged try/catch blocks found');
|
|
215
217
|
return { success: true };
|
|
216
218
|
}
|
|
219
|
+
scan.recordSites('no-unmanaged-exceptions', violations.map((v) => v.file));
|
|
217
220
|
reportViolations(violations, mode, disableAllowed);
|
|
218
221
|
return { success: false };
|
|
219
222
|
}
|
|
220
223
|
let NoUnmanagedExceptionsValidator = class NoUnmanagedExceptionsValidator extends code_validator_1.CodeValidator {
|
|
221
|
-
|
|
224
|
+
scanScope;
|
|
225
|
+
constructor(config, scanScope) {
|
|
222
226
|
super(config, 'no-unmanaged-exceptions', 'no-unmanaged-exceptions');
|
|
227
|
+
this.scanScope = scanScope;
|
|
223
228
|
}
|
|
224
229
|
async run(workspaceRoot) {
|
|
225
|
-
return runValidatorImpl(this.config, workspaceRoot);
|
|
230
|
+
return runValidatorImpl(this.scanScope, this.config, workspaceRoot);
|
|
226
231
|
}
|
|
227
232
|
};
|
|
228
233
|
exports.NoUnmanagedExceptionsValidator = NoUnmanagedExceptionsValidator;
|
|
229
234
|
exports.NoUnmanagedExceptionsValidator = NoUnmanagedExceptionsValidator = tslib_1.__decorate([
|
|
230
235
|
(0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
|
|
231
|
-
tslib_1.__metadata("design:paramtypes", [rules_config_1.NoUnmanagedExceptionsConfig])
|
|
236
|
+
tslib_1.__metadata("design:paramtypes", [rules_config_1.NoUnmanagedExceptionsConfig, scan_scope_1.ScanScope])
|
|
232
237
|
], NoUnmanagedExceptionsValidator);
|
|
233
238
|
//# sourceMappingURL=validate-no-unmanaged-exceptions.js.map
|