@webpieces/code-rules 0.4.817 → 0.4.818

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/code-rules",
3
- "version": "0.4.817",
3
+ "version": "0.4.818",
4
4
  "description": "Standalone code validation rules extracted from architecture-validators, no Nx dependency required",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -16,7 +16,7 @@
16
16
  "directory": "packages/tooling/code-rules"
17
17
  },
18
18
  "dependencies": {
19
- "@webpieces/rules-config": "0.4.817",
19
+ "@webpieces/rules-config": "0.4.818",
20
20
  "@inversifyjs/binding-decorators": "1.1.5",
21
21
  "inversify": "7.10.4",
22
22
  "reflect-metadata": "0.2.2"
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * The shared half of the api-library source rules: the two `role:api-lib` spelling rules (#1023),
3
- * `no-inline-import-in-api-lib` and `one-enum-spelling-in-api-lib`, and `no-utility-types-in-api-lib`
4
- * (#1026), which scopes itself by its configured `paths` globs instead of the role tag.
3
+ * `no-inline-import-in-api-lib` and `one-enum-spelling-in-api-lib`, `no-utility-types-in-api-lib`
4
+ * (#1026), which scopes itself by its configured `paths` globs instead of the role tag, and
5
+ * `required-type-suffix` (#1037), which scopes itself by its configured entries' `paths` globs.
5
6
  *
6
7
  * Both judge the SOURCE of an api library — the contract every consumer and the OpenAPI / MCP
7
8
  * generator read — and both have the same rollout shape: `mode` NEW_AND_MODIFIED_CODE judges only the
@@ -14,7 +15,7 @@
14
15
  * what it refuses, and a parse cannot be diverted to a `.d.ts` by module resolution.
15
16
  */
16
17
  import * as ts from 'typescript';
17
- import { DiffScope, NoInlineImportInApiLibConfig, NoUtilityTypesInApiLibConfig, OneEnumSpellingInApiLibConfig } from '@webpieces/rules-config';
18
+ import { DiffScope, NoInlineImportInApiLibConfig, NoUtilityTypesInApiLibConfig, OneEnumSpellingInApiLibConfig, RequiredTypeSuffixConfig } from '@webpieces/rules-config';
18
19
  import { CodeValidator, ExecutorResult } from './code-validator';
19
20
  import { ProjectRoleResolver } from './project-role-resolver';
20
21
  /** One violating site: where, what it is, and the edit that replaces it. Data-only. */
@@ -48,7 +49,7 @@ export declare class ApiLibFile {
48
49
  /** A site at `node`, its text collapsed to one line. */
49
50
  site(node: ts.Node, what: string, cure: string): ApiLibSite;
50
51
  }
51
- type ApiLibConfig = NoInlineImportInApiLibConfig | OneEnumSpellingInApiLibConfig | NoUtilityTypesInApiLibConfig;
52
+ type ApiLibConfig = NoInlineImportInApiLibConfig | OneEnumSpellingInApiLibConfig | NoUtilityTypesInApiLibConfig | RequiredTypeSuffixConfig;
52
53
  export declare abstract class ApiLibSourceRule<C extends ApiLibConfig> extends CodeValidator<C> {
53
54
  private readonly roleResolver;
54
55
  private readonly diffScope;
@@ -1,8 +1,9 @@
1
1
  "use strict";
2
2
  /**
3
3
  * The shared half of the api-library source rules: the two `role:api-lib` spelling rules (#1023),
4
- * `no-inline-import-in-api-lib` and `one-enum-spelling-in-api-lib`, and `no-utility-types-in-api-lib`
5
- * (#1026), which scopes itself by its configured `paths` globs instead of the role tag.
4
+ * `no-inline-import-in-api-lib` and `one-enum-spelling-in-api-lib`, `no-utility-types-in-api-lib`
5
+ * (#1026), which scopes itself by its configured `paths` globs instead of the role tag, and
6
+ * `required-type-suffix` (#1037), which scopes itself by its configured entries' `paths` globs.
6
7
  *
7
8
  * Both judge the SOURCE of an api library — the contract every consumer and the OpenAPI / MCP
8
9
  * generator read — and both have the same rollout shape: `mode` NEW_AND_MODIFIED_CODE judges only the
@@ -1 +1 @@
1
- {"version":3,"file":"api-lib-source-rule.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/api-lib-source-rule.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,uDAAiC;AACjC,0DAUiC;AACjC,qDAAiE;AAGjE,kC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CACJ;AAxGD,4CAwGC","sourcesContent":["/**\n * The shared half of the api-library source rules: the two `role:api-lib` spelling rules (#1023),\n * `no-inline-import-in-api-lib` and `one-enum-spelling-in-api-lib`, and `no-utility-types-in-api-lib`\n * (#1026), which scopes itself by its configured `paths` globs instead of the role tag.\n *\n * Both judge the SOURCE of an api library — the contract every consumer and the OpenAPI / MCP\n * generator read — and both have the same rollout shape: `mode` NEW_AND_MODIFIED_CODE judges only the\n * changed lines (so existing code is grandfathered until someone touches it), NEW_AND_MODIFIED_FILES\n * judges every site in a changed file. This class owns that scoping, the api-lib test, the escape\n * hatches, and the ONE failure spelling: a thrown `RuleFailError` with one `Option` per site, which\n * `RuleReporter` renders. A subclass only says what a violating site IS.\n *\n * Parser-only on purpose (no `ts.Program`): each rule reads the syntax as written, which is exactly\n * what it refuses, and a parse cannot be diverted to a `.d.ts` by module resolution.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as ts from 'typescript';\nimport {\n DiffScope,\n ModifiedCodeMode,\n NoInlineImportInApiLibConfig,\n NoUtilityTypesInApiLibConfig,\n OneEnumSpellingInApiLibConfig,\n Option,\n RuleFailError,\n hasDisable,\n isPathExcluded,\n} from '@webpieces/rules-config';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { ProjectRoleResolver } from './project-role-resolver';\n\n/** The role these rules judge. */\nconst API_LIB_ROLE = 'api-lib';\n\n/** One violating site: where, what it is, and the edit that replaces it. Data-only. */\nexport class ApiLibSite {\n constructor(\n /** 1-based line of the site's first character. */\n readonly line: number,\n /** The offending source text, trimmed to one line. */\n readonly snippet: string,\n readonly what: string,\n readonly cure: string,\n ) {}\n}\n\n/** One api-library source file, parsed, with the project directory that owns it. Data-only. */\nexport class ApiLibFile {\n constructor(\n /** Workspace-relative. */\n readonly relFile: string,\n readonly source: ts.SourceFile,\n /** Absolute path of the owning project's directory (the one holding project.json). */\n readonly projectDir: string,\n ) {}\n\n /** The 1-based line a node starts on. */\n lineOf(node: ts.Node): number {\n return this.source.getLineAndCharacterOfPosition(node.getStart(this.source)).line + 1;\n }\n\n /** A site at `node`, its text collapsed to one line. */\n site(node: ts.Node, what: string, cure: string): ApiLibSite {\n const text = node.getText(this.source).replace(/\\s+/g, ' ').trim();\n return new ApiLibSite(this.lineOf(node), text, what, cure);\n }\n}\n\n/** A located site, for the failure message. Data-only. */\nclass FoundSite {\n constructor(\n readonly relFile: string,\n readonly site: ApiLibSite,\n ) {}\n}\n\ntype ApiLibConfig = NoInlineImportInApiLibConfig | OneEnumSpellingInApiLibConfig | NoUtilityTypesInApiLibConfig;\n\nexport abstract class ApiLibSourceRule<C extends ApiLibConfig> extends CodeValidator<C> {\n constructor(\n config: C,\n ruleName: string,\n private readonly roleResolver: ProjectRoleResolver,\n private readonly diffScope: DiffScope,\n ) {\n super(config, ruleName, ruleName);\n }\n\n /** Every violating site in one api-library file. */\n protected abstract sitesIn(file: ApiLibFile): ApiLibSite[];\n\n /** The one-sentence WHY printed above the sites. */\n protected abstract why(): string;\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n const mode: ModifiedCodeMode | undefined = this.config.mode;\n if (mode === undefined || mode === 'OFF') return { success: true };\n // NX_BASE / NX_HEAD when nx set them, else the merge-base with main.\n const range = this.diffScope.resolveBase(workspaceRoot);\n const base = range.base;\n if (base === undefined) {\n console.log(`\\n⏭️ Skipping ${this.name} validation (could not detect base branch)\\n`);\n return { success: true };\n }\n const found: FoundSite[] = [];\n for (const relFile of this.diffScope.getChangedFiles(workspaceRoot, base, range.head)) {\n found.push(...this.judge(workspaceRoot, relFile, mode, base, range.head));\n }\n if (found.length === 0) return { success: true };\n throw this.failure(found);\n }\n\n /** The unexempt, in-scope violating sites of one changed file. */\n private judge(\n workspaceRoot: string,\n relFile: string,\n mode: ModifiedCodeMode,\n base: string,\n head: string | undefined,\n ): FoundSite[] {\n if (!this.inScope(workspaceRoot, relFile)) return [];\n const changedLines = mode === 'NEW_AND_MODIFIED_CODE'\n ? this.diffScope.getChangedLineNumbers(this.diffScope.getFileDiff(workspaceRoot, relFile, base, head))\n : undefined;\n if (changedLines !== undefined && changedLines.size === 0) return [];\n const absFile = path.join(workspaceRoot, relFile);\n const text = fs.readFileSync(absFile, 'utf8');\n const lines = text.split('\\n');\n const source = ts.createSourceFile(absFile, text, ts.ScriptTarget.Latest, true);\n const file = new ApiLibFile(relFile, source, this.projectDirOf(workspaceRoot, relFile));\n return this.sitesIn(file)\n .filter((site: ApiLibSite) => changedLines === undefined || changedLines.has(site.line))\n .filter((site: ApiLibSite) => !this.disabled(lines, site.line))\n .map((site: ApiLibSite) => new FoundSite(relFile, site));\n }\n\n /** A non-test `.ts` file, not under `allowedPaths`, that {@link isApiLibrarySource} claims. */\n private inScope(workspaceRoot: string, relFile: string): boolean {\n if (!relFile.endsWith('.ts') || relFile.endsWith('.d.ts')) return false;\n if (/\\.(spec|test)\\.ts$/.test(relFile) || relFile.includes('__tests__/')) return false;\n if (isPathExcluded(relFile, this.config.allowedPaths ?? [])) return false;\n if (!fs.existsSync(path.join(workspaceRoot, relFile))) return false;\n return this.isApiLibrarySource(workspaceRoot, relFile);\n }\n\n /** Is `relFile` part of an api library? By default: its owning project is tagged `role:api-lib`. */\n protected isApiLibrarySource(workspaceRoot: string, relFile: string): boolean {\n return this.roleResolver.roleOf(workspaceRoot, relFile) === API_LIB_ROLE;\n }\n\n /** How the failure names where the sites are — must agree with {@link isApiLibrarySource}. */\n protected scopeLabel(): string {\n return 'a role:api-lib project';\n }\n\n /** `// webpieces-disable <rule> -- <reason>` on the site's line or the line above. */\n private disabled(lines: readonly string[], line: number): boolean {\n return hasDisable(lines[line - 1] ?? '', this.name) || hasDisable(lines[line - 2] ?? '', this.name);\n }\n\n /** The nearest ancestor of `relFile` holding a project.json, absolute. */\n private projectDirOf(workspaceRoot: string, relFile: string): string {\n let dir = path.dirname(path.join(workspaceRoot, relFile));\n while (!fs.existsSync(path.join(dir, 'project.json')) && path.dirname(dir) !== dir) {\n dir = path.dirname(dir);\n }\n return dir;\n }\n\n private failure(found: readonly FoundSite[]): RuleFailError {\n const message =\n `${found.length} site(s) in ${this.scopeLabel()}: ${this.why()}\\n` +\n found.map((each: FoundSite) => ` ${each.relFile}:${each.site.line} — ${each.site.what}\\n ${each.site.snippet}`).join('\\n') +\n `\\n Last resort, per site: // webpieces-disable ${this.name} -- <reason>`;\n return new RuleFailError(\n this.name,\n message,\n undefined,\n undefined,\n found.map((each: FoundSite) => new Option(`${each.relFile}:${each.site.line}: ${each.site.cure}`, true)),\n );\n }\n}\n"]}
1
+ {"version":3,"file":"api-lib-source-rule.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/api-lib-source-rule.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,uDAAiC;AACjC,0DAWiC;AACjC,qDAAiE;AAGjE,kCAAkC;AAClC,MAAM,YAAY,GAAG,SAAS,CAAC;AAE/B,uFAAuF;AACvF,MAAa,UAAU;IAGN;IAEA;IACA;IACA;IANb;IACI,kDAAkD;IACzC,IAAY;IACrB,sDAAsD;IAC7C,OAAe,EACf,IAAY,EACZ,IAAY;QAJZ,SAAI,GAAJ,IAAI,CAAQ;QAEZ,YAAO,GAAP,OAAO,CAAQ;QACf,SAAI,GAAJ,IAAI,CAAQ;QACZ,SAAI,GAAJ,IAAI,CAAQ;IACtB,CAAC;CACP;AATD,gCASC;AAED,+FAA+F;AAC/F,MAAa,UAAU;IAGN;IACA;IAEA;IALb;IACI,0BAA0B;IACjB,OAAe,EACf,MAAqB;IAC9B,sFAAsF;IAC7E,UAAkB;QAHlB,YAAO,GAAP,OAAO,CAAQ;QACf,WAAM,GAAN,MAAM,CAAe;QAErB,eAAU,GAAV,UAAU,CAAQ;IAC5B,CAAC;IAEJ,yCAAyC;IACzC,MAAM,CAAC,IAAa;QAChB,OAAO,IAAI,CAAC,MAAM,CAAC,6BAA6B,CAAC,IAAI,CAAC,QAAQ,CAAC,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IAAe,EAAE,EAAE,CAAC,KAAK,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,MAAM,IAAI,CAAC,IAAI,CAAC,IAAI,WAAW,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;YAChI,mDAAmD,IAAI,CAAC,IAAI,cAAc,CAAC;QAC/E,OAAO,IAAI,4BAAa,CACpB,IAAI,CAAC,IAAI,EACT,OAAO,EACP,SAAS,EACT,SAAS,EACT,KAAK,CAAC,GAAG,CAAC,CAAC,IAAe,EAAE,EAAE,CAAC,IAAI,qBAAM,CAAC,GAAG,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,KAAK,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,EAAE,IAAI,CAAC,CAAC,CAC3G,CAAC;IACN,CAAC;CACJ;AAxGD,4CAwGC","sourcesContent":["/**\n * The shared half of the api-library source rules: the two `role:api-lib` spelling rules (#1023),\n * `no-inline-import-in-api-lib` and `one-enum-spelling-in-api-lib`, `no-utility-types-in-api-lib`\n * (#1026), which scopes itself by its configured `paths` globs instead of the role tag, and\n * `required-type-suffix` (#1037), which scopes itself by its configured entries' `paths` globs.\n *\n * Both judge the SOURCE of an api library — the contract every consumer and the OpenAPI / MCP\n * generator read — and both have the same rollout shape: `mode` NEW_AND_MODIFIED_CODE judges only the\n * changed lines (so existing code is grandfathered until someone touches it), NEW_AND_MODIFIED_FILES\n * judges every site in a changed file. This class owns that scoping, the api-lib test, the escape\n * hatches, and the ONE failure spelling: a thrown `RuleFailError` with one `Option` per site, which\n * `RuleReporter` renders. A subclass only says what a violating site IS.\n *\n * Parser-only on purpose (no `ts.Program`): each rule reads the syntax as written, which is exactly\n * what it refuses, and a parse cannot be diverted to a `.d.ts` by module resolution.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as ts from 'typescript';\nimport {\n DiffScope,\n ModifiedCodeMode,\n NoInlineImportInApiLibConfig,\n NoUtilityTypesInApiLibConfig,\n OneEnumSpellingInApiLibConfig,\n Option,\n RequiredTypeSuffixConfig,\n RuleFailError,\n hasDisable,\n isPathExcluded,\n} from '@webpieces/rules-config';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { ProjectRoleResolver } from './project-role-resolver';\n\n/** The role these rules judge. */\nconst API_LIB_ROLE = 'api-lib';\n\n/** One violating site: where, what it is, and the edit that replaces it. Data-only. */\nexport class ApiLibSite {\n constructor(\n /** 1-based line of the site's first character. */\n readonly line: number,\n /** The offending source text, trimmed to one line. */\n readonly snippet: string,\n readonly what: string,\n readonly cure: string,\n ) {}\n}\n\n/** One api-library source file, parsed, with the project directory that owns it. Data-only. */\nexport class ApiLibFile {\n constructor(\n /** Workspace-relative. */\n readonly relFile: string,\n readonly source: ts.SourceFile,\n /** Absolute path of the owning project's directory (the one holding project.json). */\n readonly projectDir: string,\n ) {}\n\n /** The 1-based line a node starts on. */\n lineOf(node: ts.Node): number {\n return this.source.getLineAndCharacterOfPosition(node.getStart(this.source)).line + 1;\n }\n\n /** A site at `node`, its text collapsed to one line. */\n site(node: ts.Node, what: string, cure: string): ApiLibSite {\n const text = node.getText(this.source).replace(/\\s+/g, ' ').trim();\n return new ApiLibSite(this.lineOf(node), text, what, cure);\n }\n}\n\n/** A located site, for the failure message. Data-only. */\nclass FoundSite {\n constructor(\n readonly relFile: string,\n readonly site: ApiLibSite,\n ) {}\n}\n\ntype ApiLibConfig =\n | NoInlineImportInApiLibConfig\n | OneEnumSpellingInApiLibConfig\n | NoUtilityTypesInApiLibConfig\n | RequiredTypeSuffixConfig;\n\nexport abstract class ApiLibSourceRule<C extends ApiLibConfig> extends CodeValidator<C> {\n constructor(\n config: C,\n ruleName: string,\n private readonly roleResolver: ProjectRoleResolver,\n private readonly diffScope: DiffScope,\n ) {\n super(config, ruleName, ruleName);\n }\n\n /** Every violating site in one api-library file. */\n protected abstract sitesIn(file: ApiLibFile): ApiLibSite[];\n\n /** The one-sentence WHY printed above the sites. */\n protected abstract why(): string;\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n const mode: ModifiedCodeMode | undefined = this.config.mode;\n if (mode === undefined || mode === 'OFF') return { success: true };\n // NX_BASE / NX_HEAD when nx set them, else the merge-base with main.\n const range = this.diffScope.resolveBase(workspaceRoot);\n const base = range.base;\n if (base === undefined) {\n console.log(`\\n⏭️ Skipping ${this.name} validation (could not detect base branch)\\n`);\n return { success: true };\n }\n const found: FoundSite[] = [];\n for (const relFile of this.diffScope.getChangedFiles(workspaceRoot, base, range.head)) {\n found.push(...this.judge(workspaceRoot, relFile, mode, base, range.head));\n }\n if (found.length === 0) return { success: true };\n throw this.failure(found);\n }\n\n /** The unexempt, in-scope violating sites of one changed file. */\n private judge(\n workspaceRoot: string,\n relFile: string,\n mode: ModifiedCodeMode,\n base: string,\n head: string | undefined,\n ): FoundSite[] {\n if (!this.inScope(workspaceRoot, relFile)) return [];\n const changedLines = mode === 'NEW_AND_MODIFIED_CODE'\n ? this.diffScope.getChangedLineNumbers(this.diffScope.getFileDiff(workspaceRoot, relFile, base, head))\n : undefined;\n if (changedLines !== undefined && changedLines.size === 0) return [];\n const absFile = path.join(workspaceRoot, relFile);\n const text = fs.readFileSync(absFile, 'utf8');\n const lines = text.split('\\n');\n const source = ts.createSourceFile(absFile, text, ts.ScriptTarget.Latest, true);\n const file = new ApiLibFile(relFile, source, this.projectDirOf(workspaceRoot, relFile));\n return this.sitesIn(file)\n .filter((site: ApiLibSite) => changedLines === undefined || changedLines.has(site.line))\n .filter((site: ApiLibSite) => !this.disabled(lines, site.line))\n .map((site: ApiLibSite) => new FoundSite(relFile, site));\n }\n\n /** A non-test `.ts` file, not under `allowedPaths`, that {@link isApiLibrarySource} claims. */\n private inScope(workspaceRoot: string, relFile: string): boolean {\n if (!relFile.endsWith('.ts') || relFile.endsWith('.d.ts')) return false;\n if (/\\.(spec|test)\\.ts$/.test(relFile) || relFile.includes('__tests__/')) return false;\n if (isPathExcluded(relFile, this.config.allowedPaths ?? [])) return false;\n if (!fs.existsSync(path.join(workspaceRoot, relFile))) return false;\n return this.isApiLibrarySource(workspaceRoot, relFile);\n }\n\n /** Is `relFile` part of an api library? By default: its owning project is tagged `role:api-lib`. */\n protected isApiLibrarySource(workspaceRoot: string, relFile: string): boolean {\n return this.roleResolver.roleOf(workspaceRoot, relFile) === API_LIB_ROLE;\n }\n\n /** How the failure names where the sites are — must agree with {@link isApiLibrarySource}. */\n protected scopeLabel(): string {\n return 'a role:api-lib project';\n }\n\n /** `// webpieces-disable <rule> -- <reason>` on the site's line or the line above. */\n private disabled(lines: readonly string[], line: number): boolean {\n return hasDisable(lines[line - 1] ?? '', this.name) || hasDisable(lines[line - 2] ?? '', this.name);\n }\n\n /** The nearest ancestor of `relFile` holding a project.json, absolute. */\n private projectDirOf(workspaceRoot: string, relFile: string): string {\n let dir = path.dirname(path.join(workspaceRoot, relFile));\n while (!fs.existsSync(path.join(dir, 'project.json')) && path.dirname(dir) !== dir) {\n dir = path.dirname(dir);\n }\n return dir;\n }\n\n private failure(found: readonly FoundSite[]): RuleFailError {\n const message =\n `${found.length} site(s) in ${this.scopeLabel()}: ${this.why()}\\n` +\n found.map((each: FoundSite) => ` ${each.relFile}:${each.site.line} — ${each.site.what}\\n ${each.site.snippet}`).join('\\n') +\n `\\n Last resort, per site: // webpieces-disable ${this.name} -- <reason>`;\n return new RuleFailError(\n this.name,\n message,\n undefined,\n undefined,\n found.map((each: FoundSite) => new Option(`${each.relFile}:${each.site.line}: ${each.site.cure}`, true)),\n );\n }\n}\n"]}
@@ -37,5 +37,6 @@ exports.CONFIG_BINDINGS = [
37
37
  [rules_config_1.NoInlineImportInApiLibConfig, 'no-inline-import-in-api-lib'],
38
38
  [rules_config_1.OneEnumSpellingInApiLibConfig, 'one-enum-spelling-in-api-lib'],
39
39
  [rules_config_1.NoUtilityTypesInApiLibConfig, 'no-utility-types-in-api-lib'],
40
+ [rules_config_1.RequiredTypeSuffixConfig, 'required-type-suffix'],
40
41
  ];
41
42
  //# sourceMappingURL=code-rules-config-table.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"code-rules-config-table.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/code-rules-config-table.ts"],"names":[],"mappings":";;;AAAA,0DA4BiC;AAKjC;;;;;GAKG;AACU,QAAA,eAAe,GAAqE;IAC7F,CAAC,mCAAoB,EAAE,kBAAkB,CAAC;IAC1C,CAAC,iCAAkB,EAAE,gBAAgB,CAAC;IACtC,CAAC,sCAAuB,EAAE,qBAAqB,CAAC;IAChD,CAAC,yCAA0B,EAAE,yBAAyB,CAAC;IACvD,CAAC,iCAAkB,EAAE,gBAAgB,CAAC;IACtC,CAAC,kCAAmB,EAAE,iBAAiB,CAAC;IACxC,CAAC,uCAAwB,EAAE,sBAAsB,CAAC;IAClD,CAAC,oCAAqB,EAAE,kBAAkB,CAAC;IAC3C,CAAC,kCAAmB,EAAE,gBAAgB,CAAC;IACvC,CAAC,sCAAuB,EAAE,qBAAqB,CAAC;IAChD,CAAC,0CAA2B,EAAE,yBAAyB,CAAC;IACxD,CAAC,iDAAkC,EAAE,mCAAmC,CAAC;IACzE,CAAC,qCAAsB,EAAE,qBAAqB,CAAC;IAC/C,CAAC,0DAA2C,EAAE,6CAA6C,CAAC;IAC5F,CAAC,gCAAiB,EAAE,eAAe,CAAC;IACpC,CAAC,4CAA6B,EAAE,6BAA6B,CAAC;IAC9D,CAAC,6CAA8B,EAAE,8BAA8B,CAAC;IAChE,CAAC,2CAA4B,EAAE,2BAA2B,CAAC;IAC3D;QACI,8DAA+C;QAC/C,iDAAiD;KACpD;IACD,CAAC,iCAAkB,EAAE,eAAe,CAAC;IACrC,CAAC,4BAAa,EAAE,UAAU,CAAC;IAC3B,CAAC,sCAAuB,EAAE,sBAAsB,CAAC;IACjD,CAAC,2CAA4B,EAAE,6BAA6B,CAAC;IAC7D,CAAC,4CAA6B,EAAE,8BAA8B,CAAC;IAC/D,CAAC,2CAA4B,EAAE,6BAA6B,CAAC;CAChE,CAAC","sourcesContent":["import {\n BaseRuleConfig,\n WebpiecesRulesConfig,\n MaxMethodLinesConfig,\n MaxFileLinesConfig,\n RequireReturnTypeConfig,\n NoInlineTypeLiteralsConfig,\n NoAnyUnknownConfig,\n NoImplicitAnyConfig,\n PrismaValidateDtosConfig,\n PrismaConverterConfig,\n NoDestructureConfig,\n CatchErrorPatternConfig,\n NoUnmanagedExceptionsConfig,\n AngularNoDirectApiInResolverConfig,\n NoSymbolDiTokensConfig,\n NoClientCreationOutsideServerOrClientConfig,\n NoCustomCssConfig,\n NoStatePathsInTemplatesConfig,\n NoProcessExitOutsideMainConfig,\n NoFunctionOutsideClassConfig,\n InjectAnnotationNotNeededForConcreteClassConfig,\n FrameworkTagConfig,\n RoleTagConfig,\n EnsureWeAreSecureConfig,\n NoInlineImportInApiLibConfig,\n OneEnumSpellingInApiLibConfig,\n NoUtilityTypesInApiLibConfig,\n} from '@webpieces/rules-config';\n\n/** A rule config class usable as an inversify inject-by-type token. */\nexport type ConfigCtor = new () => BaseRuleConfig;\n\n/**\n * The 1:1 table of `[config class, webpieces.config.json rule key]`. The composition root iterates it\n * to bind each rule's config into the container (`bind(ConfigClass).toConstantValue(config[key] ??\n * new ConfigClass())`), so every `@provideSingleton` validator injects its config by type. Data only\n * — the binding loop lives inline in the bin (an inline loop, exempt from no-function-outside-class).\n */\nexport const CONFIG_BINDINGS: ReadonlyArray<readonly [ConfigCtor, keyof WebpiecesRulesConfig]> = [\n [MaxMethodLinesConfig, 'max-method-lines'],\n [MaxFileLinesConfig, 'max-file-lines'],\n [RequireReturnTypeConfig, 'require-return-type'],\n [NoInlineTypeLiteralsConfig, 'no-inline-type-literals'],\n [NoAnyUnknownConfig, 'no-any-unknown'],\n [NoImplicitAnyConfig, 'no-implicit-any'],\n [PrismaValidateDtosConfig, 'prisma-validate-dtos'],\n [PrismaConverterConfig, 'prisma-converter'],\n [NoDestructureConfig, 'no-destructure'],\n [CatchErrorPatternConfig, 'catch-error-pattern'],\n [NoUnmanagedExceptionsConfig, 'no-unmanaged-exceptions'],\n [AngularNoDirectApiInResolverConfig, 'angular-no-direct-api-in-resolver'],\n [NoSymbolDiTokensConfig, 'no-symbol-di-tokens'],\n [NoClientCreationOutsideServerOrClientConfig, 'no-client-creation-outside-server-or-client'],\n [NoCustomCssConfig, 'no-custom-css'],\n [NoStatePathsInTemplatesConfig, 'no-state-paths-in-templates'],\n [NoProcessExitOutsideMainConfig, 'no-process-exit-outside-main'],\n [NoFunctionOutsideClassConfig, 'no-function-outside-class'],\n [\n InjectAnnotationNotNeededForConcreteClassConfig,\n 'inject-annotation-not-needed-for-concrete-class',\n ],\n [FrameworkTagConfig, 'framework-tag'],\n [RoleTagConfig, 'role-tag'],\n [EnsureWeAreSecureConfig, 'ensure-we-are-secure'],\n [NoInlineImportInApiLibConfig, 'no-inline-import-in-api-lib'],\n [OneEnumSpellingInApiLibConfig, 'one-enum-spelling-in-api-lib'],\n [NoUtilityTypesInApiLibConfig, 'no-utility-types-in-api-lib'],\n];\n"]}
1
+ {"version":3,"file":"code-rules-config-table.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/code-rules-config-table.ts"],"names":[],"mappings":";;;AAAA,0DA6BiC;AAKjC;;;;;GAKG;AACU,QAAA,eAAe,GAAqE;IAC7F,CAAC,mCAAoB,EAAE,kBAAkB,CAAC;IAC1C,CAAC,iCAAkB,EAAE,gBAAgB,CAAC;IACtC,CAAC,sCAAuB,EAAE,qBAAqB,CAAC;IAChD,CAAC,yCAA0B,EAAE,yBAAyB,CAAC;IACvD,CAAC,iCAAkB,EAAE,gBAAgB,CAAC;IACtC,CAAC,kCAAmB,EAAE,iBAAiB,CAAC;IACxC,CAAC,uCAAwB,EAAE,sBAAsB,CAAC;IAClD,CAAC,oCAAqB,EAAE,kBAAkB,CAAC;IAC3C,CAAC,kCAAmB,EAAE,gBAAgB,CAAC;IACvC,CAAC,sCAAuB,EAAE,qBAAqB,CAAC;IAChD,CAAC,0CAA2B,EAAE,yBAAyB,CAAC;IACxD,CAAC,iDAAkC,EAAE,mCAAmC,CAAC;IACzE,CAAC,qCAAsB,EAAE,qBAAqB,CAAC;IAC/C,CAAC,0DAA2C,EAAE,6CAA6C,CAAC;IAC5F,CAAC,gCAAiB,EAAE,eAAe,CAAC;IACpC,CAAC,4CAA6B,EAAE,6BAA6B,CAAC;IAC9D,CAAC,6CAA8B,EAAE,8BAA8B,CAAC;IAChE,CAAC,2CAA4B,EAAE,2BAA2B,CAAC;IAC3D;QACI,8DAA+C;QAC/C,iDAAiD;KACpD;IACD,CAAC,iCAAkB,EAAE,eAAe,CAAC;IACrC,CAAC,4BAAa,EAAE,UAAU,CAAC;IAC3B,CAAC,sCAAuB,EAAE,sBAAsB,CAAC;IACjD,CAAC,2CAA4B,EAAE,6BAA6B,CAAC;IAC7D,CAAC,4CAA6B,EAAE,8BAA8B,CAAC;IAC/D,CAAC,2CAA4B,EAAE,6BAA6B,CAAC;IAC7D,CAAC,uCAAwB,EAAE,sBAAsB,CAAC;CACrD,CAAC","sourcesContent":["import {\n BaseRuleConfig,\n WebpiecesRulesConfig,\n MaxMethodLinesConfig,\n MaxFileLinesConfig,\n RequireReturnTypeConfig,\n NoInlineTypeLiteralsConfig,\n NoAnyUnknownConfig,\n NoImplicitAnyConfig,\n PrismaValidateDtosConfig,\n PrismaConverterConfig,\n NoDestructureConfig,\n CatchErrorPatternConfig,\n NoUnmanagedExceptionsConfig,\n AngularNoDirectApiInResolverConfig,\n NoSymbolDiTokensConfig,\n NoClientCreationOutsideServerOrClientConfig,\n NoCustomCssConfig,\n NoStatePathsInTemplatesConfig,\n NoProcessExitOutsideMainConfig,\n NoFunctionOutsideClassConfig,\n InjectAnnotationNotNeededForConcreteClassConfig,\n FrameworkTagConfig,\n RoleTagConfig,\n EnsureWeAreSecureConfig,\n NoInlineImportInApiLibConfig,\n OneEnumSpellingInApiLibConfig,\n NoUtilityTypesInApiLibConfig,\n RequiredTypeSuffixConfig,\n} from '@webpieces/rules-config';\n\n/** A rule config class usable as an inversify inject-by-type token. */\nexport type ConfigCtor = new () => BaseRuleConfig;\n\n/**\n * The 1:1 table of `[config class, webpieces.config.json rule key]`. The composition root iterates it\n * to bind each rule's config into the container (`bind(ConfigClass).toConstantValue(config[key] ??\n * new ConfigClass())`), so every `@provideSingleton` validator injects its config by type. Data only\n * — the binding loop lives inline in the bin (an inline loop, exempt from no-function-outside-class).\n */\nexport const CONFIG_BINDINGS: ReadonlyArray<readonly [ConfigCtor, keyof WebpiecesRulesConfig]> = [\n [MaxMethodLinesConfig, 'max-method-lines'],\n [MaxFileLinesConfig, 'max-file-lines'],\n [RequireReturnTypeConfig, 'require-return-type'],\n [NoInlineTypeLiteralsConfig, 'no-inline-type-literals'],\n [NoAnyUnknownConfig, 'no-any-unknown'],\n [NoImplicitAnyConfig, 'no-implicit-any'],\n [PrismaValidateDtosConfig, 'prisma-validate-dtos'],\n [PrismaConverterConfig, 'prisma-converter'],\n [NoDestructureConfig, 'no-destructure'],\n [CatchErrorPatternConfig, 'catch-error-pattern'],\n [NoUnmanagedExceptionsConfig, 'no-unmanaged-exceptions'],\n [AngularNoDirectApiInResolverConfig, 'angular-no-direct-api-in-resolver'],\n [NoSymbolDiTokensConfig, 'no-symbol-di-tokens'],\n [NoClientCreationOutsideServerOrClientConfig, 'no-client-creation-outside-server-or-client'],\n [NoCustomCssConfig, 'no-custom-css'],\n [NoStatePathsInTemplatesConfig, 'no-state-paths-in-templates'],\n [NoProcessExitOutsideMainConfig, 'no-process-exit-outside-main'],\n [NoFunctionOutsideClassConfig, 'no-function-outside-class'],\n [\n InjectAnnotationNotNeededForConcreteClassConfig,\n 'inject-annotation-not-needed-for-concrete-class',\n ],\n [FrameworkTagConfig, 'framework-tag'],\n [RoleTagConfig, 'role-tag'],\n [EnsureWeAreSecureConfig, 'ensure-we-are-secure'],\n [NoInlineImportInApiLibConfig, 'no-inline-import-in-api-lib'],\n [OneEnumSpellingInApiLibConfig, 'one-enum-spelling-in-api-lib'],\n [NoUtilityTypesInApiLibConfig, 'no-utility-types-in-api-lib'],\n [RequiredTypeSuffixConfig, 'required-type-suffix'],\n];\n"]}
@@ -31,6 +31,7 @@ import { EnsureWeAreSecureValidator } from './validate-ensure-we-are-secure';
31
31
  import { NoInlineImportInApiLibValidator } from './validate-no-inline-import-in-api-lib';
32
32
  import { OneEnumSpellingInApiLibValidator } from './validate-one-enum-spelling-in-api-lib';
33
33
  import { NoUtilityTypesInApiLibValidator } from './validate-no-utility-types-in-api-lib';
34
+ import { RequiredTypeSuffixValidator } from './validate-required-type-suffix';
34
35
  /**
35
36
  * Owns running the code-rules suite. Every built-in validator is injected as a singleton (its config
36
37
  * is bound in the container at bootstrap), so this class IS the code-rules DI DAG the design graph
@@ -71,7 +72,8 @@ export declare class CodeRulesEngine {
71
72
  private readonly noInlineImportInApiLib;
72
73
  private readonly oneEnumSpellingInApiLib;
73
74
  private readonly noUtilityTypesInApiLib;
74
- constructor(workspace: WorkspaceRoot, reporter: RuleReporter, matchRules: MatchRulesHolder, matchChecker: MatchRulesChecker, request: CodeRulesRunRequest, scopes: RuleScopes, debugReport: DebugRunReport, diffScope: DiffScope, maxMethodLines: MaxMethodLinesValidator, maxFileLines: MaxFileLinesValidator, requireReturnType: RequireReturnTypeValidator, noInlineTypeLiterals: NoInlineTypeLiteralsValidator, noAnyUnknown: NoAnyUnknownValidator, noImplicitAny: NoImplicitAnyValidator, prismaValidateDtos: PrismaValidateDtosValidator, prismaConverter: PrismaConverterValidator, noDestructure: NoDestructureValidator, catchErrorPattern: CatchErrorPatternValidator, noUnmanagedExceptions: NoUnmanagedExceptionsValidator, noDirectApiResolver: NoDirectApiResolverValidator, noSymbolDiTokens: NoSymbolDiTokensValidator, noClientCreationOutsideServerOrClient: NoClientCreationOutsideServerOrClientValidator, noCustomCss: NoCustomCssValidator, noStatePathsInTemplates: NoStatePathsInTemplatesValidator, noProcessExitOutsideMain: NoProcessExitOutsideMainValidator, noFunctionOutsideClass: NoFunctionOutsideClassValidator, injectAnnotationNotNeeded: InjectAnnotationNotNeededForConcreteClassValidator, frameworkTag: FrameworkTagValidator, roleTag: RoleTagValidator, ensureWeAreSecure: EnsureWeAreSecureValidator, noInlineImportInApiLib: NoInlineImportInApiLibValidator, oneEnumSpellingInApiLib: OneEnumSpellingInApiLibValidator, noUtilityTypesInApiLib: NoUtilityTypesInApiLibValidator);
75
+ private readonly requiredTypeSuffix;
76
+ constructor(workspace: WorkspaceRoot, reporter: RuleReporter, matchRules: MatchRulesHolder, matchChecker: MatchRulesChecker, request: CodeRulesRunRequest, scopes: RuleScopes, debugReport: DebugRunReport, diffScope: DiffScope, maxMethodLines: MaxMethodLinesValidator, maxFileLines: MaxFileLinesValidator, requireReturnType: RequireReturnTypeValidator, noInlineTypeLiterals: NoInlineTypeLiteralsValidator, noAnyUnknown: NoAnyUnknownValidator, noImplicitAny: NoImplicitAnyValidator, prismaValidateDtos: PrismaValidateDtosValidator, prismaConverter: PrismaConverterValidator, noDestructure: NoDestructureValidator, catchErrorPattern: CatchErrorPatternValidator, noUnmanagedExceptions: NoUnmanagedExceptionsValidator, noDirectApiResolver: NoDirectApiResolverValidator, noSymbolDiTokens: NoSymbolDiTokensValidator, noClientCreationOutsideServerOrClient: NoClientCreationOutsideServerOrClientValidator, noCustomCss: NoCustomCssValidator, noStatePathsInTemplates: NoStatePathsInTemplatesValidator, noProcessExitOutsideMain: NoProcessExitOutsideMainValidator, noFunctionOutsideClass: NoFunctionOutsideClassValidator, injectAnnotationNotNeeded: InjectAnnotationNotNeededForConcreteClassValidator, frameworkTag: FrameworkTagValidator, roleTag: RoleTagValidator, ensureWeAreSecure: EnsureWeAreSecureValidator, noInlineImportInApiLib: NoInlineImportInApiLibValidator, oneEnumSpellingInApiLib: OneEnumSpellingInApiLibValidator, noUtilityTypesInApiLib: NoUtilityTypesInApiLibValidator, requiredTypeSuffix: RequiredTypeSuffixValidator);
75
77
  /** The injected built-in validators, in run order. */
76
78
  private builtIns;
77
79
  /**
@@ -36,6 +36,7 @@ const validate_ensure_we_are_secure_1 = require("./validate-ensure-we-are-secure
36
36
  const validate_no_inline_import_in_api_lib_1 = require("./validate-no-inline-import-in-api-lib");
37
37
  const validate_one_enum_spelling_in_api_lib_1 = require("./validate-one-enum-spelling-in-api-lib");
38
38
  const validate_no_utility_types_in_api_lib_1 = require("./validate-no-utility-types-in-api-lib");
39
+ const validate_required_type_suffix_1 = require("./validate-required-type-suffix");
39
40
  /**
40
41
  * Owns running the code-rules suite. Every built-in validator is injected as a singleton (its config
41
42
  * is bound in the container at bootstrap), so this class IS the code-rules DI DAG the design graph
@@ -76,8 +77,9 @@ let CodeRulesEngine = class CodeRulesEngine {
76
77
  noInlineImportInApiLib;
77
78
  oneEnumSpellingInApiLib;
78
79
  noUtilityTypesInApiLib;
80
+ requiredTypeSuffix;
79
81
  // webpieces-disable max-lines-new-methods -- the built-in validator set is flat; each is one injected field
80
- constructor(workspace, reporter, matchRules, matchChecker, request, scopes, debugReport, diffScope, maxMethodLines, maxFileLines, requireReturnType, noInlineTypeLiterals, noAnyUnknown, noImplicitAny, prismaValidateDtos, prismaConverter, noDestructure, catchErrorPattern, noUnmanagedExceptions, noDirectApiResolver, noSymbolDiTokens, noClientCreationOutsideServerOrClient, noCustomCss, noStatePathsInTemplates, noProcessExitOutsideMain, noFunctionOutsideClass, injectAnnotationNotNeeded, frameworkTag, roleTag, ensureWeAreSecure, noInlineImportInApiLib, oneEnumSpellingInApiLib, noUtilityTypesInApiLib) {
82
+ constructor(workspace, reporter, matchRules, matchChecker, request, scopes, debugReport, diffScope, maxMethodLines, maxFileLines, requireReturnType, noInlineTypeLiterals, noAnyUnknown, noImplicitAny, prismaValidateDtos, prismaConverter, noDestructure, catchErrorPattern, noUnmanagedExceptions, noDirectApiResolver, noSymbolDiTokens, noClientCreationOutsideServerOrClient, noCustomCss, noStatePathsInTemplates, noProcessExitOutsideMain, noFunctionOutsideClass, injectAnnotationNotNeeded, frameworkTag, roleTag, ensureWeAreSecure, noInlineImportInApiLib, oneEnumSpellingInApiLib, noUtilityTypesInApiLib, requiredTypeSuffix) {
81
83
  this.workspace = workspace;
82
84
  this.reporter = reporter;
83
85
  this.matchRules = matchRules;
@@ -111,6 +113,7 @@ let CodeRulesEngine = class CodeRulesEngine {
111
113
  this.noInlineImportInApiLib = noInlineImportInApiLib;
112
114
  this.oneEnumSpellingInApiLib = oneEnumSpellingInApiLib;
113
115
  this.noUtilityTypesInApiLib = noUtilityTypesInApiLib;
116
+ this.requiredTypeSuffix = requiredTypeSuffix;
114
117
  }
115
118
  /** The injected built-in validators, in run order. */
116
119
  builtIns() {
@@ -140,6 +143,7 @@ let CodeRulesEngine = class CodeRulesEngine {
140
143
  this.noInlineImportInApiLib,
141
144
  this.oneEnumSpellingInApiLib,
142
145
  this.noUtilityTypesInApiLib,
146
+ this.requiredTypeSuffix,
143
147
  ];
144
148
  }
145
149
  /**
@@ -226,6 +230,7 @@ exports.CodeRulesEngine = CodeRulesEngine = tslib_1.__decorate([
226
230
  validate_ensure_we_are_secure_1.EnsureWeAreSecureValidator,
227
231
  validate_no_inline_import_in_api_lib_1.NoInlineImportInApiLibValidator,
228
232
  validate_one_enum_spelling_in_api_lib_1.OneEnumSpellingInApiLibValidator,
229
- validate_no_utility_types_in_api_lib_1.NoUtilityTypesInApiLibValidator])
233
+ validate_no_utility_types_in_api_lib_1.NoUtilityTypesInApiLibValidator,
234
+ validate_required_type_suffix_1.RequiredTypeSuffixValidator])
230
235
  ], CodeRulesEngine);
231
236
  //# sourceMappingURL=code-rules-engine.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"code-rules-engine.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/code-rules-engine.ts"],"names":[],"mappings":";;;;AAAA,0DAA+E;AAC/E,yCAA2D;AAE3D,qDAA0E;AAC1E,mDAA+C;AAC/C,6DAAuE;AACvE,qEAA+D;AAC/D,yDAAoD;AACpD,uDAA+C;AAC/C,iE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EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAC/E,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAEhB,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;QACvD,OAAO,CAAC,GAAG,CACP,MAAM,CAAC,OAAO;YACV,CAAC,CAAC,mCAAmC;YACrC,CAAC,CAAC,oCAAoC,CAC7C,CAAC;QACF,OAAO,MAAM,CAAC;IAClB,CAAC;CACJ,CAAA;AA3HY,0CAAe;0BAAf,eAAe;IAD3B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAIL,kCAAa;QACd,4BAAY;QACV,qCAAgB;QACd,wCAAiB;QACtB,4CAAmB;QACpB,4BAAU;QACL,iCAAc;QAChB,wBAAS;QACJ,mDAAuB;QACzB,+CAAqB;QAChB,kDAA0B;QACvB,wDAA6B;QACrC,+CAAqB;QACpB,iDAAsB;QACjB,2CAA2B;QAC9B,qDAAwB;QAC1B,gDAAsB;QAClB,yDAA0B;QACtB,iEAA8B;QAChC,8DAA4B;QAC/B,wDAAyB;QACJ,qGAA8C;QACxE,6CAAoB;QACR,uEAAgC;QAC/B,yEAAiC;QACnC,oEAA+B;QAC5B,6GAAkD;QAC/D,8CAAqB;QAC1B,oCAAgB;QACN,0DAA0B;QACrB,sEAA+B;QAC9B,wEAAgC;QACjC,sEAA+B;GAnCnE,eAAe,CA2H3B","sourcesContent":["import { BaseRuleConfig, DiffScope, FileScope } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { CodeValidator, ExecutorResult, RuleRun } from './code-validator';\nimport { RuleReporter } from './rule-reporter';\nimport { WorkspaceRoot, MatchRulesHolder } from './code-rules-context';\nimport { CodeRulesRunRequest } from './code-rules-run-request';\nimport { DebugRunReport } from './debug-run-report';\nimport { RuleScopes } from './rule-scope-plan';\nimport { MatchRulesChecker } from './validate-match-rules';\nimport { MaxMethodLinesValidator } from './validate-modified-methods';\nimport { MaxFileLinesValidator } from './validate-modified-files';\nimport { RequireReturnTypeValidator } from './validate-return-types';\nimport { NoInlineTypeLiteralsValidator } from './validate-no-inline-types';\nimport { NoAnyUnknownValidator } from './validate-no-any-unknown';\nimport { NoImplicitAnyValidator } from './validate-no-implicit-any';\nimport { PrismaValidateDtosValidator } from './validate-dtos';\nimport { PrismaConverterValidator } from './validate-prisma-converters';\nimport { NoDestructureValidator } from './validate-no-destructure';\nimport { CatchErrorPatternValidator } from './validate-catch-error-pattern';\nimport { NoUnmanagedExceptionsValidator } from './validate-no-unmanaged-exceptions';\nimport { NoDirectApiResolverValidator } from './validate-no-direct-api-resolver';\nimport { NoSymbolDiTokensValidator } from './validate-no-symbol-di-tokens';\nimport { NoClientCreationOutsideServerOrClientValidator } from './validate-no-client-creation-outside-server-or-client';\nimport { NoCustomCssValidator } from './validate-no-custom-css';\nimport { NoStatePathsInTemplatesValidator } from './validate-no-state-paths-in-templates';\nimport { NoProcessExitOutsideMainValidator } from './validate-no-process-exit-outside-main';\nimport { NoFunctionOutsideClassValidator } from './validate-no-function-outside-class';\nimport { InjectAnnotationNotNeededForConcreteClassValidator } from './validate-inject-annotation-not-needed-for-concrete-class';\nimport { FrameworkTagValidator } from './validate-framework-tag';\nimport { RoleTagValidator } from './validate-role-tag';\nimport { EnsureWeAreSecureValidator } from './validate-ensure-we-are-secure';\nimport { NoInlineImportInApiLibValidator } from './validate-no-inline-import-in-api-lib';\nimport { OneEnumSpellingInApiLibValidator } from './validate-one-enum-spelling-in-api-lib';\nimport { NoUtilityTypesInApiLibValidator } from './validate-no-utility-types-in-api-lib';\n\n/**\n * Owns running the code-rules suite. Every built-in validator is injected as a singleton (its config\n * is bound in the container at bootstrap), so this class IS the code-rules DI DAG the design graph\n * draws. The per-entry match-rules validators are the one exception — they are config-per-instance,\n * so they are built from the injected {@link MatchRulesHolder}.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class CodeRulesEngine {\n // webpieces-disable max-lines-new-methods -- the built-in validator set is flat; each is one injected field\n constructor(\n private readonly workspace: WorkspaceRoot,\n private readonly reporter: RuleReporter,\n private readonly matchRules: MatchRulesHolder,\n private readonly matchChecker: MatchRulesChecker,\n private readonly request: CodeRulesRunRequest,\n private readonly scopes: RuleScopes,\n private readonly debugReport: DebugRunReport,\n private readonly diffScope: DiffScope,\n private readonly maxMethodLines: MaxMethodLinesValidator,\n private readonly maxFileLines: MaxFileLinesValidator,\n private readonly requireReturnType: RequireReturnTypeValidator,\n private readonly noInlineTypeLiterals: NoInlineTypeLiteralsValidator,\n private readonly noAnyUnknown: NoAnyUnknownValidator,\n private readonly noImplicitAny: NoImplicitAnyValidator,\n private readonly prismaValidateDtos: PrismaValidateDtosValidator,\n private readonly prismaConverter: PrismaConverterValidator,\n private readonly noDestructure: NoDestructureValidator,\n private readonly catchErrorPattern: CatchErrorPatternValidator,\n private readonly noUnmanagedExceptions: NoUnmanagedExceptionsValidator,\n private readonly noDirectApiResolver: NoDirectApiResolverValidator,\n private readonly noSymbolDiTokens: NoSymbolDiTokensValidator,\n private readonly noClientCreationOutsideServerOrClient: NoClientCreationOutsideServerOrClientValidator,\n private readonly noCustomCss: NoCustomCssValidator,\n private readonly noStatePathsInTemplates: NoStatePathsInTemplatesValidator,\n private readonly noProcessExitOutsideMain: NoProcessExitOutsideMainValidator,\n private readonly noFunctionOutsideClass: NoFunctionOutsideClassValidator,\n private readonly injectAnnotationNotNeeded: InjectAnnotationNotNeededForConcreteClassValidator,\n private readonly frameworkTag: FrameworkTagValidator,\n private readonly roleTag: RoleTagValidator,\n private readonly ensureWeAreSecure: EnsureWeAreSecureValidator,\n private readonly noInlineImportInApiLib: NoInlineImportInApiLibValidator,\n private readonly oneEnumSpellingInApiLib: OneEnumSpellingInApiLibValidator,\n private readonly noUtilityTypesInApiLib: NoUtilityTypesInApiLibValidator,\n ) {}\n\n /** The injected built-in validators, in run order. */\n private builtIns(): CodeValidator<BaseRuleConfig>[] {\n return [\n this.maxMethodLines,\n this.maxFileLines,\n this.requireReturnType,\n this.noInlineTypeLiterals,\n this.noAnyUnknown,\n this.noImplicitAny,\n this.prismaValidateDtos,\n this.prismaConverter,\n this.noDestructure,\n this.catchErrorPattern,\n this.noUnmanagedExceptions,\n this.noDirectApiResolver,\n this.noSymbolDiTokens,\n this.noClientCreationOutsideServerOrClient,\n this.noCustomCss,\n this.noStatePathsInTemplates,\n this.noProcessExitOutsideMain,\n this.noFunctionOutsideClass,\n this.injectAnnotationNotNeeded,\n this.frameworkTag,\n this.roleTag,\n this.ensureWeAreSecure,\n this.noInlineImportInApiLib,\n this.oneEnumSpellingInApiLib,\n this.noUtilityTypesInApiLib,\n ];\n }\n\n /**\n * Every ACTIVE run: an injected built-in validator whose `shouldRun()` is true, or an injected\n * match-rule check per configured entry that is active. Built as {@link RuleRun} value objects\n * (name + thunk) so NO DAG member is `new`-ed — the validators and the checker are injected.\n */\n private activeRuns(root: string): RuleRun[] {\n const runs: RuleRun[] = [];\n for (const v of this.builtIns()) {\n if (this.selected(v.configKey) && v.shouldRun())\n runs.push(new RuleRun(v.name, () => this.scoped(this.scopes.of(v.configKey), () => v.run(root))));\n }\n for (const mr of this.matchRules.rules) {\n if (this.selected(mr.name) && this.matchChecker.shouldRun(mr))\n runs.push(new RuleRun(mr.name, () => this.scoped(this.scopes.of(mr.name), () => this.matchChecker.runForConfig(mr, root))));\n }\n return runs;\n }\n\n /** The gate runs every rule; a debug run only the one it names. */\n private selected(key: string): boolean {\n return this.request.rule === null || this.request.rule === key;\n }\n\n /** Run one rule inside its planned {@link FileScope} (whole-scope modes, `--projects`). */\n private scoped(scope: FileScope, work: () => Promise<ExecutorResult>): Promise<ExecutorResult> {\n return this.diffScope.within(scope, work);\n }\n\n /**\n * Run all configured code validators against the workspace. A validator runs only when\n * `shouldRun()` is true (mode not OFF and no branch/epoch escape hatch). Per-run isolation lives\n * in {@link RuleReporter} so one validator can never abort the rest.\n */\n async run(): Promise<ExecutorResult> {\n const runs = this.activeRuns(this.workspace.path);\n const target = this.scopes.debugTarget;\n if (target !== null) return this.debugReport.run(this.workspace.path, runs, target);\n if (runs.length === 0) {\n console.log('\\n⏭️ Skipping all code validations (all modes: OFF)\\n');\n return { success: true };\n }\n\n console.log('\\n📏 Running Code Validations\\n');\n console.log(` Active rules: ${runs.map((r: RuleRun) => r.name).join(', ')}`);\n console.log('');\n\n const result = await this.reporter.runValidators(runs);\n console.log(\n result.success\n ? '\\n✅ All code validations passed\\n'\n : '\\n❌ Some code validations failed\\n',\n );\n return result;\n }\n}\n"]}
1
+ {"version":3,"file":"code-rules-engine.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/code-rules-engine.ts"],"names":[],"mappings":";;;;AAAA,0DAA+E;AAC/E,yCAA2D;AAE3D,qDAA0E;AAC1E,mDAA+C;AAC/C,6DAAuE;AACvE,qEAA+D;AAC/D,yDAAoD;AACpD,uDAA+C;AAC/C,iEAA2D;AAC3D,2EAAsE;AACtE,uEAAkE;AAClE,mEAAqE;AACrE,yEAA2E;AAC3E,uEAAkE;AAClE,yEAAoE;AACpE,mDAA8D;AAC9D,6EAAwE;AACxE,uEAAmE;AACnE,iFAA4E;AAC5E,yFAAoF;AACpF,uFAAiF;AACjF,iFAA2E;AAC3E,iIAAwH;AACxH,qEAAgE;AAChE,iGAA0F;AAC1F,mGAA4F;AAC5F,6FAAuF;AACvF,yIAAgI;AAChI,qEAAiE;AACjE,2DAAuD;AACvD,mFAA6E;AAC7E,iGAAyF;AACzF,mGAA2F;AAC3F,iGAAyF;AACzF,mFAA8E;AAE9E;;;;;GAKG;AAEI,IAAM,eAAe,GAArB,MAAM,eAAe;IAGH;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;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,wCAAiB;QACtB,4CAAmB;QACpB,4BAAU;QACL,iCAAc;QAChB,wBAAS;QACJ,mDAAuB;QACzB,+CAAqB;QAChB,kDAA0B;QACvB,wDAA6B;QACrC,+CAAqB;QACpB,iDAAsB;QACjB,2CAA2B;QAC9B,qDAAwB;QAC1B,gDAAsB;QAClB,yDAA0B;QACtB,iEAA8B;QAChC,8DAA4B;QAC/B,wDAAyB;QACJ,qGAA8C;QACxE,6CAAoB;QACR,uEAAgC;QAC/B,yEAAiC;QACnC,oEAA+B;QAC5B,6GAAkD;QAC/D,8CAAqB;QAC1B,oCAAgB;QACN,0DAA0B;QACrB,sEAA+B;QAC9B,wEAAgC;QACjC,sEAA+B;QACnC,2DAA2B;GApC3D,eAAe,CA6H3B","sourcesContent":["import { BaseRuleConfig, DiffScope, FileScope } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { CodeValidator, ExecutorResult, RuleRun } from './code-validator';\nimport { RuleReporter } from './rule-reporter';\nimport { WorkspaceRoot, MatchRulesHolder } from './code-rules-context';\nimport { CodeRulesRunRequest } from './code-rules-run-request';\nimport { DebugRunReport } from './debug-run-report';\nimport { RuleScopes } from './rule-scope-plan';\nimport { MatchRulesChecker } from './validate-match-rules';\nimport { MaxMethodLinesValidator } from './validate-modified-methods';\nimport { MaxFileLinesValidator } from './validate-modified-files';\nimport { RequireReturnTypeValidator } from './validate-return-types';\nimport { NoInlineTypeLiteralsValidator } from './validate-no-inline-types';\nimport { NoAnyUnknownValidator } from './validate-no-any-unknown';\nimport { NoImplicitAnyValidator } from './validate-no-implicit-any';\nimport { PrismaValidateDtosValidator } from './validate-dtos';\nimport { PrismaConverterValidator } from './validate-prisma-converters';\nimport { NoDestructureValidator } from './validate-no-destructure';\nimport { CatchErrorPatternValidator } from './validate-catch-error-pattern';\nimport { NoUnmanagedExceptionsValidator } from './validate-no-unmanaged-exceptions';\nimport { NoDirectApiResolverValidator } from './validate-no-direct-api-resolver';\nimport { NoSymbolDiTokensValidator } from './validate-no-symbol-di-tokens';\nimport { NoClientCreationOutsideServerOrClientValidator } from './validate-no-client-creation-outside-server-or-client';\nimport { NoCustomCssValidator } from './validate-no-custom-css';\nimport { NoStatePathsInTemplatesValidator } from './validate-no-state-paths-in-templates';\nimport { NoProcessExitOutsideMainValidator } from './validate-no-process-exit-outside-main';\nimport { NoFunctionOutsideClassValidator } from './validate-no-function-outside-class';\nimport { InjectAnnotationNotNeededForConcreteClassValidator } from './validate-inject-annotation-not-needed-for-concrete-class';\nimport { FrameworkTagValidator } from './validate-framework-tag';\nimport { RoleTagValidator } from './validate-role-tag';\nimport { EnsureWeAreSecureValidator } from './validate-ensure-we-are-secure';\nimport { NoInlineImportInApiLibValidator } from './validate-no-inline-import-in-api-lib';\nimport { OneEnumSpellingInApiLibValidator } from './validate-one-enum-spelling-in-api-lib';\nimport { NoUtilityTypesInApiLibValidator } from './validate-no-utility-types-in-api-lib';\nimport { RequiredTypeSuffixValidator } from './validate-required-type-suffix';\n\n/**\n * Owns running the code-rules suite. Every built-in validator is injected as a singleton (its config\n * is bound in the container at bootstrap), so this class IS the code-rules DI DAG the design graph\n * draws. The per-entry match-rules validators are the one exception — they are config-per-instance,\n * so they are built from the injected {@link MatchRulesHolder}.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class CodeRulesEngine {\n // webpieces-disable max-lines-new-methods -- the built-in validator set is flat; each is one injected field\n constructor(\n private readonly workspace: WorkspaceRoot,\n private readonly reporter: RuleReporter,\n private readonly matchRules: MatchRulesHolder,\n private readonly matchChecker: MatchRulesChecker,\n private readonly request: CodeRulesRunRequest,\n private readonly scopes: RuleScopes,\n private readonly debugReport: DebugRunReport,\n private readonly diffScope: DiffScope,\n private readonly maxMethodLines: MaxMethodLinesValidator,\n private readonly maxFileLines: MaxFileLinesValidator,\n private readonly requireReturnType: RequireReturnTypeValidator,\n private readonly noInlineTypeLiterals: NoInlineTypeLiteralsValidator,\n private readonly noAnyUnknown: NoAnyUnknownValidator,\n private readonly noImplicitAny: NoImplicitAnyValidator,\n private readonly prismaValidateDtos: PrismaValidateDtosValidator,\n private readonly prismaConverter: PrismaConverterValidator,\n private readonly noDestructure: NoDestructureValidator,\n private readonly catchErrorPattern: CatchErrorPatternValidator,\n private readonly noUnmanagedExceptions: NoUnmanagedExceptionsValidator,\n private readonly noDirectApiResolver: NoDirectApiResolverValidator,\n private readonly noSymbolDiTokens: NoSymbolDiTokensValidator,\n private readonly noClientCreationOutsideServerOrClient: NoClientCreationOutsideServerOrClientValidator,\n private readonly noCustomCss: NoCustomCssValidator,\n private readonly noStatePathsInTemplates: NoStatePathsInTemplatesValidator,\n private readonly noProcessExitOutsideMain: NoProcessExitOutsideMainValidator,\n private readonly noFunctionOutsideClass: NoFunctionOutsideClassValidator,\n private readonly injectAnnotationNotNeeded: InjectAnnotationNotNeededForConcreteClassValidator,\n private readonly frameworkTag: FrameworkTagValidator,\n private readonly roleTag: RoleTagValidator,\n private readonly ensureWeAreSecure: EnsureWeAreSecureValidator,\n private readonly noInlineImportInApiLib: NoInlineImportInApiLibValidator,\n private readonly oneEnumSpellingInApiLib: OneEnumSpellingInApiLibValidator,\n private readonly noUtilityTypesInApiLib: NoUtilityTypesInApiLibValidator,\n private readonly requiredTypeSuffix: RequiredTypeSuffixValidator,\n ) {}\n\n /** The injected built-in validators, in run order. */\n private builtIns(): CodeValidator<BaseRuleConfig>[] {\n return [\n this.maxMethodLines,\n this.maxFileLines,\n this.requireReturnType,\n this.noInlineTypeLiterals,\n this.noAnyUnknown,\n this.noImplicitAny,\n this.prismaValidateDtos,\n this.prismaConverter,\n this.noDestructure,\n this.catchErrorPattern,\n this.noUnmanagedExceptions,\n this.noDirectApiResolver,\n this.noSymbolDiTokens,\n this.noClientCreationOutsideServerOrClient,\n this.noCustomCss,\n this.noStatePathsInTemplates,\n this.noProcessExitOutsideMain,\n this.noFunctionOutsideClass,\n this.injectAnnotationNotNeeded,\n this.frameworkTag,\n this.roleTag,\n this.ensureWeAreSecure,\n this.noInlineImportInApiLib,\n this.oneEnumSpellingInApiLib,\n this.noUtilityTypesInApiLib,\n this.requiredTypeSuffix,\n ];\n }\n\n /**\n * Every ACTIVE run: an injected built-in validator whose `shouldRun()` is true, or an injected\n * match-rule check per configured entry that is active. Built as {@link RuleRun} value objects\n * (name + thunk) so NO DAG member is `new`-ed — the validators and the checker are injected.\n */\n private activeRuns(root: string): RuleRun[] {\n const runs: RuleRun[] = [];\n for (const v of this.builtIns()) {\n if (this.selected(v.configKey) && v.shouldRun())\n runs.push(new RuleRun(v.name, () => this.scoped(this.scopes.of(v.configKey), () => v.run(root))));\n }\n for (const mr of this.matchRules.rules) {\n if (this.selected(mr.name) && this.matchChecker.shouldRun(mr))\n runs.push(new RuleRun(mr.name, () => this.scoped(this.scopes.of(mr.name), () => this.matchChecker.runForConfig(mr, root))));\n }\n return runs;\n }\n\n /** The gate runs every rule; a debug run only the one it names. */\n private selected(key: string): boolean {\n return this.request.rule === null || this.request.rule === key;\n }\n\n /** Run one rule inside its planned {@link FileScope} (whole-scope modes, `--projects`). */\n private scoped(scope: FileScope, work: () => Promise<ExecutorResult>): Promise<ExecutorResult> {\n return this.diffScope.within(scope, work);\n }\n\n /**\n * Run all configured code validators against the workspace. A validator runs only when\n * `shouldRun()` is true (mode not OFF and no branch/epoch escape hatch). Per-run isolation lives\n * in {@link RuleReporter} so one validator can never abort the rest.\n */\n async run(): Promise<ExecutorResult> {\n const runs = this.activeRuns(this.workspace.path);\n const target = this.scopes.debugTarget;\n if (target !== null) return this.debugReport.run(this.workspace.path, runs, target);\n if (runs.length === 0) {\n console.log('\\n⏭️ Skipping all code validations (all modes: OFF)\\n');\n return { success: true };\n }\n\n console.log('\\n📏 Running Code Validations\\n');\n console.log(` Active rules: ${runs.map((r: RuleRun) => r.name).join(', ')}`);\n console.log('');\n\n const result = await this.reporter.runValidators(runs);\n console.log(\n result.success\n ? '\\n✅ All code validations passed\\n'\n : '\\n❌ Some code validations failed\\n',\n );\n return result;\n }\n}\n"]}
package/src/index.d.ts CHANGED
@@ -24,6 +24,7 @@ export { ApiLibFile, ApiLibSite } from './api-lib-source-rule';
24
24
  export { NoInlineImportInApiLibValidator, InlineImportScanner } from './validate-no-inline-import-in-api-lib';
25
25
  export { OneEnumSpellingInApiLibValidator, EnumSpellingScanner } from './validate-one-enum-spelling-in-api-lib';
26
26
  export { NoUtilityTypesInApiLibValidator, UtilityTypeScanner } from './validate-no-utility-types-in-api-lib';
27
+ export { RequiredTypeSuffixValidator, ExportedTypeScanner, SuffixEntryPicker, SuffixRename, RankedGlob, } from './validate-required-type-suffix';
27
28
  export { ApiLibEnumIndex } from './api-lib-enum-index';
28
29
  export { EnumText } from './api-lib-enum-text';
29
30
  export { PrismaValidateDtosValidator } from './validate-dtos';
package/src/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ReactNativeCompatibility = exports.CodeRulesRunRequestParser = exports.CodeRulesRunRequest = exports.validateCode = exports.PrismaConverterValidator = exports.PrismaValidateDtosValidator = exports.EnumText = exports.ApiLibEnumIndex = exports.UtilityTypeScanner = exports.NoUtilityTypesInApiLibValidator = exports.EnumSpellingScanner = exports.OneEnumSpellingInApiLibValidator = exports.InlineImportScanner = exports.NoInlineImportInApiLibValidator = exports.ApiLibSite = exports.ApiLibFile = exports.findDirectlyChangedProjectRoots = exports.auditSecurityContracts = exports.SecurityContractViolation = exports.EnsureWeAreSecureValidator = exports.RoleTagValidator = exports.FrameworkTagValidator = exports.findRedundantInjectInSource = exports.InjectAnnotationNotNeededForConcreteClassValidator = exports.NoFunctionOutsideClassValidator = exports.NoProcessExitOutsideMainValidator = exports.ProjectRoleResolver = exports.StatePathViolation = exports.StatePathHit = exports.NoStatePathsInTemplatesValidator = exports.NoClientCreationOutsideServerOrClientValidator = exports.NoSymbolDiTokensValidator = exports.NoDirectApiResolverValidator = exports.NoDestructureValidator = exports.NoUnmanagedExceptionsValidator = exports.CatchErrorPatternValidator = exports.NoInlineTypeLiteralsValidator = exports.RequireReturnTypeValidator = exports.MaxFileLinesValidator = exports.runNewMethods = exports.runModifiedMethods = exports.MaxMethodLinesValidator = exports.NoImplicitAnyValidator = exports.NoAnyUnknownValidator = exports.CodeValidator = void 0;
3
+ exports.ReactNativeCompatibility = exports.CodeRulesRunRequestParser = exports.CodeRulesRunRequest = exports.validateCode = exports.PrismaConverterValidator = exports.PrismaValidateDtosValidator = exports.EnumText = exports.ApiLibEnumIndex = exports.RankedGlob = exports.SuffixRename = exports.SuffixEntryPicker = exports.ExportedTypeScanner = exports.RequiredTypeSuffixValidator = exports.UtilityTypeScanner = exports.NoUtilityTypesInApiLibValidator = exports.EnumSpellingScanner = exports.OneEnumSpellingInApiLibValidator = exports.InlineImportScanner = exports.NoInlineImportInApiLibValidator = exports.ApiLibSite = exports.ApiLibFile = exports.findDirectlyChangedProjectRoots = exports.auditSecurityContracts = exports.SecurityContractViolation = exports.EnsureWeAreSecureValidator = exports.RoleTagValidator = exports.FrameworkTagValidator = exports.findRedundantInjectInSource = exports.InjectAnnotationNotNeededForConcreteClassValidator = exports.NoFunctionOutsideClassValidator = exports.NoProcessExitOutsideMainValidator = exports.ProjectRoleResolver = exports.StatePathViolation = exports.StatePathHit = exports.NoStatePathsInTemplatesValidator = exports.NoClientCreationOutsideServerOrClientValidator = exports.NoSymbolDiTokensValidator = exports.NoDirectApiResolverValidator = exports.NoDestructureValidator = exports.NoUnmanagedExceptionsValidator = exports.CatchErrorPatternValidator = exports.NoInlineTypeLiteralsValidator = exports.RequireReturnTypeValidator = exports.MaxFileLinesValidator = exports.runNewMethods = exports.runModifiedMethods = exports.MaxMethodLinesValidator = exports.NoImplicitAnyValidator = exports.NoAnyUnknownValidator = exports.CodeValidator = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  var code_validator_1 = require("./code-validator");
6
6
  Object.defineProperty(exports, "CodeValidator", { enumerable: true, get: function () { return code_validator_1.CodeValidator; } });
@@ -65,6 +65,12 @@ Object.defineProperty(exports, "EnumSpellingScanner", { enumerable: true, get: f
65
65
  var validate_no_utility_types_in_api_lib_1 = require("./validate-no-utility-types-in-api-lib");
66
66
  Object.defineProperty(exports, "NoUtilityTypesInApiLibValidator", { enumerable: true, get: function () { return validate_no_utility_types_in_api_lib_1.NoUtilityTypesInApiLibValidator; } });
67
67
  Object.defineProperty(exports, "UtilityTypeScanner", { enumerable: true, get: function () { return validate_no_utility_types_in_api_lib_1.UtilityTypeScanner; } });
68
+ var validate_required_type_suffix_1 = require("./validate-required-type-suffix");
69
+ Object.defineProperty(exports, "RequiredTypeSuffixValidator", { enumerable: true, get: function () { return validate_required_type_suffix_1.RequiredTypeSuffixValidator; } });
70
+ Object.defineProperty(exports, "ExportedTypeScanner", { enumerable: true, get: function () { return validate_required_type_suffix_1.ExportedTypeScanner; } });
71
+ Object.defineProperty(exports, "SuffixEntryPicker", { enumerable: true, get: function () { return validate_required_type_suffix_1.SuffixEntryPicker; } });
72
+ Object.defineProperty(exports, "SuffixRename", { enumerable: true, get: function () { return validate_required_type_suffix_1.SuffixRename; } });
73
+ Object.defineProperty(exports, "RankedGlob", { enumerable: true, get: function () { return validate_required_type_suffix_1.RankedGlob; } });
68
74
  var api_lib_enum_index_1 = require("./api-lib-enum-index");
69
75
  Object.defineProperty(exports, "ApiLibEnumIndex", { enumerable: true, get: function () { return api_lib_enum_index_1.ApiLibEnumIndex; } });
70
76
  var api_lib_enum_text_1 = require("./api-lib-enum-text");
package/src/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/index.ts"],"names":[],"mappings":";;;;AAAA,mDAAiE;AAAxD,+GAAA,aAAa,OAAA;AAEtB,qEAAkE;AAAzD,gIAAA,qBAAqB,OAAA;AAC9B,uEAAoE;AAA3D,kIAAA,sBAAsB,OAAA;AAC/B,yEAA0F;AAAjF,oIAAA,uBAAuB,OAAA;AAAE,+HAAA,kBAAkB,OA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A;AAC5D,2DAAuD;AAA9C,qHAAA,eAAe,OAAA;AACxB,yDAA+C;AAAtC,6GAAA,QAAQ,OAAA;AACjB,iDAA8D;AAArD,4HAAA,2BAA2B,OAAA;AACpC,2EAAwE;AAA/D,sIAAA,wBAAwB,OAAA;AACjC,iDAA0D;AAAjD,sIAAA,OAAO,OAAgB;AAChC,mEAA0F;AAAjF,6HAAA,mBAAmB,OAAA;AAAE,mIAAA,yBAAyB,OAAA;AAEvD,2EAAwE;AAA/D,sIAAA,wBAAwB,OAAA","sourcesContent":["export { CodeValidator, ExecutorResult } from './code-validator';\n\nexport { NoAnyUnknownValidator } from './validate-no-any-unknown';\nexport { NoImplicitAnyValidator } from './validate-no-implicit-any';\nexport { MaxMethodLinesValidator, runModifiedMethods } from './validate-modified-methods';\nexport { runNewMethods } from './validate-new-methods';\nexport { MaxFileLinesValidator } from './validate-modified-files';\nexport { RequireReturnTypeValidator } from './validate-return-types';\nexport { NoInlineTypeLiteralsValidator } from './validate-no-inline-types';\nexport { CatchErrorPatternValidator } from './validate-catch-error-pattern';\nexport { NoUnmanagedExceptionsValidator } from './validate-no-unmanaged-exceptions';\nexport { NoDestructureValidator } from './validate-no-destructure';\nexport { NoDirectApiResolverValidator } from './validate-no-direct-api-resolver';\nexport { NoSymbolDiTokensValidator } from './validate-no-symbol-di-tokens';\nexport { NoClientCreationOutsideServerOrClientValidator } from './validate-no-client-creation-outside-server-or-client';\nexport {\n NoStatePathsInTemplatesValidator,\n StatePathHit,\n StatePathViolation,\n} from './validate-no-state-paths-in-templates';\nexport { ProjectRoleResolver } from './project-role-resolver';\nexport { NoProcessExitOutsideMainValidator } from './validate-no-process-exit-outside-main';\nexport { NoFunctionOutsideClassValidator } from './validate-no-function-outside-class';\nexport {\n InjectAnnotationNotNeededForConcreteClassValidator,\n findRedundantInjectInSource,\n} from './validate-inject-annotation-not-needed-for-concrete-class';\nexport { FrameworkTagValidator } from './validate-framework-tag';\nexport { RoleTagValidator } from './validate-role-tag';\nexport {\n EnsureWeAreSecureValidator,\n SecurityContractViolation,\n auditSecurityContracts,\n findDirectlyChangedProjectRoots,\n} from './validate-ensure-we-are-secure';\nexport { ApiLibFile, ApiLibSite } from './api-lib-source-rule';\nexport { NoInlineImportInApiLibValidator, InlineImportScanner } from './validate-no-inline-import-in-api-lib';\nexport { OneEnumSpellingInApiLibValidator, EnumSpellingScanner } from './validate-one-enum-spelling-in-api-lib';\nexport { NoUtilityTypesInApiLibValidator, UtilityTypeScanner } from './validate-no-utility-types-in-api-lib';\nexport { ApiLibEnumIndex } from './api-lib-enum-index';\nexport { EnumText } from './api-lib-enum-text';\nexport { PrismaValidateDtosValidator } from './validate-dtos';\nexport { PrismaConverterValidator } from './validate-prisma-converters';\nexport { default as validateCode } from './validate-code';\nexport { CodeRulesRunRequest, CodeRulesRunRequestParser } from './code-rules-run-request';\n\nexport { ReactNativeCompatibility } from './react-native-compatibility';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/index.ts"],"names":[],"mappings":";;;;AAAA,mDAAiE;AAAxD,+GAAA,aAAa,OAAA;AAEtB,qEAAkE;AAAzD,gIAAA,qBAAqB,OAAA;AAC9B,uEAAoE;AAA3D,kIAAA,sBAAsB,OAAA;AAC/B,yEAA0F;AAAjF,oIAAA,uBAAuB,OAAA;AAAE,+HAAA,kBAAkB,OAAA;AACpD,+DAAuD;AAA9C,qHAAA,aAAa,OAAA;AACtB,qEAAkE;AAAzD,gIAAA,qBAAqB,OAAA;AAC9B,iEAAqE;AAA5D,mIAAA,0BAA0B,OAAA;AACnC,uEAA2E;AAAlE,yIAAA,6BAA6B,OAAA;AACtC,+EAA4E;AAAnE,0IAAA,0BAA0B,OAAA;AACnC,uFAAoF;AAA3E,kJAAA,8BAA8B,OAAA;AACvC,qEAAmE;AAA1D,iIAAA,sBAAsB,OAAA;AAC/B,qFAAiF;AAAxE,+IAAA,4BAA4B,OAAA;AACrC,+EAA2E;AAAlE,yIAAA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AAAjF,6HAAA,mBAAmB,OAAA;AAAE,mIAAA,yBAAyB,OAAA;AAEvD,2EAAwE;AAA/D,sIAAA,wBAAwB,OAAA","sourcesContent":["export { CodeValidator, ExecutorResult } from './code-validator';\n\nexport { NoAnyUnknownValidator } from './validate-no-any-unknown';\nexport { NoImplicitAnyValidator } from './validate-no-implicit-any';\nexport { MaxMethodLinesValidator, runModifiedMethods } from './validate-modified-methods';\nexport { runNewMethods } from './validate-new-methods';\nexport { MaxFileLinesValidator } from './validate-modified-files';\nexport { RequireReturnTypeValidator } from './validate-return-types';\nexport { NoInlineTypeLiteralsValidator } from './validate-no-inline-types';\nexport { CatchErrorPatternValidator } from './validate-catch-error-pattern';\nexport { NoUnmanagedExceptionsValidator } from './validate-no-unmanaged-exceptions';\nexport { NoDestructureValidator } from './validate-no-destructure';\nexport { NoDirectApiResolverValidator } from './validate-no-direct-api-resolver';\nexport { NoSymbolDiTokensValidator } from './validate-no-symbol-di-tokens';\nexport { NoClientCreationOutsideServerOrClientValidator } from './validate-no-client-creation-outside-server-or-client';\nexport {\n NoStatePathsInTemplatesValidator,\n StatePathHit,\n StatePathViolation,\n} from './validate-no-state-paths-in-templates';\nexport { ProjectRoleResolver } from './project-role-resolver';\nexport { NoProcessExitOutsideMainValidator } from './validate-no-process-exit-outside-main';\nexport { NoFunctionOutsideClassValidator } from './validate-no-function-outside-class';\nexport {\n InjectAnnotationNotNeededForConcreteClassValidator,\n findRedundantInjectInSource,\n} from './validate-inject-annotation-not-needed-for-concrete-class';\nexport { FrameworkTagValidator } from './validate-framework-tag';\nexport { RoleTagValidator } from './validate-role-tag';\nexport {\n EnsureWeAreSecureValidator,\n SecurityContractViolation,\n auditSecurityContracts,\n findDirectlyChangedProjectRoots,\n} from './validate-ensure-we-are-secure';\nexport { ApiLibFile, ApiLibSite } from './api-lib-source-rule';\nexport { NoInlineImportInApiLibValidator, InlineImportScanner } from './validate-no-inline-import-in-api-lib';\nexport { OneEnumSpellingInApiLibValidator, EnumSpellingScanner } from './validate-one-enum-spelling-in-api-lib';\nexport { NoUtilityTypesInApiLibValidator, UtilityTypeScanner } from './validate-no-utility-types-in-api-lib';\nexport {\n RequiredTypeSuffixValidator,\n ExportedTypeScanner,\n SuffixEntryPicker,\n SuffixRename,\n RankedGlob,\n} from './validate-required-type-suffix';\nexport { ApiLibEnumIndex } from './api-lib-enum-index';\nexport { EnumText } from './api-lib-enum-text';\nexport { PrismaValidateDtosValidator } from './validate-dtos';\nexport { PrismaConverterValidator } from './validate-prisma-converters';\nexport { default as validateCode } from './validate-code';\nexport { CodeRulesRunRequest, CodeRulesRunRequestParser } from './code-rules-run-request';\n\nexport { ReactNativeCompatibility } from './react-native-compatibility';\n"]}
@@ -0,0 +1,90 @@
1
+ /**
2
+ * `required-type-suffix` (#1037) — a type's name says which layer it belongs to.
3
+ *
4
+ * Configured as a list of entries, each pairing path globs with the suffixes allowed there:
5
+ *
6
+ * { "paths": ["libraries/apis/internal/**"], "suffixes": ["Request", "Response", "Event", "Dto", "Api"] }
7
+ * { "paths": ["libraries/browser-node/fs-*-model/**"], "suffixes": ["Fs"] }
8
+ *
9
+ * Every EXPORTED `interface`, `class` (abstract too), `enum` and `type` alias in a non-test `.ts` file under
10
+ * an entry's paths must end in one of that entry's suffixes — a plain, case-sensitive `endsWith`, and the
11
+ * suffix alone is not a name (`FooDto` passes; `FooDTO` and `Dto` fail). A non-exported, file-local type
12
+ * is not judged, and neither is an exported `const` (a DI token's `Symbol` holder is not a type). A type
13
+ * exported through a local `export { Foo as FooDto }` list is judged by the name it is exported AS.
14
+ *
15
+ * Why: in review a `…Dto` is a wire type and a `…Fs` a Firestore document, while `TopNamePlaceInput` reads
16
+ * the same as a server-internal or vendor type. The suffix is the one place the layer can be stated.
17
+ *
18
+ * Overlapping entries: the MOST SPECIFIC entry governs a file ({@link SuffixEntryPicker}); suffixes are
19
+ * never unioned across entries.
20
+ *
21
+ * Under NEW_AND_MODIFIED_CODE only a declaration whose NAME line is new or changed is judged — a new type
22
+ * or a renamed one — so legacy names are grandfathered and a repo with hundreds of them can convert slowly.
23
+ */
24
+ import { DiffScope, RequiredTypeSuffixConfig, RequiredTypeSuffixEntry } from '@webpieces/rules-config';
25
+ import { ApiLibFile, ApiLibSite, ApiLibSourceRule } from './api-lib-source-rule';
26
+ import { ProjectRoleResolver } from './project-role-resolver';
27
+ /** One glob of one entry, with how specific it is. Data-only. */
28
+ export declare class RankedGlob {
29
+ readonly entry: RequiredTypeSuffixEntry;
30
+ readonly glob: string;
31
+ /** Characters before the first glob metacharacter (`*`, `?`, `[`, `{`). */
32
+ readonly literalPrefix: number;
33
+ /** Every non-metacharacter in the glob. */
34
+ readonly literalChars: number;
35
+ /** Position of the entry in the config — the final tie-break. */
36
+ readonly order: number;
37
+ constructor(entry: RequiredTypeSuffixEntry, glob: string,
38
+ /** Characters before the first glob metacharacter (`*`, `?`, `[`, `{`). */
39
+ literalPrefix: number,
40
+ /** Every non-metacharacter in the glob. */
41
+ literalChars: number,
42
+ /** Position of the entry in the config — the final tie-break. */
43
+ order: number);
44
+ }
45
+ /**
46
+ * Picks the ONE entry that governs a file. Among the entries with a glob matching the file, the one whose
47
+ * matching glob has the longest LITERAL PREFIX (the characters before its first `*`, `?`, `[` or `{`)
48
+ * wins; a tie goes to the glob with more literal characters overall, then to the entry listed first. So
49
+ * `libraries/apis/internal/**` beats `libraries/apis/**` whatever order they are listed in.
50
+ */
51
+ export declare class SuffixEntryPicker {
52
+ private static readonly META;
53
+ entryFor(relFile: string, entries: readonly RequiredTypeSuffixEntry[]): RequiredTypeSuffixEntry | undefined;
54
+ /** The winning glob (and its entry) for `relFile`, or undefined when no entry covers it. */
55
+ winner(relFile: string, entries: readonly RequiredTypeSuffixEntry[]): RankedGlob | undefined;
56
+ private rank;
57
+ private beats;
58
+ }
59
+ /** The rename a failure suggests: the name's layer-less tail swapped for each allowed suffix. */
60
+ export declare class SuffixRename {
61
+ /**
62
+ * Trailing words that name no layer, dropped before a suffix is appended (`TopNamePlaceInput` →
63
+ * `TopNamePlaceDto`, not `TopNamePlaceInputDto`). Longest first, so `Object` wins over `Obj`.
64
+ */
65
+ private static readonly LAYERLESS_TAILS;
66
+ /** Candidate names, one per allowed suffix, in the configured order. */
67
+ candidates(name: string, suffixes: readonly string[]): string[];
68
+ private stem;
69
+ }
70
+ /** Finds every exported type in one parsed file whose name does not end in the governing entry's suffixes. */
71
+ export declare class ExportedTypeScanner {
72
+ private readonly rename;
73
+ scan(file: ApiLibFile, entry: RequiredTypeSuffixEntry, glob: string): ApiLibSite[];
74
+ /** `export { Local as Exported }` of a local type: judged by the exported name, at the specifier. */
75
+ private exportListSites;
76
+ private typeDeclaration;
77
+ private isExported;
78
+ private judge;
79
+ private kindOf;
80
+ }
81
+ export declare class RequiredTypeSuffixValidator extends ApiLibSourceRule<RequiredTypeSuffixConfig> {
82
+ private readonly picker;
83
+ private readonly scanner;
84
+ constructor(config: RequiredTypeSuffixConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope);
85
+ protected sitesIn(file: ApiLibFile): ApiLibSite[];
86
+ /** Scoped by the configured entries' `paths` globs, not the role tag. */
87
+ protected isApiLibrarySource(_workspaceRoot: string, relFile: string): boolean;
88
+ protected scopeLabel(): string;
89
+ protected why(): string;
90
+ }
@@ -0,0 +1,236 @@
1
+ "use strict";
2
+ /**
3
+ * `required-type-suffix` (#1037) — a type's name says which layer it belongs to.
4
+ *
5
+ * Configured as a list of entries, each pairing path globs with the suffixes allowed there:
6
+ *
7
+ * { "paths": ["libraries/apis/internal/**"], "suffixes": ["Request", "Response", "Event", "Dto", "Api"] }
8
+ * { "paths": ["libraries/browser-node/fs-*-model/**"], "suffixes": ["Fs"] }
9
+ *
10
+ * Every EXPORTED `interface`, `class` (abstract too), `enum` and `type` alias in a non-test `.ts` file under
11
+ * an entry's paths must end in one of that entry's suffixes — a plain, case-sensitive `endsWith`, and the
12
+ * suffix alone is not a name (`FooDto` passes; `FooDTO` and `Dto` fail). A non-exported, file-local type
13
+ * is not judged, and neither is an exported `const` (a DI token's `Symbol` holder is not a type). A type
14
+ * exported through a local `export { Foo as FooDto }` list is judged by the name it is exported AS.
15
+ *
16
+ * Why: in review a `…Dto` is a wire type and a `…Fs` a Firestore document, while `TopNamePlaceInput` reads
17
+ * the same as a server-internal or vendor type. The suffix is the one place the layer can be stated.
18
+ *
19
+ * Overlapping entries: the MOST SPECIFIC entry governs a file ({@link SuffixEntryPicker}); suffixes are
20
+ * never unioned across entries.
21
+ *
22
+ * Under NEW_AND_MODIFIED_CODE only a declaration whose NAME line is new or changed is judged — a new type
23
+ * or a renamed one — so legacy names are grandfathered and a repo with hundreds of them can convert slowly.
24
+ */
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.RequiredTypeSuffixValidator = exports.ExportedTypeScanner = exports.SuffixRename = exports.SuffixEntryPicker = exports.RankedGlob = void 0;
27
+ const tslib_1 = require("tslib");
28
+ const rules_config_1 = require("@webpieces/rules-config");
29
+ const inversify_1 = require("inversify");
30
+ const ts = tslib_1.__importStar(require("typescript"));
31
+ const api_lib_source_rule_1 = require("./api-lib-source-rule");
32
+ const project_role_resolver_1 = require("./project-role-resolver");
33
+ /** One glob of one entry, with how specific it is. Data-only. */
34
+ class RankedGlob {
35
+ entry;
36
+ glob;
37
+ literalPrefix;
38
+ literalChars;
39
+ order;
40
+ constructor(entry, glob,
41
+ /** Characters before the first glob metacharacter (`*`, `?`, `[`, `{`). */
42
+ literalPrefix,
43
+ /** Every non-metacharacter in the glob. */
44
+ literalChars,
45
+ /** Position of the entry in the config — the final tie-break. */
46
+ order) {
47
+ this.entry = entry;
48
+ this.glob = glob;
49
+ this.literalPrefix = literalPrefix;
50
+ this.literalChars = literalChars;
51
+ this.order = order;
52
+ }
53
+ }
54
+ exports.RankedGlob = RankedGlob;
55
+ /**
56
+ * Picks the ONE entry that governs a file. Among the entries with a glob matching the file, the one whose
57
+ * matching glob has the longest LITERAL PREFIX (the characters before its first `*`, `?`, `[` or `{`)
58
+ * wins; a tie goes to the glob with more literal characters overall, then to the entry listed first. So
59
+ * `libraries/apis/internal/**` beats `libraries/apis/**` whatever order they are listed in.
60
+ */
61
+ class SuffixEntryPicker {
62
+ static META = /[*?[\]{}]/;
63
+ entryFor(relFile, entries) {
64
+ return this.winner(relFile, entries)?.entry;
65
+ }
66
+ /** The winning glob (and its entry) for `relFile`, or undefined when no entry covers it. */
67
+ winner(relFile, entries) {
68
+ let best;
69
+ entries.forEach((entry, order) => {
70
+ for (const glob of entry.paths) {
71
+ if (!(0, rules_config_1.matchesAnyGlob)(relFile, [glob]))
72
+ continue;
73
+ const ranked = this.rank(entry, glob, order);
74
+ if (best === undefined || this.beats(ranked, best))
75
+ best = ranked;
76
+ }
77
+ });
78
+ return best;
79
+ }
80
+ rank(entry, glob, order) {
81
+ const firstMeta = glob.search(SuffixEntryPicker.META);
82
+ const literalPrefix = firstMeta === -1 ? glob.length : firstMeta;
83
+ const literalChars = glob.replace(/[*?[\]{}]/g, '').length;
84
+ return new RankedGlob(entry, glob, literalPrefix, literalChars, order);
85
+ }
86
+ beats(a, b) {
87
+ if (a.literalPrefix !== b.literalPrefix)
88
+ return a.literalPrefix > b.literalPrefix;
89
+ if (a.literalChars !== b.literalChars)
90
+ return a.literalChars > b.literalChars;
91
+ return a.order < b.order;
92
+ }
93
+ }
94
+ exports.SuffixEntryPicker = SuffixEntryPicker;
95
+ /** The rename a failure suggests: the name's layer-less tail swapped for each allowed suffix. */
96
+ class SuffixRename {
97
+ /**
98
+ * Trailing words that name no layer, dropped before a suffix is appended (`TopNamePlaceInput` →
99
+ * `TopNamePlaceDto`, not `TopNamePlaceInputDto`). Longest first, so `Object` wins over `Obj`.
100
+ */
101
+ static LAYERLESS_TAILS = [
102
+ 'Interface', 'Payload', 'Options', 'Object', 'Params', 'Output', 'Option', 'Record', 'Input', 'Model',
103
+ 'Entry', 'Shape', 'Data', 'Info', 'Item', 'Type', 'Body', 'Row', 'Obj',
104
+ ];
105
+ /** Candidate names, one per allowed suffix, in the configured order. */
106
+ candidates(name, suffixes) {
107
+ const stem = this.stem(name, suffixes);
108
+ return suffixes.map((suffix) => `${stem}${suffix}`);
109
+ }
110
+ stem(name, suffixes) {
111
+ // `FooDTO` → `Foo`: the suffix is there, in the wrong case.
112
+ const wrongCase = suffixes.find((s) => name.length > s.length && name.toLowerCase().endsWith(s.toLowerCase()));
113
+ if (wrongCase !== undefined)
114
+ return name.slice(0, name.length - wrongCase.length);
115
+ // `Dto` alone → `<Name>Dto`: there is no stem to keep.
116
+ if (suffixes.includes(name))
117
+ return '<Name>';
118
+ const tail = SuffixRename.LAYERLESS_TAILS.find((t) => name.length > t.length && name.endsWith(t));
119
+ return tail === undefined ? name : name.slice(0, name.length - tail.length);
120
+ }
121
+ }
122
+ exports.SuffixRename = SuffixRename;
123
+ /** Finds every exported type in one parsed file whose name does not end in the governing entry's suffixes. */
124
+ class ExportedTypeScanner {
125
+ rename = new SuffixRename();
126
+ scan(file, entry, glob) {
127
+ const sites = [];
128
+ const locals = new Map();
129
+ for (const statement of file.source.statements) {
130
+ const declared = this.typeDeclaration(statement);
131
+ if (declared === undefined)
132
+ continue;
133
+ if (this.isExported(declared)) {
134
+ const site = this.judge(file, declared, declared.name, declared.name?.getText(file.source) ?? '', entry, glob);
135
+ if (site !== undefined)
136
+ sites.push(site);
137
+ }
138
+ else if (declared.name !== undefined) {
139
+ locals.set(declared.name.getText(file.source), declared);
140
+ }
141
+ }
142
+ sites.push(...this.exportListSites(file, locals, entry, glob));
143
+ return sites.sort((a, b) => a.line - b.line);
144
+ }
145
+ /** `export { Local as Exported }` of a local type: judged by the exported name, at the specifier. */
146
+ exportListSites(file, locals, entry, glob) {
147
+ const sites = [];
148
+ for (const statement of file.source.statements) {
149
+ if (!ts.isExportDeclaration(statement) || statement.moduleSpecifier !== undefined)
150
+ continue;
151
+ if (statement.exportClause === undefined || !ts.isNamedExports(statement.exportClause))
152
+ continue;
153
+ for (const element of statement.exportClause.elements) {
154
+ const local = locals.get((element.propertyName ?? element.name).getText(file.source));
155
+ if (local === undefined)
156
+ continue;
157
+ const site = this.judge(file, local, element.name, element.name.getText(file.source), entry, glob);
158
+ if (site !== undefined)
159
+ sites.push(site);
160
+ }
161
+ }
162
+ return sites;
163
+ }
164
+ typeDeclaration(statement) {
165
+ if (ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement) ||
166
+ ts.isEnumDeclaration(statement) || ts.isClassDeclaration(statement)) {
167
+ return statement;
168
+ }
169
+ return undefined;
170
+ }
171
+ isExported(statement) {
172
+ const modifiers = ts.canHaveModifiers(statement) ? ts.getModifiers(statement) ?? [] : [];
173
+ return modifiers.some((m) => m.kind === ts.SyntaxKind.ExportKeyword);
174
+ }
175
+ judge(file, declared, at, name, entry, glob) {
176
+ // `export default class { … }` has no name to judge.
177
+ if (at === undefined || name === '')
178
+ return undefined;
179
+ if (entry.suffixes.some((suffix) => name.length > suffix.length && name.endsWith(suffix)))
180
+ return undefined;
181
+ const kind = this.kindOf(declared);
182
+ const allowed = entry.suffixes.join(' | ');
183
+ const line = file.lineOf(at);
184
+ const snippet = (file.source.text.split('\n')[line - 1] ?? name).replace(/\s+/g, ' ').trim();
185
+ const what = `exported ${kind} \`${name}\` does not end in a suffix allowed under ${glob} (${allowed})`;
186
+ const candidates = this.rename.candidates(name, entry.suffixes);
187
+ const others = candidates.slice(1).map((c) => `\`${c}\``).join(' / ');
188
+ const cure = `rename ${kind} \`${name}\` → \`${candidates[0]}\`` +
189
+ (others === '' ? '' : ` (or ${others} — pick the suffix that names its layer, e.g. …Request for an endpoint body)`) +
190
+ ` and update every reference. Allowed suffixes under ${glob}: ${allowed} — the suffix tells a reader ` +
191
+ `which layer the type belongs to.`;
192
+ return new api_lib_source_rule_1.ApiLibSite(line, snippet, what, cure);
193
+ }
194
+ kindOf(declared) {
195
+ if (ts.isInterfaceDeclaration(declared))
196
+ return 'interface';
197
+ if (ts.isEnumDeclaration(declared))
198
+ return 'enum';
199
+ if (ts.isTypeAliasDeclaration(declared))
200
+ return 'type';
201
+ return 'class';
202
+ }
203
+ }
204
+ exports.ExportedTypeScanner = ExportedTypeScanner;
205
+ let RequiredTypeSuffixValidator = class RequiredTypeSuffixValidator extends api_lib_source_rule_1.ApiLibSourceRule {
206
+ picker = new SuffixEntryPicker();
207
+ scanner = new ExportedTypeScanner();
208
+ constructor(config, roleResolver, diffScope) {
209
+ super(config, rules_config_1.RULE_NAMES.REQUIRED_TYPE_SUFFIX, roleResolver, diffScope);
210
+ }
211
+ sitesIn(file) {
212
+ const winner = this.picker.winner(file.relFile, this.config.entries);
213
+ if (winner === undefined)
214
+ return [];
215
+ return this.scanner.scan(file, winner.entry, winner.glob);
216
+ }
217
+ /** Scoped by the configured entries' `paths` globs, not the role tag. */
218
+ isApiLibrarySource(_workspaceRoot, relFile) {
219
+ return this.picker.entryFor(relFile, this.config.entries) !== undefined;
220
+ }
221
+ scopeLabel() {
222
+ const paths = this.config.entries.flatMap((entry) => entry.paths);
223
+ return `a directory required-type-suffix governs (${paths.join(', ')})`;
224
+ }
225
+ why() {
226
+ return 'every exported interface / class / enum / type there must end in one of its path\'s allowed suffixes — ' +
227
+ 'the suffix tells a reader which layer a type belongs to (a …Dto is on the wire, a …Fs is a Firestore ' +
228
+ 'document), where an unsuffixed name reads the same as a server-internal or vendor type.';
229
+ }
230
+ };
231
+ exports.RequiredTypeSuffixValidator = RequiredTypeSuffixValidator;
232
+ exports.RequiredTypeSuffixValidator = RequiredTypeSuffixValidator = tslib_1.__decorate([
233
+ (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
234
+ tslib_1.__metadata("design:paramtypes", [rules_config_1.RequiredTypeSuffixConfig, project_role_resolver_1.ProjectRoleResolver, rules_config_1.DiffScope])
235
+ ], RequiredTypeSuffixValidator);
236
+ //# sourceMappingURL=validate-required-type-suffix.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validate-required-type-suffix.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-required-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CAAC,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QACrE,IAAI,MAAM,KAAK,SAAS;YAAE,OAAO,EAAE,CAAC;QACpC,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;IAC9D,CAAC;IAED,yEAAyE;IACtD,kBAAkB,CAAC,cAAsB,EAAE,OAAe;QACzE,OAAO,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,SAAS,CAAC;IAC5E,CAAC;IAEkB,UAAU;QACzB,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,KAA8B,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QAC3F,OAAO,6CAA6C,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC;IAC5E,CAAC;IAES,GAAG;QACT,OAAO,yGAAyG;YAC5G,uGAAuG;YACvG,yFAAyF,CAAC;IAClG,CAAC;CACJ,CAAA;AA7BY,kEAA2B;sCAA3B,2BAA2B;IADvC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAKjB,uCAAwB,EAAgB,2CAAmB,EAAa,wBAAS;GAJ5F,2BAA2B,CA6BvC","sourcesContent":["/**\n * `required-type-suffix` (#1037) — a type's name says which layer it belongs to.\n *\n * Configured as a list of entries, each pairing path globs with the suffixes allowed there:\n *\n * { \"paths\": [\"libraries/apis/internal/**\"], \"suffixes\": [\"Request\", \"Response\", \"Event\", \"Dto\", \"Api\"] }\n * { \"paths\": [\"libraries/browser-node/fs-*-model/**\"], \"suffixes\": [\"Fs\"] }\n *\n * Every EXPORTED `interface`, `class` (abstract too), `enum` and `type` alias in a non-test `.ts` file under\n * an entry's paths must end in one of that entry's suffixes — a plain, case-sensitive `endsWith`, and the\n * suffix alone is not a name (`FooDto` passes; `FooDTO` and `Dto` fail). A non-exported, file-local type\n * is not judged, and neither is an exported `const` (a DI token's `Symbol` holder is not a type). A type\n * exported through a local `export { Foo as FooDto }` list is judged by the name it is exported AS.\n *\n * Why: in review a `…Dto` is a wire type and a `…Fs` a Firestore document, while `TopNamePlaceInput` reads\n * the same as a server-internal or vendor type. The suffix is the one place the layer can be stated.\n *\n * Overlapping entries: the MOST SPECIFIC entry governs a file ({@link SuffixEntryPicker}); suffixes are\n * never unioned across entries.\n *\n * Under NEW_AND_MODIFIED_CODE only a declaration whose NAME line is new or changed is judged — a new type\n * or a renamed one — so legacy names are grandfathered and a repo with hundreds of them can convert slowly.\n */\n\nimport {\n DiffScope,\n RULE_NAMES,\n RequiredTypeSuffixConfig,\n RequiredTypeSuffixEntry,\n matchesAnyGlob,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport * as ts from 'typescript';\nimport { ApiLibFile, ApiLibSite, ApiLibSourceRule } from './api-lib-source-rule';\nimport { ProjectRoleResolver } from './project-role-resolver';\n\n/** One glob of one entry, with how specific it is. Data-only. */\nexport class RankedGlob {\n constructor(\n readonly entry: RequiredTypeSuffixEntry,\n readonly glob: string,\n /** Characters before the first glob metacharacter (`*`, `?`, `[`, `{`). */\n readonly literalPrefix: number,\n /** Every non-metacharacter in the glob. */\n readonly literalChars: number,\n /** Position of the entry in the config — the final tie-break. */\n readonly order: number,\n ) {}\n}\n\n/**\n * Picks the ONE entry that governs a file. Among the entries with a glob matching the file, the one whose\n * matching glob has the longest LITERAL PREFIX (the characters before its first `*`, `?`, `[` or `{`)\n * wins; a tie goes to the glob with more literal characters overall, then to the entry listed first. So\n * `libraries/apis/internal/**` beats `libraries/apis/**` whatever order they are listed in.\n */\nexport class SuffixEntryPicker {\n private static readonly META = /[*?[\\]{}]/;\n\n entryFor(relFile: string, entries: readonly RequiredTypeSuffixEntry[]): RequiredTypeSuffixEntry | undefined {\n return this.winner(relFile, entries)?.entry;\n }\n\n /** The winning glob (and its entry) for `relFile`, or undefined when no entry covers it. */\n winner(relFile: string, entries: readonly RequiredTypeSuffixEntry[]): RankedGlob | undefined {\n let best: RankedGlob | undefined;\n entries.forEach((entry: RequiredTypeSuffixEntry, order: number) => {\n for (const glob of entry.paths) {\n if (!matchesAnyGlob(relFile, [glob])) continue;\n const ranked = this.rank(entry, glob, order);\n if (best === undefined || this.beats(ranked, best)) best = ranked;\n }\n });\n return best;\n }\n\n private rank(entry: RequiredTypeSuffixEntry, glob: string, order: number): RankedGlob {\n const firstMeta = glob.search(SuffixEntryPicker.META);\n const literalPrefix = firstMeta === -1 ? glob.length : firstMeta;\n const literalChars = glob.replace(/[*?[\\]{}]/g, '').length;\n return new RankedGlob(entry, glob, literalPrefix, literalChars, order);\n }\n\n private beats(a: RankedGlob, b: RankedGlob): boolean {\n if (a.literalPrefix !== b.literalPrefix) return a.literalPrefix > b.literalPrefix;\n if (a.literalChars !== b.literalChars) return a.literalChars > b.literalChars;\n return a.order < b.order;\n }\n}\n\n/** The rename a failure suggests: the name's layer-less tail swapped for each allowed suffix. */\nexport class SuffixRename {\n /**\n * Trailing words that name no layer, dropped before a suffix is appended (`TopNamePlaceInput` →\n * `TopNamePlaceDto`, not `TopNamePlaceInputDto`). Longest first, so `Object` wins over `Obj`.\n */\n private static readonly LAYERLESS_TAILS: readonly string[] = [\n 'Interface', 'Payload', 'Options', 'Object', 'Params', 'Output', 'Option', 'Record', 'Input', 'Model',\n 'Entry', 'Shape', 'Data', 'Info', 'Item', 'Type', 'Body', 'Row', 'Obj',\n ];\n\n /** Candidate names, one per allowed suffix, in the configured order. */\n candidates(name: string, suffixes: readonly string[]): string[] {\n const stem = this.stem(name, suffixes);\n return suffixes.map((suffix: string) => `${stem}${suffix}`);\n }\n\n private stem(name: string, suffixes: readonly string[]): string {\n // `FooDTO` → `Foo`: the suffix is there, in the wrong case.\n const wrongCase = suffixes.find((s: string) => name.length > s.length && name.toLowerCase().endsWith(s.toLowerCase()));\n if (wrongCase !== undefined) return name.slice(0, name.length - wrongCase.length);\n // `Dto` alone → `<Name>Dto`: there is no stem to keep.\n if (suffixes.includes(name)) return '<Name>';\n const tail = SuffixRename.LAYERLESS_TAILS.find((t: string) => name.length > t.length && name.endsWith(t));\n return tail === undefined ? name : name.slice(0, name.length - tail.length);\n }\n}\n\n/** Finds every exported type in one parsed file whose name does not end in the governing entry's suffixes. */\nexport class ExportedTypeScanner {\n private readonly rename = new SuffixRename();\n\n scan(file: ApiLibFile, entry: RequiredTypeSuffixEntry, glob: string): ApiLibSite[] {\n const sites: ApiLibSite[] = [];\n const locals = new Map<string, ts.DeclarationStatement>();\n for (const statement of file.source.statements) {\n const declared = this.typeDeclaration(statement);\n if (declared === undefined) continue;\n if (this.isExported(declared)) {\n const site = this.judge(file, declared, declared.name, declared.name?.getText(file.source) ?? '', entry, glob);\n if (site !== undefined) sites.push(site);\n } else if (declared.name !== undefined) {\n locals.set(declared.name.getText(file.source), declared);\n }\n }\n sites.push(...this.exportListSites(file, locals, entry, glob));\n return sites.sort((a: ApiLibSite, b: ApiLibSite) => a.line - b.line);\n }\n\n /** `export { Local as Exported }` of a local type: judged by the exported name, at the specifier. */\n private exportListSites(\n file: ApiLibFile,\n locals: ReadonlyMap<string, ts.DeclarationStatement>,\n entry: RequiredTypeSuffixEntry,\n glob: string,\n ): ApiLibSite[] {\n const sites: ApiLibSite[] = [];\n for (const statement of file.source.statements) {\n if (!ts.isExportDeclaration(statement) || statement.moduleSpecifier !== undefined) continue;\n if (statement.exportClause === undefined || !ts.isNamedExports(statement.exportClause)) continue;\n for (const element of statement.exportClause.elements) {\n const local = locals.get((element.propertyName ?? element.name).getText(file.source));\n if (local === undefined) continue;\n const site = this.judge(file, local, element.name, element.name.getText(file.source), entry, glob);\n if (site !== undefined) sites.push(site);\n }\n }\n return sites;\n }\n\n private typeDeclaration(statement: ts.Statement): ts.DeclarationStatement | undefined {\n if (ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement) ||\n ts.isEnumDeclaration(statement) || ts.isClassDeclaration(statement)) {\n return statement;\n }\n return undefined;\n }\n\n private isExported(statement: ts.DeclarationStatement): boolean {\n const modifiers = ts.canHaveModifiers(statement) ? ts.getModifiers(statement) ?? [] : [];\n return modifiers.some((m: ts.ModifierLike) => m.kind === ts.SyntaxKind.ExportKeyword);\n }\n\n private judge(\n file: ApiLibFile,\n declared: ts.DeclarationStatement,\n at: ts.Node | undefined,\n name: string,\n entry: RequiredTypeSuffixEntry,\n glob: string,\n ): ApiLibSite | undefined {\n // `export default class { … }` has no name to judge.\n if (at === undefined || name === '') return undefined;\n if (entry.suffixes.some((suffix: string) => name.length > suffix.length && name.endsWith(suffix))) return undefined;\n const kind = this.kindOf(declared);\n const allowed = entry.suffixes.join(' | ');\n const line = file.lineOf(at);\n const snippet = (file.source.text.split('\\n')[line - 1] ?? name).replace(/\\s+/g, ' ').trim();\n const what = `exported ${kind} \\`${name}\\` does not end in a suffix allowed under ${glob} (${allowed})`;\n const candidates = this.rename.candidates(name, entry.suffixes);\n const others = candidates.slice(1).map((c: string) => `\\`${c}\\``).join(' / ');\n const cure = `rename ${kind} \\`${name}\\` → \\`${candidates[0]}\\`` +\n (others === '' ? '' : ` (or ${others} — pick the suffix that names its layer, e.g. …Request for an endpoint body)`) +\n ` and update every reference. Allowed suffixes under ${glob}: ${allowed} — the suffix tells a reader ` +\n `which layer the type belongs to.`;\n return new ApiLibSite(line, snippet, what, cure);\n }\n\n private kindOf(declared: ts.DeclarationStatement): string {\n if (ts.isInterfaceDeclaration(declared)) return 'interface';\n if (ts.isEnumDeclaration(declared)) return 'enum';\n if (ts.isTypeAliasDeclaration(declared)) return 'type';\n return 'class';\n }\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class RequiredTypeSuffixValidator extends ApiLibSourceRule<RequiredTypeSuffixConfig> {\n private readonly picker = new SuffixEntryPicker();\n private readonly scanner = new ExportedTypeScanner();\n\n constructor(config: RequiredTypeSuffixConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope) {\n super(config, RULE_NAMES.REQUIRED_TYPE_SUFFIX, roleResolver, diffScope);\n }\n\n protected sitesIn(file: ApiLibFile): ApiLibSite[] {\n const winner = this.picker.winner(file.relFile, this.config.entries);\n if (winner === undefined) return [];\n return this.scanner.scan(file, winner.entry, winner.glob);\n }\n\n /** Scoped by the configured entries' `paths` globs, not the role tag. */\n protected override isApiLibrarySource(_workspaceRoot: string, relFile: string): boolean {\n return this.picker.entryFor(relFile, this.config.entries) !== undefined;\n }\n\n protected override scopeLabel(): string {\n const paths = this.config.entries.flatMap((entry: RequiredTypeSuffixEntry) => entry.paths);\n return `a directory required-type-suffix governs (${paths.join(', ')})`;\n }\n\n protected why(): string {\n return 'every exported interface / class / enum / type there must end in one of its path\\'s allowed suffixes — ' +\n 'the suffix tells a reader which layer a type belongs to (a …Dto is on the wire, a …Fs is a Firestore ' +\n 'document), where an unsuffixed name reads the same as a server-internal or vendor type.';\n }\n}\n"]}