@webpieces/code-rules 0.4.844 → 0.4.846

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 (135) hide show
  1. package/package.json +6 -6
  2. package/src/api-lib-source-rule.d.ts +4 -1
  3. package/src/api-lib-source-rule.js.map +1 -1
  4. package/src/code-rules-bootstrap.js +8 -7
  5. package/src/code-rules-bootstrap.js.map +1 -1
  6. package/src/code-rules-config-table.d.ts +9 -11
  7. package/src/code-rules-config-table.js +48 -33
  8. package/src/code-rules-config-table.js.map +1 -1
  9. package/src/configs/api-lib-spelling-configs.d.ts +40 -0
  10. package/src/configs/api-lib-spelling-configs.js +52 -0
  11. package/src/configs/api-lib-spelling-configs.js.map +1 -0
  12. package/src/configs/no-client-creation-config.d.ts +12 -0
  13. package/src/configs/no-client-creation-config.js +40 -0
  14. package/src/configs/no-client-creation-config.js.map +1 -0
  15. package/src/configs/no-state-paths-config.d.ts +41 -0
  16. package/src/configs/no-state-paths-config.js +51 -0
  17. package/src/configs/no-state-paths-config.js.map +1 -0
  18. package/src/configs/no-utility-types-config.d.ts +30 -0
  19. package/src/configs/no-utility-types-config.js +39 -0
  20. package/src/configs/no-utility-types-config.js.map +1 -0
  21. package/src/configs/required-type-suffix-config.d.ts +49 -0
  22. package/src/configs/required-type-suffix-config.js +62 -0
  23. package/src/configs/required-type-suffix-config.js.map +1 -0
  24. package/src/configs/rule-configs.d.ts +131 -0
  25. package/src/configs/rule-configs.js +309 -0
  26. package/src/configs/rule-configs.js.map +1 -0
  27. package/src/configs/tag-truth-configs.d.ts +66 -0
  28. package/src/configs/tag-truth-configs.js +82 -0
  29. package/src/configs/tag-truth-configs.js.map +1 -0
  30. package/src/index.d.ts +10 -0
  31. package/src/index.js +50 -1
  32. package/src/index.js.map +1 -1
  33. package/src/project-scan-targets.d.ts +2 -1
  34. package/src/project-scan-targets.js.map +1 -1
  35. package/src/rule-pack.d.ts +1 -0
  36. package/src/rule-pack.js +4 -35
  37. package/src/rule-pack.js.map +1 -1
  38. package/src/rule-settings.d.ts +5 -0
  39. package/src/rule-settings.js +269 -0
  40. package/src/rule-settings.js.map +1 -0
  41. package/src/scan-scope.d.ts +2 -1
  42. package/src/scan-scope.js.map +1 -1
  43. package/src/tag-rule.d.ts +1 -1
  44. package/src/tag-rule.js.map +1 -1
  45. package/src/validate-catch-error-pattern.d.ts +1 -1
  46. package/src/validate-catch-error-pattern.js +4 -3
  47. package/src/validate-catch-error-pattern.js.map +1 -1
  48. package/src/validate-dtos.d.ts +1 -1
  49. package/src/validate-dtos.js +2 -1
  50. package/src/validate-dtos.js.map +1 -1
  51. package/src/validate-ensure-we-are-secure.d.ts +2 -1
  52. package/src/validate-ensure-we-are-secure.js +3 -2
  53. package/src/validate-ensure-we-are-secure.js.map +1 -1
  54. package/src/validate-framework-packages.d.ts +2 -1
  55. package/src/validate-framework-packages.js +7 -6
  56. package/src/validate-framework-packages.js.map +1 -1
  57. package/src/validate-framework-tag.d.ts +1 -1
  58. package/src/validate-framework-tag.js +2 -2
  59. package/src/validate-framework-tag.js.map +1 -1
  60. package/src/validate-framework-tsconfig.d.ts +2 -1
  61. package/src/validate-framework-tsconfig.js +5 -4
  62. package/src/validate-framework-tsconfig.js.map +1 -1
  63. package/src/validate-inject-annotation-not-needed-for-concrete-class.d.ts +1 -1
  64. package/src/validate-inject-annotation-not-needed-for-concrete-class.js +3 -2
  65. package/src/validate-inject-annotation-not-needed-for-concrete-class.js.map +1 -1
  66. package/src/validate-match-rules.d.ts +1 -1
  67. package/src/validate-match-rules.js.map +1 -1
  68. package/src/validate-modified-files.d.ts +2 -1
  69. package/src/validate-modified-files.js +3 -2
  70. package/src/validate-modified-files.js.map +1 -1
  71. package/src/validate-modified-methods.d.ts +1 -1
  72. package/src/validate-modified-methods.js +4 -3
  73. package/src/validate-modified-methods.js.map +1 -1
  74. package/src/validate-new-methods.d.ts +1 -1
  75. package/src/validate-new-methods.js +1 -1
  76. package/src/validate-new-methods.js.map +1 -1
  77. package/src/validate-no-any-unknown.d.ts +1 -1
  78. package/src/validate-no-any-unknown.js +3 -2
  79. package/src/validate-no-any-unknown.js.map +1 -1
  80. package/src/validate-no-client-creation-outside-server-or-client.d.ts +1 -1
  81. package/src/validate-no-client-creation-outside-server-or-client.js +3 -2
  82. package/src/validate-no-client-creation-outside-server-or-client.js.map +1 -1
  83. package/src/validate-no-custom-css.d.ts +1 -1
  84. package/src/validate-no-custom-css.js +3 -2
  85. package/src/validate-no-custom-css.js.map +1 -1
  86. package/src/validate-no-destructure.d.ts +1 -1
  87. package/src/validate-no-destructure.js +3 -2
  88. package/src/validate-no-destructure.js.map +1 -1
  89. package/src/validate-no-direct-api-resolver.d.ts +1 -1
  90. package/src/validate-no-direct-api-resolver.js +3 -2
  91. package/src/validate-no-direct-api-resolver.js.map +1 -1
  92. package/src/validate-no-function-outside-class.d.ts +1 -1
  93. package/src/validate-no-function-outside-class.js +4 -3
  94. package/src/validate-no-function-outside-class.js.map +1 -1
  95. package/src/validate-no-implicit-any.d.ts +1 -1
  96. package/src/validate-no-implicit-any.js +3 -2
  97. package/src/validate-no-implicit-any.js.map +1 -1
  98. package/src/validate-no-inline-import-in-api-lib.d.ts +2 -1
  99. package/src/validate-no-inline-import-in-api-lib.js +3 -2
  100. package/src/validate-no-inline-import-in-api-lib.js.map +1 -1
  101. package/src/validate-no-inline-types.d.ts +1 -1
  102. package/src/validate-no-inline-types.js +3 -2
  103. package/src/validate-no-inline-types.js.map +1 -1
  104. package/src/validate-no-process-exit-outside-main.d.ts +1 -1
  105. package/src/validate-no-process-exit-outside-main.js +3 -2
  106. package/src/validate-no-process-exit-outside-main.js.map +1 -1
  107. package/src/validate-no-state-paths-in-templates.d.ts +1 -1
  108. package/src/validate-no-state-paths-in-templates.js +7 -6
  109. package/src/validate-no-state-paths-in-templates.js.map +1 -1
  110. package/src/validate-no-symbol-di-tokens.d.ts +1 -1
  111. package/src/validate-no-symbol-di-tokens.js +3 -2
  112. package/src/validate-no-symbol-di-tokens.js.map +1 -1
  113. package/src/validate-no-unmanaged-exceptions.d.ts +1 -1
  114. package/src/validate-no-unmanaged-exceptions.js +3 -2
  115. package/src/validate-no-unmanaged-exceptions.js.map +1 -1
  116. package/src/validate-no-utility-types-in-api-lib.d.ts +2 -1
  117. package/src/validate-no-utility-types-in-api-lib.js +3 -2
  118. package/src/validate-no-utility-types-in-api-lib.js.map +1 -1
  119. package/src/validate-one-enum-spelling-in-api-lib.d.ts +2 -1
  120. package/src/validate-one-enum-spelling-in-api-lib.js +3 -2
  121. package/src/validate-one-enum-spelling-in-api-lib.js.map +1 -1
  122. package/src/validate-prisma-converters.d.ts +1 -1
  123. package/src/validate-prisma-converters.js +3 -2
  124. package/src/validate-prisma-converters.js.map +1 -1
  125. package/src/validate-required-type-suffix.d.ts +2 -1
  126. package/src/validate-required-type-suffix.js +3 -2
  127. package/src/validate-required-type-suffix.js.map +1 -1
  128. package/src/validate-return-types.d.ts +1 -1
  129. package/src/validate-return-types.js +3 -2
  130. package/src/validate-return-types.js.map +1 -1
  131. package/src/validate-role-tag.d.ts +1 -1
  132. package/src/validate-role-tag.js +2 -2
  133. package/src/validate-role-tag.js.map +1 -1
  134. package/src/wp-ci.js +2 -2
  135. package/src/wp-ci.js.map +1 -1
@@ -47,6 +47,7 @@ const tslib_1 = require("tslib");
47
47
  const fs = tslib_1.__importStar(require("fs"));
48
48
  const path = tslib_1.__importStar(require("path"));
49
49
  const rules_config_1 = require("@webpieces/rules-config");
50
+ const no_state_paths_config_1 = require("./configs/no-state-paths-config");
50
51
  const inversify_1 = require("inversify");
51
52
  const code_validator_1 = require("./code-validator");
52
53
  const resolve_mode_1 = require("./resolve-mode");
@@ -82,7 +83,7 @@ exports.StatePathHit = StatePathHit;
82
83
  let NoStatePathsInTemplatesValidator = class NoStatePathsInTemplatesValidator extends code_validator_1.CodeValidator {
83
84
  scanScope;
84
85
  constructor(config, scanScope) {
85
- super(config, rules_config_1.RULE_NAMES.NO_STATE_PATHS_IN_TEMPLATES, rules_config_1.RULE_NAMES.NO_STATE_PATHS_IN_TEMPLATES);
86
+ super(config, "no-state-paths-in-templates", "no-state-paths-in-templates");
86
87
  this.scanScope = scanScope;
87
88
  }
88
89
  async run(workspaceRoot) {
@@ -136,7 +137,7 @@ let NoStatePathsInTemplatesValidator = class NoStatePathsInTemplatesValidator ex
136
137
  const detail = violations.map((violation) => ` ${violation.file}:${String(violation.line)}:${String(violation.column)} restates \`${violation.detail}…\``)
137
138
  .join('\n');
138
139
  const first = violations[0];
139
- return new rules_config_1.RuleFailError(rules_config_1.RULE_NAMES.NO_STATE_PATHS_IN_TEMPLATES, 'A generated-doc template RESTATES a webpieces state path instead of computing it. These docs are '
140
+ return new rules_config_1.RuleFailError("no-state-paths-in-templates", 'A generated-doc template RESTATES a webpieces state path instead of computing it. These docs are '
140
141
  + 'regenerated into every governed repo and handed to an agent by absolute path AS INSTRUCTION, and '
141
142
  + 'every .webpieces/ path is per-tree — a linked worktree keeps its state under '
142
143
  + `<primary>/.webpieces/worktrees/<name>/ — so the relative spelling names a file that DOES NOT EXIST `
@@ -230,17 +231,17 @@ let NoStatePathsInTemplatesValidator = class NoStatePathsInTemplatesValidator ex
230
231
  return this.findHits(fs.readFileSync(fullPath, 'utf-8'));
231
232
  }
232
233
  templateDirs() {
233
- const dirs = this.config.templateDirs ?? rules_config_1.DEFAULT_TEMPLATE_DIRS;
234
+ const dirs = this.config.templateDirs ?? no_state_paths_config_1.DEFAULT_TEMPLATE_DIRS;
234
235
  return dirs.map((dir) => dir.replace(/\\/g, '/').replace(/\/+$/, ''));
235
236
  }
236
237
  bannedPrefixes() {
237
- return this.config.bannedPathPrefixes ?? rules_config_1.DEFAULT_BANNED_STATE_PATH_PREFIXES;
238
+ return this.config.bannedPathPrefixes ?? no_state_paths_config_1.DEFAULT_BANNED_STATE_PATH_PREFIXES;
238
239
  }
239
240
  /** True if a `webpieces-disable no-state-paths-in-templates` sits on this line or up to 3 above. */
240
241
  hasDisableComment(lines, lineNumber) {
241
242
  const start = Math.max(0, lineNumber - 4);
242
243
  for (let i = lineNumber - 1; i >= start; i--) {
243
- if ((0, rules_config_1.hasDisable)(lines[i] ?? '', rules_config_1.RULE_NAMES.NO_STATE_PATHS_IN_TEMPLATES))
244
+ if ((0, rules_config_1.hasDisable)(lines[i] ?? '', "no-state-paths-in-templates"))
244
245
  return true;
245
246
  }
246
247
  return false;
@@ -259,6 +260,6 @@ let NoStatePathsInTemplatesValidator = class NoStatePathsInTemplatesValidator ex
259
260
  exports.NoStatePathsInTemplatesValidator = NoStatePathsInTemplatesValidator;
260
261
  exports.NoStatePathsInTemplatesValidator = NoStatePathsInTemplatesValidator = tslib_1.__decorate([
261
262
  (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
262
- tslib_1.__metadata("design:paramtypes", [rules_config_1.NoStatePathsInTemplatesConfig, scan_scope_1.ScanScope])
263
+ tslib_1.__metadata("design:paramtypes", [no_state_paths_config_1.NoStatePathsInTemplatesConfig, scan_scope_1.ScanScope])
263
264
  ], NoStatePathsInTemplatesValidator);
264
265
  //# sourceMappingURL=validate-no-state-paths-in-templates.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"validate-no-state-paths-in-templates.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-state-paths-in-templates.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,0DAYiC;AACjC,yCAA2D;AAE3D,qDAAiE;AACjE,iDAAgD;AAChD,6CAAyC;AAEzC,sDAAsD;AACtD,MAAa,kBAAkB;IAEd;IACA;IACA;IACA;IAJb,YACa,IAAY,EACZ,IAAY,EACZ,MAAc,EACd,MAAc;QAHd,SAAI,GAAJ,IAAI,CAAQ;QACZ,SAAI,GAAJ,IAAI,CAAQ;QACZ,WAAM,GAAN,MAAM,CAAQ;QACd,WAAM,GAAN,MAAM,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,CAAC,EAAE,EAAE,CAAC;YAC3C,IAAI,IAAA,yBAAU,EAAC,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EAAE,yBAAU,CAAC,2BAA2B,CAAC;gBAAE,OAAO,IAAI,CAAC;QACxF,CAAC;QACD,OAAO,KAAK,CAAC;IACjB,CAAC;IAEO,WAAW,CACf,UAA4B,EAC5B,KAAyB,EACzB,aAAiC;QAEjC,IAAI,UAAU,KAAK,KAAK;YAAE,OAAO,UAAU,CAAC;QAC5C,MAAM,IAAI,GAAG,IAAA,6BAAc,EAAC,KAAK,EAAE,aAAa,CAAC,CAAC;QAClD,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;YACZ,OAAO,CAAC,GAAG,CAAC,0DAA0D,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC;YACxF,OAAO,KAAK,CAAC;QACjB,CAAC;QACD,OAAO,UAAU,CAAC;IACtB,CAAC;CACJ,CAAA;AA7MY,4EAAgC;2CAAhC,gCAAgC;IAD5C,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEjB,4CAA6B,EAA8B,sBAAS;GAD/E,gCAAgC,CA6M5C","sourcesContent":["/**\n * Validate No State Paths In Templates\n *\n * FAILS when a GENERATED-doc template restates a webpieces state path (`.webpieces/…`) as a literal\n * instead of rendering it from the resolver that already computes it.\n *\n * ## The incident this exists for\n *\n * `webpieces.git-workflow.md` — an AI-instruction doc regenerated into `.webpieces/instruct-ai/` of\n * every governed repo on every `wp-*` command — carried the literal\n * `.webpieces/logs/branch-mutations.log`. That log is deliberately PER-WORKTREE (one appender each):\n *\n * primary clone → `<primary>/.webpieces/logs/branch-mutations.log`\n * linked worktree → `<primary>/.webpieces/worktrees/<name>/logs/branch-mutations.log`\n *\n * So in a linked worktree the doc named a file that DOES NOT EXIST. The reader greps nothing, and the\n * silence reads as \"no deletions were logged\" — the opposite of the truth, from the one file whose\n * entire job is to prove every deletion is recoverable.\n *\n * The cure is not \"fix that line\". Every one of these paths already has a resolver, and the template\n * engine already substitutes (`{{MERGE_DIR}}`, `{{RUN_STATE}}`, `{{BRANCH_MUTATION_LOG}}` …). This\n * rule makes RESTATING the thing that fails and RENDERING the thing that passes, so the next one\n * cannot land.\n *\n * ## Scope\n *\n * `templateDirs` (workspace-relative dirs, recursive, `.md` only) — default\n * `packages/tooling/rules-config/templates`. A repo that generates no AI docs matches no files and the\n * rule is a no-op. Deliberately NOT widened to `backlog/**` (frozen records of past requests — editing\n * them falsifies the record) or to hand-written docs that name a FILE rather than a path.\n *\n * MODES: OFF | NEW_AND_MODIFIED_CODE (changed lines only) | NEW_AND_MODIFIED_FILES (whole changed file)\n * | MODIFIED_PROJECTS / RUN_EVERY_TIME (whole files of every touched project / of the repo — #1027).\n * Diff-scoped by default, so the docs whose SUBJECT is the layout (they print both rows on purpose)\n * are not retroactively flooded — the rule bites when a template is next edited.\n *\n * ESCAPE HATCH (this table IS the layout, and printing it is the point):\n * <!-- webpieces-disable no-state-paths-in-templates -- <reason> -->\n *\n * `~/.webpieces/…` is NOT a violation: the machine-local tier has no per-tree resolver and no\n * per-tree answer, so the literal is the correct and only spelling of it.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport {\n hasDisable,\n RULE_NAMES,\n NoStatePathsInTemplatesConfig,\n Option,\n RuleFailError,\n DEFAULT_TEMPLATE_DIRS,\n DEFAULT_BANNED_STATE_PATH_PREFIXES,\n ModifiedCodeMode,\n detectBase,\n getFileDiff,\n getChangedLineNumbers,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { shouldSkipRule } from './resolve-mode';\nimport { ScanScope } from './scan-scope';\n\n/** One restated state path, located in a template. */\nexport class StatePathViolation {\n constructor(\n readonly file: string,\n readonly line: number,\n readonly column: number,\n readonly detail: string,\n ) {}\n}\n\n/** One restated state path within a single file, plus whether its line carries a disable. */\nexport class StatePathHit {\n constructor(\n readonly line: number,\n readonly column: number,\n readonly detail: string,\n readonly hasDisableComment: boolean,\n ) {}\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoStatePathsInTemplatesValidator extends CodeValidator<NoStatePathsInTemplatesConfig> {\n constructor(config: NoStatePathsInTemplatesConfig, private readonly scanScope: ScanScope) {\n super(config, RULE_NAMES.NO_STATE_PATHS_IN_TEMPLATES, RULE_NAMES.NO_STATE_PATHS_IN_TEMPLATES);\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n const opts = this.config;\n const mode = this.resolveMode(\n opts.mode ?? 'NEW_AND_MODIFIED_CODE', opts.turnOffRuleUntilEpoch, opts.turnOffRuleWhileOnBranch ?? undefined);\n const disableAllowed = opts.disableAllowed ?? true;\n if (mode === 'OFF') {\n console.log('\\n⏭️ Skipping no-state-paths-in-templates validation (mode: OFF)\\n');\n return { success: true };\n }\n\n console.log('\\n📏 Validating No State Paths In Templates\\n');\n console.log(` Mode: ${mode}`);\n\n let base = process.env['NX_BASE'];\n const head = process.env['NX_HEAD'];\n if (base === undefined || base === '') {\n base = detectBase(workspaceRoot) ?? undefined;\n if (base === undefined || base === '') {\n console.log('\\n⏭️ Skipping no-state-paths-in-templates validation (could not detect base branch)\\n');\n return { success: true };\n }\n }\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}\\n`);\n\n const changedFiles = this.scanScope.files(workspaceRoot, mode, base, head, { tsOnly: false })\n .filter((file: string): boolean => this.isRelevantFile(file));\n if (changedFiles.length === 0) {\n console.log('✅ No generated-doc templates changed');\n return { success: true };\n }\n console.log(`📂 Checking ${String(changedFiles.length)} changed template(s)...`);\n\n const violations = this.scanScope.isLineScoped(mode)\n ? this.violationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed)\n : this.violationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);\n\n if (violations.length === 0) {\n console.log('✅ No hard-coded state paths in generated-doc templates');\n return { success: true };\n }\n this.scanScope.recordSites(this.name, violations.map((v: StatePathViolation) => v.file));\n throw this.failure(violations, mode);\n }\n\n /**\n * The ONE spelling of \"this validator failed\": a thrown {@link RuleFailError} carrying its cures as\n * `Option[]`, which {@link RuleReporter} catches and renders.\n *\n * NOT `console.error` + `{ success: false }`. That pair is a second spelling of the same fact (see\n * RuleReporter.runValidators, which calls it a back-compat shim scheduled for deletion), and\n * hand-written \"To fix: … / Escape hatch: …\" prose is a second spelling of `Option[]` — the\n * framework owns the `Fix Option N:` numbering and the `(preferred)` tag, so a rule never writes them.\n */\n private failure(violations: StatePathViolation[], mode: ModifiedCodeMode): RuleFailError {\n const detail = violations.map((violation: StatePathViolation): string =>\n ` ${violation.file}:${String(violation.line)}:${String(violation.column)} restates \\`${violation.detail}…\\``)\n .join('\\n');\n const first = violations[0];\n return new RuleFailError(\n RULE_NAMES.NO_STATE_PATHS_IN_TEMPLATES,\n 'A generated-doc template RESTATES a webpieces state path instead of computing it. These docs are '\n + 'regenerated into every governed repo and handed to an agent by absolute path AS INSTRUCTION, and '\n + 'every .webpieces/ path is per-tree — a linked worktree keeps its state under '\n + `<primary>/.webpieces/worktrees/<name>/ — so the relative spelling names a file that DOES NOT EXIST `\n + `in half the trees that read it. Current mode: ${mode}.\\n${detail}`,\n first?.line,\n first?.detail,\n [\n new Option(\n 'Put a {{PLACEHOLDER}} in the template and render it from the resolver that already computes '\n + 'that path, the way {{BRANCH_MUTATION_LOG}} is rendered from '\n + 'BranchMutationLog.branchMutationLogPath(root) in GitWorkflowDoc.render',\n true),\n new Option(\n 'If the doc\\'s SUBJECT is the layout and printing the literal is the point, say so out loud:\\n'\n + '<!-- webpieces-disable no-state-paths-in-templates -- <reason> -->'),\n ],\n );\n }\n\n /**\n * A changed file this rule looks at: a `.md` under one of the configured template dirs.\n *\n * The ONE place the file set is narrowed, so both modes run over the same list and a scope change\n * cannot be applied in one and forgotten in the other.\n */\n isRelevantFile(file: string): boolean {\n const norm = file.replace(/\\\\/g, '/');\n if (!norm.endsWith('.md')) return false;\n return this.templateDirs().some((dir: string): boolean => norm.startsWith(`${dir}/`));\n }\n\n /** Every restated state path in `text`, one hit per line (the first match on that line). */\n findHits(text: string): StatePathHit[] {\n const lines = text.split('\\n');\n const hits: StatePathHit[] = [];\n for (let i = 0; i < lines.length; i++) {\n const raw = lines[i] ?? '';\n for (const prefix of this.bannedPrefixes()) {\n const column = this.columnOf(raw, prefix);\n if (column < 0) continue;\n hits.push(new StatePathHit(i + 1, column + 1, prefix, this.hasDisableComment(lines, i + 1)));\n break;\n }\n }\n return hits;\n }\n\n /**\n * Where `prefix` is restated in `raw`, or -1.\n *\n * `~/.webpieces/…` is skipped: the machine-local tier is the same absolute path from every tree, so\n * there is no resolver to call and the literal is the only spelling there is. Everything else —\n * including the bare relative form that started this — is a restatement of a per-tree path.\n */\n private columnOf(raw: string, prefix: string): number {\n let from = 0;\n for (;;) {\n const at = raw.indexOf(prefix, from);\n if (at < 0) return -1;\n if (raw.slice(Math.max(0, at - 2), at) !== '~/') return at;\n from = at + 1;\n }\n }\n\n /** NEW_AND_MODIFIED_CODE: only hits whose line is in the diff hunks. */\n private violationsForModifiedCode(\n workspaceRoot: string,\n changedFiles: string[],\n base: string,\n head: string | undefined,\n disableAllowed: boolean,\n ): StatePathViolation[] {\n const violations: StatePathViolation[] = [];\n for (const file of changedFiles) {\n const changedLines = getChangedLineNumbers(getFileDiff(workspaceRoot, file, base, head));\n if (changedLines.size === 0) continue;\n for (const hit of this.hitsForFile(file, workspaceRoot)) {\n if (disableAllowed && hit.hasDisableComment) continue;\n if (!changedLines.has(hit.line)) continue;\n violations.push(new StatePathViolation(file, hit.line, hit.column, hit.detail));\n }\n }\n return violations;\n }\n\n /** NEW_AND_MODIFIED_FILES: every hit in any changed template. */\n private violationsForModifiedFiles(\n workspaceRoot: string,\n changedFiles: string[],\n disableAllowed: boolean,\n ): StatePathViolation[] {\n const violations: StatePathViolation[] = [];\n for (const file of changedFiles) {\n for (const hit of this.hitsForFile(file, workspaceRoot)) {\n if (disableAllowed && hit.hasDisableComment) continue;\n violations.push(new StatePathViolation(file, hit.line, hit.column, hit.detail));\n }\n }\n return violations;\n }\n\n private hitsForFile(file: string, workspaceRoot: string): StatePathHit[] {\n const fullPath = path.join(workspaceRoot, file);\n if (!fs.existsSync(fullPath)) return [];\n return this.findHits(fs.readFileSync(fullPath, 'utf-8'));\n }\n\n private templateDirs(): readonly string[] {\n const dirs = this.config.templateDirs ?? DEFAULT_TEMPLATE_DIRS;\n return dirs.map((dir: string): string => dir.replace(/\\\\/g, '/').replace(/\\/+$/, ''));\n }\n\n private bannedPrefixes(): readonly string[] {\n return this.config.bannedPathPrefixes ?? DEFAULT_BANNED_STATE_PATH_PREFIXES;\n }\n\n /** True if a `webpieces-disable no-state-paths-in-templates` sits on this line or up to 3 above. */\n private hasDisableComment(lines: string[], lineNumber: number): boolean {\n const start = Math.max(0, lineNumber - 4);\n for (let i = lineNumber - 1; i >= start; i--) {\n if (hasDisable(lines[i] ?? '', RULE_NAMES.NO_STATE_PATHS_IN_TEMPLATES)) return true;\n }\n return false;\n }\n\n private resolveMode(\n normalMode: ModifiedCodeMode,\n epoch: number | undefined,\n branchPattern: string | undefined,\n ): ModifiedCodeMode {\n if (normalMode === 'OFF') return normalMode;\n const skip = shouldSkipRule(epoch, branchPattern);\n if (skip.skip) {\n console.log(`\\n⏭️ Skipping no-state-paths-in-templates validation (${skip.reason})\\n`);\n return 'OFF';\n }\n return normalMode;\n }\n}\n"]}
1
+ {"version":3,"file":"validate-no-state-paths-in-templates.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-state-paths-in-templates.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA4H;AAC5H,2EAA2I;AAE3I,yCAA2D;AAE3D,qDAAiE;AACjE,iDAAgD;AAChD,6CAAyC;AAEzC,sDAAsD;AACtD,MAAa,k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M,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,UAAU,GAAG,CAAC,CAAC,CAAC;QAC1C,KAAK,IAAI,CAAC,GAAG,UAAU,GAAG,CAAC,EAAE,CAAC,IAAI,KAAK,EAAE,CAAC,EAAE,EAAE,CAAC;YAC3C,IAAI,IAAA,yBAAU,EAAC,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EAAE,6BAA6B,CAAC;gBAAE,OAAO,IAAI,CAAC;QAC/E,CAAC;QACD,OAAO,KAAK,CAAC;IACjB,CAAC;IAEO,WAAW,CACf,UAA4B,EAC5B,KAAyB,EACzB,aAAiC;QAEjC,IAAI,UAAU,KAAK,KAAK;YAAE,OAAO,UAAU,CAAC;QAC5C,MAAM,IAAI,GAAG,IAAA,6BAAc,EAAC,KAAK,EAAE,aAAa,CAAC,CAAC;QAClD,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;YACZ,OAAO,CAAC,GAAG,CAAC,0DAA0D,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC;YACxF,OAAO,KAAK,CAAC;QACjB,CAAC;QACD,OAAO,UAAU,CAAC;IACtB,CAAC;CACJ,CAAA;AA7MY,4EAAgC;2CAAhC,gCAAgC;IAD5C,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEjB,qDAA6B,EAA8B,sBAAS;GAD/E,gCAAgC,CA6M5C","sourcesContent":["/**\n * Validate No State Paths In Templates\n *\n * FAILS when a GENERATED-doc template restates a webpieces state path (`.webpieces/…`) as a literal\n * instead of rendering it from the resolver that already computes it.\n *\n * ## The incident this exists for\n *\n * `webpieces.git-workflow.md` — an AI-instruction doc regenerated into `.webpieces/instruct-ai/` of\n * every governed repo on every `wp-*` command — carried the literal\n * `.webpieces/logs/branch-mutations.log`. That log is deliberately PER-WORKTREE (one appender each):\n *\n * primary clone → `<primary>/.webpieces/logs/branch-mutations.log`\n * linked worktree → `<primary>/.webpieces/worktrees/<name>/logs/branch-mutations.log`\n *\n * So in a linked worktree the doc named a file that DOES NOT EXIST. The reader greps nothing, and the\n * silence reads as \"no deletions were logged\" — the opposite of the truth, from the one file whose\n * entire job is to prove every deletion is recoverable.\n *\n * The cure is not \"fix that line\". Every one of these paths already has a resolver, and the template\n * engine already substitutes (`{{MERGE_DIR}}`, `{{RUN_STATE}}`, `{{BRANCH_MUTATION_LOG}}` …). This\n * rule makes RESTATING the thing that fails and RENDERING the thing that passes, so the next one\n * cannot land.\n *\n * ## Scope\n *\n * `templateDirs` (workspace-relative dirs, recursive, `.md` only) — default\n * `packages/tooling/rules-config/templates`. A repo that generates no AI docs matches no files and the\n * rule is a no-op. Deliberately NOT widened to `backlog/**` (frozen records of past requests — editing\n * them falsifies the record) or to hand-written docs that name a FILE rather than a path.\n *\n * MODES: OFF | NEW_AND_MODIFIED_CODE (changed lines only) | NEW_AND_MODIFIED_FILES (whole changed file)\n * | MODIFIED_PROJECTS / RUN_EVERY_TIME (whole files of every touched project / of the repo — #1027).\n * Diff-scoped by default, so the docs whose SUBJECT is the layout (they print both rows on purpose)\n * are not retroactively flooded — the rule bites when a template is next edited.\n *\n * ESCAPE HATCH (this table IS the layout, and printing it is the point):\n * <!-- webpieces-disable no-state-paths-in-templates -- <reason> -->\n *\n * `~/.webpieces/…` is NOT a violation: the machine-local tier has no per-tree resolver and no\n * per-tree answer, so the literal is the correct and only spelling of it.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { hasDisable, Option, RuleFailError, detectBase, getFileDiff, getChangedLineNumbers } from \"@webpieces/rules-config\";\nimport { NoStatePathsInTemplatesConfig, DEFAULT_TEMPLATE_DIRS, DEFAULT_BANNED_STATE_PATH_PREFIXES } from \"./configs/no-state-paths-config\";\nimport { ModifiedCodeMode } from '@webpieces/rules-sdk';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { shouldSkipRule } from './resolve-mode';\nimport { ScanScope } from './scan-scope';\n\n/** One restated state path, located in a template. */\nexport class StatePathViolation {\n constructor(\n readonly file: string,\n readonly line: number,\n readonly column: number,\n readonly detail: string,\n ) {}\n}\n\n/** One restated state path within a single file, plus whether its line carries a disable. */\nexport class StatePathHit {\n constructor(\n readonly line: number,\n readonly column: number,\n readonly detail: string,\n readonly hasDisableComment: boolean,\n ) {}\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoStatePathsInTemplatesValidator extends CodeValidator<NoStatePathsInTemplatesConfig> {\n constructor(config: NoStatePathsInTemplatesConfig, private readonly scanScope: ScanScope) {\n super(config, \"no-state-paths-in-templates\", \"no-state-paths-in-templates\");\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n const opts = this.config;\n const mode = this.resolveMode(\n opts.mode ?? 'NEW_AND_MODIFIED_CODE', opts.turnOffRuleUntilEpoch, opts.turnOffRuleWhileOnBranch ?? undefined);\n const disableAllowed = opts.disableAllowed ?? true;\n if (mode === 'OFF') {\n console.log('\\n⏭️ Skipping no-state-paths-in-templates validation (mode: OFF)\\n');\n return { success: true };\n }\n\n console.log('\\n📏 Validating No State Paths In Templates\\n');\n console.log(` Mode: ${mode}`);\n\n let base = process.env['NX_BASE'];\n const head = process.env['NX_HEAD'];\n if (base === undefined || base === '') {\n base = detectBase(workspaceRoot) ?? undefined;\n if (base === undefined || base === '') {\n console.log('\\n⏭️ Skipping no-state-paths-in-templates validation (could not detect base branch)\\n');\n return { success: true };\n }\n }\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}\\n`);\n\n const changedFiles = this.scanScope.files(workspaceRoot, mode, base, head, { tsOnly: false })\n .filter((file: string): boolean => this.isRelevantFile(file));\n if (changedFiles.length === 0) {\n console.log('✅ No generated-doc templates changed');\n return { success: true };\n }\n console.log(`📂 Checking ${String(changedFiles.length)} changed template(s)...`);\n\n const violations = this.scanScope.isLineScoped(mode)\n ? this.violationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed)\n : this.violationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);\n\n if (violations.length === 0) {\n console.log('✅ No hard-coded state paths in generated-doc templates');\n return { success: true };\n }\n this.scanScope.recordSites(this.name, violations.map((v: StatePathViolation) => v.file));\n throw this.failure(violations, mode);\n }\n\n /**\n * The ONE spelling of \"this validator failed\": a thrown {@link RuleFailError} carrying its cures as\n * `Option[]`, which {@link RuleReporter} catches and renders.\n *\n * NOT `console.error` + `{ success: false }`. That pair is a second spelling of the same fact (see\n * RuleReporter.runValidators, which calls it a back-compat shim scheduled for deletion), and\n * hand-written \"To fix: … / Escape hatch: …\" prose is a second spelling of `Option[]` — the\n * framework owns the `Fix Option N:` numbering and the `(preferred)` tag, so a rule never writes them.\n */\n private failure(violations: StatePathViolation[], mode: ModifiedCodeMode): RuleFailError {\n const detail = violations.map((violation: StatePathViolation): string =>\n ` ${violation.file}:${String(violation.line)}:${String(violation.column)} restates \\`${violation.detail}…\\``)\n .join('\\n');\n const first = violations[0];\n return new RuleFailError(\n \"no-state-paths-in-templates\",\n 'A generated-doc template RESTATES a webpieces state path instead of computing it. These docs are '\n + 'regenerated into every governed repo and handed to an agent by absolute path AS INSTRUCTION, and '\n + 'every .webpieces/ path is per-tree — a linked worktree keeps its state under '\n + `<primary>/.webpieces/worktrees/<name>/ — so the relative spelling names a file that DOES NOT EXIST `\n + `in half the trees that read it. Current mode: ${mode}.\\n${detail}`,\n first?.line,\n first?.detail,\n [\n new Option(\n 'Put a {{PLACEHOLDER}} in the template and render it from the resolver that already computes '\n + 'that path, the way {{BRANCH_MUTATION_LOG}} is rendered from '\n + 'BranchMutationLog.branchMutationLogPath(root) in GitWorkflowDoc.render',\n true),\n new Option(\n 'If the doc\\'s SUBJECT is the layout and printing the literal is the point, say so out loud:\\n'\n + '<!-- webpieces-disable no-state-paths-in-templates -- <reason> -->'),\n ],\n );\n }\n\n /**\n * A changed file this rule looks at: a `.md` under one of the configured template dirs.\n *\n * The ONE place the file set is narrowed, so both modes run over the same list and a scope change\n * cannot be applied in one and forgotten in the other.\n */\n isRelevantFile(file: string): boolean {\n const norm = file.replace(/\\\\/g, '/');\n if (!norm.endsWith('.md')) return false;\n return this.templateDirs().some((dir: string): boolean => norm.startsWith(`${dir}/`));\n }\n\n /** Every restated state path in `text`, one hit per line (the first match on that line). */\n findHits(text: string): StatePathHit[] {\n const lines = text.split('\\n');\n const hits: StatePathHit[] = [];\n for (let i = 0; i < lines.length; i++) {\n const raw = lines[i] ?? '';\n for (const prefix of this.bannedPrefixes()) {\n const column = this.columnOf(raw, prefix);\n if (column < 0) continue;\n hits.push(new StatePathHit(i + 1, column + 1, prefix, this.hasDisableComment(lines, i + 1)));\n break;\n }\n }\n return hits;\n }\n\n /**\n * Where `prefix` is restated in `raw`, or -1.\n *\n * `~/.webpieces/…` is skipped: the machine-local tier is the same absolute path from every tree, so\n * there is no resolver to call and the literal is the only spelling there is. Everything else —\n * including the bare relative form that started this — is a restatement of a per-tree path.\n */\n private columnOf(raw: string, prefix: string): number {\n let from = 0;\n for (;;) {\n const at = raw.indexOf(prefix, from);\n if (at < 0) return -1;\n if (raw.slice(Math.max(0, at - 2), at) !== '~/') return at;\n from = at + 1;\n }\n }\n\n /** NEW_AND_MODIFIED_CODE: only hits whose line is in the diff hunks. */\n private violationsForModifiedCode(\n workspaceRoot: string,\n changedFiles: string[],\n base: string,\n head: string | undefined,\n disableAllowed: boolean,\n ): StatePathViolation[] {\n const violations: StatePathViolation[] = [];\n for (const file of changedFiles) {\n const changedLines = getChangedLineNumbers(getFileDiff(workspaceRoot, file, base, head));\n if (changedLines.size === 0) continue;\n for (const hit of this.hitsForFile(file, workspaceRoot)) {\n if (disableAllowed && hit.hasDisableComment) continue;\n if (!changedLines.has(hit.line)) continue;\n violations.push(new StatePathViolation(file, hit.line, hit.column, hit.detail));\n }\n }\n return violations;\n }\n\n /** NEW_AND_MODIFIED_FILES: every hit in any changed template. */\n private violationsForModifiedFiles(\n workspaceRoot: string,\n changedFiles: string[],\n disableAllowed: boolean,\n ): StatePathViolation[] {\n const violations: StatePathViolation[] = [];\n for (const file of changedFiles) {\n for (const hit of this.hitsForFile(file, workspaceRoot)) {\n if (disableAllowed && hit.hasDisableComment) continue;\n violations.push(new StatePathViolation(file, hit.line, hit.column, hit.detail));\n }\n }\n return violations;\n }\n\n private hitsForFile(file: string, workspaceRoot: string): StatePathHit[] {\n const fullPath = path.join(workspaceRoot, file);\n if (!fs.existsSync(fullPath)) return [];\n return this.findHits(fs.readFileSync(fullPath, 'utf-8'));\n }\n\n private templateDirs(): readonly string[] {\n const dirs = this.config.templateDirs ?? DEFAULT_TEMPLATE_DIRS;\n return dirs.map((dir: string): string => dir.replace(/\\\\/g, '/').replace(/\\/+$/, ''));\n }\n\n private bannedPrefixes(): readonly string[] {\n return this.config.bannedPathPrefixes ?? DEFAULT_BANNED_STATE_PATH_PREFIXES;\n }\n\n /** True if a `webpieces-disable no-state-paths-in-templates` sits on this line or up to 3 above. */\n private hasDisableComment(lines: string[], lineNumber: number): boolean {\n const start = Math.max(0, lineNumber - 4);\n for (let i = lineNumber - 1; i >= start; i--) {\n if (hasDisable(lines[i] ?? '', \"no-state-paths-in-templates\")) return true;\n }\n return false;\n }\n\n private resolveMode(\n normalMode: ModifiedCodeMode,\n epoch: number | undefined,\n branchPattern: string | undefined,\n ): ModifiedCodeMode {\n if (normalMode === 'OFF') return normalMode;\n const skip = shouldSkipRule(epoch, branchPattern);\n if (skip.skip) {\n console.log(`\\n⏭️ Skipping no-state-paths-in-templates validation (${skip.reason})\\n`);\n return 'OFF';\n }\n return normalMode;\n }\n}\n"]}
@@ -34,7 +34,7 @@
34
34
  * // webpieces-disable no-symbol-di-tokens -- [your justification]
35
35
  * export const MY_TOKEN = Symbol('MY_TOKEN');
36
36
  */
37
- import { NoSymbolDiTokensConfig } from '@webpieces/rules-config';
37
+ import { NoSymbolDiTokensConfig } from "./configs/rule-configs";
38
38
  import { CodeValidator, ExecutorResult } from './code-validator';
39
39
  import { ScanScope } from './scan-scope';
40
40
  interface SymbolViolationInfo {
@@ -42,6 +42,7 @@ const tslib_1 = require("tslib");
42
42
  const fs = tslib_1.__importStar(require("fs"));
43
43
  const path = tslib_1.__importStar(require("path"));
44
44
  const rules_config_1 = require("@webpieces/rules-config");
45
+ const rule_configs_1 = require("./configs/rule-configs");
45
46
  const code_validator_1 = require("./code-validator");
46
47
  const inversify_1 = require("inversify");
47
48
  const resolve_mode_1 = require("./resolve-mode");
@@ -110,7 +111,7 @@ function stripLineComments(line) {
110
111
  return line.substring(0, idx);
111
112
  }
112
113
  function hasDisableOnLine(line) {
113
- return (0, rules_config_1.hasDisable)(line, rules_config_1.RULE_NAMES.NO_SYMBOL_DI_TOKENS);
114
+ return (0, rules_config_1.hasDisable)(line, "no-symbol-di-tokens");
114
115
  }
115
116
  function resolveDisable(disabled, disableAllowed) {
116
117
  if (!disableAllowed && disabled) {
@@ -269,6 +270,6 @@ let NoSymbolDiTokensValidator = class NoSymbolDiTokensValidator extends code_val
269
270
  exports.NoSymbolDiTokensValidator = NoSymbolDiTokensValidator;
270
271
  exports.NoSymbolDiTokensValidator = NoSymbolDiTokensValidator = tslib_1.__decorate([
271
272
  (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
272
- tslib_1.__metadata("design:paramtypes", [rules_config_1.NoSymbolDiTokensConfig, scan_scope_1.ScanScope])
273
+ tslib_1.__metadata("design:paramtypes", [rule_configs_1.NoSymbolDiTokensConfig, scan_scope_1.ScanScope])
273
274
  ], NoSymbolDiTokensValidator);
274
275
  //# sourceMappingURL=validate-no-symbol-di-tokens.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"validate-no-symbol-di-tokens.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-symbol-di-tokens.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;;;AAoGH,gEAkCC;;AApID,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA2J;AAC3J,qDAA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AAE,cAAc,CAAC,CAAC;IAEnD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC9B,CAAC;AAGM,IAAM,yBAAyB,GAA/B,MAAM,yBAA0B,SAAQ,8BAAqC;IACnB;IAA7D,YAAY,MAA8B,EAAmB,SAAoB;QAC7E,KAAK,CAAC,MAAM,EAAE,qBAAqB,EAAE,qBAAqB,CAAC,CAAC;QADH,cAAS,GAAT,SAAS,CAAW;IAEjF,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,aAAqB;QAC3B,OAAO,gBAAgB,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IACxE,CAAC;CACJ,CAAA;AARY,8DAAyB;oCAAzB,yBAAyB;IADrC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEjB,qCAAsB,EAA8B,sBAAS;GADxE,yBAAyB,CAQrC","sourcesContent":["/**\n * Validate No Symbol DI Tokens Executor\n *\n * Validates that Symbol() / Symbol.for() are not used to create DI tokens\n * outside of the designated API-binding packages.\n *\n * ============================================================================\n * VIOLATIONS (BAD) - These patterns are flagged:\n * ============================================================================\n *\n * - export const MY_TOKEN = Symbol('MY_TOKEN')\n * - export const MY_TOKEN = Symbol.for('MY_TOKEN')\n * - const TOKEN: symbol = Symbol('TOKEN')\n *\n * ============================================================================\n * ALLOWED\n * ============================================================================\n *\n * - Files under allowedPaths (configured in webpieces.config.json, defaults to [])\n * - Test files (*.test.ts, *.spec.ts, __tests__/**)\n * - Lines with // webpieces-disable no-symbol-di-tokens -- <reason> (when disableAllowed: true)\n *\n * ============================================================================\n * MODES (LINE-BASED)\n * ============================================================================\n * - OFF: Skip validation entirely\n * - NEW_AND_MODIFIED_CODE: Flag Symbol DI tokens on changed lines (lines in diff hunks)\n * - NEW_AND_MODIFIED_FILES: Flag ALL Symbol DI tokens in files that were modified\n *\n * ============================================================================\n * ESCAPE HATCH\n * ============================================================================\n * Add comment on the same line or line above the violation:\n * // webpieces-disable no-symbol-di-tokens -- [your justification]\n * export const MY_TOKEN = Symbol('MY_TOKEN');\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { hasDisable, RULE_NAMES, NoSymbolDiTokensConfig, ModifiedCodeMode, detectBase, getFileDiff, getChangedLineNumbers } from '@webpieces/rules-config';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { shouldSkipRule } from './resolve-mode';\nimport { ScanScope } from './scan-scope';\n\nconst SYMBOL_DI_REGEX = /=\\s*Symbol(?:\\.for)?\\(/;\n\nconst SHARED_MESSAGE = `Do not create a dependency-injection token with Symbol(). Choose the right pattern:\nOption 1: OWN class — annotate it with @injectable(bindingScopeValues.Singleton) and inject by concrete class TYPE — no Symbol, no @inject.\n constructor(private readonly myService: MyService) {}\nOption 2: API IMPLEMENTATION — import the Symbol from the API definition file and use:\n @provideSingletonDefaultForApi(SOME_API_TOKEN)\n export class SomeApiImpl implements SomeApi { ... }\nOption 3: External lib class you cannot decorate (DataSource, Anthropic, etc.):\n bind in a ContainerModule using the class itself as token — no Symbol needed:\n bind<Anthropic>(Anthropic).toDynamicValue(() => new Anthropic({ apiKey: ... })).inSingletonScope()\n Then inject by type — no Symbol, no @inject.\nOption 4 (last resort): append // webpieces-disable no-symbol-di-tokens -- <reason> to justify this specific line.`;\n\ninterface SymbolViolation {\n file: string;\n line: number;\n context: string;\n}\n\ninterface SymbolViolationInfo {\n line: number;\n context: string;\n hasDisableComment: boolean;\n}\n\nfunction isTestFile(filePath: string): boolean {\n return filePath.includes('.spec.ts') ||\n filePath.includes('.test.ts') ||\n filePath.includes('__tests__/');\n}\n\nfunction globToRegex(pattern: string): RegExp {\n let re = '';\n let i = 0;\n while (i < pattern.length) {\n const ch = pattern[i];\n if (ch === '*') {\n if (pattern[i + 1] === '*') {\n re += '.*';\n i += 2;\n if (pattern[i] === '/') i += 1;\n continue;\n }\n re += '[^/]*';\n i += 1;\n continue;\n }\n if (ch === '?') {\n re += '[^/]';\n i += 1;\n continue;\n }\n if ('.+^$(){}|[]\\\\'.includes(ch)) {\n re += '\\\\' + ch;\n i += 1;\n continue;\n }\n re += ch;\n i += 1;\n }\n return new RegExp('^' + re + '$');\n}\n\nfunction isAllowedPath(filePath: string, allowedPaths: string[]): boolean {\n for (const pattern of allowedPaths) {\n if (globToRegex(pattern).test(filePath)) {\n return true;\n }\n }\n return false;\n}\n\nfunction stripLineComments(line: string): string {\n const idx = line.indexOf('//');\n if (idx === -1) return line;\n return line.substring(0, idx);\n}\n\nfunction hasDisableOnLine(line: string): boolean {\n return hasDisable(line, RULE_NAMES.NO_SYMBOL_DI_TOKENS);\n}\n\nfunction resolveDisable(disabled: boolean, disableAllowed: boolean): boolean {\n if (!disableAllowed && disabled) {\n return false;\n }\n return disabled;\n}\n\nexport function findSymbolViolationsInFile(\n filePath: string,\n workspaceRoot: string,\n disableAllowed: boolean,\n allowedPaths: string[],\n): SymbolViolationInfo[] {\n if (isTestFile(filePath)) return [];\n if (isAllowedPath(filePath, allowedPaths)) return [];\n\n const fullPath = path.join(workspaceRoot, filePath);\n if (!fs.existsSync(fullPath)) return [];\n\n const content = fs.readFileSync(fullPath, 'utf-8');\n const lines = content.split('\\n');\n const violations: SymbolViolationInfo[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? '';\n const stripped = stripLineComments(line);\n\n if (!SYMBOL_DI_REGEX.test(stripped)) continue;\n\n const lineNum = i + 1;\n const prevLine = i > 0 ? (lines[i - 1] ?? '') : '';\n const disabled = hasDisableOnLine(line) || hasDisableOnLine(prevLine);\n\n violations.push({\n line: lineNum,\n context: line.trim(),\n hasDisableComment: resolveDisable(disabled, disableAllowed),\n });\n }\n\n return violations;\n}\n\nfunction findViolationsForModifiedCode(\n workspaceRoot: string,\n changedFiles: string[],\n base: string,\n head: string | undefined,\n disableAllowed: boolean,\n allowedPaths: string[],\n): SymbolViolation[] {\n const violations: SymbolViolation[] = [];\n\n for (const file of changedFiles) {\n const diff = getFileDiff(workspaceRoot, file, base, head);\n const changedLines = getChangedLineNumbers(diff);\n\n if (changedLines.size === 0) continue;\n\n const allViolations = findSymbolViolationsInFile(file, workspaceRoot, disableAllowed, allowedPaths);\n\n for (const v of allViolations) {\n if (disableAllowed && v.hasDisableComment) continue;\n if (!changedLines.has(v.line)) continue;\n\n violations.push({ file, line: v.line, context: v.context });\n }\n }\n\n return violations;\n}\n\nfunction findViolationsForModifiedFiles(\n workspaceRoot: string,\n changedFiles: string[],\n disableAllowed: boolean,\n allowedPaths: string[],\n): SymbolViolation[] {\n const violations: SymbolViolation[] = [];\n\n for (const file of changedFiles) {\n const allViolations = findSymbolViolationsInFile(file, workspaceRoot, disableAllowed, allowedPaths);\n\n for (const v of allViolations) {\n if (disableAllowed && v.hasDisableComment) continue;\n violations.push({ file, line: v.line, context: v.context });\n }\n }\n\n return violations;\n}\n\n// webpieces-disable max-lines-new-methods -- Console output with guidance message and violation list\nfunction reportViolations(violations: SymbolViolation[], mode: ModifiedCodeMode, disableAllowed: boolean): void {\n console.error('');\n console.error('❌ Symbol() DI tokens are not allowed outside api(-external) packages!');\n console.error('');\n console.error(SHARED_MESSAGE);\n console.error('');\n\n for (const v of violations) {\n console.error(` ❌ ${v.file}:${v.line}`);\n console.error(` ${v.context}`);\n }\n console.error('');\n\n if (disableAllowed) {\n console.error(' Escape hatch (use sparingly):');\n console.error(' // webpieces-disable no-symbol-di-tokens -- <reason>');\n } else {\n console.error(' Escape hatch: DISABLED (disableAllowed: false)');\n }\n console.error('');\n console.error(` Current mode: ${mode}`);\n console.error('');\n}\n\nfunction resolveMode(normalMode: ModifiedCodeMode, epoch: number | undefined, branchPattern: string | undefined): ModifiedCodeMode {\n if (normalMode === 'OFF') {\n return normalMode;\n }\n const skip = shouldSkipRule(epoch, branchPattern);\n if (skip.skip) {\n console.log(`\\n⏭️ Skipping no-symbol-di-tokens validation (${skip.reason})`);\n console.log('');\n return 'OFF';\n }\n return normalMode;\n}\n\nasync function runValidatorImpl(\n scan: ScanScope,\n options: NoSymbolDiTokensConfig,\n workspaceRoot: string,\n): Promise<ExecutorResult> {\n const mode: ModifiedCodeMode = resolveMode(options.mode ?? 'OFF', options.turnOffRuleUntilEpoch, (options.turnOffRuleWhileOnBranch ?? undefined));\n const disableAllowed = options.disableAllowed ?? true;\n const allowedPaths = options.allowedPaths ?? [];\n\n if (mode === 'OFF') {\n console.log('\\n⏭️ Skipping no-symbol-di-tokens validation (mode: OFF)');\n console.log('');\n return { success: true };\n }\n\n console.log('\\n📏 Validating No Symbol DI Tokens\\n');\n console.log(` Mode: ${mode}`);\n\n let base = process.env['NX_BASE'];\n const head = process.env['NX_HEAD'];\n\n if (!base) {\n base = detectBase(workspaceRoot) ?? undefined;\n\n if (!base) {\n console.log('\\n⏭️ Skipping no-symbol-di-tokens validation (could not detect base branch)');\n console.log('');\n return { success: true };\n }\n }\n\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);\n console.log('');\n\n const changedFiles = scan.files(workspaceRoot, mode, base, head);\n\n if (changedFiles.length === 0) {\n console.log('✅ No TypeScript files changed');\n return { success: true };\n }\n\n console.log(`📂 Checking ${changedFiles.length} changed file(s)...`);\n\n let violations: SymbolViolation[] = [];\n\n if (mode === 'NEW_AND_MODIFIED_CODE') {\n violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed, allowedPaths);\n } else {\n // NEW_AND_MODIFIED_FILES and the whole-scope modes (#1027) all judge every site of every file.\n violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed, allowedPaths);\n }\n\n if (violations.length === 0) {\n console.log('✅ No Symbol DI token violations found');\n return { success: true };\n }\n\n scan.recordSites('no-symbol-di-tokens', violations.map((v: SymbolViolation) => v.file));\n reportViolations(violations, mode, disableAllowed);\n\n return { success: false };\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoSymbolDiTokensValidator extends CodeValidator<NoSymbolDiTokensConfig> {\n constructor(config: NoSymbolDiTokensConfig, private readonly scanScope: ScanScope) {\n super(config, 'no-symbol-di-tokens', 'no-symbol-di-tokens');\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runValidatorImpl(this.scanScope, this.config, workspaceRoot);\n }\n}\n"]}
1
+ {"version":3,"file":"validate-no-symbol-di-tokens.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-symbol-di-tokens.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;;;AAsGH,gEAkCC;;AAtID,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAqG;AACrG,yDAAgE;AAEhE,qDAAiE;AACjE,yCAA2D;AAC3D,iDAAgD;AAChD,6CAAyC;AAEzC,MAAM,eAAe,GAAG,wBAAwB,CAAC;AAEjD,MAAM,cAAc,GAAG;;;;;;;;;;mHAU4F,CAAC;AAcpH,SAAS,UAAU,CAAC,QAAgB;IAChC,OAAO,QAAQ,CAAC,QAAQ,CAAC,UAAU,CAAC;QAChC,QAAQ,CAAC,QAAQ,CAAC,UAAU,CAAC;QAC7B,QAAQ,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;AACxC,CAAC;AAED,SAAS,WAAW,CAAC,OAAe;IAChC,IAAI,EAAE,GAAG,EAAE,CAAC;IACZ,IAAI,CAAC,GAAG,CAAC,CAAC;IACV,OAAO,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;QACxB,MAAM,EAAE,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;QACtB,IAAI,EAAE,KAAK,GAAG,EAAE,CAAC;YACb,IAAI,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,GAAG,EAAE,CAAC;gBACzB,EAAE,IAAI,IAAI,CAAC;gBACX,CAAC,IAAI,CAAC,CAAC;gBACP,IAAI,OAAO,CAAC,CAAC,CAAC,KAAK,GAAG;oBAAE,CAAC,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F;QAC/F,UAAU,GAAG,8BAA8B,CAAC,aAAa,EAAE,YAAY,EAAE,cAAc,EAAE,YAAY,CAAC,CAAC;IAC3G,CAAC;IAED,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC1B,OAAO,CAAC,GAAG,CAAC,uCAAuC,CAAC,CAAC;QACrD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7B,CAAC;IAED,IAAI,CAAC,WAAW,CAAC,qBAAqB,EAAE,UAAU,CAAC,GAAG,CAAC,CAAC,CAAkB,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;IACxF,gBAAgB,CAAC,UAAU,EAAE,IAAI,EAAE,cAAc,CAAC,CAAC;IAEnD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC9B,CAAC;AAGM,IAAM,yBAAyB,GAA/B,MAAM,yBAA0B,SAAQ,8BAAqC;IACnB;IAA7D,YAAY,MAA8B,EAAmB,SAAoB;QAC7E,KAAK,CAAC,MAAM,EAAE,qBAAqB,EAAE,qBAAqB,CAAC,CAAC;QADH,cAAS,GAAT,SAAS,CAAW;IAEjF,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,aAAqB;QAC3B,OAAO,gBAAgB,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IACxE,CAAC;CACJ,CAAA;AARY,8DAAyB;oCAAzB,yBAAyB;IADrC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEjB,qCAAsB,EAA8B,sBAAS;GADxE,yBAAyB,CAQrC","sourcesContent":["/**\n * Validate No Symbol DI Tokens Executor\n *\n * Validates that Symbol() / Symbol.for() are not used to create DI tokens\n * outside of the designated API-binding packages.\n *\n * ============================================================================\n * VIOLATIONS (BAD) - These patterns are flagged:\n * ============================================================================\n *\n * - export const MY_TOKEN = Symbol('MY_TOKEN')\n * - export const MY_TOKEN = Symbol.for('MY_TOKEN')\n * - const TOKEN: symbol = Symbol('TOKEN')\n *\n * ============================================================================\n * ALLOWED\n * ============================================================================\n *\n * - Files under allowedPaths (configured in webpieces.config.json, defaults to [])\n * - Test files (*.test.ts, *.spec.ts, __tests__/**)\n * - Lines with // webpieces-disable no-symbol-di-tokens -- <reason> (when disableAllowed: true)\n *\n * ============================================================================\n * MODES (LINE-BASED)\n * ============================================================================\n * - OFF: Skip validation entirely\n * - NEW_AND_MODIFIED_CODE: Flag Symbol DI tokens on changed lines (lines in diff hunks)\n * - NEW_AND_MODIFIED_FILES: Flag ALL Symbol DI tokens in files that were modified\n *\n * ============================================================================\n * ESCAPE HATCH\n * ============================================================================\n * Add comment on the same line or line above the violation:\n * // webpieces-disable no-symbol-di-tokens -- [your justification]\n * export const MY_TOKEN = Symbol('MY_TOKEN');\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { hasDisable, detectBase, getFileDiff, getChangedLineNumbers } from \"@webpieces/rules-config\";\nimport { NoSymbolDiTokensConfig } from \"./configs/rule-configs\";\nimport { ModifiedCodeMode } from '@webpieces/rules-sdk';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { shouldSkipRule } from './resolve-mode';\nimport { ScanScope } from './scan-scope';\n\nconst SYMBOL_DI_REGEX = /=\\s*Symbol(?:\\.for)?\\(/;\n\nconst SHARED_MESSAGE = `Do not create a dependency-injection token with Symbol(). Choose the right pattern:\nOption 1: OWN class — annotate it with @injectable(bindingScopeValues.Singleton) and inject by concrete class TYPE — no Symbol, no @inject.\n constructor(private readonly myService: MyService) {}\nOption 2: API IMPLEMENTATION — import the Symbol from the API definition file and use:\n @provideSingletonDefaultForApi(SOME_API_TOKEN)\n export class SomeApiImpl implements SomeApi { ... }\nOption 3: External lib class you cannot decorate (DataSource, Anthropic, etc.):\n bind in a ContainerModule using the class itself as token — no Symbol needed:\n bind<Anthropic>(Anthropic).toDynamicValue(() => new Anthropic({ apiKey: ... })).inSingletonScope()\n Then inject by type — no Symbol, no @inject.\nOption 4 (last resort): append // webpieces-disable no-symbol-di-tokens -- <reason> to justify this specific line.`;\n\ninterface SymbolViolation {\n file: string;\n line: number;\n context: string;\n}\n\ninterface SymbolViolationInfo {\n line: number;\n context: string;\n hasDisableComment: boolean;\n}\n\nfunction isTestFile(filePath: string): boolean {\n return filePath.includes('.spec.ts') ||\n filePath.includes('.test.ts') ||\n filePath.includes('__tests__/');\n}\n\nfunction globToRegex(pattern: string): RegExp {\n let re = '';\n let i = 0;\n while (i < pattern.length) {\n const ch = pattern[i];\n if (ch === '*') {\n if (pattern[i + 1] === '*') {\n re += '.*';\n i += 2;\n if (pattern[i] === '/') i += 1;\n continue;\n }\n re += '[^/]*';\n i += 1;\n continue;\n }\n if (ch === '?') {\n re += '[^/]';\n i += 1;\n continue;\n }\n if ('.+^$(){}|[]\\\\'.includes(ch)) {\n re += '\\\\' + ch;\n i += 1;\n continue;\n }\n re += ch;\n i += 1;\n }\n return new RegExp('^' + re + '$');\n}\n\nfunction isAllowedPath(filePath: string, allowedPaths: string[]): boolean {\n for (const pattern of allowedPaths) {\n if (globToRegex(pattern).test(filePath)) {\n return true;\n }\n }\n return false;\n}\n\nfunction stripLineComments(line: string): string {\n const idx = line.indexOf('//');\n if (idx === -1) return line;\n return line.substring(0, idx);\n}\n\nfunction hasDisableOnLine(line: string): boolean {\n return hasDisable(line, \"no-symbol-di-tokens\");\n}\n\nfunction resolveDisable(disabled: boolean, disableAllowed: boolean): boolean {\n if (!disableAllowed && disabled) {\n return false;\n }\n return disabled;\n}\n\nexport function findSymbolViolationsInFile(\n filePath: string,\n workspaceRoot: string,\n disableAllowed: boolean,\n allowedPaths: string[],\n): SymbolViolationInfo[] {\n if (isTestFile(filePath)) return [];\n if (isAllowedPath(filePath, allowedPaths)) return [];\n\n const fullPath = path.join(workspaceRoot, filePath);\n if (!fs.existsSync(fullPath)) return [];\n\n const content = fs.readFileSync(fullPath, 'utf-8');\n const lines = content.split('\\n');\n const violations: SymbolViolationInfo[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? '';\n const stripped = stripLineComments(line);\n\n if (!SYMBOL_DI_REGEX.test(stripped)) continue;\n\n const lineNum = i + 1;\n const prevLine = i > 0 ? (lines[i - 1] ?? '') : '';\n const disabled = hasDisableOnLine(line) || hasDisableOnLine(prevLine);\n\n violations.push({\n line: lineNum,\n context: line.trim(),\n hasDisableComment: resolveDisable(disabled, disableAllowed),\n });\n }\n\n return violations;\n}\n\nfunction findViolationsForModifiedCode(\n workspaceRoot: string,\n changedFiles: string[],\n base: string,\n head: string | undefined,\n disableAllowed: boolean,\n allowedPaths: string[],\n): SymbolViolation[] {\n const violations: SymbolViolation[] = [];\n\n for (const file of changedFiles) {\n const diff = getFileDiff(workspaceRoot, file, base, head);\n const changedLines = getChangedLineNumbers(diff);\n\n if (changedLines.size === 0) continue;\n\n const allViolations = findSymbolViolationsInFile(file, workspaceRoot, disableAllowed, allowedPaths);\n\n for (const v of allViolations) {\n if (disableAllowed && v.hasDisableComment) continue;\n if (!changedLines.has(v.line)) continue;\n\n violations.push({ file, line: v.line, context: v.context });\n }\n }\n\n return violations;\n}\n\nfunction findViolationsForModifiedFiles(\n workspaceRoot: string,\n changedFiles: string[],\n disableAllowed: boolean,\n allowedPaths: string[],\n): SymbolViolation[] {\n const violations: SymbolViolation[] = [];\n\n for (const file of changedFiles) {\n const allViolations = findSymbolViolationsInFile(file, workspaceRoot, disableAllowed, allowedPaths);\n\n for (const v of allViolations) {\n if (disableAllowed && v.hasDisableComment) continue;\n violations.push({ file, line: v.line, context: v.context });\n }\n }\n\n return violations;\n}\n\n// webpieces-disable max-lines-new-methods -- Console output with guidance message and violation list\nfunction reportViolations(violations: SymbolViolation[], mode: ModifiedCodeMode, disableAllowed: boolean): void {\n console.error('');\n console.error('❌ Symbol() DI tokens are not allowed outside api(-external) packages!');\n console.error('');\n console.error(SHARED_MESSAGE);\n console.error('');\n\n for (const v of violations) {\n console.error(` ❌ ${v.file}:${v.line}`);\n console.error(` ${v.context}`);\n }\n console.error('');\n\n if (disableAllowed) {\n console.error(' Escape hatch (use sparingly):');\n console.error(' // webpieces-disable no-symbol-di-tokens -- <reason>');\n } else {\n console.error(' Escape hatch: DISABLED (disableAllowed: false)');\n }\n console.error('');\n console.error(` Current mode: ${mode}`);\n console.error('');\n}\n\nfunction resolveMode(normalMode: ModifiedCodeMode, epoch: number | undefined, branchPattern: string | undefined): ModifiedCodeMode {\n if (normalMode === 'OFF') {\n return normalMode;\n }\n const skip = shouldSkipRule(epoch, branchPattern);\n if (skip.skip) {\n console.log(`\\n⏭️ Skipping no-symbol-di-tokens validation (${skip.reason})`);\n console.log('');\n return 'OFF';\n }\n return normalMode;\n}\n\nasync function runValidatorImpl(\n scan: ScanScope,\n options: NoSymbolDiTokensConfig,\n workspaceRoot: string,\n): Promise<ExecutorResult> {\n const mode: ModifiedCodeMode = resolveMode(options.mode ?? 'OFF', options.turnOffRuleUntilEpoch, (options.turnOffRuleWhileOnBranch ?? undefined));\n const disableAllowed = options.disableAllowed ?? true;\n const allowedPaths = options.allowedPaths ?? [];\n\n if (mode === 'OFF') {\n console.log('\\n⏭️ Skipping no-symbol-di-tokens validation (mode: OFF)');\n console.log('');\n return { success: true };\n }\n\n console.log('\\n📏 Validating No Symbol DI Tokens\\n');\n console.log(` Mode: ${mode}`);\n\n let base = process.env['NX_BASE'];\n const head = process.env['NX_HEAD'];\n\n if (!base) {\n base = detectBase(workspaceRoot) ?? undefined;\n\n if (!base) {\n console.log('\\n⏭️ Skipping no-symbol-di-tokens validation (could not detect base branch)');\n console.log('');\n return { success: true };\n }\n }\n\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);\n console.log('');\n\n const changedFiles = scan.files(workspaceRoot, mode, base, head);\n\n if (changedFiles.length === 0) {\n console.log('✅ No TypeScript files changed');\n return { success: true };\n }\n\n console.log(`📂 Checking ${changedFiles.length} changed file(s)...`);\n\n let violations: SymbolViolation[] = [];\n\n if (mode === 'NEW_AND_MODIFIED_CODE') {\n violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed, allowedPaths);\n } else {\n // NEW_AND_MODIFIED_FILES and the whole-scope modes (#1027) all judge every site of every file.\n violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed, allowedPaths);\n }\n\n if (violations.length === 0) {\n console.log('✅ No Symbol DI token violations found');\n return { success: true };\n }\n\n scan.recordSites('no-symbol-di-tokens', violations.map((v: SymbolViolation) => v.file));\n reportViolations(violations, mode, disableAllowed);\n\n return { success: false };\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoSymbolDiTokensValidator extends CodeValidator<NoSymbolDiTokensConfig> {\n constructor(config: NoSymbolDiTokensConfig, private readonly scanScope: ScanScope) {\n super(config, 'no-symbol-di-tokens', 'no-symbol-di-tokens');\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runValidatorImpl(this.scanScope, this.config, workspaceRoot);\n }\n}\n"]}
@@ -31,7 +31,7 @@
31
31
  * // webpieces-disable no-unmanaged-exceptions -- [your justification]
32
32
  * try {
33
33
  */
34
- import { NoUnmanagedExceptionsConfig } from '@webpieces/rules-config';
34
+ import { NoUnmanagedExceptionsConfig } from "./configs/rule-configs";
35
35
  import { CodeValidator, ExecutorResult } from './code-validator';
36
36
  import { ScanScope } from './scan-scope';
37
37
  export declare class NoUnmanagedExceptionsValidator extends CodeValidator<NoUnmanagedExceptionsConfig> {
@@ -38,6 +38,7 @@ const tslib_1 = require("tslib");
38
38
  const fs = tslib_1.__importStar(require("fs"));
39
39
  const path = tslib_1.__importStar(require("path"));
40
40
  const rules_config_1 = require("@webpieces/rules-config");
41
+ const rule_configs_1 = require("./configs/rule-configs");
41
42
  const code_validator_1 = require("./code-validator");
42
43
  const inversify_1 = require("inversify");
43
44
  const resolve_mode_1 = require("./resolve-mode");
@@ -53,7 +54,7 @@ function hasDisableComment(lines, lineNumber) {
53
54
  if (line.startsWith('function ') || line.startsWith('class ') || line.endsWith('}')) {
54
55
  break;
55
56
  }
56
- if ((0, rules_config_1.hasDisable)(line, rules_config_1.RULE_NAMES.NO_UNMANAGED_EXCEPTIONS)) {
57
+ if ((0, rules_config_1.hasDisable)(line, "no-unmanaged-exceptions")) {
57
58
  return true;
58
59
  }
59
60
  if (line.includes('@webpieces/no-unmanaged-exceptions')) {
@@ -233,6 +234,6 @@ let NoUnmanagedExceptionsValidator = class NoUnmanagedExceptionsValidator extend
233
234
  exports.NoUnmanagedExceptionsValidator = NoUnmanagedExceptionsValidator;
234
235
  exports.NoUnmanagedExceptionsValidator = NoUnmanagedExceptionsValidator = tslib_1.__decorate([
235
236
  (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
236
- tslib_1.__metadata("design:paramtypes", [rules_config_1.NoUnmanagedExceptionsConfig, scan_scope_1.ScanScope])
237
+ tslib_1.__metadata("design:paramtypes", [rule_configs_1.NoUnmanagedExceptionsConfig, scan_scope_1.ScanScope])
237
238
  ], NoUnmanagedExceptionsValidator);
238
239
  //# sourceMappingURL=validate-no-unmanaged-exceptions.js.map
@@ -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,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,I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AAE,IAAI,EAAE,cAAc,CAAC,CAAC;IAEnD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC9B,CAAC;AAGM,IAAM,8BAA8B,GAApC,MAAM,8BAA+B,SAAQ,8BAA0C;IACxB;IAAlE,YAAY,MAAmC,EAAmB,SAAoB;QAClF,KAAK,CAAC,MAAM,EAAE,yBAAyB,EAAE,yBAAyB,CAAC,CAAC;QADN,cAAS,GAAT,SAAS,CAAW;IAEtF,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,aAAqB;QAC3B,OAAO,gBAAgB,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IACxE,CAAC;CACJ,CAAA;AARY,wEAA8B;yCAA9B,8BAA8B;IAD1C,IAAA,sBAAU,EAAC,8BAAkB,CAAC,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"]}
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,0DAAqG;AACrG,yDAAqE;AAErE,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,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C,CAAC;IAC9F,gBAAgB,CAAC,UAAU,EAAE,IAAI,EAAE,cAAc,CAAC,CAAC;IAEnD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC9B,CAAC;AAGM,IAAM,8BAA8B,GAApC,MAAM,8BAA+B,SAAQ,8BAA0C;IACxB;IAAlE,YAAY,MAAmC,EAAmB,SAAoB;QAClF,KAAK,CAAC,MAAM,EAAE,yBAAyB,EAAE,yBAAyB,CAAC,CAAC;QADN,cAAS,GAAT,SAAS,CAAW;IAEtF,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,aAAqB;QAC3B,OAAO,gBAAgB,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IACxE,CAAC;CACJ,CAAA;AARY,wEAA8B;yCAA9B,8BAA8B;IAD1C,IAAA,sBAAU,EAAC,8BAAkB,CAAC,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, detectBase, getFileDiff, getChangedLineNumbers } from \"@webpieces/rules-config\";\nimport { NoUnmanagedExceptionsConfig } from \"./configs/rule-configs\";\nimport { ModifiedCodeMode } from '@webpieces/rules-sdk';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { shouldSkipRule } from './resolve-mode';\nimport { ScanScope } from './scan-scope';\n\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, \"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"]}
@@ -25,7 +25,8 @@
25
25
  * required or optional fields, or a flat interface / class listing every field. The wire JSON is
26
26
  * unchanged either way.
27
27
  */
28
- import { DiffScope, NoUtilityTypesInApiLibConfig } from '@webpieces/rules-config';
28
+ import { DiffScope } from "@webpieces/rules-config";
29
+ import { NoUtilityTypesInApiLibConfig } from "./configs/no-utility-types-config";
29
30
  import { ApiLibFile, ApiLibSite, ApiLibSourceRule } from './api-lib-source-rule';
30
31
  import { ProjectRoleResolver } from './project-role-resolver';
31
32
  import { ScanScope } from './scan-scope';
@@ -30,6 +30,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
30
30
  exports.NoUtilityTypesInApiLibValidator = exports.UtilityTypeScanner = void 0;
31
31
  const tslib_1 = require("tslib");
32
32
  const rules_config_1 = require("@webpieces/rules-config");
33
+ const no_utility_types_config_1 = require("./configs/no-utility-types-config");
33
34
  const inversify_1 = require("inversify");
34
35
  const ts = tslib_1.__importStar(require("typescript"));
35
36
  const api_lib_source_rule_1 = require("./api-lib-source-rule");
@@ -152,7 +153,7 @@ exports.UtilityTypeScanner = UtilityTypeScanner;
152
153
  let NoUtilityTypesInApiLibValidator = class NoUtilityTypesInApiLibValidator extends api_lib_source_rule_1.ApiLibSourceRule {
153
154
  scanner = new UtilityTypeScanner();
154
155
  constructor(config, roleResolver, diffScope, scanScope) {
155
- super(config, rules_config_1.RULE_NAMES.NO_UTILITY_TYPES_IN_API_LIB, roleResolver, diffScope, scanScope);
156
+ super(config, "no-utility-types-in-api-lib", roleResolver, diffScope, scanScope);
156
157
  }
157
158
  sitesIn(file) {
158
159
  return this.scanner.scan(file);
@@ -172,6 +173,6 @@ let NoUtilityTypesInApiLibValidator = class NoUtilityTypesInApiLibValidator exte
172
173
  exports.NoUtilityTypesInApiLibValidator = NoUtilityTypesInApiLibValidator;
173
174
  exports.NoUtilityTypesInApiLibValidator = NoUtilityTypesInApiLibValidator = tslib_1.__decorate([
174
175
  (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
175
- tslib_1.__metadata("design:paramtypes", [rules_config_1.NoUtilityTypesInApiLibConfig, project_role_resolver_1.ProjectRoleResolver, rules_config_1.DiffScope, scan_scope_1.ScanScope])
176
+ tslib_1.__metadata("design:paramtypes", [no_utility_types_config_1.NoUtilityTypesInApiLibConfig, project_role_resolver_1.ProjectRoleResolver, rules_config_1.DiffScope, scan_scope_1.ScanScope])
176
177
  ], NoUtilityTypesInApiLibValidator);
177
178
  //# 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":["../../../../../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AC,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"]}
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;;;;;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GAAoG,CAAC;IAC7G,CAAC;CACJ,CAAA;AAxBY,0EAA+B;0CAA/B,+BAA+B;IAD3C,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAIjB,sDAA4B,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, matchesAnyGlob } from \"@webpieces/rules-config\";\nimport { NoUtilityTypesInApiLibConfig } from \"./configs/no-utility-types-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, \"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"]}
@@ -20,7 +20,8 @@
20
20
  * partner reading `gender: 1` can interpret. The generator itself keeps supporting literal unions;
21
21
  * this rule is what forbids new ones in an api library.
22
22
  */
23
- import { DiffScope, OneEnumSpellingInApiLibConfig } from '@webpieces/rules-config';
23
+ import { DiffScope } from "@webpieces/rules-config";
24
+ import { OneEnumSpellingInApiLibConfig } from "./configs/api-lib-spelling-configs";
24
25
  import { ApiLibEnumIndex } from './api-lib-enum-index';
25
26
  import { ApiLibFile, ApiLibSite, ApiLibSourceRule } from './api-lib-source-rule';
26
27
  import { ProjectRoleResolver } from './project-role-resolver';
@@ -25,6 +25,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
25
25
  exports.OneEnumSpellingInApiLibValidator = exports.EnumSpellingScanner = void 0;
26
26
  const tslib_1 = require("tslib");
27
27
  const rules_config_1 = require("@webpieces/rules-config");
28
+ const api_lib_spelling_configs_1 = require("./configs/api-lib-spelling-configs");
28
29
  const inversify_1 = require("inversify");
29
30
  const ts = tslib_1.__importStar(require("typescript"));
30
31
  const api_lib_enum_index_1 = require("./api-lib-enum-index");
@@ -232,7 +233,7 @@ let OneEnumSpellingInApiLibValidator = class OneEnumSpellingInApiLibValidator ex
232
233
  /** One index per api-library directory, per run: the union and its branches are in different files. */
233
234
  indexes = new Map();
234
235
  constructor(config, roleResolver, diffScope, scanScope) {
235
- super(config, rules_config_1.RULE_NAMES.ONE_ENUM_SPELLING_IN_API_LIB, roleResolver, diffScope, scanScope);
236
+ super(config, "one-enum-spelling-in-api-lib", roleResolver, diffScope, scanScope);
236
237
  }
237
238
  sitesIn(file) {
238
239
  let index = this.indexes.get(file.projectDir);
@@ -251,6 +252,6 @@ let OneEnumSpellingInApiLibValidator = class OneEnumSpellingInApiLibValidator ex
251
252
  exports.OneEnumSpellingInApiLibValidator = OneEnumSpellingInApiLibValidator;
252
253
  exports.OneEnumSpellingInApiLibValidator = OneEnumSpellingInApiLibValidator = tslib_1.__decorate([
253
254
  (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
254
- tslib_1.__metadata("design:paramtypes", [rules_config_1.OneEnumSpellingInApiLibConfig, project_role_resolver_1.ProjectRoleResolver, rules_config_1.DiffScope, scan_scope_1.ScanScope])
255
+ tslib_1.__metadata("design:paramtypes", [api_lib_spelling_configs_1.OneEnumSpellingInApiLibConfig, project_role_resolver_1.ProjectRoleResolver, rules_config_1.DiffScope, scan_scope_1.ScanScope])
255
256
  ], OneEnumSpellingInApiLibValidator);
256
257
  //# sourceMappingURL=validate-one-enum-spelling-in-api-lib.js.map