@webpieces/code-rules 0.4.813 → 0.4.815
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/src/api-lib-source-rule.d.ts +10 -5
- package/src/api-lib-source-rule.js +13 -4
- package/src/api-lib-source-rule.js.map +1 -1
- package/src/cli.js +6 -14
- package/src/cli.js.map +1 -1
- package/src/code-rules-bootstrap.d.ts +13 -0
- package/src/code-rules-bootstrap.js +38 -0
- package/src/code-rules-bootstrap.js.map +1 -0
- package/src/code-rules-config-table.js +1 -0
- package/src/code-rules-config-table.js.map +1 -1
- package/src/code-rules-engine.d.ts +15 -1
- package/src/code-rules-engine.js +38 -6
- package/src/code-rules-engine.js.map +1 -1
- package/src/code-rules-run-request.d.ts +41 -0
- package/src/code-rules-run-request.js +103 -0
- package/src/code-rules-run-request.js.map +1 -0
- package/src/debug-run-report.d.ts +22 -0
- package/src/debug-run-report.js +127 -0
- package/src/debug-run-report.js.map +1 -0
- package/src/index.d.ts +2 -0
- package/src/index.js +7 -1
- package/src/index.js.map +1 -1
- package/src/rule-scope-plan.d.ts +72 -0
- package/src/rule-scope-plan.js +132 -0
- package/src/rule-scope-plan.js.map +1 -0
- package/src/validate-code.d.ts +7 -7
- package/src/validate-code.js +11 -20
- package/src/validate-code.js.map +1 -1
- package/src/validate-no-custom-css.d.ts +2 -1
- package/src/validate-no-custom-css.js +2 -1
- package/src/validate-no-custom-css.js.map +1 -1
- package/src/validate-no-state-paths-in-templates.d.ts +2 -1
- package/src/validate-no-state-paths-in-templates.js +2 -1
- package/src/validate-no-state-paths-in-templates.js.map +1 -1
- package/src/validate-no-utility-types-in-api-lib.d.ts +58 -0
- package/src/validate-no-utility-types-in-api-lib.js +176 -0
- package/src/validate-no-utility-types-in-api-lib.js.map +1 -0
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* `no-utility-types-in-api-lib` (#1026) — an API contract writes its fields out.
|
|
4
|
+
*
|
|
5
|
+
* In every `.ts` file under the configured `paths` (e.g. `libraries/apis/**`) this refuses the
|
|
6
|
+
* utility types that turn a DTO's field list, or a set of keys, into a type-level computation:
|
|
7
|
+
*
|
|
8
|
+
* export interface LessonPassageDto extends Omit<LessonPassageReservationDto, OptionalField> { … }
|
|
9
|
+
* draft?: Partial<LessonDto>;
|
|
10
|
+
* export type Summary = Pick<LessonDto, 'id' | 'title'>;
|
|
11
|
+
* export type Kind = Exclude<AllKinds, 'legacy'>;
|
|
12
|
+
*
|
|
13
|
+
* — `Omit`, `Pick`, `Partial`, `Required`, `Exclude` and `Extract`, in an `extends` / `implements`
|
|
14
|
+
* clause, a field, a type alias or a generic argument.
|
|
15
|
+
*
|
|
16
|
+
* Why: an api library is the contract every client, server and document generator reads. A utility
|
|
17
|
+
* type makes a reader open a second file and subtract (or add) names in their head to learn which
|
|
18
|
+
* fields a DTO carries; it cannot become a DTO class (`class X extends Omit<…>` does not compile — a
|
|
19
|
+
* utility type has no runtime value); and a key union that only exists to feed `Omit` collides with
|
|
20
|
+
* `one-enum-spelling-in-api-lib`, whose enum cure removes nothing from an `Omit`. The whole family is
|
|
21
|
+
* refused, not `Omit` alone, because banning one just moves the computation into its sibling
|
|
22
|
+
* (`Pick<T, Exclude<keyof T, K>>` is `Omit<T, K>`). `Record`, `Readonly` and `Array` stay allowed:
|
|
23
|
+
* they do not hide which fields a DTO carries.
|
|
24
|
+
*
|
|
25
|
+
* The cure is to write the fields out — a shared base interface both DTOs extend, each adding its own
|
|
26
|
+
* required or optional fields, or a flat interface / class listing every field. The wire JSON is
|
|
27
|
+
* unchanged either way.
|
|
28
|
+
*/
|
|
29
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
30
|
+
exports.NoUtilityTypesInApiLibValidator = exports.UtilityTypeScanner = void 0;
|
|
31
|
+
const tslib_1 = require("tslib");
|
|
32
|
+
const rules_config_1 = require("@webpieces/rules-config");
|
|
33
|
+
const inversify_1 = require("inversify");
|
|
34
|
+
const ts = tslib_1.__importStar(require("typescript"));
|
|
35
|
+
const api_lib_source_rule_1 = require("./api-lib-source-rule");
|
|
36
|
+
const project_role_resolver_1 = require("./project-role-resolver");
|
|
37
|
+
/** Finds every refused utility-type reference in one parsed file. */
|
|
38
|
+
class UtilityTypeScanner {
|
|
39
|
+
/** The refused utility types, each with what it computes. */
|
|
40
|
+
static REFUSED = new Map([
|
|
41
|
+
['Omit', 'a DTO\'s field list computed by SUBTRACTING keys from another type'],
|
|
42
|
+
['Pick', 'a DTO\'s field list computed by SELECTING keys of another type'],
|
|
43
|
+
['Partial', 'a DTO\'s field list computed by making every field of another type optional'],
|
|
44
|
+
['Required', 'a DTO\'s field list computed by making every field of another type required'],
|
|
45
|
+
['Exclude', 'a set of keys or values computed by SUBTRACTING from another union'],
|
|
46
|
+
['Extract', 'a set of keys or values computed by SELECTING from another union'],
|
|
47
|
+
]);
|
|
48
|
+
scan(file) {
|
|
49
|
+
const shadowed = this.locallyDeclaredNames(file.source);
|
|
50
|
+
const sites = [];
|
|
51
|
+
const visit = (node) => {
|
|
52
|
+
const name = this.refusedNameOf(node, shadowed);
|
|
53
|
+
if (name !== undefined)
|
|
54
|
+
sites.push(this.siteFor(file, node, name));
|
|
55
|
+
ts.forEachChild(node, visit);
|
|
56
|
+
};
|
|
57
|
+
visit(file.source);
|
|
58
|
+
return sites;
|
|
59
|
+
}
|
|
60
|
+
/** The utility's name when `node` is a refused reference: `Omit<…>` as a type, or in a heritage clause. */
|
|
61
|
+
refusedNameOf(node, shadowed) {
|
|
62
|
+
let name;
|
|
63
|
+
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName))
|
|
64
|
+
name = node.typeName.text;
|
|
65
|
+
else if (ts.isExpressionWithTypeArguments(node) && ts.isIdentifier(node.expression))
|
|
66
|
+
name = node.expression.text;
|
|
67
|
+
if (name === undefined || !UtilityTypeScanner.REFUSED.has(name) || shadowed.has(name))
|
|
68
|
+
return undefined;
|
|
69
|
+
return name;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Names the file declares or imports itself — a local `type Omit = …` or an imported `Pick` class
|
|
73
|
+
* is not the global utility type, so it is not refused.
|
|
74
|
+
*/
|
|
75
|
+
locallyDeclaredNames(source) {
|
|
76
|
+
const names = new Set();
|
|
77
|
+
for (const statement of source.statements) {
|
|
78
|
+
if ((ts.isTypeAliasDeclaration(statement) || ts.isInterfaceDeclaration(statement) ||
|
|
79
|
+
ts.isClassDeclaration(statement) || ts.isEnumDeclaration(statement)) && statement.name !== undefined) {
|
|
80
|
+
names.add(statement.name.text);
|
|
81
|
+
}
|
|
82
|
+
const bindings = ts.isImportDeclaration(statement) ? statement.importClause?.namedBindings : undefined;
|
|
83
|
+
if (bindings !== undefined && ts.isNamedImports(bindings)) {
|
|
84
|
+
for (const element of bindings.elements)
|
|
85
|
+
names.add(element.name.text);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return names;
|
|
89
|
+
}
|
|
90
|
+
siteFor(file, node, name) {
|
|
91
|
+
const args = this.typeArgumentsOf(node).map((arg) => arg.getText(file.source).replace(/\s+/g, ' '));
|
|
92
|
+
const what = `\`${name}<…>\` — ${UtilityTypeScanner.REFUSED.get(name)}; an API writes its fields out`;
|
|
93
|
+
return file.site(node, what, `${this.cureFor(name, args[0] ?? 'T', args[1] ?? 'K')} ${this.owner(file, node)}`.trim());
|
|
94
|
+
}
|
|
95
|
+
typeArgumentsOf(node) {
|
|
96
|
+
if (ts.isTypeReferenceNode(node) || ts.isExpressionWithTypeArguments(node))
|
|
97
|
+
return node.typeArguments ?? [];
|
|
98
|
+
return [];
|
|
99
|
+
}
|
|
100
|
+
cureFor(name, target, keys) {
|
|
101
|
+
const wire = 'The wire JSON is unchanged.';
|
|
102
|
+
switch (name) {
|
|
103
|
+
case 'Omit':
|
|
104
|
+
return `write the fields out instead of \`Omit<${target}, ${keys}>\`: move the fields both types share into a ` +
|
|
105
|
+
`base interface that ${target} and this type both extend, each adding its own required or optional ` +
|
|
106
|
+
`fields — or list every field of ${target} except ${keys} in a flat interface or class. ${wire}`;
|
|
107
|
+
case 'Pick':
|
|
108
|
+
return `write the fields out instead of \`Pick<${target}, ${keys}>\`: put the picked fields (${keys}) in a ` +
|
|
109
|
+
`base interface that ${target} extends and use it here — or list them in a flat interface or class. ${wire}`;
|
|
110
|
+
case 'Partial':
|
|
111
|
+
return `write the fields out instead of \`Partial<${target}>\`: declare an interface or class listing every ` +
|
|
112
|
+
`field of ${target} as optional (\`field?: X\`). ${wire}`;
|
|
113
|
+
case 'Required':
|
|
114
|
+
return `write the fields out instead of \`Required<${target}>\`: declare an interface or class listing every ` +
|
|
115
|
+
`field of ${target} as required. ${wire}`;
|
|
116
|
+
default:
|
|
117
|
+
return `write the set out instead of \`${name}<${target}, ${keys}>\`: for keys of a DTO, write that DTO's ` +
|
|
118
|
+
`fields out; for values, declare the string enum holding exactly the members meant ` +
|
|
119
|
+
`(one-enum-spelling-in-api-lib), or a union of its members. ${wire}`;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/** `(on interface X)` for a heritage clause, `(in X.field)` for a member, `(in type X)` for an alias. */
|
|
123
|
+
owner(file, node) {
|
|
124
|
+
let current = node.parent;
|
|
125
|
+
let member;
|
|
126
|
+
while (current !== undefined && current !== file.source) {
|
|
127
|
+
if ((ts.isPropertySignature(current) || ts.isPropertyDeclaration(current)) && member === undefined) {
|
|
128
|
+
member = current.name.getText(file.source);
|
|
129
|
+
}
|
|
130
|
+
const declared = this.declaredName(current);
|
|
131
|
+
if (declared !== undefined) {
|
|
132
|
+
if (ts.isHeritageClause(node.parent))
|
|
133
|
+
return `(on ${declared})`;
|
|
134
|
+
return member === undefined ? `(in ${declared})` : `(in ${declared}.${member})`;
|
|
135
|
+
}
|
|
136
|
+
current = current.parent;
|
|
137
|
+
}
|
|
138
|
+
return '';
|
|
139
|
+
}
|
|
140
|
+
declaredName(node) {
|
|
141
|
+
if (ts.isInterfaceDeclaration(node))
|
|
142
|
+
return `interface ${node.name.text}`;
|
|
143
|
+
if (ts.isClassDeclaration(node) && node.name !== undefined)
|
|
144
|
+
return `class ${node.name.text}`;
|
|
145
|
+
if (ts.isTypeAliasDeclaration(node))
|
|
146
|
+
return `type ${node.name.text}`;
|
|
147
|
+
return undefined;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
exports.UtilityTypeScanner = UtilityTypeScanner;
|
|
151
|
+
let NoUtilityTypesInApiLibValidator = class NoUtilityTypesInApiLibValidator extends api_lib_source_rule_1.ApiLibSourceRule {
|
|
152
|
+
scanner = new UtilityTypeScanner();
|
|
153
|
+
constructor(config, roleResolver, diffScope) {
|
|
154
|
+
super(config, rules_config_1.RULE_NAMES.NO_UTILITY_TYPES_IN_API_LIB, roleResolver, diffScope);
|
|
155
|
+
}
|
|
156
|
+
sitesIn(file) {
|
|
157
|
+
return this.scanner.scan(file);
|
|
158
|
+
}
|
|
159
|
+
/** Scoped by the configured `paths` globs, not the role tag — an empty list judges nothing. */
|
|
160
|
+
isApiLibrarySource(_workspaceRoot, relFile) {
|
|
161
|
+
return (0, rules_config_1.matchesAnyGlob)(relFile, this.config.paths);
|
|
162
|
+
}
|
|
163
|
+
scopeLabel() {
|
|
164
|
+
return `an API contract library (paths: ${this.config.paths.join(', ')})`;
|
|
165
|
+
}
|
|
166
|
+
why() {
|
|
167
|
+
return 'an API writes its fields out — Omit / Pick / Partial / Required / Exclude / Extract make every reader ' +
|
|
168
|
+
'of the contract compute its field list from another file, and none of them can become a DTO class.';
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
exports.NoUtilityTypesInApiLibValidator = NoUtilityTypesInApiLibValidator;
|
|
172
|
+
exports.NoUtilityTypesInApiLibValidator = NoUtilityTypesInApiLibValidator = tslib_1.__decorate([
|
|
173
|
+
(0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
|
|
174
|
+
tslib_1.__metadata("design:paramtypes", [rules_config_1.NoUtilityTypesInApiLibConfig, project_role_resolver_1.ProjectRoleResolver, rules_config_1.DiffScope])
|
|
175
|
+
], NoUtilityTypesInApiLibValidator);
|
|
176
|
+
//# sourceMappingURL=validate-no-utility-types-in-api-lib.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validate-no-utility-types-in-api-lib.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-utility-types-in-api-lib.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;;;;AAEH,0DAA8G;AAC9G,yCAA2D;AAC3D,uDAAiC;AACjC,+DAAiF;AACjF,mEAA8D;AAE9D,qEAAqE;AACrE,MAAa,kBAAkB;IAC3B,6DAA6D;IAC7D,MAAM,CAAU,OAAO,GAAgC,IAAI,GAAG,CAAiB;QAC3E,CAAC,MAAM,EAAE,oEAAoE,CAAC;QAC9E,CAAC,MAAM,EAAE,gEAAgE,CAAC;QAC1E,CAAC,SAAS,EAAE,6EAA6E,CAAC;QAC1F,CAAC,UAAU,EAAE,6EAA6E,CAAC;QAC3F,CAAC,SAAS,EAAE,oEAAoE,CAAC;QACjF,CAAC,SAAS,EAAE,kEAAkE,CAAC;KAClF,CAAC,CAAC;IAEH,IAAI,CAAC,IAAgB;QACjB,MAAM,QAAQ,GAAG,IAAI,CAAC,oBAAoB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACxD,MAAM,KAAK,GAAiB,EAAE,CAAC;QAC/B,MAAM,KAAK,GAAG,CAAC,IAAa,EAAQ,EAAE;YAClC,MAAM,IAAI,GAAG,IAAI,CAAC,aAAa,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;YAChD,IAAI,IAAI,KAAK,SAAS;gBAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;YACnE,EAAE,CAAC,YAAY,CAAC,IAAI,EAAE,KAAK,CAA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OAAe;QACzE,OAAO,IAAA,6BAAc,EAAC,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACtD,CAAC;IAEkB,UAAU;QACzB,OAAO,mCAAmC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC;IAC9E,CAAC;IAES,GAAG;QACT,OAAO,wGAAwG;YAC3G,oGAAoG,CAAC;IAC7G,CAAC;CACJ,CAAA;AAxBY,0EAA+B;0CAA/B,+BAA+B;IAD3C,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAIjB,2CAA4B,EAAgB,2CAAmB,EAAa,wBAAS;GAHhG,+BAA+B,CAwB3C","sourcesContent":["/**\n * `no-utility-types-in-api-lib` (#1026) — an API contract writes its fields out.\n *\n * In every `.ts` file under the configured `paths` (e.g. `libraries/apis/**`) this refuses the\n * utility types that turn a DTO's field list, or a set of keys, into a type-level computation:\n *\n * export interface LessonPassageDto extends Omit<LessonPassageReservationDto, OptionalField> { … }\n * draft?: Partial<LessonDto>;\n * export type Summary = Pick<LessonDto, 'id' | 'title'>;\n * export type Kind = Exclude<AllKinds, 'legacy'>;\n *\n * — `Omit`, `Pick`, `Partial`, `Required`, `Exclude` and `Extract`, in an `extends` / `implements`\n * clause, a field, a type alias or a generic argument.\n *\n * Why: an api library is the contract every client, server and document generator reads. A utility\n * type makes a reader open a second file and subtract (or add) names in their head to learn which\n * fields a DTO carries; it cannot become a DTO class (`class X extends Omit<…>` does not compile — a\n * utility type has no runtime value); and a key union that only exists to feed `Omit` collides with\n * `one-enum-spelling-in-api-lib`, whose enum cure removes nothing from an `Omit`. The whole family is\n * refused, not `Omit` alone, because banning one just moves the computation into its sibling\n * (`Pick<T, Exclude<keyof T, K>>` is `Omit<T, K>`). `Record`, `Readonly` and `Array` stay allowed:\n * they do not hide which fields a DTO carries.\n *\n * The cure is to write the fields out — a shared base interface both DTOs extend, each adding its own\n * required or optional fields, or a flat interface / class listing every field. The wire JSON is\n * unchanged either way.\n */\n\nimport { DiffScope, NoUtilityTypesInApiLibConfig, RULE_NAMES, matchesAnyGlob } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport * as ts from 'typescript';\nimport { ApiLibFile, ApiLibSite, ApiLibSourceRule } from './api-lib-source-rule';\nimport { ProjectRoleResolver } from './project-role-resolver';\n\n/** Finds every refused utility-type reference in one parsed file. */\nexport class UtilityTypeScanner {\n /** The refused utility types, each with what it computes. */\n static readonly REFUSED: ReadonlyMap<string, string> = new Map<string, string>([\n ['Omit', 'a DTO\\'s field list computed by SUBTRACTING keys from another type'],\n ['Pick', 'a DTO\\'s field list computed by SELECTING keys of another type'],\n ['Partial', 'a DTO\\'s field list computed by making every field of another type optional'],\n ['Required', 'a DTO\\'s field list computed by making every field of another type required'],\n ['Exclude', 'a set of keys or values computed by SUBTRACTING from another union'],\n ['Extract', 'a set of keys or values computed by SELECTING from another union'],\n ]);\n\n scan(file: ApiLibFile): ApiLibSite[] {\n const shadowed = this.locallyDeclaredNames(file.source);\n const sites: ApiLibSite[] = [];\n const visit = (node: ts.Node): void => {\n const name = this.refusedNameOf(node, shadowed);\n if (name !== undefined) sites.push(this.siteFor(file, node, name));\n ts.forEachChild(node, visit);\n };\n visit(file.source);\n return sites;\n }\n\n /** The utility's name when `node` is a refused reference: `Omit<…>` as a type, or in a heritage clause. */\n private refusedNameOf(node: ts.Node, shadowed: ReadonlySet<string>): string | undefined {\n let name: string | undefined;\n if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) name = node.typeName.text;\n else if (ts.isExpressionWithTypeArguments(node) && ts.isIdentifier(node.expression)) name = node.expression.text;\n if (name === undefined || !UtilityTypeScanner.REFUSED.has(name) || shadowed.has(name)) return undefined;\n return name;\n }\n\n /**\n * Names the file declares or imports itself — a local `type Omit = …` or an imported `Pick` class\n * is not the global utility type, so it is not refused.\n */\n private locallyDeclaredNames(source: ts.SourceFile): Set<string> {\n const names = new Set<string>();\n for (const statement of source.statements) {\n if ((ts.isTypeAliasDeclaration(statement) || ts.isInterfaceDeclaration(statement) ||\n ts.isClassDeclaration(statement) || ts.isEnumDeclaration(statement)) && statement.name !== undefined) {\n names.add(statement.name.text);\n }\n const bindings = ts.isImportDeclaration(statement) ? statement.importClause?.namedBindings : undefined;\n if (bindings !== undefined && ts.isNamedImports(bindings)) {\n for (const element of bindings.elements) names.add(element.name.text);\n }\n }\n return names;\n }\n\n private siteFor(file: ApiLibFile, node: ts.Node, name: string): ApiLibSite {\n const args = this.typeArgumentsOf(node).map((arg: ts.TypeNode) => arg.getText(file.source).replace(/\\s+/g, ' '));\n const what = `\\`${name}<…>\\` — ${UtilityTypeScanner.REFUSED.get(name)}; an API writes its fields out`;\n return file.site(node, what, `${this.cureFor(name, args[0] ?? 'T', args[1] ?? 'K')} ${this.owner(file, node)}`.trim());\n }\n\n private typeArgumentsOf(node: ts.Node): readonly ts.TypeNode[] {\n if (ts.isTypeReferenceNode(node) || ts.isExpressionWithTypeArguments(node)) return node.typeArguments ?? [];\n return [];\n }\n\n private cureFor(name: string, target: string, keys: string): string {\n const wire = 'The wire JSON is unchanged.';\n switch (name) {\n case 'Omit':\n return `write the fields out instead of \\`Omit<${target}, ${keys}>\\`: move the fields both types share into a ` +\n `base interface that ${target} and this type both extend, each adding its own required or optional ` +\n `fields — or list every field of ${target} except ${keys} in a flat interface or class. ${wire}`;\n case 'Pick':\n return `write the fields out instead of \\`Pick<${target}, ${keys}>\\`: put the picked fields (${keys}) in a ` +\n `base interface that ${target} extends and use it here — or list them in a flat interface or class. ${wire}`;\n case 'Partial':\n return `write the fields out instead of \\`Partial<${target}>\\`: declare an interface or class listing every ` +\n `field of ${target} as optional (\\`field?: X\\`). ${wire}`;\n case 'Required':\n return `write the fields out instead of \\`Required<${target}>\\`: declare an interface or class listing every ` +\n `field of ${target} as required. ${wire}`;\n default:\n return `write the set out instead of \\`${name}<${target}, ${keys}>\\`: for keys of a DTO, write that DTO's ` +\n `fields out; for values, declare the string enum holding exactly the members meant ` +\n `(one-enum-spelling-in-api-lib), or a union of its members. ${wire}`;\n }\n }\n\n /** `(on interface X)` for a heritage clause, `(in X.field)` for a member, `(in type X)` for an alias. */\n private owner(file: ApiLibFile, node: ts.Node): string {\n let current: ts.Node | undefined = node.parent;\n let member: string | undefined;\n while (current !== undefined && current !== file.source) {\n if ((ts.isPropertySignature(current) || ts.isPropertyDeclaration(current)) && member === undefined) {\n member = current.name.getText(file.source);\n }\n const declared = this.declaredName(current);\n if (declared !== undefined) {\n if (ts.isHeritageClause(node.parent)) return `(on ${declared})`;\n return member === undefined ? `(in ${declared})` : `(in ${declared}.${member})`;\n }\n current = current.parent;\n }\n return '';\n }\n\n private declaredName(node: ts.Node): string | undefined {\n if (ts.isInterfaceDeclaration(node)) return `interface ${node.name.text}`;\n if (ts.isClassDeclaration(node) && node.name !== undefined) return `class ${node.name.text}`;\n if (ts.isTypeAliasDeclaration(node)) return `type ${node.name.text}`;\n return undefined;\n }\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoUtilityTypesInApiLibValidator extends ApiLibSourceRule<NoUtilityTypesInApiLibConfig> {\n private readonly scanner = new UtilityTypeScanner();\n\n constructor(config: NoUtilityTypesInApiLibConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope) {\n super(config, RULE_NAMES.NO_UTILITY_TYPES_IN_API_LIB, roleResolver, diffScope);\n }\n\n protected sitesIn(file: ApiLibFile): ApiLibSite[] {\n return this.scanner.scan(file);\n }\n\n /** Scoped by the configured `paths` globs, not the role tag — an empty list judges nothing. */\n protected override isApiLibrarySource(_workspaceRoot: string, relFile: string): boolean {\n return matchesAnyGlob(relFile, this.config.paths);\n }\n\n protected override scopeLabel(): string {\n return `an API contract library (paths: ${this.config.paths.join(', ')})`;\n }\n\n protected why(): string {\n return 'an API writes its fields out — Omit / Pick / Partial / Required / Exclude / Extract make every reader ' +\n 'of the contract compute its field list from another file, and none of them can become a DTO class.';\n }\n}\n"]}
|