@webpieces/code-rules 0.4.812 → 0.4.814

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.
@@ -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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ACnF,CAAC;IAES,OAAO,CAAC,IAAgB;QAC9B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACnC,CAAC;IAED,+FAA+F;IAC5E,kBAAkB,CAAC,cAAsB,EAAE,OAAe;QACzE,OAAO,IAAA,6BAAc,EAAC,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACtD,CAAC;IAEkB,UAAU;QACzB,OAAO,mCAAmC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC;IAC9E,CAAC;IAES,GAAG;QACT,OAAO,wGAAwG;YAC3G,oGAAoG,CAAC;IAC7G,CAAC;CACJ,CAAA;AAxBY,0EAA+B;0CAA/B,+BAA+B;IAD3C,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAIjB,2CAA4B,EAAgB,2CAAmB,EAAa,wBAAS;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"]}
@@ -0,0 +1,61 @@
1
+ /**
2
+ * `one-enum-spelling-in-api-lib` (#1023) — ONE spelling for a fixed set of string values in an API:
3
+ *
4
+ * export enum SpeakerGender { FEMALE = 'female', MALE = 'male' }
5
+ * gender!: SpeakerGender; // the enum
6
+ * mode: VoiceMode.RANDOM; // one member (a union discriminator)
7
+ * mode: VoiceMode.A | VoiceMode.B; // a union of members
8
+ *
9
+ * In every `role:api-lib` project this refuses, each with a cure that PRINTS the enum to write:
10
+ *
11
+ * type LessonType = 'story' | 'lesson'; kind?: 'audio' | 'slot'; (a 2+ string-literal union)
12
+ * gender!: (typeof SPEAKER_GENDERS)[number]; key: keyof typeof LABELS;
13
+ * mode: 'random'; (a single literal used as a union discriminator)
14
+ * enum Level { LOW, HIGH } enum Mixed { A = 'a', B = 2 } const enum Tone { … }
15
+ *
16
+ * Why ONE spelling: two ways to write a closed set means every reader, reviewer and the document
17
+ * generator has to understand both, and the derived spellings (`(typeof X)[number]`, a `string` field
18
+ * whose legal values live in some array) are exactly the ones the generator does not read — they can
19
+ * only be supported later, deliberately, if ever. A numeric enum puts NUMBERS on the wire, which no
20
+ * partner reading `gender: 1` can interpret. The generator itself keeps supporting literal unions;
21
+ * this rule is what forbids new ones in an api library.
22
+ */
23
+ import { DiffScope, OneEnumSpellingInApiLibConfig } from '@webpieces/rules-config';
24
+ import { ApiLibEnumIndex } from './api-lib-enum-index';
25
+ import { ApiLibFile, ApiLibSite, ApiLibSourceRule } from './api-lib-source-rule';
26
+ import { ProjectRoleResolver } from './project-role-resolver';
27
+ /** Finds every non-enum spelling of a closed string set in one parsed file. */
28
+ export declare class EnumSpellingScanner {
29
+ scan(file: ApiLibFile, index: ApiLibEnumIndex): ApiLibSite[];
30
+ private siteAt;
31
+ /** `'a' | 'b'` — two or more string-literal branches, anywhere a type is written. */
32
+ private literalUnion;
33
+ /** `mode: 'random'` on a branch of a union — a discriminator, which is one enum member. */
34
+ private singleLiteral;
35
+ /** `(typeof X)[number]` — the values live in a runtime list; the enum IS that list. */
36
+ private typeofIndex;
37
+ /** `keyof typeof X` — the values are an object's keys; the enum states them. */
38
+ private keyofTypeof;
39
+ /** A `const`, numeric, heterogeneous or uninitialised enum. */
40
+ private badEnum;
41
+ /** The declaration a written type belongs to — climbing through arrays, parens, unions and generics. */
42
+ private holderOf;
43
+ /** The nearest enclosing named interface, class, type alias or function. */
44
+ private ownerOf;
45
+ /**
46
+ * When the holder is a property of a union BRANCH that every branch declares, it discriminates the
47
+ * union: the enum is named for the union and property, and holds every branch's values.
48
+ */
49
+ private discriminatorOf;
50
+ /** The string literals a property type spells: `'a'` or `'a' | 'b'`. */
51
+ private literalValues;
52
+ private enumNameFor;
53
+ }
54
+ export declare class OneEnumSpellingInApiLibValidator extends ApiLibSourceRule<OneEnumSpellingInApiLibConfig> {
55
+ private readonly scanner;
56
+ /** One index per api-library directory, per run: the union and its branches are in different files. */
57
+ private readonly indexes;
58
+ constructor(config: OneEnumSpellingInApiLibConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope);
59
+ protected sitesIn(file: ApiLibFile): ApiLibSite[];
60
+ protected why(): string;
61
+ }
@@ -0,0 +1,255 @@
1
+ "use strict";
2
+ /**
3
+ * `one-enum-spelling-in-api-lib` (#1023) — ONE spelling for a fixed set of string values in an API:
4
+ *
5
+ * export enum SpeakerGender { FEMALE = 'female', MALE = 'male' }
6
+ * gender!: SpeakerGender; // the enum
7
+ * mode: VoiceMode.RANDOM; // one member (a union discriminator)
8
+ * mode: VoiceMode.A | VoiceMode.B; // a union of members
9
+ *
10
+ * In every `role:api-lib` project this refuses, each with a cure that PRINTS the enum to write:
11
+ *
12
+ * type LessonType = 'story' | 'lesson'; kind?: 'audio' | 'slot'; (a 2+ string-literal union)
13
+ * gender!: (typeof SPEAKER_GENDERS)[number]; key: keyof typeof LABELS;
14
+ * mode: 'random'; (a single literal used as a union discriminator)
15
+ * enum Level { LOW, HIGH } enum Mixed { A = 'a', B = 2 } const enum Tone { … }
16
+ *
17
+ * Why ONE spelling: two ways to write a closed set means every reader, reviewer and the document
18
+ * generator has to understand both, and the derived spellings (`(typeof X)[number]`, a `string` field
19
+ * whose legal values live in some array) are exactly the ones the generator does not read — they can
20
+ * only be supported later, deliberately, if ever. A numeric enum puts NUMBERS on the wire, which no
21
+ * partner reading `gender: 1` can interpret. The generator itself keeps supporting literal unions;
22
+ * this rule is what forbids new ones in an api library.
23
+ */
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.OneEnumSpellingInApiLibValidator = exports.EnumSpellingScanner = void 0;
26
+ const tslib_1 = require("tslib");
27
+ const rules_config_1 = require("@webpieces/rules-config");
28
+ const inversify_1 = require("inversify");
29
+ const ts = tslib_1.__importStar(require("typescript"));
30
+ const api_lib_enum_index_1 = require("./api-lib-enum-index");
31
+ const api_lib_enum_text_1 = require("./api-lib-enum-text");
32
+ const api_lib_source_rule_1 = require("./api-lib-source-rule");
33
+ const project_role_resolver_1 = require("./project-role-resolver");
34
+ const ONE_SPELLING = 'a fixed set of string values in an API is a string enum, and only a string enum';
35
+ /** Where a type is written: the declaration that names it, for naming the enum. Data-only. */
36
+ class Holder {
37
+ kind;
38
+ name;
39
+ owner;
40
+ constructor(
41
+ /** 'alias' | 'property' | 'parameter' | 'none'. */
42
+ kind, name,
43
+ /** The enclosing named type / class / function, when there is one. */
44
+ owner) {
45
+ this.kind = kind;
46
+ this.name = name;
47
+ this.owner = owner;
48
+ }
49
+ }
50
+ /** A property that discriminates a union, and every value the union's branches give it. Data-only. */
51
+ class Discriminator {
52
+ enumName;
53
+ values;
54
+ constructor(enumName, values) {
55
+ this.enumName = enumName;
56
+ this.values = values;
57
+ }
58
+ }
59
+ /** Finds every non-enum spelling of a closed string set in one parsed file. */
60
+ class EnumSpellingScanner {
61
+ scan(file, index) {
62
+ const sites = [];
63
+ const visit = (node) => {
64
+ const site = this.siteAt(file, index, node);
65
+ if (site !== undefined)
66
+ sites.push(site);
67
+ ts.forEachChild(node, visit);
68
+ };
69
+ visit(file.source);
70
+ return sites;
71
+ }
72
+ siteAt(file, index, node) {
73
+ if (ts.isUnionTypeNode(node))
74
+ return this.literalUnion(file, index, node);
75
+ if (ts.isLiteralTypeNode(node) && ts.isStringLiteral(node.literal))
76
+ return this.singleLiteral(file, index, node);
77
+ if (ts.isIndexedAccessTypeNode(node))
78
+ return this.typeofIndex(file, index, node);
79
+ if (ts.isTypeOperatorNode(node) && node.operator === ts.SyntaxKind.KeyOfKeyword)
80
+ return this.keyofTypeof(file, index, node);
81
+ if (ts.isEnumDeclaration(node))
82
+ return this.badEnum(file, node);
83
+ return undefined;
84
+ }
85
+ /** `'a' | 'b'` — two or more string-literal branches, anywhere a type is written. */
86
+ literalUnion(file, index, node) {
87
+ const values = node.types
88
+ .filter((t) => ts.isLiteralTypeNode(t) && ts.isStringLiteral(t.literal))
89
+ .map((t) => t.literal.text);
90
+ if (values.length < 2)
91
+ return undefined;
92
+ const holder = this.holderOf(node);
93
+ const discriminator = this.discriminatorOf(index, holder);
94
+ const what = `a string-literal union — ${ONE_SPELLING}`;
95
+ if (discriminator !== undefined) {
96
+ const members = values.map((v) => api_lib_enum_text_1.EnumText.memberRef(discriminator.enumName, v, discriminator.values)).join(' | ');
97
+ return file.site(node, what, `declare \`${api_lib_enum_text_1.EnumText.declaration(discriminator.enumName, discriminator.values)}\` (every value of the ` +
98
+ `\`${holder.name}\` discriminator) and write \`${holder.name}: ${members}\` here.`);
99
+ }
100
+ if (holder.kind === 'alias') {
101
+ return file.site(node, what, `replace \`type ${holder.name} = …\` with \`${api_lib_enum_text_1.EnumText.declaration(holder.name, values)}\` — every use of ` +
102
+ `${holder.name} as a type keeps compiling; a literal VALUE becomes ${api_lib_enum_text_1.EnumText.memberRef(holder.name, values[0], values)}.`);
103
+ }
104
+ const name = this.enumNameFor(holder);
105
+ return file.site(node, what, `declare \`${api_lib_enum_text_1.EnumText.declaration(name, values)}\` and write \`${name}\` here in place of the union.`);
106
+ }
107
+ /** `mode: 'random'` on a branch of a union — a discriminator, which is one enum member. */
108
+ singleLiteral(file, index, node) {
109
+ const direct = node.parent;
110
+ const property = ts.isUnionTypeNode(direct) ? direct.parent : direct;
111
+ if (!ts.isPropertySignature(property) && !ts.isPropertyDeclaration(property))
112
+ return undefined;
113
+ if (ts.isUnionTypeNode(direct) && direct.types.filter((t) => !api_lib_enum_index_1.ApiLibEnumIndex.isNullish(t)).length !== 1) {
114
+ return undefined;
115
+ }
116
+ const discriminator = this.discriminatorOf(index, this.holderOf(node));
117
+ if (discriminator === undefined)
118
+ return undefined;
119
+ const value = node.literal.text;
120
+ const key = property.name.getText(file.source);
121
+ return file.site(node, `a single string-literal discriminator — ${ONE_SPELLING}`, `declare \`${api_lib_enum_text_1.EnumText.declaration(discriminator.enumName, discriminator.values)}\` (every value of the ` +
122
+ `\`${key}\` discriminator) and write \`${key}: ${api_lib_enum_text_1.EnumText.memberRef(discriminator.enumName, value, discriminator.values)}\` here.`);
123
+ }
124
+ /** `(typeof X)[number]` — the values live in a runtime list; the enum IS that list. */
125
+ typeofIndex(file, index, node) {
126
+ let object = node.objectType;
127
+ while (ts.isParenthesizedTypeNode(object))
128
+ object = object.type;
129
+ if (!ts.isTypeQueryNode(object) || node.indexType.kind !== ts.SyntaxKind.NumberKeyword)
130
+ return undefined;
131
+ const list = object.exprName.getText(file.source);
132
+ const name = api_lib_enum_text_1.EnumText.singularPascal(list.split('.').pop() ?? list);
133
+ const values = index.constList(list);
134
+ const declaration = values === undefined
135
+ ? `export enum ${name} { /* one MEMBER = 'value' per element of ${list} */ }`
136
+ : api_lib_enum_text_1.EnumText.declaration(name, values);
137
+ return file.site(node, `\`(typeof ${list})[number]\` — ${ONE_SPELLING}`, `replace \`${list}\` with \`${declaration}\` and write \`${name}\` here; code that needs the runtime ` +
138
+ `list uses \`Object.values(${name})\`.`);
139
+ }
140
+ /** `keyof typeof X` — the values are an object's keys; the enum states them. */
141
+ keyofTypeof(file, index, node) {
142
+ if (!ts.isTypeQueryNode(node.type))
143
+ return undefined;
144
+ const object = node.type.exprName.getText(file.source);
145
+ const name = `${api_lib_enum_text_1.EnumText.pascal(object.split('.').pop() ?? object)}Key`;
146
+ const keys = index.constKeysOf(object);
147
+ const declaration = keys === undefined
148
+ ? `export enum ${name} { /* one MEMBER = 'key' per key of ${object} */ }`
149
+ : api_lib_enum_text_1.EnumText.declaration(name, keys);
150
+ return file.site(node, `\`keyof typeof ${object}\` — ${ONE_SPELLING}`, `declare \`${declaration}\` and write \`${name}\` here (key ${object} by it: \`Record<${name}, …>\`).`);
151
+ }
152
+ /** A `const`, numeric, heterogeneous or uninitialised enum. */
153
+ badEnum(file, node) {
154
+ const isConst = (node.modifiers ?? []).some((m) => m.kind === ts.SyntaxKind.ConstKeyword);
155
+ const bad = node.members.filter((m) => m.initializer === undefined || !ts.isStringLiteral(m.initializer));
156
+ if (!isConst && bad.length === 0)
157
+ return undefined;
158
+ const values = node.members.map((m) => m.initializer !== undefined && ts.isStringLiteral(m.initializer) ? m.initializer.text : api_lib_enum_text_1.EnumText.valueFor(m.name.getText(file.source)));
159
+ const reason = isConst
160
+ ? 'a `const enum` — it is erased at compile time, so no runtime value exists for a client or the generator to read'
161
+ : `member(s) ${bad.map((m) => m.name.getText(file.source)).join(', ')} are not initialised with a string ` +
162
+ 'literal — a numeric enum puts NUMBERS on the wire';
163
+ const members = node.members.map((m, i) => `${m.name.getText(file.source)} = '${values[i]}'`).join(', ');
164
+ return file.site(node.name, `${reason}; ${ONE_SPELLING}`, `write \`export enum ${node.name.text} { ${members} }\` — every member string-initialised, no \`const\` ` +
165
+ '(the suggested values are a starting point: they are the wire format, so choose them deliberately).');
166
+ }
167
+ /** The declaration a written type belongs to — climbing through arrays, parens, unions and generics. */
168
+ holderOf(node) {
169
+ let current = node.parent;
170
+ while (current !== undefined && ts.isTypeNode(current))
171
+ current = current.parent;
172
+ if (current === undefined)
173
+ return new Holder('none', 'Values', undefined);
174
+ if (ts.isTypeAliasDeclaration(current))
175
+ return new Holder('alias', current.name.text, undefined);
176
+ if ((ts.isPropertySignature(current) || ts.isPropertyDeclaration(current)) &&
177
+ (ts.isIdentifier(current.name) || ts.isStringLiteral(current.name))) {
178
+ return new Holder('property', current.name.text, this.ownerOf(current));
179
+ }
180
+ if (ts.isParameter(current) && ts.isIdentifier(current.name)) {
181
+ return new Holder('parameter', current.name.text, this.ownerOf(current));
182
+ }
183
+ return new Holder('none', 'Values', this.ownerOf(current));
184
+ }
185
+ /** The nearest enclosing named interface, class, type alias or function. */
186
+ ownerOf(node) {
187
+ for (let at = node.parent; at !== undefined; at = at.parent) {
188
+ if ((ts.isInterfaceDeclaration(at) || ts.isClassDeclaration(at) || ts.isTypeAliasDeclaration(at) ||
189
+ ts.isFunctionDeclaration(at) || ts.isMethodDeclaration(at)) && at.name !== undefined && ts.isIdentifier(at.name)) {
190
+ return at.name.text;
191
+ }
192
+ }
193
+ return undefined;
194
+ }
195
+ /**
196
+ * When the holder is a property of a union BRANCH that every branch declares, it discriminates the
197
+ * union: the enum is named for the union and property, and holds every branch's values.
198
+ */
199
+ discriminatorOf(index, holder) {
200
+ if (holder.kind !== 'property' || holder.owner === undefined)
201
+ return undefined;
202
+ const union = index.unionsOf(holder.owner)
203
+ .find((u) => u.branches.every((b) => index.propertyOf(b, holder.name) !== undefined));
204
+ if (union === undefined)
205
+ return undefined;
206
+ const values = [];
207
+ for (const branch of union.branches) {
208
+ for (const value of this.literalValues(index.propertyOf(branch, holder.name))) {
209
+ if (!values.includes(value))
210
+ values.push(value);
211
+ }
212
+ }
213
+ return new Discriminator(`${union.name ?? holder.owner}${api_lib_enum_text_1.EnumText.pascal(holder.name)}`, values);
214
+ }
215
+ /** The string literals a property type spells: `'a'` or `'a' | 'b'`. */
216
+ literalValues(type) {
217
+ const branches = ts.isUnionTypeNode(type) ? [...type.types] : [type];
218
+ return branches
219
+ .filter((t) => ts.isLiteralTypeNode(t) && ts.isStringLiteral(t.literal))
220
+ .map((t) => t.literal.text);
221
+ }
222
+ enumNameFor(holder) {
223
+ if (holder.kind === 'none')
224
+ return `${holder.owner === undefined ? '' : api_lib_enum_text_1.EnumText.pascal(holder.owner)}Values`;
225
+ return `${holder.owner === undefined ? '' : api_lib_enum_text_1.EnumText.pascal(holder.owner)}${api_lib_enum_text_1.EnumText.pascal(holder.name)}`;
226
+ }
227
+ }
228
+ exports.EnumSpellingScanner = EnumSpellingScanner;
229
+ let OneEnumSpellingInApiLibValidator = class OneEnumSpellingInApiLibValidator extends api_lib_source_rule_1.ApiLibSourceRule {
230
+ scanner = new EnumSpellingScanner();
231
+ /** One index per api-library directory, per run: the union and its branches are in different files. */
232
+ indexes = new Map();
233
+ constructor(config, roleResolver, diffScope) {
234
+ super(config, rules_config_1.RULE_NAMES.ONE_ENUM_SPELLING_IN_API_LIB, roleResolver, diffScope);
235
+ }
236
+ sitesIn(file) {
237
+ let index = this.indexes.get(file.projectDir);
238
+ if (index === undefined) {
239
+ index = api_lib_enum_index_1.ApiLibEnumIndex.of(file.projectDir);
240
+ this.indexes.set(file.projectDir, index);
241
+ }
242
+ return this.scanner.scan(file, index);
243
+ }
244
+ why() {
245
+ return `${ONE_SPELLING} — every member explicitly initialised with a string literal. Two spellings of one ` +
246
+ 'thing is two things every reader and the document generator must understand, and a numeric enum puts ' +
247
+ 'numbers on the wire.';
248
+ }
249
+ };
250
+ exports.OneEnumSpellingInApiLibValidator = OneEnumSpellingInApiLibValidator;
251
+ exports.OneEnumSpellingInApiLibValidator = OneEnumSpellingInApiLibValidator = tslib_1.__decorate([
252
+ (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
253
+ tslib_1.__metadata("design:paramtypes", [rules_config_1.OneEnumSpellingInApiLibConfig, project_role_resolver_1.ProjectRoleResolver, rules_config_1.DiffScope])
254
+ ], OneEnumSpellingInApiLibValidator);
255
+ //# sourceMappingURL=validate-one-enum-spelling-in-api-lib.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validate-one-enum-spelling-in-api-lib.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-one-enum-spelling-in-api-lib.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;;;;AAEH,0DAA+F;AAC/F,yCAA2D;AAC3D,uDAAiC;AACjC,6DAAoE;AACpE,2DAA+C;AAC/C,+DAAiF;AACjF,mEAA8D;AAE9D,MAAM,YAAY,GAAG,iFAAiF,CAAC;AAEvG,8FAA8F;AAC9F,MAAM,MAAM;IAGK;IACA;IAEA;IALb;IACI,mDAAmD;IAC1C,IAAY,EACZ,IAAY;IACrB,sEAAsE;IAC7D,KAAyB;QAHzB,SAAI,GAAJ,IAAI,CAAQ;QACZ,SAAI,GAAJ,IAAI,CAAQ;QAEZ,UAAK,GAAL,KAAK,CAAoB;IACnC,CAAC;CACP;AAED,sGAAsG;AACtG,MAAM,aAAa;IAEF;IACA;IAFb,YACa,QAAgB,EAChB,MAAyB;QADzB,aAAQ,GAAR,QAAQ,CAAQ;QAChB,WAAM,GAAN,MAAM,CAAmB;IACnC,CAAC;CACP;AAED,+EAA+E;AAC/E,MAAa,mBAAmB;IAC5B,IAAI,CAAC,IAAgB,EAAE,KAAsB;QACzC,MAAM,KAAK,GAAiB,EAAE,CAAC;QAC/B,MAAM,KAAK,GAAG,CAAC,IAAa,EAAQ,EAAE;YAClC,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;YAC5C,IAAI,IAAI,KAAK,SAAS;gBAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACzC,EAAE,CAAC,YAAY,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QACjC,CAAC,CAAC;QACF,KAAK,CAA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+C;IAChF,OAAO,GAAG,IAAI,mBAAmB,EAAE,CAAC;IACrD,uGAAuG;IACtF,OAAO,GAAG,IAAI,GAAG,EAA2B,CAAC;IAE9D,YAAY,MAAqC,EAAE,YAAiC,EAAE,SAAoB;QACtG,KAAK,CAAC,MAAM,EAAE,yBAAU,CAAC,4BAA4B,EAAE,YAAY,EAAE,SAAS,CAAC,CAAC;IACpF,CAAC;IAES,OAAO,CAAC,IAAgB;QAC9B,IAAI,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QAC9C,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACtB,KAAK,GAAG,oCAAe,CAAC,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;YAC5C,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;QAC7C,CAAC;QACD,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IAC1C,CAAC;IAES,GAAG;QACT,OAAO,GAAG,YAAY,qFAAqF;YACvG,uGAAuG;YACvG,sBAAsB,CAAC;IAC/B,CAAC;CACJ,CAAA;AAvBY,4EAAgC;2CAAhC,gCAAgC;IAD5C,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAMjB,4CAA6B,EAAgB,2CAAmB,EAAa,wBAAS;GALjG,gCAAgC,CAuB5C","sourcesContent":["/**\n * `one-enum-spelling-in-api-lib` (#1023) — ONE spelling for a fixed set of string values in an API:\n *\n * export enum SpeakerGender { FEMALE = 'female', MALE = 'male' }\n * gender!: SpeakerGender; // the enum\n * mode: VoiceMode.RANDOM; // one member (a union discriminator)\n * mode: VoiceMode.A | VoiceMode.B; // a union of members\n *\n * In every `role:api-lib` project this refuses, each with a cure that PRINTS the enum to write:\n *\n * type LessonType = 'story' | 'lesson'; kind?: 'audio' | 'slot'; (a 2+ string-literal union)\n * gender!: (typeof SPEAKER_GENDERS)[number]; key: keyof typeof LABELS;\n * mode: 'random'; (a single literal used as a union discriminator)\n * enum Level { LOW, HIGH } enum Mixed { A = 'a', B = 2 } const enum Tone { … }\n *\n * Why ONE spelling: two ways to write a closed set means every reader, reviewer and the document\n * generator has to understand both, and the derived spellings (`(typeof X)[number]`, a `string` field\n * whose legal values live in some array) are exactly the ones the generator does not read — they can\n * only be supported later, deliberately, if ever. A numeric enum puts NUMBERS on the wire, which no\n * partner reading `gender: 1` can interpret. The generator itself keeps supporting literal unions;\n * this rule is what forbids new ones in an api library.\n */\n\nimport { DiffScope, OneEnumSpellingInApiLibConfig, RULE_NAMES } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport * as ts from 'typescript';\nimport { ApiLibEnumIndex, ObjectUnion } from './api-lib-enum-index';\nimport { EnumText } from './api-lib-enum-text';\nimport { ApiLibFile, ApiLibSite, ApiLibSourceRule } from './api-lib-source-rule';\nimport { ProjectRoleResolver } from './project-role-resolver';\n\nconst ONE_SPELLING = 'a fixed set of string values in an API is a string enum, and only a string enum';\n\n/** Where a type is written: the declaration that names it, for naming the enum. Data-only. */\nclass Holder {\n constructor(\n /** 'alias' | 'property' | 'parameter' | 'none'. */\n readonly kind: string,\n readonly name: string,\n /** The enclosing named type / class / function, when there is one. */\n readonly owner: string | undefined,\n ) {}\n}\n\n/** A property that discriminates a union, and every value the union's branches give it. Data-only. */\nclass Discriminator {\n constructor(\n readonly enumName: string,\n readonly values: readonly string[],\n ) {}\n}\n\n/** Finds every non-enum spelling of a closed string set in one parsed file. */\nexport class EnumSpellingScanner {\n scan(file: ApiLibFile, index: ApiLibEnumIndex): ApiLibSite[] {\n const sites: ApiLibSite[] = [];\n const visit = (node: ts.Node): void => {\n const site = this.siteAt(file, index, node);\n if (site !== undefined) sites.push(site);\n ts.forEachChild(node, visit);\n };\n visit(file.source);\n return sites;\n }\n\n private siteAt(file: ApiLibFile, index: ApiLibEnumIndex, node: ts.Node): ApiLibSite | undefined {\n if (ts.isUnionTypeNode(node)) return this.literalUnion(file, index, node);\n if (ts.isLiteralTypeNode(node) && ts.isStringLiteral(node.literal)) return this.singleLiteral(file, index, node);\n if (ts.isIndexedAccessTypeNode(node)) return this.typeofIndex(file, index, node);\n if (ts.isTypeOperatorNode(node) && node.operator === ts.SyntaxKind.KeyOfKeyword) return this.keyofTypeof(file, index, node);\n if (ts.isEnumDeclaration(node)) return this.badEnum(file, node);\n return undefined;\n }\n\n /** `'a' | 'b'` — two or more string-literal branches, anywhere a type is written. */\n private literalUnion(file: ApiLibFile, index: ApiLibEnumIndex, node: ts.UnionTypeNode): ApiLibSite | undefined {\n const values = node.types\n .filter((t: ts.TypeNode) => ts.isLiteralTypeNode(t) && ts.isStringLiteral(t.literal))\n .map((t: ts.TypeNode) => ((t as ts.LiteralTypeNode).literal as ts.StringLiteral).text);\n if (values.length < 2) return undefined;\n const holder = this.holderOf(node);\n const discriminator = this.discriminatorOf(index, holder);\n const what = `a string-literal union — ${ONE_SPELLING}`;\n if (discriminator !== undefined) {\n const members = values.map((v: string) => EnumText.memberRef(discriminator.enumName, v, discriminator.values)).join(' | ');\n return file.site(node, what,\n `declare \\`${EnumText.declaration(discriminator.enumName, discriminator.values)}\\` (every value of the ` +\n `\\`${holder.name}\\` discriminator) and write \\`${holder.name}: ${members}\\` here.`);\n }\n if (holder.kind === 'alias') {\n return file.site(node, what,\n `replace \\`type ${holder.name} = …\\` with \\`${EnumText.declaration(holder.name, values)}\\` — every use of ` +\n `${holder.name} as a type keeps compiling; a literal VALUE becomes ${EnumText.memberRef(holder.name, values[0]!, values)}.`);\n }\n const name = this.enumNameFor(holder);\n return file.site(node, what,\n `declare \\`${EnumText.declaration(name, values)}\\` and write \\`${name}\\` here in place of the union.`);\n }\n\n /** `mode: 'random'` on a branch of a union — a discriminator, which is one enum member. */\n private singleLiteral(file: ApiLibFile, index: ApiLibEnumIndex, node: ts.LiteralTypeNode): ApiLibSite | undefined {\n const direct = node.parent;\n const property = ts.isUnionTypeNode(direct) ? direct.parent : direct;\n if (!ts.isPropertySignature(property) && !ts.isPropertyDeclaration(property)) return undefined;\n if (ts.isUnionTypeNode(direct) && direct.types.filter((t: ts.TypeNode) => !ApiLibEnumIndex.isNullish(t)).length !== 1) {\n return undefined;\n }\n const discriminator = this.discriminatorOf(index, this.holderOf(node));\n if (discriminator === undefined) return undefined;\n const value = (node.literal as ts.StringLiteral).text;\n const key = property.name.getText(file.source);\n return file.site(node, `a single string-literal discriminator — ${ONE_SPELLING}`,\n `declare \\`${EnumText.declaration(discriminator.enumName, discriminator.values)}\\` (every value of the ` +\n `\\`${key}\\` discriminator) and write \\`${key}: ${EnumText.memberRef(discriminator.enumName, value, discriminator.values)}\\` here.`);\n }\n\n /** `(typeof X)[number]` — the values live in a runtime list; the enum IS that list. */\n private typeofIndex(file: ApiLibFile, index: ApiLibEnumIndex, node: ts.IndexedAccessTypeNode): ApiLibSite | undefined {\n let object: ts.TypeNode = node.objectType;\n while (ts.isParenthesizedTypeNode(object)) object = object.type;\n if (!ts.isTypeQueryNode(object) || node.indexType.kind !== ts.SyntaxKind.NumberKeyword) return undefined;\n const list = object.exprName.getText(file.source);\n const name = EnumText.singularPascal(list.split('.').pop() ?? list);\n const values = index.constList(list);\n const declaration = values === undefined\n ? `export enum ${name} { /* one MEMBER = 'value' per element of ${list} */ }`\n : EnumText.declaration(name, values);\n return file.site(node, `\\`(typeof ${list})[number]\\` — ${ONE_SPELLING}`,\n `replace \\`${list}\\` with \\`${declaration}\\` and write \\`${name}\\` here; code that needs the runtime ` +\n `list uses \\`Object.values(${name})\\`.`);\n }\n\n /** `keyof typeof X` — the values are an object's keys; the enum states them. */\n private keyofTypeof(file: ApiLibFile, index: ApiLibEnumIndex, node: ts.TypeOperatorNode): ApiLibSite | undefined {\n if (!ts.isTypeQueryNode(node.type)) return undefined;\n const object = node.type.exprName.getText(file.source);\n const name = `${EnumText.pascal(object.split('.').pop() ?? object)}Key`;\n const keys = index.constKeysOf(object);\n const declaration = keys === undefined\n ? `export enum ${name} { /* one MEMBER = 'key' per key of ${object} */ }`\n : EnumText.declaration(name, keys);\n return file.site(node, `\\`keyof typeof ${object}\\` — ${ONE_SPELLING}`,\n `declare \\`${declaration}\\` and write \\`${name}\\` here (key ${object} by it: \\`Record<${name}, …>\\`).`);\n }\n\n /** A `const`, numeric, heterogeneous or uninitialised enum. */\n private badEnum(file: ApiLibFile, node: ts.EnumDeclaration): ApiLibSite | undefined {\n const isConst = (node.modifiers ?? []).some((m: ts.ModifierLike) => m.kind === ts.SyntaxKind.ConstKeyword);\n const bad = node.members.filter((m: ts.EnumMember) => m.initializer === undefined || !ts.isStringLiteral(m.initializer));\n if (!isConst && bad.length === 0) return undefined;\n const values = node.members.map((m: ts.EnumMember) =>\n m.initializer !== undefined && ts.isStringLiteral(m.initializer) ? m.initializer.text : EnumText.valueFor(m.name.getText(file.source)));\n const reason = isConst\n ? 'a `const enum` — it is erased at compile time, so no runtime value exists for a client or the generator to read'\n : `member(s) ${bad.map((m: ts.EnumMember) => m.name.getText(file.source)).join(', ')} are not initialised with a string ` +\n 'literal — a numeric enum puts NUMBERS on the wire';\n const members = node.members.map((m: ts.EnumMember, i: number) => `${m.name.getText(file.source)} = '${values[i]}'`).join(', ');\n return file.site(node.name, `${reason}; ${ONE_SPELLING}`,\n `write \\`export enum ${node.name.text} { ${members} }\\` — every member string-initialised, no \\`const\\` ` +\n '(the suggested values are a starting point: they are the wire format, so choose them deliberately).');\n }\n\n /** The declaration a written type belongs to — climbing through arrays, parens, unions and generics. */\n private holderOf(node: ts.Node): Holder {\n let current: ts.Node = node.parent;\n while (current !== undefined && ts.isTypeNode(current)) current = current.parent;\n if (current === undefined) return new Holder('none', 'Values', undefined);\n if (ts.isTypeAliasDeclaration(current)) return new Holder('alias', current.name.text, undefined);\n if ((ts.isPropertySignature(current) || ts.isPropertyDeclaration(current)) &&\n (ts.isIdentifier(current.name) || ts.isStringLiteral(current.name))) {\n return new Holder('property', current.name.text, this.ownerOf(current));\n }\n if (ts.isParameter(current) && ts.isIdentifier(current.name)) {\n return new Holder('parameter', current.name.text, this.ownerOf(current));\n }\n return new Holder('none', 'Values', this.ownerOf(current));\n }\n\n /** The nearest enclosing named interface, class, type alias or function. */\n private ownerOf(node: ts.Node): string | undefined {\n for (let at: ts.Node | undefined = node.parent; at !== undefined; at = at.parent) {\n if ((ts.isInterfaceDeclaration(at) || ts.isClassDeclaration(at) || ts.isTypeAliasDeclaration(at) ||\n ts.isFunctionDeclaration(at) || ts.isMethodDeclaration(at)) && at.name !== undefined && ts.isIdentifier(at.name)) {\n return at.name.text;\n }\n }\n return undefined;\n }\n\n /**\n * When the holder is a property of a union BRANCH that every branch declares, it discriminates the\n * union: the enum is named for the union and property, and holds every branch's values.\n */\n private discriminatorOf(index: ApiLibEnumIndex, holder: Holder): Discriminator | undefined {\n if (holder.kind !== 'property' || holder.owner === undefined) return undefined;\n const union = index.unionsOf(holder.owner)\n .find((u: ObjectUnion) => u.branches.every((b: string) => index.propertyOf(b, holder.name) !== undefined));\n if (union === undefined) return undefined;\n const values: string[] = [];\n for (const branch of union.branches) {\n for (const value of this.literalValues(index.propertyOf(branch, holder.name)!)) {\n if (!values.includes(value)) values.push(value);\n }\n }\n return new Discriminator(`${union.name ?? holder.owner}${EnumText.pascal(holder.name)}`, values);\n }\n\n /** The string literals a property type spells: `'a'` or `'a' | 'b'`. */\n private literalValues(type: ts.TypeNode): string[] {\n const branches = ts.isUnionTypeNode(type) ? [...type.types] : [type];\n return branches\n .filter((t: ts.TypeNode) => ts.isLiteralTypeNode(t) && ts.isStringLiteral(t.literal))\n .map((t: ts.TypeNode) => ((t as ts.LiteralTypeNode).literal as ts.StringLiteral).text);\n }\n\n private enumNameFor(holder: Holder): string {\n if (holder.kind === 'none') return `${holder.owner === undefined ? '' : EnumText.pascal(holder.owner)}Values`;\n return `${holder.owner === undefined ? '' : EnumText.pascal(holder.owner)}${EnumText.pascal(holder.name)}`;\n }\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class OneEnumSpellingInApiLibValidator extends ApiLibSourceRule<OneEnumSpellingInApiLibConfig> {\n private readonly scanner = new EnumSpellingScanner();\n /** One index per api-library directory, per run: the union and its branches are in different files. */\n private readonly indexes = new Map<string, ApiLibEnumIndex>();\n\n constructor(config: OneEnumSpellingInApiLibConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope) {\n super(config, RULE_NAMES.ONE_ENUM_SPELLING_IN_API_LIB, roleResolver, diffScope);\n }\n\n protected sitesIn(file: ApiLibFile): ApiLibSite[] {\n let index = this.indexes.get(file.projectDir);\n if (index === undefined) {\n index = ApiLibEnumIndex.of(file.projectDir);\n this.indexes.set(file.projectDir, index);\n }\n return this.scanner.scan(file, index);\n }\n\n protected why(): string {\n return `${ONE_SPELLING} — every member explicitly initialised with a string literal. Two spellings of one ` +\n 'thing is two things every reader and the document generator must understand, and a numeric enum puts ' +\n 'numbers on the wire.';\n }\n}\n"]}