@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.
Files changed (90) hide show
  1. package/package.json +2 -2
  2. package/src/api-lib-source-rule.d.ts +5 -2
  3. package/src/api-lib-source-rule.js +8 -4
  4. package/src/api-lib-source-rule.js.map +1 -1
  5. package/src/cli.js +13 -14
  6. package/src/cli.js.map +1 -1
  7. package/src/code-rules-bootstrap.d.ts +31 -8
  8. package/src/code-rules-bootstrap.js +136 -18
  9. package/src/code-rules-bootstrap.js.map +1 -1
  10. package/src/code-rules-config-table.d.ts +3 -1
  11. package/src/code-rules-config-table.js +0 -6
  12. package/src/code-rules-config-table.js.map +1 -1
  13. package/src/code-rules-engine.d.ts +4 -13
  14. package/src/code-rules-engine.js +9 -31
  15. package/src/code-rules-engine.js.map +1 -1
  16. package/src/code-rules-run-request.d.ts +30 -34
  17. package/src/code-rules-run-request.js +43 -80
  18. package/src/code-rules-run-request.js.map +1 -1
  19. package/src/index.d.ts +3 -1
  20. package/src/index.js +13 -2
  21. package/src/index.js.map +1 -1
  22. package/src/resolve-mode.d.ts +1 -1
  23. package/src/resolve-mode.js +2 -3
  24. package/src/resolve-mode.js.map +1 -1
  25. package/src/scan-scope.d.ts +82 -0
  26. package/src/scan-scope.js +200 -0
  27. package/src/scan-scope.js.map +1 -0
  28. package/src/validate-catch-error-pattern.d.ts +3 -1
  29. package/src/validate-catch-error-pattern.js +11 -6
  30. package/src/validate-catch-error-pattern.js.map +1 -1
  31. package/src/validate-code.d.ts +4 -5
  32. package/src/validate-code.js +6 -17
  33. package/src/validate-code.js.map +1 -1
  34. package/src/validate-inject-annotation-not-needed-for-concrete-class.d.ts +3 -1
  35. package/src/validate-inject-annotation-not-needed-for-concrete-class.js +11 -6
  36. package/src/validate-inject-annotation-not-needed-for-concrete-class.js.map +1 -1
  37. package/src/validate-match-rules.d.ts +3 -0
  38. package/src/validate-match-rules.js +10 -3
  39. package/src/validate-match-rules.js.map +1 -1
  40. package/src/validate-no-any-unknown.d.ts +3 -1
  41. package/src/validate-no-any-unknown.js +11 -6
  42. package/src/validate-no-any-unknown.js.map +1 -1
  43. package/src/validate-no-client-creation-outside-server-or-client.d.ts +4 -2
  44. package/src/validate-no-client-creation-outside-server-or-client.js +10 -5
  45. package/src/validate-no-client-creation-outside-server-or-client.js.map +1 -1
  46. package/src/validate-no-custom-css.d.ts +4 -2
  47. package/src/validate-no-custom-css.js +9 -5
  48. package/src/validate-no-custom-css.js.map +1 -1
  49. package/src/validate-no-destructure.d.ts +3 -1
  50. package/src/validate-no-destructure.js +11 -6
  51. package/src/validate-no-destructure.js.map +1 -1
  52. package/src/validate-no-function-outside-class.d.ts +3 -1
  53. package/src/validate-no-function-outside-class.js +12 -6
  54. package/src/validate-no-function-outside-class.js.map +1 -1
  55. package/src/validate-no-implicit-any.d.ts +3 -1
  56. package/src/validate-no-implicit-any.js +13 -8
  57. package/src/validate-no-implicit-any.js.map +1 -1
  58. package/src/validate-no-inline-import-in-api-lib.d.ts +2 -1
  59. package/src/validate-no-inline-import-in-api-lib.js +4 -3
  60. package/src/validate-no-inline-import-in-api-lib.js.map +1 -1
  61. package/src/validate-no-process-exit-outside-main.d.ts +3 -1
  62. package/src/validate-no-process-exit-outside-main.js +12 -6
  63. package/src/validate-no-process-exit-outside-main.js.map +1 -1
  64. package/src/validate-no-state-paths-in-templates.d.ts +4 -2
  65. package/src/validate-no-state-paths-in-templates.js +9 -5
  66. package/src/validate-no-state-paths-in-templates.js.map +1 -1
  67. package/src/validate-no-symbol-di-tokens.d.ts +3 -1
  68. package/src/validate-no-symbol-di-tokens.js +11 -6
  69. package/src/validate-no-symbol-di-tokens.js.map +1 -1
  70. package/src/validate-no-unmanaged-exceptions.d.ts +3 -1
  71. package/src/validate-no-unmanaged-exceptions.js +11 -6
  72. package/src/validate-no-unmanaged-exceptions.js.map +1 -1
  73. package/src/validate-no-utility-types-in-api-lib.d.ts +2 -1
  74. package/src/validate-no-utility-types-in-api-lib.js +4 -3
  75. package/src/validate-no-utility-types-in-api-lib.js.map +1 -1
  76. package/src/validate-one-enum-spelling-in-api-lib.d.ts +2 -1
  77. package/src/validate-one-enum-spelling-in-api-lib.js +4 -3
  78. package/src/validate-one-enum-spelling-in-api-lib.js.map +1 -1
  79. package/src/validate-required-type-suffix.d.ts +2 -1
  80. package/src/validate-required-type-suffix.js +7 -3
  81. package/src/validate-required-type-suffix.js.map +1 -1
  82. package/src/wp-ci.d.ts +2 -2
  83. package/src/wp-ci.js +11 -5
  84. package/src/wp-ci.js.map +1 -1
  85. package/src/debug-run-report.d.ts +0 -22
  86. package/src/debug-run-report.js +0 -127
  87. package/src/debug-run-report.js.map +0 -1
  88. package/src/rule-scope-plan.d.ts +0 -72
  89. package/src/rule-scope-plan.js +0 -132
  90. package/src/rule-scope-plan.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"validate-no-unmanaged-exceptions.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-unmanaged-exceptions.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAiL;AACjL,qDAAiE;AACjE,yCAA2D;AAC3D,iDAAgD;AAQhD;;;GAGG;AACH,SAAS,iBAAiB,CAAC,KAAe,EAAE,UAAkB;IAC1D,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,UAAU,GAAG,CAAC,CAAC,CAAC;IAC/C,KAAK,IAAI,CAAC,GAAG,UAAU,GAAG,CAAC,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,EAAE,EAAE,CAAC;QAChD,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;QACpC,IAAI,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC,UAAU,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a,CAAC,CAAC;IACxD,CAAC;CACJ,CAAA;AARY,wEAA8B;yCAA9B,8BAA8B;IAD1C,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEjB,0CAA2B;GADtC,8BAA8B,CAQ1C","sourcesContent":["/**\n * Validate No Unmanaged Exceptions Executor\n *\n * Validates that try/catch blocks are not used outside chokepoints.\n * Uses LINE-BASED detection (not method-based) for git diff filtering.\n *\n * ============================================================================\n * VIOLATIONS (BAD) - These patterns are flagged:\n * ============================================================================\n *\n * - try { — any try/catch block in non-test code\n *\n * ============================================================================\n * ALLOWED (skip — NOT violations)\n * ============================================================================\n *\n * - Test files (.spec.ts, .test.ts, __tests__/)\n * - Lines with // webpieces-disable no-unmanaged-exceptions -- [reason]\n *\n * ============================================================================\n * MODES (LINE-BASED)\n * ============================================================================\n * - OFF: Skip validation entirely\n * - NEW_AND_MODIFIED_CODE: Flag try/catch on changed lines (lines in diff hunks)\n * - NEW_AND_MODIFIED_FILES: Flag ALL try/catch in files that were modified\n *\n * ============================================================================\n * ESCAPE HATCH\n * ============================================================================\n * Add comment above the violation:\n * // webpieces-disable no-unmanaged-exceptions -- [your justification]\n * try {\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { hasDisable, RULE_NAMES, NoUnmanagedExceptionsConfig, ModifiedCodeMode, detectBase, getChangedFiles, getFileDiff, getChangedLineNumbers } from '@webpieces/rules-config';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { shouldSkipRule } from './resolve-mode';\n\ninterface TryCatchViolation {\n file: string;\n line: number;\n context: string;\n}\n\n/**\n * Check if a line contains a disable comment for no-unmanaged-exceptions.\n * Recognizes both webpieces-disable and eslint-disable-next-line @webpieces/ formats.\n */\nfunction hasDisableComment(lines: string[], lineNumber: number): boolean {\n const startCheck = Math.max(0, lineNumber - 5);\n for (let i = lineNumber - 2; i >= startCheck; i--) {\n const line = lines[i]?.trim() ?? '';\n if (line.startsWith('function ') || line.startsWith('class ') || line.endsWith('}')) {\n break;\n }\n if (hasDisable(line, RULE_NAMES.NO_UNMANAGED_EXCEPTIONS)) {\n return true;\n }\n if (line.includes('@webpieces/no-unmanaged-exceptions')) {\n return true;\n }\n }\n return false;\n}\n\nconst TRY_PATTERN = /\\btry\\s*\\{/;\n\ninterface TryCatchInfo {\n line: number;\n context: string;\n hasDisableComment: boolean;\n}\n\n/**\n * Find all try/catch patterns in a file using line-based scanning.\n */\nfunction findTryCatchInFile(filePath: string, workspaceRoot: string, disableAllowed: boolean): TryCatchInfo[] {\n const fullPath = path.join(workspaceRoot, filePath);\n if (!fs.existsSync(fullPath)) return [];\n\n const content = fs.readFileSync(fullPath, 'utf-8');\n const fileLines = content.split('\\n');\n const violations: TryCatchInfo[] = [];\n\n for (let i = 0; i < fileLines.length; i++) {\n const line = fileLines[i];\n const trimmed = line.trim();\n // Skip comment lines (JSDoc, block comments, line comments)\n if (trimmed.startsWith('*') || trimmed.startsWith('//') || trimmed.startsWith('/*')) continue;\n if (!TRY_PATTERN.test(line)) continue;\n\n const lineNum = i + 1;\n const disabled = hasDisableComment(fileLines, lineNum);\n\n if (!disableAllowed && disabled) {\n violations.push({ line: lineNum, context: line.trim(), hasDisableComment: false });\n } else {\n violations.push({ line: lineNum, context: line.trim(), hasDisableComment: disabled });\n }\n }\n\n return violations;\n}\n\n/**\n * NEW_AND_MODIFIED_CODE mode: Flag violations on changed lines in diff hunks.\n */\nfunction findViolationsForModifiedCode(\n workspaceRoot: string,\n changedFiles: string[],\n base: string,\n head: string | undefined,\n disableAllowed: boolean,\n): TryCatchViolation[] {\n const violations: TryCatchViolation[] = [];\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 = findTryCatchInFile(file, workspaceRoot, disableAllowed);\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\n/**\n * NEW_AND_MODIFIED_FILES mode: Flag ALL violations in files that were modified.\n */\nfunction findViolationsForModifiedFiles(\n workspaceRoot: string,\n changedFiles: string[],\n disableAllowed: boolean,\n): TryCatchViolation[] {\n const violations: TryCatchViolation[] = [];\n\n for (const file of changedFiles) {\n const allViolations = findTryCatchInFile(file, workspaceRoot, disableAllowed);\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/**\n * Report violations to console.\n */\nfunction reportViolations(violations: TryCatchViolation[], mode: ModifiedCodeMode, disableAllowed: boolean): void {\n console.error('');\n console.error('\\u274c Unmanaged try/catch blocks found! Exceptions should bubble to chokepoints.');\n console.error('');\n console.error('\\ud83d\\udcda Philosophy: Most code should NOT catch exceptions.');\n console.error(' Exceptions should bubble to chokepoints (filter in Node.js, globalErrorHandler in Angular)');\n console.error(' where they are logged with traceId for debugging.');\n console.error('');\n\n for (const v of violations) {\n console.error(` \\u274c ${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-unmanaged-exceptions -- [your reason]');\n console.error('');\n console.error(' When try/catch IS used, the catch block MUST follow:');\n console.error(' catch (err: unknown) { const error = toError(err); ... }');\n console.error(' or: catch (err: unknown) { //const error = toError(err); }');\n } else {\n console.error(' Escape hatch: DISABLED (disableAllowed: false)');\n console.error(' Disable comments are ignored. Remove the try/catch.');\n }\n console.error('');\n console.error(` Current mode: ${mode}`);\n console.error('');\n}\n\n/**\n * Resolve mode considering turnOffRuleUntilEpoch override.\n */\nfunction resolveMode(normalMode: ModifiedCodeMode, epoch: number | undefined, branchPattern: string | undefined): ModifiedCodeMode {\n if (normalMode === 'OFF') {\n return normalMode;\n }\n const skip = shouldSkipRule(epoch, branchPattern);\n if (skip.skip) {\n console.log(`\\n\\u23ed\\ufe0f Skipping no-unmanaged-exceptions validation (${skip.reason})`);\n console.log('');\n return 'OFF';\n }\n return normalMode;\n}\n\nasync function runValidatorImpl(\n options: NoUnmanagedExceptionsConfig,\n workspaceRoot: string\n): Promise<ExecutorResult> {\n const mode: ModifiedCodeMode = resolveMode(options.mode ?? 'OFF', options.turnOffRuleUntilEpoch, (options.turnOffRuleWhileOnBranch ?? undefined));\n const disableAllowed = options.disableAllowed ?? true;\n\n if (mode === 'OFF') {\n console.log('\\n\\u23ed\\ufe0f Skipping no-unmanaged-exceptions validation (mode: OFF)');\n console.log('');\n return { success: true };\n }\n\n console.log('\\n\\ud83d\\udccf Validating No Unmanaged Exceptions\\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\\u23ed\\ufe0f Skipping no-unmanaged-exceptions 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('\\u2705 No TypeScript files changed');\n return { success: true };\n }\n\n console.log(`\\ud83d\\udcc2 Checking ${changedFiles.length} changed file(s)...`);\n\n let violations: TryCatchViolation[] = [];\n\n if (mode === 'NEW_AND_MODIFIED_CODE') {\n violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed);\n } else if (mode === 'NEW_AND_MODIFIED_FILES') {\n violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);\n }\n\n if (violations.length === 0) {\n console.log('\\u2705 No unmanaged try/catch blocks 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 NoUnmanagedExceptionsValidator extends CodeValidator<NoUnmanagedExceptionsConfig> {\n constructor(config: NoUnmanagedExceptionsConfig) {\n super(config, 'no-unmanaged-exceptions', 'no-unmanaged-exceptions');\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runValidatorImpl(this.config, workspaceRoot);\n }\n}\n"]}
1
+ {"version":3,"file":"validate-no-unmanaged-exceptions.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-unmanaged-exceptions.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAgK;AAChK,qDAAiE;AACjE,yCAA2D;AAC3D,iDAAgD;AAChD,6CAAyC;AAQzC;;;GAGG;AACH,SAAS,iBAAiB,CAAC,KAAe,EAAE,UAAkB;IAC1D,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,UAAU,GAAG,CAAC,CAAC,CAAC;IAC/C,KAAK,IAAI,CAAC,GAAG,UAAU,GAAG,CAAC,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,EAAE,EAAE,CAAC;QAChD,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;QACpC,IAAI,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;YAClF,MAAM;QACV,CAAC;QACD,IAAI,IAAA,yBAAU,EAAC,IAAI,EAAE,yBAAU,CAAC,uBAAuB,CAAC,EAAE,CAAC;YACvD,OAAO,IAAI,CAAC;QAChB,CAAC;QACD,IAAI,IAAI,CAAC,QAAQ,CAAC,oCAAoC,CAAC,EAAE,CAAC;YACtD,OAAO,IAAI,CAAC;QAChB,CAAC;IACL,CAAC;IACD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,SAAS,CAAC;6CAEjB,0CAA2B,EAA8B,sBAAS;GAD7E,8BAA8B,CAQ1C","sourcesContent":["/**\n * Validate No Unmanaged Exceptions Executor\n *\n * Validates that try/catch blocks are not used outside chokepoints.\n * Uses LINE-BASED detection (not method-based) for git diff filtering.\n *\n * ============================================================================\n * VIOLATIONS (BAD) - These patterns are flagged:\n * ============================================================================\n *\n * - try { — any try/catch block in non-test code\n *\n * ============================================================================\n * ALLOWED (skip — NOT violations)\n * ============================================================================\n *\n * - Test files (.spec.ts, .test.ts, __tests__/)\n * - Lines with // webpieces-disable no-unmanaged-exceptions -- [reason]\n *\n * ============================================================================\n * MODES (LINE-BASED)\n * ============================================================================\n * - OFF: Skip validation entirely\n * - NEW_AND_MODIFIED_CODE: Flag try/catch on changed lines (lines in diff hunks)\n * - NEW_AND_MODIFIED_FILES: Flag ALL try/catch in files that were modified\n *\n * ============================================================================\n * ESCAPE HATCH\n * ============================================================================\n * Add comment above the violation:\n * // webpieces-disable no-unmanaged-exceptions -- [your justification]\n * try {\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { hasDisable, RULE_NAMES, NoUnmanagedExceptionsConfig, ModifiedCodeMode, detectBase, getFileDiff, getChangedLineNumbers } from '@webpieces/rules-config';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { shouldSkipRule } from './resolve-mode';\nimport { ScanScope } from './scan-scope';\n\ninterface TryCatchViolation {\n file: string;\n line: number;\n context: string;\n}\n\n/**\n * Check if a line contains a disable comment for no-unmanaged-exceptions.\n * Recognizes both webpieces-disable and eslint-disable-next-line @webpieces/ formats.\n */\nfunction hasDisableComment(lines: string[], lineNumber: number): boolean {\n const startCheck = Math.max(0, lineNumber - 5);\n for (let i = lineNumber - 2; i >= startCheck; i--) {\n const line = lines[i]?.trim() ?? '';\n if (line.startsWith('function ') || line.startsWith('class ') || line.endsWith('}')) {\n break;\n }\n if (hasDisable(line, RULE_NAMES.NO_UNMANAGED_EXCEPTIONS)) {\n return true;\n }\n if (line.includes('@webpieces/no-unmanaged-exceptions')) {\n return true;\n }\n }\n return false;\n}\n\nconst TRY_PATTERN = /\\btry\\s*\\{/;\n\ninterface TryCatchInfo {\n line: number;\n context: string;\n hasDisableComment: boolean;\n}\n\n/**\n * Find all try/catch patterns in a file using line-based scanning.\n */\nfunction findTryCatchInFile(filePath: string, workspaceRoot: string, disableAllowed: boolean): TryCatchInfo[] {\n const fullPath = path.join(workspaceRoot, filePath);\n if (!fs.existsSync(fullPath)) return [];\n\n const content = fs.readFileSync(fullPath, 'utf-8');\n const fileLines = content.split('\\n');\n const violations: TryCatchInfo[] = [];\n\n for (let i = 0; i < fileLines.length; i++) {\n const line = fileLines[i];\n const trimmed = line.trim();\n // Skip comment lines (JSDoc, block comments, line comments)\n if (trimmed.startsWith('*') || trimmed.startsWith('//') || trimmed.startsWith('/*')) continue;\n if (!TRY_PATTERN.test(line)) continue;\n\n const lineNum = i + 1;\n const disabled = hasDisableComment(fileLines, lineNum);\n\n if (!disableAllowed && disabled) {\n violations.push({ line: lineNum, context: line.trim(), hasDisableComment: false });\n } else {\n violations.push({ line: lineNum, context: line.trim(), hasDisableComment: disabled });\n }\n }\n\n return violations;\n}\n\n/**\n * NEW_AND_MODIFIED_CODE mode: Flag violations on changed lines in diff hunks.\n */\nfunction findViolationsForModifiedCode(\n workspaceRoot: string,\n changedFiles: string[],\n base: string,\n head: string | undefined,\n disableAllowed: boolean,\n): TryCatchViolation[] {\n const violations: TryCatchViolation[] = [];\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 = findTryCatchInFile(file, workspaceRoot, disableAllowed);\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\n/**\n * NEW_AND_MODIFIED_FILES mode: Flag ALL violations in files that were modified.\n */\nfunction findViolationsForModifiedFiles(\n workspaceRoot: string,\n changedFiles: string[],\n disableAllowed: boolean,\n): TryCatchViolation[] {\n const violations: TryCatchViolation[] = [];\n\n for (const file of changedFiles) {\n const allViolations = findTryCatchInFile(file, workspaceRoot, disableAllowed);\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/**\n * Report violations to console.\n */\nfunction reportViolations(violations: TryCatchViolation[], mode: ModifiedCodeMode, disableAllowed: boolean): void {\n console.error('');\n console.error('\\u274c Unmanaged try/catch blocks found! Exceptions should bubble to chokepoints.');\n console.error('');\n console.error('\\ud83d\\udcda Philosophy: Most code should NOT catch exceptions.');\n console.error(' Exceptions should bubble to chokepoints (filter in Node.js, globalErrorHandler in Angular)');\n console.error(' where they are logged with traceId for debugging.');\n console.error('');\n\n for (const v of violations) {\n console.error(` \\u274c ${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-unmanaged-exceptions -- [your reason]');\n console.error('');\n console.error(' When try/catch IS used, the catch block MUST follow:');\n console.error(' catch (err: unknown) { const error = toError(err); ... }');\n console.error(' or: catch (err: unknown) { //const error = toError(err); }');\n } else {\n console.error(' Escape hatch: DISABLED (disableAllowed: false)');\n console.error(' Disable comments are ignored. Remove the try/catch.');\n }\n console.error('');\n console.error(` Current mode: ${mode}`);\n console.error('');\n}\n\n/**\n * Resolve mode considering turnOffRuleUntilEpoch override.\n */\nfunction resolveMode(normalMode: ModifiedCodeMode, epoch: number | undefined, branchPattern: string | undefined): ModifiedCodeMode {\n if (normalMode === 'OFF') {\n return normalMode;\n }\n const skip = shouldSkipRule(epoch, branchPattern);\n if (skip.skip) {\n console.log(`\\n\\u23ed\\ufe0f Skipping no-unmanaged-exceptions validation (${skip.reason})`);\n console.log('');\n return 'OFF';\n }\n return normalMode;\n}\n\nasync function runValidatorImpl(\n scan: ScanScope,\n options: NoUnmanagedExceptionsConfig,\n workspaceRoot: string\n): Promise<ExecutorResult> {\n const mode: ModifiedCodeMode = resolveMode(options.mode ?? 'OFF', options.turnOffRuleUntilEpoch, (options.turnOffRuleWhileOnBranch ?? undefined));\n const disableAllowed = options.disableAllowed ?? true;\n\n if (mode === 'OFF') {\n console.log('\\n\\u23ed\\ufe0f Skipping no-unmanaged-exceptions validation (mode: OFF)');\n console.log('');\n return { success: true };\n }\n\n console.log('\\n\\ud83d\\udccf Validating No Unmanaged Exceptions\\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\\u23ed\\ufe0f Skipping no-unmanaged-exceptions 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('\\u2705 No TypeScript files changed');\n return { success: true };\n }\n\n console.log(`\\ud83d\\udcc2 Checking ${changedFiles.length} changed file(s)...`);\n\n let violations: TryCatchViolation[] = [];\n\n if (mode === 'NEW_AND_MODIFIED_CODE') {\n violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed);\n } else {\n // NEW_AND_MODIFIED_FILES and the whole-scope modes (#1027) all judge every site of every file.\n violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);\n }\n\n if (violations.length === 0) {\n console.log('\\u2705 No unmanaged try/catch blocks found');\n return { success: true };\n }\n\n scan.recordSites('no-unmanaged-exceptions', violations.map((v: TryCatchViolation) => v.file));\n reportViolations(violations, mode, disableAllowed);\n\n return { success: false };\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoUnmanagedExceptionsValidator extends CodeValidator<NoUnmanagedExceptionsConfig> {\n constructor(config: NoUnmanagedExceptionsConfig, private readonly scanScope: ScanScope) {\n super(config, 'no-unmanaged-exceptions', 'no-unmanaged-exceptions');\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runValidatorImpl(this.scanScope, this.config, workspaceRoot);\n }\n}\n"]}
@@ -28,6 +28,7 @@
28
28
  import { DiffScope, NoUtilityTypesInApiLibConfig } from '@webpieces/rules-config';
29
29
  import { ApiLibFile, ApiLibSite, ApiLibSourceRule } from './api-lib-source-rule';
30
30
  import { ProjectRoleResolver } from './project-role-resolver';
31
+ import { ScanScope } from './scan-scope';
31
32
  /** Finds every refused utility-type reference in one parsed file. */
32
33
  export declare class UtilityTypeScanner {
33
34
  /** The refused utility types, each with what it computes. */
@@ -49,7 +50,7 @@ export declare class UtilityTypeScanner {
49
50
  }
50
51
  export declare class NoUtilityTypesInApiLibValidator extends ApiLibSourceRule<NoUtilityTypesInApiLibConfig> {
51
52
  private readonly scanner;
52
- constructor(config: NoUtilityTypesInApiLibConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope);
53
+ constructor(config: NoUtilityTypesInApiLibConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope, scanScope: ScanScope);
53
54
  protected sitesIn(file: ApiLibFile): ApiLibSite[];
54
55
  /** Scoped by the configured `paths` globs, not the role tag — an empty list judges nothing. */
55
56
  protected isApiLibrarySource(_workspaceRoot: string, relFile: string): boolean;
@@ -34,6 +34,7 @@ const inversify_1 = require("inversify");
34
34
  const ts = tslib_1.__importStar(require("typescript"));
35
35
  const api_lib_source_rule_1 = require("./api-lib-source-rule");
36
36
  const project_role_resolver_1 = require("./project-role-resolver");
37
+ const scan_scope_1 = require("./scan-scope");
37
38
  /** Finds every refused utility-type reference in one parsed file. */
38
39
  class UtilityTypeScanner {
39
40
  /** The refused utility types, each with what it computes. */
@@ -150,8 +151,8 @@ class UtilityTypeScanner {
150
151
  exports.UtilityTypeScanner = UtilityTypeScanner;
151
152
  let NoUtilityTypesInApiLibValidator = class NoUtilityTypesInApiLibValidator extends api_lib_source_rule_1.ApiLibSourceRule {
152
153
  scanner = new UtilityTypeScanner();
153
- constructor(config, roleResolver, diffScope) {
154
- super(config, rules_config_1.RULE_NAMES.NO_UTILITY_TYPES_IN_API_LIB, roleResolver, diffScope);
154
+ constructor(config, roleResolver, diffScope, scanScope) {
155
+ super(config, rules_config_1.RULE_NAMES.NO_UTILITY_TYPES_IN_API_LIB, roleResolver, diffScope, scanScope);
155
156
  }
156
157
  sitesIn(file) {
157
158
  return this.scanner.scan(file);
@@ -171,6 +172,6 @@ let NoUtilityTypesInApiLibValidator = class NoUtilityTypesInApiLibValidator exte
171
172
  exports.NoUtilityTypesInApiLibValidator = NoUtilityTypesInApiLibValidator;
172
173
  exports.NoUtilityTypesInApiLibValidator = NoUtilityTypesInApiLibValidator = tslib_1.__decorate([
173
174
  (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
174
- tslib_1.__metadata("design:paramtypes", [rules_config_1.NoUtilityTypesInApiLibConfig, project_role_resolver_1.ProjectRoleResolver, rules_config_1.DiffScope])
175
+ tslib_1.__metadata("design:paramtypes", [rules_config_1.NoUtilityTypesInApiLibConfig, project_role_resolver_1.ProjectRoleResolver, rules_config_1.DiffScope, scan_scope_1.ScanScope])
175
176
  ], NoUtilityTypesInApiLibValidator);
176
177
  //# sourceMappingURL=validate-no-utility-types-in-api-lib.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"validate-no-utility-types-in-api-lib.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-utility-types-in-api-lib.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;;;;AAEH,0DAA8G;AAC9G,yCAA2D;AAC3D,uDAAiC;AACjC,+DAAiF;AACjF,mEAA8D;AAE9D,qEAAqE;AACrE,MAAa,kBAAkB;IA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C","sourcesContent":["/**\n * `no-utility-types-in-api-lib` (#1026) — an API contract writes its fields out.\n *\n * In every `.ts` file under the configured `paths` (e.g. `libraries/apis/**`) this refuses the\n * utility types that turn a DTO's field list, or a set of keys, into a type-level computation:\n *\n * export interface LessonPassageDto extends Omit<LessonPassageReservationDto, OptionalField> { … }\n * draft?: Partial<LessonDto>;\n * export type Summary = Pick<LessonDto, 'id' | 'title'>;\n * export type Kind = Exclude<AllKinds, 'legacy'>;\n *\n * — `Omit`, `Pick`, `Partial`, `Required`, `Exclude` and `Extract`, in an `extends` / `implements`\n * clause, a field, a type alias or a generic argument.\n *\n * Why: an api library is the contract every client, server and document generator reads. A utility\n * type makes a reader open a second file and subtract (or add) names in their head to learn which\n * fields a DTO carries; it cannot become a DTO class (`class X extends Omit<…>` does not compile — a\n * utility type has no runtime value); and a key union that only exists to feed `Omit` collides with\n * `one-enum-spelling-in-api-lib`, whose enum cure removes nothing from an `Omit`. The whole family is\n * refused, not `Omit` alone, because banning one just moves the computation into its sibling\n * (`Pick<T, Exclude<keyof T, K>>` is `Omit<T, K>`). `Record`, `Readonly` and `Array` stay allowed:\n * they do not hide which fields a DTO carries.\n *\n * The cure is to write the fields out — a shared base interface both DTOs extend, each adding its own\n * required or optional fields, or a flat interface / class listing every field. The wire JSON is\n * unchanged either way.\n */\n\nimport { DiffScope, NoUtilityTypesInApiLibConfig, RULE_NAMES, matchesAnyGlob } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport * as ts from 'typescript';\nimport { ApiLibFile, ApiLibSite, ApiLibSourceRule } from './api-lib-source-rule';\nimport { ProjectRoleResolver } from './project-role-resolver';\n\n/** Finds every refused utility-type reference in one parsed file. */\nexport class UtilityTypeScanner {\n /** The refused utility types, each with what it computes. */\n static readonly REFUSED: ReadonlyMap<string, string> = new Map<string, string>([\n ['Omit', 'a DTO\\'s field list computed by SUBTRACTING keys from another type'],\n ['Pick', 'a DTO\\'s field list computed by SELECTING keys of another type'],\n ['Partial', 'a DTO\\'s field list computed by making every field of another type optional'],\n ['Required', 'a DTO\\'s field list computed by making every field of another type required'],\n ['Exclude', 'a set of keys or values computed by SUBTRACTING from another union'],\n ['Extract', 'a set of keys or values computed by SELECTING from another union'],\n ]);\n\n scan(file: ApiLibFile): ApiLibSite[] {\n const shadowed = this.locallyDeclaredNames(file.source);\n const sites: ApiLibSite[] = [];\n const visit = (node: ts.Node): void => {\n const name = this.refusedNameOf(node, shadowed);\n if (name !== undefined) sites.push(this.siteFor(file, node, name));\n ts.forEachChild(node, visit);\n };\n visit(file.source);\n return sites;\n }\n\n /** The utility's name when `node` is a refused reference: `Omit<…>` as a type, or in a heritage clause. */\n private refusedNameOf(node: ts.Node, shadowed: ReadonlySet<string>): string | undefined {\n let name: string | undefined;\n if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) name = node.typeName.text;\n else if (ts.isExpressionWithTypeArguments(node) && ts.isIdentifier(node.expression)) name = node.expression.text;\n if (name === undefined || !UtilityTypeScanner.REFUSED.has(name) || shadowed.has(name)) return undefined;\n return name;\n }\n\n /**\n * Names the file declares or imports itself — a local `type Omit = …` or an imported `Pick` class\n * is not the global utility type, so it is not refused.\n */\n private locallyDeclaredNames(source: ts.SourceFile): Set<string> {\n const names = new Set<string>();\n for (const statement of source.statements) {\n if ((ts.isTypeAliasDeclaration(statement) || ts.isInterfaceDeclaration(statement) ||\n ts.isClassDeclaration(statement) || ts.isEnumDeclaration(statement)) && statement.name !== undefined) {\n names.add(statement.name.text);\n }\n const bindings = ts.isImportDeclaration(statement) ? statement.importClause?.namedBindings : undefined;\n if (bindings !== undefined && ts.isNamedImports(bindings)) {\n for (const element of bindings.elements) names.add(element.name.text);\n }\n }\n return names;\n }\n\n private siteFor(file: ApiLibFile, node: ts.Node, name: string): ApiLibSite {\n const args = this.typeArgumentsOf(node).map((arg: ts.TypeNode) => arg.getText(file.source).replace(/\\s+/g, ' '));\n const what = `\\`${name}<…>\\` — ${UtilityTypeScanner.REFUSED.get(name)}; an API writes its fields out`;\n return file.site(node, what, `${this.cureFor(name, args[0] ?? 'T', args[1] ?? 'K')} ${this.owner(file, node)}`.trim());\n }\n\n private typeArgumentsOf(node: ts.Node): readonly ts.TypeNode[] {\n if (ts.isTypeReferenceNode(node) || ts.isExpressionWithTypeArguments(node)) return node.typeArguments ?? [];\n return [];\n }\n\n private cureFor(name: string, target: string, keys: string): string {\n const wire = 'The wire JSON is unchanged.';\n switch (name) {\n case 'Omit':\n return `write the fields out instead of \\`Omit<${target}, ${keys}>\\`: move the fields both types share into a ` +\n `base interface that ${target} and this type both extend, each adding its own required or optional ` +\n `fields — or list every field of ${target} except ${keys} in a flat interface or class. ${wire}`;\n case 'Pick':\n return `write the fields out instead of \\`Pick<${target}, ${keys}>\\`: put the picked fields (${keys}) in a ` +\n `base interface that ${target} extends and use it here — or list them in a flat interface or class. ${wire}`;\n case 'Partial':\n return `write the fields out instead of \\`Partial<${target}>\\`: declare an interface or class listing every ` +\n `field of ${target} as optional (\\`field?: X\\`). ${wire}`;\n case 'Required':\n return `write the fields out instead of \\`Required<${target}>\\`: declare an interface or class listing every ` +\n `field of ${target} as required. ${wire}`;\n default:\n return `write the set out instead of \\`${name}<${target}, ${keys}>\\`: for keys of a DTO, write that DTO's ` +\n `fields out; for values, declare the string enum holding exactly the members meant ` +\n `(one-enum-spelling-in-api-lib), or a union of its members. ${wire}`;\n }\n }\n\n /** `(on interface X)` for a heritage clause, `(in X.field)` for a member, `(in type X)` for an alias. */\n private owner(file: ApiLibFile, node: ts.Node): string {\n let current: ts.Node | undefined = node.parent;\n let member: string | undefined;\n while (current !== undefined && current !== file.source) {\n if ((ts.isPropertySignature(current) || ts.isPropertyDeclaration(current)) && member === undefined) {\n member = current.name.getText(file.source);\n }\n const declared = this.declaredName(current);\n if (declared !== undefined) {\n if (ts.isHeritageClause(node.parent)) return `(on ${declared})`;\n return member === undefined ? `(in ${declared})` : `(in ${declared}.${member})`;\n }\n current = current.parent;\n }\n return '';\n }\n\n private declaredName(node: ts.Node): string | undefined {\n if (ts.isInterfaceDeclaration(node)) return `interface ${node.name.text}`;\n if (ts.isClassDeclaration(node) && node.name !== undefined) return `class ${node.name.text}`;\n if (ts.isTypeAliasDeclaration(node)) return `type ${node.name.text}`;\n return undefined;\n }\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoUtilityTypesInApiLibValidator extends ApiLibSourceRule<NoUtilityTypesInApiLibConfig> {\n private readonly scanner = new UtilityTypeScanner();\n\n constructor(config: NoUtilityTypesInApiLibConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope) {\n super(config, RULE_NAMES.NO_UTILITY_TYPES_IN_API_LIB, roleResolver, diffScope);\n }\n\n protected sitesIn(file: ApiLibFile): ApiLibSite[] {\n return this.scanner.scan(file);\n }\n\n /** Scoped by the configured `paths` globs, not the role tag — an empty list judges nothing. */\n protected override isApiLibrarySource(_workspaceRoot: string, relFile: string): boolean {\n return matchesAnyGlob(relFile, this.config.paths);\n }\n\n protected override scopeLabel(): string {\n return `an API contract library (paths: ${this.config.paths.join(', ')})`;\n }\n\n protected why(): string {\n return 'an API writes its fields out — Omit / Pick / Partial / Required / Exclude / Extract make every reader ' +\n 'of the contract compute its field list from another file, and none of them can become a DTO class.';\n }\n}\n"]}
1
+ {"version":3,"file":"validate-no-utility-types-in-api-lib.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-utility-types-in-api-lib.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;;;;AAEH,0DAA8G;AAC9G,yCAA2D;AAC3D,uDAAiC;AACjC,+DAAiF;AACjF,mEAA8D;AAC9D,6CAAyC;AAEzC,qEAAqE;AACrE,MAAa,kBAAkB;IAC3B,6DAA6D;IAC7D,MAAM,CAAU,OAAO,GAAgC,IAAI,GAAG,CAAiB;QAC3E,CAAC,MAAM,EAAE,oEAAoE,CAAC;QAC9E,CAAC,MAAM,EAAE,gEAAgE,CAAC;QAC1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AS;YAAE,OAAO,SAAS,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;QAC7F,IAAI,EAAE,CAAC,sBAAsB,CAAC,IAAI,CAAC;YAAE,OAAO,QAAQ,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;QACrE,OAAO,SAAS,CAAC;IACrB,CAAC;;AA5GL,gDA6GC;AAGM,IAAM,+BAA+B,GAArC,MAAM,+BAAgC,SAAQ,sCAA8C;IAC9E,OAAO,GAAG,IAAI,kBAAkB,EAAE,CAAC;IAEpD,YAAY,MAAoC,EAAE,YAAiC,EAAE,SAAoB,EAAE,SAAoB;QAC3H,KAAK,CAAC,MAAM,EAAE,yBAAU,CAAC,2BAA2B,EAAE,YAAY,EAAE,SAAS,EAAE,SAAS,CAAC,CAAC;IAC9F,CAAC;IAES,OAAO,CAAC,IAAgB;QAC9B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACnC,CAAC;IAED,+FAA+F;IAC5E,kBAAkB,CAAC,cAAsB,EAAE,OAAe;QACzE,OAAO,IAAA,6BAAc,EAAC,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACtD,CAAC;IAEkB,UAAU;QACzB,OAAO,mCAAmC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC;IAC9E,CAAC;IAES,GAAG;QACT,OAAO,wGAAwG;YAC3G,oGAAoG,CAAC;IAC7G,CAAC;CACJ,CAAA;AAxBY,0EAA+B;0CAA/B,+BAA+B;IAD3C,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAIjB,2CAA4B,EAAgB,2CAAmB,EAAa,wBAAS,EAAa,sBAAS;GAHtH,+BAA+B,CAwB3C","sourcesContent":["/**\n * `no-utility-types-in-api-lib` (#1026) — an API contract writes its fields out.\n *\n * In every `.ts` file under the configured `paths` (e.g. `libraries/apis/**`) this refuses the\n * utility types that turn a DTO's field list, or a set of keys, into a type-level computation:\n *\n * export interface LessonPassageDto extends Omit<LessonPassageReservationDto, OptionalField> { … }\n * draft?: Partial<LessonDto>;\n * export type Summary = Pick<LessonDto, 'id' | 'title'>;\n * export type Kind = Exclude<AllKinds, 'legacy'>;\n *\n * — `Omit`, `Pick`, `Partial`, `Required`, `Exclude` and `Extract`, in an `extends` / `implements`\n * clause, a field, a type alias or a generic argument.\n *\n * Why: an api library is the contract every client, server and document generator reads. A utility\n * type makes a reader open a second file and subtract (or add) names in their head to learn which\n * fields a DTO carries; it cannot become a DTO class (`class X extends Omit<…>` does not compile — a\n * utility type has no runtime value); and a key union that only exists to feed `Omit` collides with\n * `one-enum-spelling-in-api-lib`, whose enum cure removes nothing from an `Omit`. The whole family is\n * refused, not `Omit` alone, because banning one just moves the computation into its sibling\n * (`Pick<T, Exclude<keyof T, K>>` is `Omit<T, K>`). `Record`, `Readonly` and `Array` stay allowed:\n * they do not hide which fields a DTO carries.\n *\n * The cure is to write the fields out — a shared base interface both DTOs extend, each adding its own\n * required or optional fields, or a flat interface / class listing every field. The wire JSON is\n * unchanged either way.\n */\n\nimport { DiffScope, NoUtilityTypesInApiLibConfig, RULE_NAMES, matchesAnyGlob } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport * as ts from 'typescript';\nimport { ApiLibFile, ApiLibSite, ApiLibSourceRule } from './api-lib-source-rule';\nimport { ProjectRoleResolver } from './project-role-resolver';\nimport { ScanScope } from './scan-scope';\n\n/** Finds every refused utility-type reference in one parsed file. */\nexport class UtilityTypeScanner {\n /** The refused utility types, each with what it computes. */\n static readonly REFUSED: ReadonlyMap<string, string> = new Map<string, string>([\n ['Omit', 'a DTO\\'s field list computed by SUBTRACTING keys from another type'],\n ['Pick', 'a DTO\\'s field list computed by SELECTING keys of another type'],\n ['Partial', 'a DTO\\'s field list computed by making every field of another type optional'],\n ['Required', 'a DTO\\'s field list computed by making every field of another type required'],\n ['Exclude', 'a set of keys or values computed by SUBTRACTING from another union'],\n ['Extract', 'a set of keys or values computed by SELECTING from another union'],\n ]);\n\n scan(file: ApiLibFile): ApiLibSite[] {\n const shadowed = this.locallyDeclaredNames(file.source);\n const sites: ApiLibSite[] = [];\n const visit = (node: ts.Node): void => {\n const name = this.refusedNameOf(node, shadowed);\n if (name !== undefined) sites.push(this.siteFor(file, node, name));\n ts.forEachChild(node, visit);\n };\n visit(file.source);\n return sites;\n }\n\n /** The utility's name when `node` is a refused reference: `Omit<…>` as a type, or in a heritage clause. */\n private refusedNameOf(node: ts.Node, shadowed: ReadonlySet<string>): string | undefined {\n let name: string | undefined;\n if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) name = node.typeName.text;\n else if (ts.isExpressionWithTypeArguments(node) && ts.isIdentifier(node.expression)) name = node.expression.text;\n if (name === undefined || !UtilityTypeScanner.REFUSED.has(name) || shadowed.has(name)) return undefined;\n return name;\n }\n\n /**\n * Names the file declares or imports itself — a local `type Omit = …` or an imported `Pick` class\n * is not the global utility type, so it is not refused.\n */\n private locallyDeclaredNames(source: ts.SourceFile): Set<string> {\n const names = new Set<string>();\n for (const statement of source.statements) {\n if ((ts.isTypeAliasDeclaration(statement) || ts.isInterfaceDeclaration(statement) ||\n ts.isClassDeclaration(statement) || ts.isEnumDeclaration(statement)) && statement.name !== undefined) {\n names.add(statement.name.text);\n }\n const bindings = ts.isImportDeclaration(statement) ? statement.importClause?.namedBindings : undefined;\n if (bindings !== undefined && ts.isNamedImports(bindings)) {\n for (const element of bindings.elements) names.add(element.name.text);\n }\n }\n return names;\n }\n\n private siteFor(file: ApiLibFile, node: ts.Node, name: string): ApiLibSite {\n const args = this.typeArgumentsOf(node).map((arg: ts.TypeNode) => arg.getText(file.source).replace(/\\s+/g, ' '));\n const what = `\\`${name}<…>\\` — ${UtilityTypeScanner.REFUSED.get(name)}; an API writes its fields out`;\n return file.site(node, what, `${this.cureFor(name, args[0] ?? 'T', args[1] ?? 'K')} ${this.owner(file, node)}`.trim());\n }\n\n private typeArgumentsOf(node: ts.Node): readonly ts.TypeNode[] {\n if (ts.isTypeReferenceNode(node) || ts.isExpressionWithTypeArguments(node)) return node.typeArguments ?? [];\n return [];\n }\n\n private cureFor(name: string, target: string, keys: string): string {\n const wire = 'The wire JSON is unchanged.';\n switch (name) {\n case 'Omit':\n return `write the fields out instead of \\`Omit<${target}, ${keys}>\\`: move the fields both types share into a ` +\n `base interface that ${target} and this type both extend, each adding its own required or optional ` +\n `fields — or list every field of ${target} except ${keys} in a flat interface or class. ${wire}`;\n case 'Pick':\n return `write the fields out instead of \\`Pick<${target}, ${keys}>\\`: put the picked fields (${keys}) in a ` +\n `base interface that ${target} extends and use it here — or list them in a flat interface or class. ${wire}`;\n case 'Partial':\n return `write the fields out instead of \\`Partial<${target}>\\`: declare an interface or class listing every ` +\n `field of ${target} as optional (\\`field?: X\\`). ${wire}`;\n case 'Required':\n return `write the fields out instead of \\`Required<${target}>\\`: declare an interface or class listing every ` +\n `field of ${target} as required. ${wire}`;\n default:\n return `write the set out instead of \\`${name}<${target}, ${keys}>\\`: for keys of a DTO, write that DTO's ` +\n `fields out; for values, declare the string enum holding exactly the members meant ` +\n `(one-enum-spelling-in-api-lib), or a union of its members. ${wire}`;\n }\n }\n\n /** `(on interface X)` for a heritage clause, `(in X.field)` for a member, `(in type X)` for an alias. */\n private owner(file: ApiLibFile, node: ts.Node): string {\n let current: ts.Node | undefined = node.parent;\n let member: string | undefined;\n while (current !== undefined && current !== file.source) {\n if ((ts.isPropertySignature(current) || ts.isPropertyDeclaration(current)) && member === undefined) {\n member = current.name.getText(file.source);\n }\n const declared = this.declaredName(current);\n if (declared !== undefined) {\n if (ts.isHeritageClause(node.parent)) return `(on ${declared})`;\n return member === undefined ? `(in ${declared})` : `(in ${declared}.${member})`;\n }\n current = current.parent;\n }\n return '';\n }\n\n private declaredName(node: ts.Node): string | undefined {\n if (ts.isInterfaceDeclaration(node)) return `interface ${node.name.text}`;\n if (ts.isClassDeclaration(node) && node.name !== undefined) return `class ${node.name.text}`;\n if (ts.isTypeAliasDeclaration(node)) return `type ${node.name.text}`;\n return undefined;\n }\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoUtilityTypesInApiLibValidator extends ApiLibSourceRule<NoUtilityTypesInApiLibConfig> {\n private readonly scanner = new UtilityTypeScanner();\n\n constructor(config: NoUtilityTypesInApiLibConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope, scanScope: ScanScope) {\n super(config, RULE_NAMES.NO_UTILITY_TYPES_IN_API_LIB, roleResolver, diffScope, scanScope);\n }\n\n protected sitesIn(file: ApiLibFile): ApiLibSite[] {\n return this.scanner.scan(file);\n }\n\n /** Scoped by the configured `paths` globs, not the role tag — an empty list judges nothing. */\n protected override isApiLibrarySource(_workspaceRoot: string, relFile: string): boolean {\n return matchesAnyGlob(relFile, this.config.paths);\n }\n\n protected override scopeLabel(): string {\n return `an API contract library (paths: ${this.config.paths.join(', ')})`;\n }\n\n protected why(): string {\n return 'an API writes its fields out — Omit / Pick / Partial / Required / Exclude / Extract make every reader ' +\n 'of the contract compute its field list from another file, and none of them can become a DTO class.';\n }\n}\n"]}
@@ -24,6 +24,7 @@ import { DiffScope, OneEnumSpellingInApiLibConfig } from '@webpieces/rules-confi
24
24
  import { ApiLibEnumIndex } from './api-lib-enum-index';
25
25
  import { ApiLibFile, ApiLibSite, ApiLibSourceRule } from './api-lib-source-rule';
26
26
  import { ProjectRoleResolver } from './project-role-resolver';
27
+ import { ScanScope } from './scan-scope';
27
28
  /** Finds every non-enum spelling of a closed string set in one parsed file. */
28
29
  export declare class EnumSpellingScanner {
29
30
  scan(file: ApiLibFile, index: ApiLibEnumIndex): ApiLibSite[];
@@ -55,7 +56,7 @@ export declare class OneEnumSpellingInApiLibValidator extends ApiLibSourceRule<O
55
56
  private readonly scanner;
56
57
  /** One index per api-library directory, per run: the union and its branches are in different files. */
57
58
  private readonly indexes;
58
- constructor(config: OneEnumSpellingInApiLibConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope);
59
+ constructor(config: OneEnumSpellingInApiLibConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope, scanScope: ScanScope);
59
60
  protected sitesIn(file: ApiLibFile): ApiLibSite[];
60
61
  protected why(): string;
61
62
  }
@@ -31,6 +31,7 @@ const api_lib_enum_index_1 = require("./api-lib-enum-index");
31
31
  const api_lib_enum_text_1 = require("./api-lib-enum-text");
32
32
  const api_lib_source_rule_1 = require("./api-lib-source-rule");
33
33
  const project_role_resolver_1 = require("./project-role-resolver");
34
+ const scan_scope_1 = require("./scan-scope");
34
35
  const ONE_SPELLING = 'a fixed set of string values in an API is a string enum, and only a string enum';
35
36
  /** Where a type is written: the declaration that names it, for naming the enum. Data-only. */
36
37
  class Holder {
@@ -230,8 +231,8 @@ let OneEnumSpellingInApiLibValidator = class OneEnumSpellingInApiLibValidator ex
230
231
  scanner = new EnumSpellingScanner();
231
232
  /** One index per api-library directory, per run: the union and its branches are in different files. */
232
233
  indexes = new Map();
233
- constructor(config, roleResolver, diffScope) {
234
- super(config, rules_config_1.RULE_NAMES.ONE_ENUM_SPELLING_IN_API_LIB, roleResolver, diffScope);
234
+ constructor(config, roleResolver, diffScope, scanScope) {
235
+ super(config, rules_config_1.RULE_NAMES.ONE_ENUM_SPELLING_IN_API_LIB, roleResolver, diffScope, scanScope);
235
236
  }
236
237
  sitesIn(file) {
237
238
  let index = this.indexes.get(file.projectDir);
@@ -250,6 +251,6 @@ let OneEnumSpellingInApiLibValidator = class OneEnumSpellingInApiLibValidator ex
250
251
  exports.OneEnumSpellingInApiLibValidator = OneEnumSpellingInApiLibValidator;
251
252
  exports.OneEnumSpellingInApiLibValidator = OneEnumSpellingInApiLibValidator = tslib_1.__decorate([
252
253
  (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
253
- tslib_1.__metadata("design:paramtypes", [rules_config_1.OneEnumSpellingInApiLibConfig, project_role_resolver_1.ProjectRoleResolver, rules_config_1.DiffScope])
254
+ tslib_1.__metadata("design:paramtypes", [rules_config_1.OneEnumSpellingInApiLibConfig, project_role_resolver_1.ProjectRoleResolver, rules_config_1.DiffScope, scan_scope_1.ScanScope])
254
255
  ], OneEnumSpellingInApiLibValidator);
255
256
  //# sourceMappingURL=validate-one-enum-spelling-in-api-lib.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"validate-one-enum-spelling-in-api-lib.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-one-enum-spelling-in-api-lib.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;;;;AAEH,0DAA+F;AAC/F,yCAA2D;AAC3D,uDAAiC;AACjC,6DAAoE;AACpE,2DAA+C;AAC/C,+DAAiF;AACjF,mEAA8D;AAE9D,MAAM,YAAY,GAAG,iFAAiF,CAAC;AAEvG,8FAA8F;AAC9F,MAAM,MAAM;IAGK;IACA;IAEA;IALb;IACI,mDAAmD;IAC1C,IAAY,EACZ,IAAY;IACrB,sEAAsE;IAC7D,KAAyB;QAHzB,SAAI,GAAJ,IAAI,CAAQ;QACZ,SAAI,GAAJ,IAAI,CAAQ;QAEZ,UAAK,GAAL,KAAK,CAAoB;IACnC,CAAC;CACP;AAED,sGAAsG;AACtG,MAAM,aAAa;IAEF;IACA;IAFb,YACa,QAAgB,EAChB,MAAyB;QADzB,aAAQ,GAAR,QAAQ,CAAQ;QAChB,WAAM,GAAN,MAAM,CAAmB;IACnC,CAAC;CACP;AAED,+EAA+E;AAC/E,MAAa,mBAAmB;IAC5B,IAAI,CAAC,IAAgB,EAAE,KAAsB;QACzC,MAAM,KAAK,GAAiB,EAAE,CAAC;QAC/B,MAAM,KAAK,GAAG,CAAC,IAAa,EAAQ,EAAE;YAClC,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;YAC5C,IAAI,IAAI,KAAK,SAAS;gBAAE,KAAK,CAAC,IAAI,CAAC,IAAI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AAC,EAAE,CAAC;IAC/G,CAAC;CACJ;AAtKD,kDAsKC;AAGM,IAAM,gCAAgC,GAAtC,MAAM,gCAAiC,SAAQ,sCAA+C;IAChF,OAAO,GAAG,IAAI,mBAAmB,EAAE,CAAC;IACrD,uGAAuG;IACtF,OAAO,GAAG,IAAI,GAAG,EAA2B,CAAC;IAE9D,YAAY,MAAqC,EAAE,YAAiC,EAAE,SAAoB;QACtG,KAAK,CAAC,MAAM,EAAE,yBAAU,CAAC,4BAA4B,EAAE,YAAY,EAAE,SAAS,CAAC,CAAC;IACpF,CAAC;IAES,OAAO,CAAC,IAAgB;QAC9B,IAAI,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QAC9C,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACtB,KAAK,GAAG,oCAAe,CAAC,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;YAC5C,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;QAC7C,CAAC;QACD,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IAC1C,CAAC;IAES,GAAG;QACT,OAAO,GAAG,YAAY,qFAAqF;YACvG,uGAAuG;YACvG,sBAAsB,CAAC;IAC/B,CAAC;CACJ,CAAA;AAvBY,4EAAgC;2CAAhC,gCAAgC;IAD5C,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAMjB,4CAA6B,EAAgB,2CAAmB,EAAa,wBAAS;GALjG,gCAAgC,CAuB5C","sourcesContent":["/**\n * `one-enum-spelling-in-api-lib` (#1023) — ONE spelling for a fixed set of string values in an API:\n *\n * export enum SpeakerGender { FEMALE = 'female', MALE = 'male' }\n * gender!: SpeakerGender; // the enum\n * mode: VoiceMode.RANDOM; // one member (a union discriminator)\n * mode: VoiceMode.A | VoiceMode.B; // a union of members\n *\n * In every `role:api-lib` project this refuses, each with a cure that PRINTS the enum to write:\n *\n * type LessonType = 'story' | 'lesson'; kind?: 'audio' | 'slot'; (a 2+ string-literal union)\n * gender!: (typeof SPEAKER_GENDERS)[number]; key: keyof typeof LABELS;\n * mode: 'random'; (a single literal used as a union discriminator)\n * enum Level { LOW, HIGH } enum Mixed { A = 'a', B = 2 } const enum Tone { … }\n *\n * Why ONE spelling: two ways to write a closed set means every reader, reviewer and the document\n * generator has to understand both, and the derived spellings (`(typeof X)[number]`, a `string` field\n * whose legal values live in some array) are exactly the ones the generator does not read — they can\n * only be supported later, deliberately, if ever. A numeric enum puts NUMBERS on the wire, which no\n * partner reading `gender: 1` can interpret. The generator itself keeps supporting literal unions;\n * this rule is what forbids new ones in an api library.\n */\n\nimport { DiffScope, OneEnumSpellingInApiLibConfig, RULE_NAMES } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport * as ts from 'typescript';\nimport { ApiLibEnumIndex, ObjectUnion } from './api-lib-enum-index';\nimport { EnumText } from './api-lib-enum-text';\nimport { ApiLibFile, ApiLibSite, ApiLibSourceRule } from './api-lib-source-rule';\nimport { ProjectRoleResolver } from './project-role-resolver';\n\nconst ONE_SPELLING = 'a fixed set of string values in an API is a string enum, and only a string enum';\n\n/** Where a type is written: the declaration that names it, for naming the enum. Data-only. */\nclass Holder {\n constructor(\n /** 'alias' | 'property' | 'parameter' | 'none'. */\n readonly kind: string,\n readonly name: string,\n /** The enclosing named type / class / function, when there is one. */\n readonly owner: string | undefined,\n ) {}\n}\n\n/** A property that discriminates a union, and every value the union's branches give it. Data-only. */\nclass Discriminator {\n constructor(\n readonly enumName: string,\n readonly values: readonly string[],\n ) {}\n}\n\n/** Finds every non-enum spelling of a closed string set in one parsed file. */\nexport class EnumSpellingScanner {\n scan(file: ApiLibFile, index: ApiLibEnumIndex): ApiLibSite[] {\n const sites: ApiLibSite[] = [];\n const visit = (node: ts.Node): void => {\n const site = this.siteAt(file, index, node);\n if (site !== undefined) sites.push(site);\n ts.forEachChild(node, visit);\n };\n visit(file.source);\n return sites;\n }\n\n private siteAt(file: ApiLibFile, index: ApiLibEnumIndex, node: ts.Node): ApiLibSite | undefined {\n if (ts.isUnionTypeNode(node)) return this.literalUnion(file, index, node);\n if (ts.isLiteralTypeNode(node) && ts.isStringLiteral(node.literal)) return this.singleLiteral(file, index, node);\n if (ts.isIndexedAccessTypeNode(node)) return this.typeofIndex(file, index, node);\n if (ts.isTypeOperatorNode(node) && node.operator === ts.SyntaxKind.KeyOfKeyword) return this.keyofTypeof(file, index, node);\n if (ts.isEnumDeclaration(node)) return this.badEnum(file, node);\n return undefined;\n }\n\n /** `'a' | 'b'` — two or more string-literal branches, anywhere a type is written. */\n private literalUnion(file: ApiLibFile, index: ApiLibEnumIndex, node: ts.UnionTypeNode): ApiLibSite | undefined {\n const values = node.types\n .filter((t: ts.TypeNode) => ts.isLiteralTypeNode(t) && ts.isStringLiteral(t.literal))\n .map((t: ts.TypeNode) => ((t as ts.LiteralTypeNode).literal as ts.StringLiteral).text);\n if (values.length < 2) return undefined;\n const holder = this.holderOf(node);\n const discriminator = this.discriminatorOf(index, holder);\n const what = `a string-literal union — ${ONE_SPELLING}`;\n if (discriminator !== undefined) {\n const members = values.map((v: string) => EnumText.memberRef(discriminator.enumName, v, discriminator.values)).join(' | ');\n return file.site(node, what,\n `declare \\`${EnumText.declaration(discriminator.enumName, discriminator.values)}\\` (every value of the ` +\n `\\`${holder.name}\\` discriminator) and write \\`${holder.name}: ${members}\\` here.`);\n }\n if (holder.kind === 'alias') {\n return file.site(node, what,\n `replace \\`type ${holder.name} = …\\` with \\`${EnumText.declaration(holder.name, values)}\\` — every use of ` +\n `${holder.name} as a type keeps compiling; a literal VALUE becomes ${EnumText.memberRef(holder.name, values[0]!, values)}.`);\n }\n const name = this.enumNameFor(holder);\n return file.site(node, what,\n `declare \\`${EnumText.declaration(name, values)}\\` and write \\`${name}\\` here in place of the union.`);\n }\n\n /** `mode: 'random'` on a branch of a union — a discriminator, which is one enum member. */\n private singleLiteral(file: ApiLibFile, index: ApiLibEnumIndex, node: ts.LiteralTypeNode): ApiLibSite | undefined {\n const direct = node.parent;\n const property = ts.isUnionTypeNode(direct) ? direct.parent : direct;\n if (!ts.isPropertySignature(property) && !ts.isPropertyDeclaration(property)) return undefined;\n if (ts.isUnionTypeNode(direct) && direct.types.filter((t: ts.TypeNode) => !ApiLibEnumIndex.isNullish(t)).length !== 1) {\n return undefined;\n }\n const discriminator = this.discriminatorOf(index, this.holderOf(node));\n if (discriminator === undefined) return undefined;\n const value = (node.literal as ts.StringLiteral).text;\n const key = property.name.getText(file.source);\n return file.site(node, `a single string-literal discriminator — ${ONE_SPELLING}`,\n `declare \\`${EnumText.declaration(discriminator.enumName, discriminator.values)}\\` (every value of the ` +\n `\\`${key}\\` discriminator) and write \\`${key}: ${EnumText.memberRef(discriminator.enumName, value, discriminator.values)}\\` here.`);\n }\n\n /** `(typeof X)[number]` — the values live in a runtime list; the enum IS that list. */\n private typeofIndex(file: ApiLibFile, index: ApiLibEnumIndex, node: ts.IndexedAccessTypeNode): ApiLibSite | undefined {\n let object: ts.TypeNode = node.objectType;\n while (ts.isParenthesizedTypeNode(object)) object = object.type;\n if (!ts.isTypeQueryNode(object) || node.indexType.kind !== ts.SyntaxKind.NumberKeyword) return undefined;\n const list = object.exprName.getText(file.source);\n const name = EnumText.singularPascal(list.split('.').pop() ?? list);\n const values = index.constList(list);\n const declaration = values === undefined\n ? `export enum ${name} { /* one MEMBER = 'value' per element of ${list} */ }`\n : EnumText.declaration(name, values);\n return file.site(node, `\\`(typeof ${list})[number]\\` — ${ONE_SPELLING}`,\n `replace \\`${list}\\` with \\`${declaration}\\` and write \\`${name}\\` here; code that needs the runtime ` +\n `list uses \\`Object.values(${name})\\`.`);\n }\n\n /** `keyof typeof X` — the values are an object's keys; the enum states them. */\n private keyofTypeof(file: ApiLibFile, index: ApiLibEnumIndex, node: ts.TypeOperatorNode): ApiLibSite | undefined {\n if (!ts.isTypeQueryNode(node.type)) return undefined;\n const object = node.type.exprName.getText(file.source);\n const name = `${EnumText.pascal(object.split('.').pop() ?? object)}Key`;\n const keys = index.constKeysOf(object);\n const declaration = keys === undefined\n ? `export enum ${name} { /* one MEMBER = 'key' per key of ${object} */ }`\n : EnumText.declaration(name, keys);\n return file.site(node, `\\`keyof typeof ${object}\\` — ${ONE_SPELLING}`,\n `declare \\`${declaration}\\` and write \\`${name}\\` here (key ${object} by it: \\`Record<${name}, …>\\`).`);\n }\n\n /** A `const`, numeric, heterogeneous or uninitialised enum. */\n private badEnum(file: ApiLibFile, node: ts.EnumDeclaration): ApiLibSite | undefined {\n const isConst = (node.modifiers ?? []).some((m: ts.ModifierLike) => m.kind === ts.SyntaxKind.ConstKeyword);\n const bad = node.members.filter((m: ts.EnumMember) => m.initializer === undefined || !ts.isStringLiteral(m.initializer));\n if (!isConst && bad.length === 0) return undefined;\n const values = node.members.map((m: ts.EnumMember) =>\n m.initializer !== undefined && ts.isStringLiteral(m.initializer) ? m.initializer.text : EnumText.valueFor(m.name.getText(file.source)));\n const reason = isConst\n ? 'a `const enum` — it is erased at compile time, so no runtime value exists for a client or the generator to read'\n : `member(s) ${bad.map((m: ts.EnumMember) => m.name.getText(file.source)).join(', ')} are not initialised with a string ` +\n 'literal — a numeric enum puts NUMBERS on the wire';\n const members = node.members.map((m: ts.EnumMember, i: number) => `${m.name.getText(file.source)} = '${values[i]}'`).join(', ');\n return file.site(node.name, `${reason}; ${ONE_SPELLING}`,\n `write \\`export enum ${node.name.text} { ${members} }\\` — every member string-initialised, no \\`const\\` ` +\n '(the suggested values are a starting point: they are the wire format, so choose them deliberately).');\n }\n\n /** The declaration a written type belongs to — climbing through arrays, parens, unions and generics. */\n private holderOf(node: ts.Node): Holder {\n let current: ts.Node = node.parent;\n while (current !== undefined && ts.isTypeNode(current)) current = current.parent;\n if (current === undefined) return new Holder('none', 'Values', undefined);\n if (ts.isTypeAliasDeclaration(current)) return new Holder('alias', current.name.text, undefined);\n if ((ts.isPropertySignature(current) || ts.isPropertyDeclaration(current)) &&\n (ts.isIdentifier(current.name) || ts.isStringLiteral(current.name))) {\n return new Holder('property', current.name.text, this.ownerOf(current));\n }\n if (ts.isParameter(current) && ts.isIdentifier(current.name)) {\n return new Holder('parameter', current.name.text, this.ownerOf(current));\n }\n return new Holder('none', 'Values', this.ownerOf(current));\n }\n\n /** The nearest enclosing named interface, class, type alias or function. */\n private ownerOf(node: ts.Node): string | undefined {\n for (let at: ts.Node | undefined = node.parent; at !== undefined; at = at.parent) {\n if ((ts.isInterfaceDeclaration(at) || ts.isClassDeclaration(at) || ts.isTypeAliasDeclaration(at) ||\n ts.isFunctionDeclaration(at) || ts.isMethodDeclaration(at)) && at.name !== undefined && ts.isIdentifier(at.name)) {\n return at.name.text;\n }\n }\n return undefined;\n }\n\n /**\n * When the holder is a property of a union BRANCH that every branch declares, it discriminates the\n * union: the enum is named for the union and property, and holds every branch's values.\n */\n private discriminatorOf(index: ApiLibEnumIndex, holder: Holder): Discriminator | undefined {\n if (holder.kind !== 'property' || holder.owner === undefined) return undefined;\n const union = index.unionsOf(holder.owner)\n .find((u: ObjectUnion) => u.branches.every((b: string) => index.propertyOf(b, holder.name) !== undefined));\n if (union === undefined) return undefined;\n const values: string[] = [];\n for (const branch of union.branches) {\n for (const value of this.literalValues(index.propertyOf(branch, holder.name)!)) {\n if (!values.includes(value)) values.push(value);\n }\n }\n return new Discriminator(`${union.name ?? holder.owner}${EnumText.pascal(holder.name)}`, values);\n }\n\n /** The string literals a property type spells: `'a'` or `'a' | 'b'`. */\n private literalValues(type: ts.TypeNode): string[] {\n const branches = ts.isUnionTypeNode(type) ? [...type.types] : [type];\n return branches\n .filter((t: ts.TypeNode) => ts.isLiteralTypeNode(t) && ts.isStringLiteral(t.literal))\n .map((t: ts.TypeNode) => ((t as ts.LiteralTypeNode).literal as ts.StringLiteral).text);\n }\n\n private enumNameFor(holder: Holder): string {\n if (holder.kind === 'none') return `${holder.owner === undefined ? '' : EnumText.pascal(holder.owner)}Values`;\n return `${holder.owner === undefined ? '' : EnumText.pascal(holder.owner)}${EnumText.pascal(holder.name)}`;\n }\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class OneEnumSpellingInApiLibValidator extends ApiLibSourceRule<OneEnumSpellingInApiLibConfig> {\n private readonly scanner = new EnumSpellingScanner();\n /** One index per api-library directory, per run: the union and its branches are in different files. */\n private readonly indexes = new Map<string, ApiLibEnumIndex>();\n\n constructor(config: OneEnumSpellingInApiLibConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope) {\n super(config, RULE_NAMES.ONE_ENUM_SPELLING_IN_API_LIB, roleResolver, diffScope);\n }\n\n protected sitesIn(file: ApiLibFile): ApiLibSite[] {\n let index = this.indexes.get(file.projectDir);\n if (index === undefined) {\n index = ApiLibEnumIndex.of(file.projectDir);\n this.indexes.set(file.projectDir, index);\n }\n return this.scanner.scan(file, index);\n }\n\n protected why(): string {\n return `${ONE_SPELLING} — every member explicitly initialised with a string literal. Two spellings of one ` +\n 'thing is two things every reader and the document generator must understand, and a numeric enum puts ' +\n 'numbers on the wire.';\n }\n}\n"]}
1
+ {"version":3,"file":"validate-one-enum-spelling-in-api-lib.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-one-enum-spelling-in-api-lib.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;;;;AAEH,0DAA+F;AAC/F,yCAA2D;AAC3D,uDAAiC;AACjC,6DAAoE;AACpE,2DAA+C;AAC/C,+DAAiF;AACjF,mEAA8D;AAC9D,6CAAyC;AAEzC,MAAM,YAAY,GAAG,iFAAiF,CAAC;AAEvG,8FAA8F;AAC9F,MAAM,MAAM;IAGK;IACA;IAEA;IALb;IACI,mDAAmD;IAC1C,IAAY,EACZ,IAAY;IACrB,sEAAsE;IAC7D,KAAyB;QAHzB,SAAI,GAAJ,IAAI,CAAQ;QACZ,SAAI,GAAJ,IAAI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AAC;QAC7C,CAAC;QACD,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IAC1C,CAAC;IAES,GAAG;QACT,OAAO,GAAG,YAAY,qFAAqF;YACvG,uGAAuG;YACvG,sBAAsB,CAAC;IAC/B,CAAC;CACJ,CAAA;AAvBY,4EAAgC;2CAAhC,gCAAgC;IAD5C,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAMjB,4CAA6B,EAAgB,2CAAmB,EAAa,wBAAS,EAAa,sBAAS;GALvH,gCAAgC,CAuB5C","sourcesContent":["/**\n * `one-enum-spelling-in-api-lib` (#1023) — ONE spelling for a fixed set of string values in an API:\n *\n * export enum SpeakerGender { FEMALE = 'female', MALE = 'male' }\n * gender!: SpeakerGender; // the enum\n * mode: VoiceMode.RANDOM; // one member (a union discriminator)\n * mode: VoiceMode.A | VoiceMode.B; // a union of members\n *\n * In every `role:api-lib` project this refuses, each with a cure that PRINTS the enum to write:\n *\n * type LessonType = 'story' | 'lesson'; kind?: 'audio' | 'slot'; (a 2+ string-literal union)\n * gender!: (typeof SPEAKER_GENDERS)[number]; key: keyof typeof LABELS;\n * mode: 'random'; (a single literal used as a union discriminator)\n * enum Level { LOW, HIGH } enum Mixed { A = 'a', B = 2 } const enum Tone { … }\n *\n * Why ONE spelling: two ways to write a closed set means every reader, reviewer and the document\n * generator has to understand both, and the derived spellings (`(typeof X)[number]`, a `string` field\n * whose legal values live in some array) are exactly the ones the generator does not read — they can\n * only be supported later, deliberately, if ever. A numeric enum puts NUMBERS on the wire, which no\n * partner reading `gender: 1` can interpret. The generator itself keeps supporting literal unions;\n * this rule is what forbids new ones in an api library.\n */\n\nimport { DiffScope, OneEnumSpellingInApiLibConfig, RULE_NAMES } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport * as ts from 'typescript';\nimport { ApiLibEnumIndex, ObjectUnion } from './api-lib-enum-index';\nimport { EnumText } from './api-lib-enum-text';\nimport { ApiLibFile, ApiLibSite, ApiLibSourceRule } from './api-lib-source-rule';\nimport { ProjectRoleResolver } from './project-role-resolver';\nimport { ScanScope } from './scan-scope';\n\nconst ONE_SPELLING = 'a fixed set of string values in an API is a string enum, and only a string enum';\n\n/** Where a type is written: the declaration that names it, for naming the enum. Data-only. */\nclass Holder {\n constructor(\n /** 'alias' | 'property' | 'parameter' | 'none'. */\n readonly kind: string,\n readonly name: string,\n /** The enclosing named type / class / function, when there is one. */\n readonly owner: string | undefined,\n ) {}\n}\n\n/** A property that discriminates a union, and every value the union's branches give it. Data-only. */\nclass Discriminator {\n constructor(\n readonly enumName: string,\n readonly values: readonly string[],\n ) {}\n}\n\n/** Finds every non-enum spelling of a closed string set in one parsed file. */\nexport class EnumSpellingScanner {\n scan(file: ApiLibFile, index: ApiLibEnumIndex): ApiLibSite[] {\n const sites: ApiLibSite[] = [];\n const visit = (node: ts.Node): void => {\n const site = this.siteAt(file, index, node);\n if (site !== undefined) sites.push(site);\n ts.forEachChild(node, visit);\n };\n visit(file.source);\n return sites;\n }\n\n private siteAt(file: ApiLibFile, index: ApiLibEnumIndex, node: ts.Node): ApiLibSite | undefined {\n if (ts.isUnionTypeNode(node)) return this.literalUnion(file, index, node);\n if (ts.isLiteralTypeNode(node) && ts.isStringLiteral(node.literal)) return this.singleLiteral(file, index, node);\n if (ts.isIndexedAccessTypeNode(node)) return this.typeofIndex(file, index, node);\n if (ts.isTypeOperatorNode(node) && node.operator === ts.SyntaxKind.KeyOfKeyword) return this.keyofTypeof(file, index, node);\n if (ts.isEnumDeclaration(node)) return this.badEnum(file, node);\n return undefined;\n }\n\n /** `'a' | 'b'` — two or more string-literal branches, anywhere a type is written. */\n private literalUnion(file: ApiLibFile, index: ApiLibEnumIndex, node: ts.UnionTypeNode): ApiLibSite | undefined {\n const values = node.types\n .filter((t: ts.TypeNode) => ts.isLiteralTypeNode(t) && ts.isStringLiteral(t.literal))\n .map((t: ts.TypeNode) => ((t as ts.LiteralTypeNode).literal as ts.StringLiteral).text);\n if (values.length < 2) return undefined;\n const holder = this.holderOf(node);\n const discriminator = this.discriminatorOf(index, holder);\n const what = `a string-literal union — ${ONE_SPELLING}`;\n if (discriminator !== undefined) {\n const members = values.map((v: string) => EnumText.memberRef(discriminator.enumName, v, discriminator.values)).join(' | ');\n return file.site(node, what,\n `declare \\`${EnumText.declaration(discriminator.enumName, discriminator.values)}\\` (every value of the ` +\n `\\`${holder.name}\\` discriminator) and write \\`${holder.name}: ${members}\\` here.`);\n }\n if (holder.kind === 'alias') {\n return file.site(node, what,\n `replace \\`type ${holder.name} = …\\` with \\`${EnumText.declaration(holder.name, values)}\\` — every use of ` +\n `${holder.name} as a type keeps compiling; a literal VALUE becomes ${EnumText.memberRef(holder.name, values[0]!, values)}.`);\n }\n const name = this.enumNameFor(holder);\n return file.site(node, what,\n `declare \\`${EnumText.declaration(name, values)}\\` and write \\`${name}\\` here in place of the union.`);\n }\n\n /** `mode: 'random'` on a branch of a union — a discriminator, which is one enum member. */\n private singleLiteral(file: ApiLibFile, index: ApiLibEnumIndex, node: ts.LiteralTypeNode): ApiLibSite | undefined {\n const direct = node.parent;\n const property = ts.isUnionTypeNode(direct) ? direct.parent : direct;\n if (!ts.isPropertySignature(property) && !ts.isPropertyDeclaration(property)) return undefined;\n if (ts.isUnionTypeNode(direct) && direct.types.filter((t: ts.TypeNode) => !ApiLibEnumIndex.isNullish(t)).length !== 1) {\n return undefined;\n }\n const discriminator = this.discriminatorOf(index, this.holderOf(node));\n if (discriminator === undefined) return undefined;\n const value = (node.literal as ts.StringLiteral).text;\n const key = property.name.getText(file.source);\n return file.site(node, `a single string-literal discriminator — ${ONE_SPELLING}`,\n `declare \\`${EnumText.declaration(discriminator.enumName, discriminator.values)}\\` (every value of the ` +\n `\\`${key}\\` discriminator) and write \\`${key}: ${EnumText.memberRef(discriminator.enumName, value, discriminator.values)}\\` here.`);\n }\n\n /** `(typeof X)[number]` — the values live in a runtime list; the enum IS that list. */\n private typeofIndex(file: ApiLibFile, index: ApiLibEnumIndex, node: ts.IndexedAccessTypeNode): ApiLibSite | undefined {\n let object: ts.TypeNode = node.objectType;\n while (ts.isParenthesizedTypeNode(object)) object = object.type;\n if (!ts.isTypeQueryNode(object) || node.indexType.kind !== ts.SyntaxKind.NumberKeyword) return undefined;\n const list = object.exprName.getText(file.source);\n const name = EnumText.singularPascal(list.split('.').pop() ?? list);\n const values = index.constList(list);\n const declaration = values === undefined\n ? `export enum ${name} { /* one MEMBER = 'value' per element of ${list} */ }`\n : EnumText.declaration(name, values);\n return file.site(node, `\\`(typeof ${list})[number]\\` — ${ONE_SPELLING}`,\n `replace \\`${list}\\` with \\`${declaration}\\` and write \\`${name}\\` here; code that needs the runtime ` +\n `list uses \\`Object.values(${name})\\`.`);\n }\n\n /** `keyof typeof X` — the values are an object's keys; the enum states them. */\n private keyofTypeof(file: ApiLibFile, index: ApiLibEnumIndex, node: ts.TypeOperatorNode): ApiLibSite | undefined {\n if (!ts.isTypeQueryNode(node.type)) return undefined;\n const object = node.type.exprName.getText(file.source);\n const name = `${EnumText.pascal(object.split('.').pop() ?? object)}Key`;\n const keys = index.constKeysOf(object);\n const declaration = keys === undefined\n ? `export enum ${name} { /* one MEMBER = 'key' per key of ${object} */ }`\n : EnumText.declaration(name, keys);\n return file.site(node, `\\`keyof typeof ${object}\\` — ${ONE_SPELLING}`,\n `declare \\`${declaration}\\` and write \\`${name}\\` here (key ${object} by it: \\`Record<${name}, …>\\`).`);\n }\n\n /** A `const`, numeric, heterogeneous or uninitialised enum. */\n private badEnum(file: ApiLibFile, node: ts.EnumDeclaration): ApiLibSite | undefined {\n const isConst = (node.modifiers ?? []).some((m: ts.ModifierLike) => m.kind === ts.SyntaxKind.ConstKeyword);\n const bad = node.members.filter((m: ts.EnumMember) => m.initializer === undefined || !ts.isStringLiteral(m.initializer));\n if (!isConst && bad.length === 0) return undefined;\n const values = node.members.map((m: ts.EnumMember) =>\n m.initializer !== undefined && ts.isStringLiteral(m.initializer) ? m.initializer.text : EnumText.valueFor(m.name.getText(file.source)));\n const reason = isConst\n ? 'a `const enum` — it is erased at compile time, so no runtime value exists for a client or the generator to read'\n : `member(s) ${bad.map((m: ts.EnumMember) => m.name.getText(file.source)).join(', ')} are not initialised with a string ` +\n 'literal — a numeric enum puts NUMBERS on the wire';\n const members = node.members.map((m: ts.EnumMember, i: number) => `${m.name.getText(file.source)} = '${values[i]}'`).join(', ');\n return file.site(node.name, `${reason}; ${ONE_SPELLING}`,\n `write \\`export enum ${node.name.text} { ${members} }\\` — every member string-initialised, no \\`const\\` ` +\n '(the suggested values are a starting point: they are the wire format, so choose them deliberately).');\n }\n\n /** The declaration a written type belongs to — climbing through arrays, parens, unions and generics. */\n private holderOf(node: ts.Node): Holder {\n let current: ts.Node = node.parent;\n while (current !== undefined && ts.isTypeNode(current)) current = current.parent;\n if (current === undefined) return new Holder('none', 'Values', undefined);\n if (ts.isTypeAliasDeclaration(current)) return new Holder('alias', current.name.text, undefined);\n if ((ts.isPropertySignature(current) || ts.isPropertyDeclaration(current)) &&\n (ts.isIdentifier(current.name) || ts.isStringLiteral(current.name))) {\n return new Holder('property', current.name.text, this.ownerOf(current));\n }\n if (ts.isParameter(current) && ts.isIdentifier(current.name)) {\n return new Holder('parameter', current.name.text, this.ownerOf(current));\n }\n return new Holder('none', 'Values', this.ownerOf(current));\n }\n\n /** The nearest enclosing named interface, class, type alias or function. */\n private ownerOf(node: ts.Node): string | undefined {\n for (let at: ts.Node | undefined = node.parent; at !== undefined; at = at.parent) {\n if ((ts.isInterfaceDeclaration(at) || ts.isClassDeclaration(at) || ts.isTypeAliasDeclaration(at) ||\n ts.isFunctionDeclaration(at) || ts.isMethodDeclaration(at)) && at.name !== undefined && ts.isIdentifier(at.name)) {\n return at.name.text;\n }\n }\n return undefined;\n }\n\n /**\n * When the holder is a property of a union BRANCH that every branch declares, it discriminates the\n * union: the enum is named for the union and property, and holds every branch's values.\n */\n private discriminatorOf(index: ApiLibEnumIndex, holder: Holder): Discriminator | undefined {\n if (holder.kind !== 'property' || holder.owner === undefined) return undefined;\n const union = index.unionsOf(holder.owner)\n .find((u: ObjectUnion) => u.branches.every((b: string) => index.propertyOf(b, holder.name) !== undefined));\n if (union === undefined) return undefined;\n const values: string[] = [];\n for (const branch of union.branches) {\n for (const value of this.literalValues(index.propertyOf(branch, holder.name)!)) {\n if (!values.includes(value)) values.push(value);\n }\n }\n return new Discriminator(`${union.name ?? holder.owner}${EnumText.pascal(holder.name)}`, values);\n }\n\n /** The string literals a property type spells: `'a'` or `'a' | 'b'`. */\n private literalValues(type: ts.TypeNode): string[] {\n const branches = ts.isUnionTypeNode(type) ? [...type.types] : [type];\n return branches\n .filter((t: ts.TypeNode) => ts.isLiteralTypeNode(t) && ts.isStringLiteral(t.literal))\n .map((t: ts.TypeNode) => ((t as ts.LiteralTypeNode).literal as ts.StringLiteral).text);\n }\n\n private enumNameFor(holder: Holder): string {\n if (holder.kind === 'none') return `${holder.owner === undefined ? '' : EnumText.pascal(holder.owner)}Values`;\n return `${holder.owner === undefined ? '' : EnumText.pascal(holder.owner)}${EnumText.pascal(holder.name)}`;\n }\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class OneEnumSpellingInApiLibValidator extends ApiLibSourceRule<OneEnumSpellingInApiLibConfig> {\n private readonly scanner = new EnumSpellingScanner();\n /** One index per api-library directory, per run: the union and its branches are in different files. */\n private readonly indexes = new Map<string, ApiLibEnumIndex>();\n\n constructor(config: OneEnumSpellingInApiLibConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope, scanScope: ScanScope) {\n super(config, RULE_NAMES.ONE_ENUM_SPELLING_IN_API_LIB, roleResolver, diffScope, scanScope);\n }\n\n protected sitesIn(file: ApiLibFile): ApiLibSite[] {\n let index = this.indexes.get(file.projectDir);\n if (index === undefined) {\n index = ApiLibEnumIndex.of(file.projectDir);\n this.indexes.set(file.projectDir, index);\n }\n return this.scanner.scan(file, index);\n }\n\n protected why(): string {\n return `${ONE_SPELLING} — every member explicitly initialised with a string literal. Two spellings of one ` +\n 'thing is two things every reader and the document generator must understand, and a numeric enum puts ' +\n 'numbers on the wire.';\n }\n}\n"]}
@@ -25,6 +25,7 @@
25
25
  import { DiffScope, RequiredTypeSuffixConfig, RequiredTypeSuffixEntry } from '@webpieces/rules-config';
26
26
  import { ApiLibFile, ApiLibSite, ApiLibSourceRule } from './api-lib-source-rule';
27
27
  import { ProjectRoleResolver } from './project-role-resolver';
28
+ import { ScanScope } from './scan-scope';
28
29
  /** The entry that governs a file, and the glob of it that matched — named in every failure. Data-only. */
29
30
  export declare class GoverningGlob {
30
31
  readonly entry: RequiredTypeSuffixEntry;
@@ -66,7 +67,7 @@ export declare class ExportedTypeScanner {
66
67
  export declare class RequiredTypeSuffixValidator extends ApiLibSourceRule<RequiredTypeSuffixConfig> {
67
68
  private readonly picker;
68
69
  private readonly scanner;
69
- constructor(config: RequiredTypeSuffixConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope);
70
+ constructor(config: RequiredTypeSuffixConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope, scanScope: ScanScope);
70
71
  protected sitesIn(file: ApiLibFile): ApiLibSite[];
71
72
  /** Scoped by the configured entries' `paths` globs, not the role tag. */
72
73
  protected isApiLibrarySource(_workspaceRoot: string, relFile: string): boolean;
@@ -31,6 +31,7 @@ const inversify_1 = require("inversify");
31
31
  const ts = tslib_1.__importStar(require("typescript"));
32
32
  const api_lib_source_rule_1 = require("./api-lib-source-rule");
33
33
  const project_role_resolver_1 = require("./project-role-resolver");
34
+ const scan_scope_1 = require("./scan-scope");
34
35
  /** The entry that governs a file, and the glob of it that matched — named in every failure. Data-only. */
35
36
  class GoverningGlob {
36
37
  entry;
@@ -174,8 +175,8 @@ exports.ExportedTypeScanner = ExportedTypeScanner;
174
175
  let RequiredTypeSuffixValidator = class RequiredTypeSuffixValidator extends api_lib_source_rule_1.ApiLibSourceRule {
175
176
  picker = new SuffixEntryPicker();
176
177
  scanner = new ExportedTypeScanner();
177
- constructor(config, roleResolver, diffScope) {
178
- super(config, rules_config_1.RULE_NAMES.REQUIRED_TYPE_SUFFIX, roleResolver, diffScope);
178
+ constructor(config, roleResolver, diffScope, scanScope) {
179
+ super(config, rules_config_1.RULE_NAMES.REQUIRED_TYPE_SUFFIX, roleResolver, diffScope, scanScope);
179
180
  }
180
181
  sitesIn(file) {
181
182
  const winner = this.picker.winner(file.relFile, this.config.entries);
@@ -200,6 +201,9 @@ let RequiredTypeSuffixValidator = class RequiredTypeSuffixValidator extends api_
200
201
  exports.RequiredTypeSuffixValidator = RequiredTypeSuffixValidator;
201
202
  exports.RequiredTypeSuffixValidator = RequiredTypeSuffixValidator = tslib_1.__decorate([
202
203
  (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
203
- tslib_1.__metadata("design:paramtypes", [rules_config_1.RequiredTypeSuffixConfig, project_role_resolver_1.ProjectRoleResolver, rules_config_1.DiffScope])
204
+ tslib_1.__metadata("design:paramtypes", [rules_config_1.RequiredTypeSuffixConfig,
205
+ project_role_resolver_1.ProjectRoleResolver,
206
+ rules_config_1.DiffScope,
207
+ scan_scope_1.ScanScope])
204
208
  ], RequiredTypeSuffixValidator);
205
209
  //# sourceMappingURL=validate-required-type-suffix.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"validate-required-type-suffix.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-required-type-suffix.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;;;;AAEH,0DAMiC;AACjC,yCAA2D;AAC3D,uDAAiC;AACjC,+DAAiF;AACjF,mEAA8D;AAE9D,0GAA0G;AAC1G,MAAa,aAAa;IAET;IACA;IAFb,YACa,KAA8B,EAC9B,IAAY;QADZ,UAAK,GAAL,KAAK,CAAyB;QAC9B,SAAI,GAAJ,IAAI,CAAQ;IACtB,CAAC;CACP;AALD,sCAKC;AAED;;;;GAIG;AACH,MAAa,iBAAiB;IAC1B,Q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CAAC,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,SAAS,CAAC;IAC5E,CAAC;IAEkB,UAAU;QACzB,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,KAA8B,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QAC3F,OAAO,6CAA6C,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC;IAC5E,CAAC;IAES,GAAG;QACT,OAAO,yGAAyG;YAC5G,uGAAuG;YACvG,yFAAyF,CAAC;IAClG,CAAC;CACJ,CAAA;AA7BY,kEAA2B;sCAA3B,2BAA2B;IADvC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAKjB,uCAAwB,EAAgB,2CAAmB,EAAa,wBAAS;GAJ5F,2BAA2B,CA6BvC","sourcesContent":["/**\n * `required-type-suffix` (#1037) — a type's name says which layer it belongs to.\n *\n * Configured as a list of entries, each pairing path globs with the suffixes allowed there:\n *\n * { \"paths\": [\"libraries/apis/internal/**\"], \"suffixes\": [\"Request\", \"Response\", \"Event\", \"Dto\", \"Api\"] }\n * { \"paths\": [\"libraries/browser-node/fs-*-model/**\"], \"suffixes\": [\"Fs\"] }\n *\n * Every EXPORTED `interface`, `class` (abstract too), `enum` and `type` alias in a non-test `.ts` file under\n * an entry's paths must end in one of that entry's suffixes — a plain, case-sensitive `endsWith`, and the\n * suffix alone is not a name (`FooDto` passes; `FooDTO` and `Dto` fail). A non-exported, file-local type\n * is not judged, and neither is an exported `const` (a DI token's `Symbol` holder is not a type). A type\n * exported through a local `export { Foo as FooDto }` list is judged by the name it is exported AS.\n *\n * Why: in review a `…Dto` is a wire type and a `…Fs` a Firestore document, while `TopNamePlaceInput` reads\n * the same as a server-internal or vendor type. The suffix is the one place the layer can be stated.\n *\n * Overlapping entries: the FIRST entry in config order whose paths match governs a file\n * ({@link SuffixEntryPicker}), so a narrower entry must be listed before a broader one; suffixes are never\n * unioned across entries.\n *\n * Under NEW_AND_MODIFIED_CODE only a declaration whose NAME line is new or changed is judged — a new type\n * or a renamed one — so legacy names are grandfathered and a repo with hundreds of them can convert slowly.\n */\n\nimport {\n DiffScope,\n RULE_NAMES,\n RequiredTypeSuffixConfig,\n RequiredTypeSuffixEntry,\n matchesAnyGlob,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport * as ts from 'typescript';\nimport { ApiLibFile, ApiLibSite, ApiLibSourceRule } from './api-lib-source-rule';\nimport { ProjectRoleResolver } from './project-role-resolver';\n\n/** The entry that governs a file, and the glob of it that matched — named in every failure. Data-only. */\nexport class GoverningGlob {\n constructor(\n readonly entry: RequiredTypeSuffixEntry,\n readonly glob: string,\n ) {}\n}\n\n/**\n * Picks the ONE entry that governs a file: the FIRST entry, in config order, with a glob matching the\n * file. Order matters — to give a narrower directory stricter suffixes, list its entry ABOVE the broader\n * one; listed below, it never applies to the files the broader entry already covers.\n */\nexport class SuffixEntryPicker {\n entryFor(relFile: string, entries: readonly RequiredTypeSuffixEntry[]): RequiredTypeSuffixEntry | undefined {\n return this.winner(relFile, entries)?.entry;\n }\n\n /** The first matching entry (and its matching glob) for `relFile`, or undefined when no entry covers it. */\n winner(relFile: string, entries: readonly RequiredTypeSuffixEntry[]): GoverningGlob | undefined {\n for (const entry of entries) {\n const glob = entry.paths.find((g: string) => matchesAnyGlob(relFile, [g]));\n if (glob !== undefined) return new GoverningGlob(entry, glob);\n }\n return undefined;\n }\n}\n\n/** The rename a failure suggests: the name's layer-less tail swapped for each allowed suffix. */\nexport class SuffixRename {\n /**\n * Trailing words that name no layer, dropped before a suffix is appended (`TopNamePlaceInput` →\n * `TopNamePlaceDto`, not `TopNamePlaceInputDto`). Longest first, so `Object` wins over `Obj`.\n */\n private static readonly LAYERLESS_TAILS: readonly string[] = [\n 'Interface', 'Payload', 'Options', 'Object', 'Params', 'Output', 'Option', 'Record', 'Input', 'Model',\n 'Entry', 'Shape', 'Data', 'Info', 'Item', 'Type', 'Body', 'Row', 'Obj',\n ];\n\n /** Candidate names, one per allowed suffix, in the configured order. */\n candidates(name: string, suffixes: readonly string[]): string[] {\n const stem = this.stem(name, suffixes);\n return suffixes.map((suffix: string) => `${stem}${suffix}`);\n }\n\n private stem(name: string, suffixes: readonly string[]): string {\n // `FooDTO` → `Foo`: the suffix is there, in the wrong case.\n const wrongCase = suffixes.find((s: string) => name.length > s.length && name.toLowerCase().endsWith(s.toLowerCase()));\n if (wrongCase !== undefined) return name.slice(0, name.length - wrongCase.length);\n // `Dto` alone → `<Name>Dto`: there is no stem to keep.\n if (suffixes.includes(name)) return '<Name>';\n const tail = SuffixRename.LAYERLESS_TAILS.find((t: string) => name.length > t.length && name.endsWith(t));\n return tail === undefined ? name : name.slice(0, name.length - tail.length);\n }\n}\n\n/** Finds every exported type in one parsed file whose name does not end in the governing entry's suffixes. */\nexport class ExportedTypeScanner {\n private readonly rename = new SuffixRename();\n\n scan(file: ApiLibFile, entry: RequiredTypeSuffixEntry, glob: string): ApiLibSite[] {\n const sites: ApiLibSite[] = [];\n const locals = new Map<string, ts.DeclarationStatement>();\n for (const statement of file.source.statements) {\n const declared = this.typeDeclaration(statement);\n if (declared === undefined) continue;\n if (this.isExported(declared)) {\n const site = this.judge(file, declared, declared.name, declared.name?.getText(file.source) ?? '', entry, glob);\n if (site !== undefined) sites.push(site);\n } else if (declared.name !== undefined) {\n locals.set(declared.name.getText(file.source), declared);\n }\n }\n sites.push(...this.exportListSites(file, locals, entry, glob));\n return sites.sort((a: ApiLibSite, b: ApiLibSite) => a.line - b.line);\n }\n\n /** `export { Local as Exported }` of a local type: judged by the exported name, at the specifier. */\n private exportListSites(\n file: ApiLibFile,\n locals: ReadonlyMap<string, ts.DeclarationStatement>,\n entry: RequiredTypeSuffixEntry,\n glob: string,\n ): ApiLibSite[] {\n const sites: ApiLibSite[] = [];\n for (const statement of file.source.statements) {\n if (!ts.isExportDeclaration(statement) || statement.moduleSpecifier !== undefined) continue;\n if (statement.exportClause === undefined || !ts.isNamedExports(statement.exportClause)) continue;\n for (const element of statement.exportClause.elements) {\n const local = locals.get((element.propertyName ?? element.name).getText(file.source));\n if (local === undefined) continue;\n const site = this.judge(file, local, element.name, element.name.getText(file.source), entry, glob);\n if (site !== undefined) sites.push(site);\n }\n }\n return sites;\n }\n\n private typeDeclaration(statement: ts.Statement): ts.DeclarationStatement | undefined {\n if (ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement) ||\n ts.isEnumDeclaration(statement) || ts.isClassDeclaration(statement)) {\n return statement;\n }\n return undefined;\n }\n\n private isExported(statement: ts.DeclarationStatement): boolean {\n const modifiers = ts.canHaveModifiers(statement) ? ts.getModifiers(statement) ?? [] : [];\n return modifiers.some((m: ts.ModifierLike) => m.kind === ts.SyntaxKind.ExportKeyword);\n }\n\n private judge(\n file: ApiLibFile,\n declared: ts.DeclarationStatement,\n at: ts.Node | undefined,\n name: string,\n entry: RequiredTypeSuffixEntry,\n glob: string,\n ): ApiLibSite | undefined {\n // `export default class { … }` has no name to judge.\n if (at === undefined || name === '') return undefined;\n if (entry.suffixes.some((suffix: string) => name.length > suffix.length && name.endsWith(suffix))) return undefined;\n const kind = this.kindOf(declared);\n const allowed = entry.suffixes.join(' | ');\n const line = file.lineOf(at);\n const snippet = (file.source.text.split('\\n')[line - 1] ?? name).replace(/\\s+/g, ' ').trim();\n const what = `exported ${kind} \\`${name}\\` does not end in a suffix allowed under ${glob} (${allowed})`;\n const candidates = this.rename.candidates(name, entry.suffixes);\n const others = candidates.slice(1).map((c: string) => `\\`${c}\\``).join(' / ');\n const cure = `rename ${kind} \\`${name}\\` → \\`${candidates[0]}\\`` +\n (others === '' ? '' : ` (or ${others} — pick the suffix that names its layer, e.g. …Request for an endpoint body)`) +\n ` and update every reference. Allowed suffixes under ${glob}: ${allowed} — the suffix tells a reader ` +\n `which layer the type belongs to.`;\n return new ApiLibSite(line, snippet, what, cure);\n }\n\n private kindOf(declared: ts.DeclarationStatement): string {\n if (ts.isInterfaceDeclaration(declared)) return 'interface';\n if (ts.isEnumDeclaration(declared)) return 'enum';\n if (ts.isTypeAliasDeclaration(declared)) return 'type';\n return 'class';\n }\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class RequiredTypeSuffixValidator extends ApiLibSourceRule<RequiredTypeSuffixConfig> {\n private readonly picker = new SuffixEntryPicker();\n private readonly scanner = new ExportedTypeScanner();\n\n constructor(config: RequiredTypeSuffixConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope) {\n super(config, RULE_NAMES.REQUIRED_TYPE_SUFFIX, roleResolver, diffScope);\n }\n\n protected sitesIn(file: ApiLibFile): ApiLibSite[] {\n const winner = this.picker.winner(file.relFile, this.config.entries);\n if (winner === undefined) return [];\n return this.scanner.scan(file, winner.entry, winner.glob);\n }\n\n /** Scoped by the configured entries' `paths` globs, not the role tag. */\n protected override isApiLibrarySource(_workspaceRoot: string, relFile: string): boolean {\n return this.picker.entryFor(relFile, this.config.entries) !== undefined;\n }\n\n protected override scopeLabel(): string {\n const paths = this.config.entries.flatMap((entry: RequiredTypeSuffixEntry) => entry.paths);\n return `a directory required-type-suffix governs (${paths.join(', ')})`;\n }\n\n protected why(): string {\n return 'every exported interface / class / enum / type there must end in one of its path\\'s allowed suffixes — ' +\n 'the suffix tells a reader which layer a type belongs to (a …Dto is on the wire, a …Fs is a Firestore ' +\n 'document), where an unsuffixed name reads the same as a server-internal or vendor type.';\n }\n}\n"]}
1
+ {"version":3,"file":"validate-required-type-suffix.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-required-type-suffix.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;;;;AAEH,0DAMiC;AACjC,yCAA2D;AAC3D,uDAAiC;AACjC,+DAAiF;AACjF,mEAA8D;AAC9D,6CAAyC;AAEzC,0GAA0G;AAC1G,MAAa,aAAa;IAET;IACA;IAFb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OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;IAC9D,CAAC;IAED,yEAAyE;IACtD,kBAAkB,CAAC,cAAsB,EAAE,OAAe;QACzE,OAAO,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,SAAS,CAAC;IAC5E,CAAC;IAEkB,UAAU;QACzB,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,KAA8B,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QAC3F,OAAO,6CAA6C,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC;IAC5E,CAAC;IAES,GAAG;QACT,OAAO,yGAAyG;YAC5G,uGAAuG;YACvG,yFAAyF,CAAC;IAClG,CAAC;CACJ,CAAA;AAlCY,kEAA2B;sCAA3B,2BAA2B;IADvC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAMzB,uCAAwB;QAClB,2CAAmB;QACtB,wBAAS;QACT,sBAAS;GARf,2BAA2B,CAkCvC","sourcesContent":["/**\n * `required-type-suffix` (#1037) — a type's name says which layer it belongs to.\n *\n * Configured as a list of entries, each pairing path globs with the suffixes allowed there:\n *\n * { \"paths\": [\"libraries/apis/internal/**\"], \"suffixes\": [\"Request\", \"Response\", \"Event\", \"Dto\", \"Api\"] }\n * { \"paths\": [\"libraries/browser-node/fs-*-model/**\"], \"suffixes\": [\"Fs\"] }\n *\n * Every EXPORTED `interface`, `class` (abstract too), `enum` and `type` alias in a non-test `.ts` file under\n * an entry's paths must end in one of that entry's suffixes — a plain, case-sensitive `endsWith`, and the\n * suffix alone is not a name (`FooDto` passes; `FooDTO` and `Dto` fail). A non-exported, file-local type\n * is not judged, and neither is an exported `const` (a DI token's `Symbol` holder is not a type). A type\n * exported through a local `export { Foo as FooDto }` list is judged by the name it is exported AS.\n *\n * Why: in review a `…Dto` is a wire type and a `…Fs` a Firestore document, while `TopNamePlaceInput` reads\n * the same as a server-internal or vendor type. The suffix is the one place the layer can be stated.\n *\n * Overlapping entries: the FIRST entry in config order whose paths match governs a file\n * ({@link SuffixEntryPicker}), so a narrower entry must be listed before a broader one; suffixes are never\n * unioned across entries.\n *\n * Under NEW_AND_MODIFIED_CODE only a declaration whose NAME line is new or changed is judged — a new type\n * or a renamed one — so legacy names are grandfathered and a repo with hundreds of them can convert slowly.\n */\n\nimport {\n DiffScope,\n RULE_NAMES,\n RequiredTypeSuffixConfig,\n RequiredTypeSuffixEntry,\n matchesAnyGlob,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport * as ts from 'typescript';\nimport { ApiLibFile, ApiLibSite, ApiLibSourceRule } from './api-lib-source-rule';\nimport { ProjectRoleResolver } from './project-role-resolver';\nimport { ScanScope } from './scan-scope';\n\n/** The entry that governs a file, and the glob of it that matched — named in every failure. Data-only. */\nexport class GoverningGlob {\n constructor(\n readonly entry: RequiredTypeSuffixEntry,\n readonly glob: string,\n ) {}\n}\n\n/**\n * Picks the ONE entry that governs a file: the FIRST entry, in config order, with a glob matching the\n * file. Order matters — to give a narrower directory stricter suffixes, list its entry ABOVE the broader\n * one; listed below, it never applies to the files the broader entry already covers.\n */\nexport class SuffixEntryPicker {\n entryFor(relFile: string, entries: readonly RequiredTypeSuffixEntry[]): RequiredTypeSuffixEntry | undefined {\n return this.winner(relFile, entries)?.entry;\n }\n\n /** The first matching entry (and its matching glob) for `relFile`, or undefined when no entry covers it. */\n winner(relFile: string, entries: readonly RequiredTypeSuffixEntry[]): GoverningGlob | undefined {\n for (const entry of entries) {\n const glob = entry.paths.find((g: string) => matchesAnyGlob(relFile, [g]));\n if (glob !== undefined) return new GoverningGlob(entry, glob);\n }\n return undefined;\n }\n}\n\n/** The rename a failure suggests: the name's layer-less tail swapped for each allowed suffix. */\nexport class SuffixRename {\n /**\n * Trailing words that name no layer, dropped before a suffix is appended (`TopNamePlaceInput` →\n * `TopNamePlaceDto`, not `TopNamePlaceInputDto`). Longest first, so `Object` wins over `Obj`.\n */\n private static readonly LAYERLESS_TAILS: readonly string[] = [\n 'Interface', 'Payload', 'Options', 'Object', 'Params', 'Output', 'Option', 'Record', 'Input', 'Model',\n 'Entry', 'Shape', 'Data', 'Info', 'Item', 'Type', 'Body', 'Row', 'Obj',\n ];\n\n /** Candidate names, one per allowed suffix, in the configured order. */\n candidates(name: string, suffixes: readonly string[]): string[] {\n const stem = this.stem(name, suffixes);\n return suffixes.map((suffix: string) => `${stem}${suffix}`);\n }\n\n private stem(name: string, suffixes: readonly string[]): string {\n // `FooDTO` → `Foo`: the suffix is there, in the wrong case.\n const wrongCase = suffixes.find((s: string) => name.length > s.length && name.toLowerCase().endsWith(s.toLowerCase()));\n if (wrongCase !== undefined) return name.slice(0, name.length - wrongCase.length);\n // `Dto` alone → `<Name>Dto`: there is no stem to keep.\n if (suffixes.includes(name)) return '<Name>';\n const tail = SuffixRename.LAYERLESS_TAILS.find((t: string) => name.length > t.length && name.endsWith(t));\n return tail === undefined ? name : name.slice(0, name.length - tail.length);\n }\n}\n\n/** Finds every exported type in one parsed file whose name does not end in the governing entry's suffixes. */\nexport class ExportedTypeScanner {\n private readonly rename = new SuffixRename();\n\n scan(file: ApiLibFile, entry: RequiredTypeSuffixEntry, glob: string): ApiLibSite[] {\n const sites: ApiLibSite[] = [];\n const locals = new Map<string, ts.DeclarationStatement>();\n for (const statement of file.source.statements) {\n const declared = this.typeDeclaration(statement);\n if (declared === undefined) continue;\n if (this.isExported(declared)) {\n const site = this.judge(file, declared, declared.name, declared.name?.getText(file.source) ?? '', entry, glob);\n if (site !== undefined) sites.push(site);\n } else if (declared.name !== undefined) {\n locals.set(declared.name.getText(file.source), declared);\n }\n }\n sites.push(...this.exportListSites(file, locals, entry, glob));\n return sites.sort((a: ApiLibSite, b: ApiLibSite) => a.line - b.line);\n }\n\n /** `export { Local as Exported }` of a local type: judged by the exported name, at the specifier. */\n private exportListSites(\n file: ApiLibFile,\n locals: ReadonlyMap<string, ts.DeclarationStatement>,\n entry: RequiredTypeSuffixEntry,\n glob: string,\n ): ApiLibSite[] {\n const sites: ApiLibSite[] = [];\n for (const statement of file.source.statements) {\n if (!ts.isExportDeclaration(statement) || statement.moduleSpecifier !== undefined) continue;\n if (statement.exportClause === undefined || !ts.isNamedExports(statement.exportClause)) continue;\n for (const element of statement.exportClause.elements) {\n const local = locals.get((element.propertyName ?? element.name).getText(file.source));\n if (local === undefined) continue;\n const site = this.judge(file, local, element.name, element.name.getText(file.source), entry, glob);\n if (site !== undefined) sites.push(site);\n }\n }\n return sites;\n }\n\n private typeDeclaration(statement: ts.Statement): ts.DeclarationStatement | undefined {\n if (ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement) ||\n ts.isEnumDeclaration(statement) || ts.isClassDeclaration(statement)) {\n return statement;\n }\n return undefined;\n }\n\n private isExported(statement: ts.DeclarationStatement): boolean {\n const modifiers = ts.canHaveModifiers(statement) ? ts.getModifiers(statement) ?? [] : [];\n return modifiers.some((m: ts.ModifierLike) => m.kind === ts.SyntaxKind.ExportKeyword);\n }\n\n private judge(\n file: ApiLibFile,\n declared: ts.DeclarationStatement,\n at: ts.Node | undefined,\n name: string,\n entry: RequiredTypeSuffixEntry,\n glob: string,\n ): ApiLibSite | undefined {\n // `export default class { … }` has no name to judge.\n if (at === undefined || name === '') return undefined;\n if (entry.suffixes.some((suffix: string) => name.length > suffix.length && name.endsWith(suffix))) return undefined;\n const kind = this.kindOf(declared);\n const allowed = entry.suffixes.join(' | ');\n const line = file.lineOf(at);\n const snippet = (file.source.text.split('\\n')[line - 1] ?? name).replace(/\\s+/g, ' ').trim();\n const what = `exported ${kind} \\`${name}\\` does not end in a suffix allowed under ${glob} (${allowed})`;\n const candidates = this.rename.candidates(name, entry.suffixes);\n const others = candidates.slice(1).map((c: string) => `\\`${c}\\``).join(' / ');\n const cure = `rename ${kind} \\`${name}\\` → \\`${candidates[0]}\\`` +\n (others === '' ? '' : ` (or ${others} — pick the suffix that names its layer, e.g. …Request for an endpoint body)`) +\n ` and update every reference. Allowed suffixes under ${glob}: ${allowed} — the suffix tells a reader ` +\n `which layer the type belongs to.`;\n return new ApiLibSite(line, snippet, what, cure);\n }\n\n private kindOf(declared: ts.DeclarationStatement): string {\n if (ts.isInterfaceDeclaration(declared)) return 'interface';\n if (ts.isEnumDeclaration(declared)) return 'enum';\n if (ts.isTypeAliasDeclaration(declared)) return 'type';\n return 'class';\n }\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class RequiredTypeSuffixValidator extends ApiLibSourceRule<RequiredTypeSuffixConfig> {\n private readonly picker = new SuffixEntryPicker();\n private readonly scanner = new ExportedTypeScanner();\n\n constructor(\n config: RequiredTypeSuffixConfig,\n roleResolver: ProjectRoleResolver,\n diffScope: DiffScope,\n scanScope: ScanScope,\n ) {\n super(config, RULE_NAMES.REQUIRED_TYPE_SUFFIX, roleResolver, diffScope, scanScope);\n }\n\n protected sitesIn(file: ApiLibFile): ApiLibSite[] {\n const winner = this.picker.winner(file.relFile, this.config.entries);\n if (winner === undefined) return [];\n return this.scanner.scan(file, winner.entry, winner.glob);\n }\n\n /** Scoped by the configured entries' `paths` globs, not the role tag. */\n protected override isApiLibrarySource(_workspaceRoot: string, relFile: string): boolean {\n return this.picker.entryFor(relFile, this.config.entries) !== undefined;\n }\n\n protected override scopeLabel(): string {\n const paths = this.config.entries.flatMap((entry: RequiredTypeSuffixEntry) => entry.paths);\n return `a directory required-type-suffix governs (${paths.join(', ')})`;\n }\n\n protected why(): string {\n return 'every exported interface / class / enum / type there must end in one of its path\\'s allowed suffixes — ' +\n 'the suffix tells a reader which layer a type belongs to (a …Dto is on the wire, a …Fs is a Firestore ' +\n 'document), where an unsuffixed name reads the same as a server-internal or vendor type.';\n }\n}\n"]}
package/src/wp-ci.d.ts CHANGED
@@ -8,8 +8,8 @@
8
8
  *
9
9
  * - no nx.json (non-Nx repo) -> run the standalone code validators, succeed.
10
10
  * - nx.json present, plugin NOT in it -> fail with the exact install command.
11
- * - nx.json present, plugin registered -> run validators (incl. the wiring guard),
12
- * then `nx affected --target=ci`.
11
+ * - nx.json present, plugin registered -> normal branch: validators + affected `ci`;
12
+ * `/hotfix/` branch: affected `hotfix-ci` (build + test only).
13
13
  *
14
14
  * Repos reference this as a bin (`"webpieces:ci": "wp-ci"`) so the logic is versioned in
15
15
  * the npm package instead of copy-pasted into each repo's package.json (which drifts).
package/src/wp-ci.js CHANGED
@@ -9,8 +9,8 @@
9
9
  *
10
10
  * - no nx.json (non-Nx repo) -> run the standalone code validators, succeed.
11
11
  * - nx.json present, plugin NOT in it -> fail with the exact install command.
12
- * - nx.json present, plugin registered -> run validators (incl. the wiring guard),
13
- * then `nx affected --target=ci`.
12
+ * - nx.json present, plugin registered -> normal branch: validators + affected `ci`;
13
+ * `/hotfix/` branch: affected `hotfix-ci` (build + test only).
14
14
  *
15
15
  * Repos reference this as a bin (`"webpieces:ci": "wp-ci"`) so the logic is versioned in
16
16
  * the npm package instead of copy-pasted into each repo's package.json (which drifts).
@@ -109,15 +109,20 @@ async function main() {
109
109
  }
110
110
  const gracePeriod = new wp_ci_survivors_1.GracePeriodResolver().resolve(process.env);
111
111
  const runner = new wp_ci_nx_runner_1.NxStepRunner(root, gracePeriod, new wp_ci_survivors_1.SurvivorWatchdog(new wp_ci_survivors_1.ProcessGroupScanner(), SURVIVOR_POLL_INTERVAL_MILLIS), new wp_ci_survivors_1.SurvivorReporter(), new wp_ci_survivors_1.ProcessGroupKiller());
112
+ const hotfix = new rules_config_1.BranchIdentity().isHotfix();
112
113
  // Run the architecture + code validators first (this also runs the wiring guard,
113
114
  // which fails loudly if nx.json no longer wires validators into the build).
114
- if (fs.existsSync(path.join(root, 'architecture'))) {
115
+ if (!hotfix && fs.existsSync(path.join(root, 'architecture'))) {
115
116
  const validateCode = await runner.run(['run', 'architecture:validate-complete'], 'architecture:validate-complete');
117
+ // webpieces-disable no-process-exit-outside-main -- this file's main() is the wp-ci bin boundary
116
118
  if (validateCode !== 0)
117
119
  process.exit(validateCode);
118
120
  }
119
- // Then the Gradle-style ci composite (lint + build + test) across affected projects.
120
- const ciCode = await runner.run(['affected', '--target=ci', ...passthrough], 'nx affected --target=ci');
121
+ // Hotfix deliberately schedules only compile/typecheck + tests. The shared branch resolver makes
122
+ // this the same decision the local PR gate makes, including detached GitHub checkouts.
123
+ const target = hotfix ? 'hotfix-ci' : 'ci';
124
+ const ciCode = await runner.run(['affected', `--target=${target}`, ...passthrough], `nx affected --target=${target}`);
125
+ // webpieces-disable no-process-exit-outside-main -- this file's main() is the wp-ci bin boundary
121
126
  process.exit(ciCode);
122
127
  }
123
128
  catch (err) {
@@ -131,6 +136,7 @@ async function main() {
131
136
  else {
132
137
  console.error(`[wp-ci] unexpected error: ${error.message}`);
133
138
  }
139
+ // webpieces-disable no-process-exit-outside-main -- this file's main() is the wp-ci bin boundary
134
140
  process.exit(1);
135
141
  }
136
142
  }