@webpieces/code-rules 0.4.811 → 0.4.813

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.811",
3
+ "version": "0.4.813",
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.811",
19
+ "@webpieces/rules-config": "0.4.813",
20
20
  "@inversifyjs/binding-decorators": "1.1.5",
21
21
  "inversify": "7.10.4",
22
22
  "reflect-metadata": "0.2.2"
@@ -0,0 +1,46 @@
1
+ /**
2
+ * What `one-enum-spelling-in-api-lib` needs to know about a WHOLE api library before it can judge one
3
+ * of its files (#1023): which object types are branches of a union (so a literal-typed property on one
4
+ * is a DISCRIMINATOR), what each named object type declares, and the values of the `as const` lists
5
+ * and objects a `(typeof X)[number]` / `keyof typeof X` reads — so the cure can print the enum with its
6
+ * real values rather than a placeholder.
7
+ *
8
+ * Built once per project directory and cached: the union and the branch it names are routinely in
9
+ * different files. Parser-only, like the rule.
10
+ */
11
+ import * as ts from 'typescript';
12
+ /** One union of named object types, e.g. `type StoryVoiceChoice = A | B | C`. Data-only. */
13
+ export declare class ObjectUnion {
14
+ /** The alias name, or undefined for a union written inline on a field. */
15
+ readonly name: string | undefined;
16
+ readonly branches: readonly string[];
17
+ constructor(
18
+ /** The alias name, or undefined for a union written inline on a field. */
19
+ name: string | undefined, branches: readonly string[]);
20
+ }
21
+ export declare class ApiLibEnumIndex {
22
+ /** branch type name -> the unions it is a branch of. */
23
+ private readonly unionsByBranch;
24
+ /** named object type -> its properties' declared type nodes. */
25
+ private readonly properties;
26
+ /** `const X = ['a', 'b'] as const` -> ['a', 'b']. */
27
+ private readonly constLists;
28
+ /** `const X = { a: …, b: … } as const` -> ['a', 'b']. */
29
+ private readonly constKeys;
30
+ /** Index every non-test `.ts` file under `projectDir`. */
31
+ static of(projectDir: string): ApiLibEnumIndex;
32
+ /** Add one parsed file — also how a spec builds an index from source text. */
33
+ add(source: ts.SourceFile): void;
34
+ unionsOf(branch: string): readonly ObjectUnion[];
35
+ propertyOf(typeName: string, property: string): ts.TypeNode | undefined;
36
+ constList(name: string): readonly string[] | undefined;
37
+ constKeysOf(name: string): readonly string[] | undefined;
38
+ private indexNode;
39
+ /** A union whose non-nullish branches are all NAMED types, two or more of them. */
40
+ private indexUnion;
41
+ private indexMembers;
42
+ /** `[...] as const` string lists and `{...} as const` objects. */
43
+ private indexConst;
44
+ static isNullish(node: ts.TypeNode): boolean;
45
+ private static sourceFiles;
46
+ }
@@ -0,0 +1,158 @@
1
+ "use strict";
2
+ /**
3
+ * What `one-enum-spelling-in-api-lib` needs to know about a WHOLE api library before it can judge one
4
+ * of its files (#1023): which object types are branches of a union (so a literal-typed property on one
5
+ * is a DISCRIMINATOR), what each named object type declares, and the values of the `as const` lists
6
+ * and objects a `(typeof X)[number]` / `keyof typeof X` reads — so the cure can print the enum with its
7
+ * real values rather than a placeholder.
8
+ *
9
+ * Built once per project directory and cached: the union and the branch it names are routinely in
10
+ * different files. Parser-only, like the rule.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.ApiLibEnumIndex = exports.ObjectUnion = void 0;
14
+ const tslib_1 = require("tslib");
15
+ const fs = tslib_1.__importStar(require("fs"));
16
+ const path = tslib_1.__importStar(require("path"));
17
+ const ts = tslib_1.__importStar(require("typescript"));
18
+ /** One union of named object types, e.g. `type StoryVoiceChoice = A | B | C`. Data-only. */
19
+ class ObjectUnion {
20
+ name;
21
+ branches;
22
+ constructor(
23
+ /** The alias name, or undefined for a union written inline on a field. */
24
+ name, branches) {
25
+ this.name = name;
26
+ this.branches = branches;
27
+ }
28
+ }
29
+ exports.ObjectUnion = ObjectUnion;
30
+ /** Directories never part of an api library's source. */
31
+ const SKIPPED_DIRS = ['node_modules', 'dist', '.nx', '__tests__'];
32
+ class ApiLibEnumIndex {
33
+ /** branch type name -> the unions it is a branch of. */
34
+ unionsByBranch = new Map();
35
+ /** named object type -> its properties' declared type nodes. */
36
+ properties = new Map();
37
+ /** `const X = ['a', 'b'] as const` -> ['a', 'b']. */
38
+ constLists = new Map();
39
+ /** `const X = { a: …, b: … } as const` -> ['a', 'b']. */
40
+ constKeys = new Map();
41
+ /** Index every non-test `.ts` file under `projectDir`. */
42
+ // webpieces-disable no-function-outside-class -- static factory of this class
43
+ static of(projectDir) {
44
+ const index = new ApiLibEnumIndex();
45
+ for (const file of ApiLibEnumIndex.sourceFiles(projectDir)) {
46
+ const text = fs.readFileSync(file, 'utf8');
47
+ index.add(ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true));
48
+ }
49
+ return index;
50
+ }
51
+ /** Add one parsed file — also how a spec builds an index from source text. */
52
+ add(source) {
53
+ const visit = (node) => {
54
+ this.indexNode(node);
55
+ ts.forEachChild(node, visit);
56
+ };
57
+ visit(source);
58
+ }
59
+ unionsOf(branch) {
60
+ return this.unionsByBranch.get(branch) ?? [];
61
+ }
62
+ propertyOf(typeName, property) {
63
+ return this.properties.get(typeName)?.get(property);
64
+ }
65
+ constList(name) {
66
+ return this.constLists.get(name);
67
+ }
68
+ constKeysOf(name) {
69
+ return this.constKeys.get(name);
70
+ }
71
+ indexNode(node) {
72
+ if (ts.isUnionTypeNode(node))
73
+ this.indexUnion(node);
74
+ if ((ts.isInterfaceDeclaration(node) || ts.isClassDeclaration(node)) && node.name !== undefined) {
75
+ this.indexMembers(node.name.text, node.members);
76
+ }
77
+ if (ts.isTypeAliasDeclaration(node) && ts.isTypeLiteralNode(node.type)) {
78
+ this.indexMembers(node.name.text, node.type.members);
79
+ }
80
+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer !== undefined) {
81
+ this.indexConst(node.name.text, node.initializer);
82
+ }
83
+ }
84
+ /** A union whose non-nullish branches are all NAMED types, two or more of them. */
85
+ indexUnion(node) {
86
+ const names = [];
87
+ for (const branch of node.types) {
88
+ if (ApiLibEnumIndex.isNullish(branch))
89
+ continue;
90
+ if (!ts.isTypeReferenceNode(branch) || !ts.isIdentifier(branch.typeName))
91
+ return;
92
+ names.push(branch.typeName.text);
93
+ }
94
+ if (names.length < 2)
95
+ return;
96
+ const union = new ObjectUnion(ts.isTypeAliasDeclaration(node.parent) ? node.parent.name.text : undefined, names);
97
+ for (const name of names) {
98
+ const list = this.unionsByBranch.get(name) ?? [];
99
+ list.push(union);
100
+ this.unionsByBranch.set(name, list);
101
+ }
102
+ }
103
+ indexMembers(owner, members) {
104
+ const byName = this.properties.get(owner) ?? new Map();
105
+ for (const member of members) {
106
+ if (!ts.isPropertySignature(member) && !ts.isPropertyDeclaration(member))
107
+ continue;
108
+ if (member.type === undefined || !(ts.isIdentifier(member.name) || ts.isStringLiteral(member.name)))
109
+ continue;
110
+ byName.set(member.name.text, member.type);
111
+ }
112
+ this.properties.set(owner, byName);
113
+ }
114
+ /** `[...] as const` string lists and `{...} as const` objects. */
115
+ indexConst(name, initializer) {
116
+ const inner = ts.isAsExpression(initializer) ? initializer.expression : initializer;
117
+ if (ts.isArrayLiteralExpression(inner)) {
118
+ const values = inner.elements.filter(ts.isStringLiteralLike).map((each) => each.text);
119
+ if (values.length === inner.elements.length)
120
+ this.constLists.set(name, values);
121
+ return;
122
+ }
123
+ if (ts.isObjectLiteralExpression(inner)) {
124
+ const keys = [];
125
+ for (const property of inner.properties) {
126
+ const key = property.name;
127
+ if (key !== undefined && (ts.isIdentifier(key) || ts.isStringLiteral(key)))
128
+ keys.push(key.text);
129
+ }
130
+ this.constKeys.set(name, keys);
131
+ }
132
+ }
133
+ // webpieces-disable no-function-outside-class -- private static predicate of this class
134
+ static isNullish(node) {
135
+ if (node.kind === ts.SyntaxKind.UndefinedKeyword || node.kind === ts.SyntaxKind.NullKeyword)
136
+ return true;
137
+ return ts.isLiteralTypeNode(node) && node.literal.kind === ts.SyntaxKind.NullKeyword;
138
+ }
139
+ // webpieces-disable no-function-outside-class -- private static file walk of this class
140
+ static sourceFiles(dir) {
141
+ const files = [];
142
+ if (!fs.existsSync(dir))
143
+ return files;
144
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
145
+ const full = path.join(dir, entry.name);
146
+ if (entry.isDirectory()) {
147
+ if (!SKIPPED_DIRS.includes(entry.name))
148
+ files.push(...ApiLibEnumIndex.sourceFiles(full));
149
+ }
150
+ else if (entry.name.endsWith('.ts') && !entry.name.endsWith('.d.ts') && !/\.(spec|test)\.ts$/.test(entry.name)) {
151
+ files.push(full);
152
+ }
153
+ }
154
+ return files;
155
+ }
156
+ }
157
+ exports.ApiLibEnumIndex = ApiLibEnumIndex;
158
+ //# sourceMappingURL=api-lib-enum-index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-lib-enum-index.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/api-lib-enum-index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;GASG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,uDAAiC;AAEjC,4FAA4F;AAC5F,MAAa,WAAW;IAGP;IACA;IAHb;IACI,0EAA0E;IACjE,IAAwB,EACxB,QAA2B;QAD3B,SAAI,GAAJ,IAAI,CAAoB;QACxB,aAAQ,GAAR,QAAQ,CAAmB;IACrC,CAAC;CACP;AAND,kCAMC;AAED,yDAAyD;AACzD,MAAM,YAAY,GAAsB,CAAC,cAAc,EAAE,MAAM,EAAE,KAAK,EAAE,WAAW,CAAC,CAAC;AAErF,MAAa,eAAe;IACxB,wDAAwD;IACvC,cAAc,GAAG,IAAI,GAAG,EAAyB,CAAC;IACnE,gEAAgE;IAC/C,UAAU,GAAG,IAAI,GAAG,EAAoC,CAAC;IAC1E,qDAAqD;IACpC,UAAU,GAAG,IAAI,GAAG,EAAoB,CAAC;I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` needs to know about a WHOLE api library before it can judge one\n * of its files (#1023): which object types are branches of a union (so a literal-typed property on one\n * is a DISCRIMINATOR), what each named object type declares, and the values of the `as const` lists\n * and objects a `(typeof X)[number]` / `keyof typeof X` reads — so the cure can print the enum with its\n * real values rather than a placeholder.\n *\n * Built once per project directory and cached: the union and the branch it names are routinely in\n * different files. Parser-only, like the rule.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as ts from 'typescript';\n\n/** One union of named object types, e.g. `type StoryVoiceChoice = A | B | C`. Data-only. */\nexport class ObjectUnion {\n constructor(\n /** The alias name, or undefined for a union written inline on a field. */\n readonly name: string | undefined,\n readonly branches: readonly string[],\n ) {}\n}\n\n/** Directories never part of an api library's source. */\nconst SKIPPED_DIRS: readonly string[] = ['node_modules', 'dist', '.nx', '__tests__'];\n\nexport class ApiLibEnumIndex {\n /** branch type name -> the unions it is a branch of. */\n private readonly unionsByBranch = new Map<string, ObjectUnion[]>();\n /** named object type -> its properties' declared type nodes. */\n private readonly properties = new Map<string, Map<string, ts.TypeNode>>();\n /** `const X = ['a', 'b'] as const` -> ['a', 'b']. */\n private readonly constLists = new Map<string, string[]>();\n /** `const X = { a: …, b: … } as const` -> ['a', 'b']. */\n private readonly constKeys = new Map<string, string[]>();\n\n /** Index every non-test `.ts` file under `projectDir`. */\n // webpieces-disable no-function-outside-class -- static factory of this class\n static of(projectDir: string): ApiLibEnumIndex {\n const index = new ApiLibEnumIndex();\n for (const file of ApiLibEnumIndex.sourceFiles(projectDir)) {\n const text = fs.readFileSync(file, 'utf8');\n index.add(ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true));\n }\n return index;\n }\n\n /** Add one parsed file — also how a spec builds an index from source text. */\n add(source: ts.SourceFile): void {\n const visit = (node: ts.Node): void => {\n this.indexNode(node);\n ts.forEachChild(node, visit);\n };\n visit(source);\n }\n\n unionsOf(branch: string): readonly ObjectUnion[] {\n return this.unionsByBranch.get(branch) ?? [];\n }\n\n propertyOf(typeName: string, property: string): ts.TypeNode | undefined {\n return this.properties.get(typeName)?.get(property);\n }\n\n constList(name: string): readonly string[] | undefined {\n return this.constLists.get(name);\n }\n\n constKeysOf(name: string): readonly string[] | undefined {\n return this.constKeys.get(name);\n }\n\n private indexNode(node: ts.Node): void {\n if (ts.isUnionTypeNode(node)) this.indexUnion(node);\n if ((ts.isInterfaceDeclaration(node) || ts.isClassDeclaration(node)) && node.name !== undefined) {\n this.indexMembers(node.name.text, node.members);\n }\n if (ts.isTypeAliasDeclaration(node) && ts.isTypeLiteralNode(node.type)) {\n this.indexMembers(node.name.text, node.type.members);\n }\n if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer !== undefined) {\n this.indexConst(node.name.text, node.initializer);\n }\n }\n\n /** A union whose non-nullish branches are all NAMED types, two or more of them. */\n private indexUnion(node: ts.UnionTypeNode): void {\n const names: string[] = [];\n for (const branch of node.types) {\n if (ApiLibEnumIndex.isNullish(branch)) continue;\n if (!ts.isTypeReferenceNode(branch) || !ts.isIdentifier(branch.typeName)) return;\n names.push(branch.typeName.text);\n }\n if (names.length < 2) return;\n const union = new ObjectUnion(ts.isTypeAliasDeclaration(node.parent) ? node.parent.name.text : undefined, names);\n for (const name of names) {\n const list = this.unionsByBranch.get(name) ?? [];\n list.push(union);\n this.unionsByBranch.set(name, list);\n }\n }\n\n private indexMembers(owner: string, members: ts.NodeArray<ts.TypeElement> | ts.NodeArray<ts.ClassElement>): void {\n const byName = this.properties.get(owner) ?? new Map<string, ts.TypeNode>();\n for (const member of members) {\n if (!ts.isPropertySignature(member) && !ts.isPropertyDeclaration(member)) continue;\n if (member.type === undefined || !(ts.isIdentifier(member.name) || ts.isStringLiteral(member.name))) continue;\n byName.set(member.name.text, member.type);\n }\n this.properties.set(owner, byName);\n }\n\n /** `[...] as const` string lists and `{...} as const` objects. */\n private indexConst(name: string, initializer: ts.Expression): void {\n const inner = ts.isAsExpression(initializer) ? initializer.expression : initializer;\n if (ts.isArrayLiteralExpression(inner)) {\n const values = inner.elements.filter(ts.isStringLiteralLike).map((each: ts.StringLiteralLike) => each.text);\n if (values.length === inner.elements.length) this.constLists.set(name, values);\n return;\n }\n if (ts.isObjectLiteralExpression(inner)) {\n const keys: string[] = [];\n for (const property of inner.properties) {\n const key = property.name;\n if (key !== undefined && (ts.isIdentifier(key) || ts.isStringLiteral(key))) keys.push(key.text);\n }\n this.constKeys.set(name, keys);\n }\n }\n\n // webpieces-disable no-function-outside-class -- private static predicate of this class\n static isNullish(node: ts.TypeNode): boolean {\n if (node.kind === ts.SyntaxKind.UndefinedKeyword || node.kind === ts.SyntaxKind.NullKeyword) return true;\n return ts.isLiteralTypeNode(node) && node.literal.kind === ts.SyntaxKind.NullKeyword;\n }\n\n // webpieces-disable no-function-outside-class -- private static file walk of this class\n private static sourceFiles(dir: string): string[] {\n const files: string[] = [];\n if (!fs.existsSync(dir)) return files;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n if (!SKIPPED_DIRS.includes(entry.name)) files.push(...ApiLibEnumIndex.sourceFiles(full));\n } else if (entry.name.endsWith('.ts') && !entry.name.endsWith('.d.ts') && !/\\.(spec|test)\\.ts$/.test(entry.name)) {\n files.push(full);\n }\n }\n return files;\n }\n}\n"]}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The text `one-enum-spelling-in-api-lib` PRINTS: the enum to write, with real member names and
3
+ * values, so the cure is an edit to paste rather than a direction to go and work one out (#1023).
4
+ */
5
+ export declare class EnumText {
6
+ /** `export enum SpeakerGender { FEMALE = 'female', MALE = 'male' }` */
7
+ static declaration(name: string, values: readonly string[]): string;
8
+ /** One member name per value, collision-free, in value order. */
9
+ static members(values: readonly string[]): EnumMemberText[];
10
+ /** `'randomWithChirp'` → `RANDOM_WITH_CHIRP`, `'en-US'` → `EN_US`, `'1x'` → `V_1X`. */
11
+ static memberName(value: string): string;
12
+ /** The member name of `name` in `enumName`, as a value would be spelled: `SpeakerGender.FEMALE`. */
13
+ static memberRef(enumName: string, value: string, all: readonly string[]): string;
14
+ /** `SPEAKER_GENDERS` → `SpeakerGender`, `kind` → `Kind`, `voiceMode` → `VoiceMode`. */
15
+ static pascal(text: string): string;
16
+ /** A list constant's singular type name: `SPEAKER_GENDERS` → `SpeakerGender`. */
17
+ static singularPascal(text: string): string;
18
+ /** An uninitialised member's suggested wire value: `RANDOM_WITH_CHIRP` → `randomWithChirp`, `Red` → `red`. */
19
+ static valueFor(memberName: string): string;
20
+ private static words;
21
+ }
22
+ /** One enum member as printed. Data-only. */
23
+ export declare class EnumMemberText {
24
+ readonly name: string;
25
+ readonly value: string;
26
+ constructor(name: string, value: string);
27
+ }
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EnumMemberText = exports.EnumText = void 0;
4
+ /**
5
+ * The text `one-enum-spelling-in-api-lib` PRINTS: the enum to write, with real member names and
6
+ * values, so the cure is an edit to paste rather than a direction to go and work one out (#1023).
7
+ */
8
+ class EnumText {
9
+ /** `export enum SpeakerGender { FEMALE = 'female', MALE = 'male' }` */
10
+ // webpieces-disable no-function-outside-class -- static formatter of this class
11
+ static declaration(name, values) {
12
+ const members = EnumText.members(values);
13
+ return `export enum ${name} { ${members.map((m) => `${m.name} = '${m.value}'`).join(', ')} }`;
14
+ }
15
+ /** One member name per value, collision-free, in value order. */
16
+ // webpieces-disable no-function-outside-class -- static formatter of this class
17
+ static members(values) {
18
+ const used = new Set();
19
+ return values.map((value) => {
20
+ const base = EnumText.memberName(value);
21
+ let name = base;
22
+ for (let n = 2; used.has(name); n++)
23
+ name = `${base}_${n}`;
24
+ used.add(name);
25
+ return new EnumMemberText(name, value);
26
+ });
27
+ }
28
+ /** `'randomWithChirp'` → `RANDOM_WITH_CHIRP`, `'en-US'` → `EN_US`, `'1x'` → `V_1X`. */
29
+ // webpieces-disable no-function-outside-class -- static formatter of this class
30
+ static memberName(value) {
31
+ const words = EnumText.words(value).map((word) => word.toUpperCase());
32
+ const joined = words.join('_') || 'EMPTY';
33
+ return /^[0-9]/.test(joined) ? `V_${joined}` : joined;
34
+ }
35
+ /** The member name of `name` in `enumName`, as a value would be spelled: `SpeakerGender.FEMALE`. */
36
+ // webpieces-disable no-function-outside-class -- static formatter of this class
37
+ static memberRef(enumName, value, all) {
38
+ const member = EnumText.members(all).find((m) => m.value === value);
39
+ return `${enumName}.${member?.name ?? EnumText.memberName(value)}`;
40
+ }
41
+ /** `SPEAKER_GENDERS` → `SpeakerGender`, `kind` → `Kind`, `voiceMode` → `VoiceMode`. */
42
+ // webpieces-disable no-function-outside-class -- static formatter of this class
43
+ static pascal(text) {
44
+ return EnumText.words(text).map((word) => word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
45
+ }
46
+ /** A list constant's singular type name: `SPEAKER_GENDERS` → `SpeakerGender`. */
47
+ // webpieces-disable no-function-outside-class -- static formatter of this class
48
+ static singularPascal(text) {
49
+ const pascal = EnumText.pascal(text);
50
+ return pascal.length > 1 && pascal.endsWith('s') && !pascal.endsWith('ss') ? pascal.slice(0, -1) : pascal;
51
+ }
52
+ /** An uninitialised member's suggested wire value: `RANDOM_WITH_CHIRP` → `randomWithChirp`, `Red` → `red`. */
53
+ // webpieces-disable no-function-outside-class -- static formatter of this class
54
+ static valueFor(memberName) {
55
+ const pascal = EnumText.pascal(memberName);
56
+ return pascal === '' ? memberName : pascal[0].toLowerCase() + pascal.slice(1);
57
+ }
58
+ // webpieces-disable no-function-outside-class -- private static splitter of this class
59
+ static words(text) {
60
+ return text
61
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
62
+ .split(/[^A-Za-z0-9]+/)
63
+ .filter((word) => word !== '');
64
+ }
65
+ }
66
+ exports.EnumText = EnumText;
67
+ /** One enum member as printed. Data-only. */
68
+ class EnumMemberText {
69
+ name;
70
+ value;
71
+ constructor(name, value) {
72
+ this.name = name;
73
+ this.value = value;
74
+ }
75
+ }
76
+ exports.EnumMemberText = EnumMemberText;
77
+ //# sourceMappingURL=api-lib-enum-text.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-lib-enum-text.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/api-lib-enum-text.ts"],"names":[],"mappings":";;;AAAA;;;GAGG;AACH,MAAa,QAAQ;IACjB,uEAAuE;IACvE,gFAAgF;IAChF,MAAM,CAAC,WAAW,CAAC,IAAY,EAAE,MAAyB;QACtD,MAAM,OAAO,GAAG,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QACzC,OAAO,eAAe,IAAI,MAAM,OAAO,CAAC,GAAG,CAAC,CAAC,CAAiB,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,IAAI,OAAO,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;IAClH,CAAC;IAED,iEAAiE;IACjE,gFAAgF;IAChF,MAAM,CAAC,OAAO,CAAC,MAAyB;QACpC,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;QAC/B,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC,KAAa,EAAE,EAAE;YAChC,MAAM,IAAI,GAAG,QAAQ,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;YACxC,IAAI,IAAI,GAAG,IAAI,CAAC;YAChB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE;gBAAE,IAAI,GAAG,GAAG,IAAI,IAAI,CAAC,EAAE,CAAC;YAC3D,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;YACf,OAAO,IAAI,cAAc,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAC3C,CAAC,CAAC,CAAC;IACP,CAAC;IAED,uFAAuF;IACvF,gFAAgF;IAChF,MAAM,CAAC,UAAU,CAAC,KAAa;QAC3B,MAAM,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC,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CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;IAC9G,CAAC;IAED,8GAA8G;IAC9G,gFAAgF;IAChF,MAAM,CAAC,QAAQ,CAAC,UAAkB;QAC9B,MAAM,MAAM,GAAG,QAAQ,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAC3C,OAAO,MAAM,KAAK,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAE,CAAC,WAAW,EAAE,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IACnF,CAAC;IAED,uFAAuF;IAC/E,MAAM,CAAC,KAAK,CAAC,IAAY;QAC7B,OAAO,IAAI;aACN,OAAO,CAAC,oBAAoB,EAAE,OAAO,CAAC;aACtC,KAAK,CAAC,eAAe,CAAC;aACtB,MAAM,CAAC,CAAC,IAAY,EAAE,EAAE,CAAC,IAAI,KAAK,EAAE,CAAC,CAAC;IAC/C,CAAC;CACJ;AA/DD,4BA+DC;AAED,6CAA6C;AAC7C,MAAa,cAAc;IAEV;IACA;IAFb,YACa,IAAY,EACZ,KAAa;QADb,SAAI,GAAJ,IAAI,CAAQ;QACZ,UAAK,GAAL,KAAK,CAAQ;IACvB,CAAC;CACP;AALD,wCAKC","sourcesContent":["/**\n * The text `one-enum-spelling-in-api-lib` PRINTS: the enum to write, with real member names and\n * values, so the cure is an edit to paste rather than a direction to go and work one out (#1023).\n */\nexport class EnumText {\n /** `export enum SpeakerGender { FEMALE = 'female', MALE = 'male' }` */\n // webpieces-disable no-function-outside-class -- static formatter of this class\n static declaration(name: string, values: readonly string[]): string {\n const members = EnumText.members(values);\n return `export enum ${name} { ${members.map((m: EnumMemberText) => `${m.name} = '${m.value}'`).join(', ')} }`;\n }\n\n /** One member name per value, collision-free, in value order. */\n // webpieces-disable no-function-outside-class -- static formatter of this class\n static members(values: readonly string[]): EnumMemberText[] {\n const used = new Set<string>();\n return values.map((value: string) => {\n const base = EnumText.memberName(value);\n let name = base;\n for (let n = 2; used.has(name); n++) name = `${base}_${n}`;\n used.add(name);\n return new EnumMemberText(name, value);\n });\n }\n\n /** `'randomWithChirp'` → `RANDOM_WITH_CHIRP`, `'en-US'` → `EN_US`, `'1x'` → `V_1X`. */\n // webpieces-disable no-function-outside-class -- static formatter of this class\n static memberName(value: string): string {\n const words = EnumText.words(value).map((word: string) => word.toUpperCase());\n const joined = words.join('_') || 'EMPTY';\n return /^[0-9]/.test(joined) ? `V_${joined}` : joined;\n }\n\n /** The member name of `name` in `enumName`, as a value would be spelled: `SpeakerGender.FEMALE`. */\n // webpieces-disable no-function-outside-class -- static formatter of this class\n static memberRef(enumName: string, value: string, all: readonly string[]): string {\n const member = EnumText.members(all).find((m: EnumMemberText) => m.value === value);\n return `${enumName}.${member?.name ?? EnumText.memberName(value)}`;\n }\n\n /** `SPEAKER_GENDERS` → `SpeakerGender`, `kind` → `Kind`, `voiceMode` → `VoiceMode`. */\n // webpieces-disable no-function-outside-class -- static formatter of this class\n static pascal(text: string): string {\n return EnumText.words(text).map((word: string) => word[0]!.toUpperCase() + word.slice(1).toLowerCase()).join('');\n }\n\n /** A list constant's singular type name: `SPEAKER_GENDERS` → `SpeakerGender`. */\n // webpieces-disable no-function-outside-class -- static formatter of this class\n static singularPascal(text: string): string {\n const pascal = EnumText.pascal(text);\n return pascal.length > 1 && pascal.endsWith('s') && !pascal.endsWith('ss') ? pascal.slice(0, -1) : pascal;\n }\n\n /** An uninitialised member's suggested wire value: `RANDOM_WITH_CHIRP` → `randomWithChirp`, `Red` → `red`. */\n // webpieces-disable no-function-outside-class -- static formatter of this class\n static valueFor(memberName: string): string {\n const pascal = EnumText.pascal(memberName);\n return pascal === '' ? memberName : pascal[0]!.toLowerCase() + pascal.slice(1);\n }\n\n // webpieces-disable no-function-outside-class -- private static splitter of this class\n private static words(text: string): string[] {\n return text\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .split(/[^A-Za-z0-9]+/)\n .filter((word: string) => word !== '');\n }\n}\n\n/** One enum member as printed. Data-only. */\nexport class EnumMemberText {\n constructor(\n readonly name: string,\n readonly value: string,\n ) {}\n}\n"]}
@@ -0,0 +1,70 @@
1
+ /**
2
+ * The shared half of the two `role:api-lib` spelling rules (#1023): `no-inline-import-in-api-lib` and
3
+ * `one-enum-spelling-in-api-lib`.
4
+ *
5
+ * Both judge the SOURCE of an api library — the contract every consumer and the OpenAPI / MCP
6
+ * generator read — and both have the same rollout shape: `mode` NEW_AND_MODIFIED_CODE judges only the
7
+ * changed lines (so existing code is grandfathered until someone touches it), NEW_AND_MODIFIED_FILES
8
+ * judges every site in a changed file. This class owns that scoping, the api-lib test, the escape
9
+ * hatches, and the ONE failure spelling: a thrown `RuleFailError` with one `Option` per site, which
10
+ * `RuleReporter` renders. A subclass only says what a violating site IS.
11
+ *
12
+ * Parser-only on purpose (no `ts.Program`): each rule reads the syntax as written, which is exactly
13
+ * what it refuses, and a parse cannot be diverted to a `.d.ts` by module resolution.
14
+ */
15
+ import * as ts from 'typescript';
16
+ import { DiffScope, NoInlineImportInApiLibConfig, OneEnumSpellingInApiLibConfig } from '@webpieces/rules-config';
17
+ import { CodeValidator, ExecutorResult } from './code-validator';
18
+ import { ProjectRoleResolver } from './project-role-resolver';
19
+ /** One violating site: where, what it is, and the edit that replaces it. Data-only. */
20
+ export declare class ApiLibSite {
21
+ /** 1-based line of the site's first character. */
22
+ readonly line: number;
23
+ /** The offending source text, trimmed to one line. */
24
+ readonly snippet: string;
25
+ readonly what: string;
26
+ readonly cure: string;
27
+ constructor(
28
+ /** 1-based line of the site's first character. */
29
+ line: number,
30
+ /** The offending source text, trimmed to one line. */
31
+ snippet: string, what: string, cure: string);
32
+ }
33
+ /** One api-library source file, parsed, with the project directory that owns it. Data-only. */
34
+ export declare class ApiLibFile {
35
+ /** Workspace-relative. */
36
+ readonly relFile: string;
37
+ readonly source: ts.SourceFile;
38
+ /** Absolute path of the owning project's directory (the one holding project.json). */
39
+ readonly projectDir: string;
40
+ constructor(
41
+ /** Workspace-relative. */
42
+ relFile: string, source: ts.SourceFile,
43
+ /** Absolute path of the owning project's directory (the one holding project.json). */
44
+ projectDir: string);
45
+ /** The 1-based line a node starts on. */
46
+ lineOf(node: ts.Node): number;
47
+ /** A site at `node`, its text collapsed to one line. */
48
+ site(node: ts.Node, what: string, cure: string): ApiLibSite;
49
+ }
50
+ type ApiLibConfig = NoInlineImportInApiLibConfig | OneEnumSpellingInApiLibConfig;
51
+ export declare abstract class ApiLibSourceRule<C extends ApiLibConfig> extends CodeValidator<C> {
52
+ private readonly roleResolver;
53
+ private readonly diffScope;
54
+ constructor(config: C, ruleName: string, roleResolver: ProjectRoleResolver, diffScope: DiffScope);
55
+ /** Every violating site in one api-library file. */
56
+ protected abstract sitesIn(file: ApiLibFile): ApiLibSite[];
57
+ /** The one-sentence WHY printed above the sites. */
58
+ protected abstract why(): string;
59
+ run(workspaceRoot: string): Promise<ExecutorResult>;
60
+ /** The unexempt, in-scope violating sites of one changed file. */
61
+ private judge;
62
+ /** A non-test `.ts` file, not under `allowedPaths`, owned by a `role:api-lib` project. */
63
+ private inScope;
64
+ /** `// webpieces-disable <rule> -- <reason>` on the site's line or the line above. */
65
+ private disabled;
66
+ /** The nearest ancestor of `relFile` holding a project.json, absolute. */
67
+ private projectDirOf;
68
+ private failure;
69
+ }
70
+ export {};
@@ -0,0 +1,156 @@
1
+ "use strict";
2
+ /**
3
+ * The shared half of the two `role:api-lib` spelling rules (#1023): `no-inline-import-in-api-lib` and
4
+ * `one-enum-spelling-in-api-lib`.
5
+ *
6
+ * Both judge the SOURCE of an api library — the contract every consumer and the OpenAPI / MCP
7
+ * generator read — and both have the same rollout shape: `mode` NEW_AND_MODIFIED_CODE judges only the
8
+ * changed lines (so existing code is grandfathered until someone touches it), NEW_AND_MODIFIED_FILES
9
+ * judges every site in a changed file. This class owns that scoping, the api-lib test, the escape
10
+ * hatches, and the ONE failure spelling: a thrown `RuleFailError` with one `Option` per site, which
11
+ * `RuleReporter` renders. A subclass only says what a violating site IS.
12
+ *
13
+ * Parser-only on purpose (no `ts.Program`): each rule reads the syntax as written, which is exactly
14
+ * what it refuses, and a parse cannot be diverted to a `.d.ts` by module resolution.
15
+ */
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.ApiLibSourceRule = exports.ApiLibFile = exports.ApiLibSite = void 0;
18
+ const tslib_1 = require("tslib");
19
+ const fs = tslib_1.__importStar(require("fs"));
20
+ const path = tslib_1.__importStar(require("path"));
21
+ const ts = tslib_1.__importStar(require("typescript"));
22
+ const rules_config_1 = require("@webpieces/rules-config");
23
+ const code_validator_1 = require("./code-validator");
24
+ /** The role these rules judge. */
25
+ const API_LIB_ROLE = 'api-lib';
26
+ /** One violating site: where, what it is, and the edit that replaces it. Data-only. */
27
+ class ApiLibSite {
28
+ line;
29
+ snippet;
30
+ what;
31
+ cure;
32
+ constructor(
33
+ /** 1-based line of the site's first character. */
34
+ line,
35
+ /** The offending source text, trimmed to one line. */
36
+ snippet, what, cure) {
37
+ this.line = line;
38
+ this.snippet = snippet;
39
+ this.what = what;
40
+ this.cure = cure;
41
+ }
42
+ }
43
+ exports.ApiLibSite = ApiLibSite;
44
+ /** One api-library source file, parsed, with the project directory that owns it. Data-only. */
45
+ class ApiLibFile {
46
+ relFile;
47
+ source;
48
+ projectDir;
49
+ constructor(
50
+ /** Workspace-relative. */
51
+ relFile, source,
52
+ /** Absolute path of the owning project's directory (the one holding project.json). */
53
+ projectDir) {
54
+ this.relFile = relFile;
55
+ this.source = source;
56
+ this.projectDir = projectDir;
57
+ }
58
+ /** The 1-based line a node starts on. */
59
+ lineOf(node) {
60
+ return this.source.getLineAndCharacterOfPosition(node.getStart(this.source)).line + 1;
61
+ }
62
+ /** A site at `node`, its text collapsed to one line. */
63
+ site(node, what, cure) {
64
+ const text = node.getText(this.source).replace(/\s+/g, ' ').trim();
65
+ return new ApiLibSite(this.lineOf(node), text, what, cure);
66
+ }
67
+ }
68
+ exports.ApiLibFile = ApiLibFile;
69
+ /** A located site, for the failure message. Data-only. */
70
+ class FoundSite {
71
+ relFile;
72
+ site;
73
+ constructor(relFile, site) {
74
+ this.relFile = relFile;
75
+ this.site = site;
76
+ }
77
+ }
78
+ class ApiLibSourceRule extends code_validator_1.CodeValidator {
79
+ roleResolver;
80
+ diffScope;
81
+ constructor(config, ruleName, roleResolver, diffScope) {
82
+ super(config, ruleName, ruleName);
83
+ this.roleResolver = roleResolver;
84
+ this.diffScope = diffScope;
85
+ }
86
+ async run(workspaceRoot) {
87
+ const mode = this.config.mode;
88
+ if (mode === undefined || mode === 'OFF')
89
+ return { success: true };
90
+ // NX_BASE / NX_HEAD when nx set them, else the merge-base with main.
91
+ const range = this.diffScope.resolveBase(workspaceRoot);
92
+ const base = range.base;
93
+ if (base === undefined) {
94
+ console.log(`\n⏭️ Skipping ${this.name} validation (could not detect base branch)\n`);
95
+ return { success: true };
96
+ }
97
+ const found = [];
98
+ for (const relFile of this.diffScope.getChangedFiles(workspaceRoot, base, range.head)) {
99
+ found.push(...this.judge(workspaceRoot, relFile, mode, base, range.head));
100
+ }
101
+ if (found.length === 0)
102
+ return { success: true };
103
+ throw this.failure(found);
104
+ }
105
+ /** The unexempt, in-scope violating sites of one changed file. */
106
+ judge(workspaceRoot, relFile, mode, base, head) {
107
+ if (!this.inScope(workspaceRoot, relFile))
108
+ return [];
109
+ const changedLines = mode === 'NEW_AND_MODIFIED_CODE'
110
+ ? this.diffScope.getChangedLineNumbers(this.diffScope.getFileDiff(workspaceRoot, relFile, base, head))
111
+ : undefined;
112
+ if (changedLines !== undefined && changedLines.size === 0)
113
+ return [];
114
+ const absFile = path.join(workspaceRoot, relFile);
115
+ const text = fs.readFileSync(absFile, 'utf8');
116
+ const lines = text.split('\n');
117
+ const source = ts.createSourceFile(absFile, text, ts.ScriptTarget.Latest, true);
118
+ const file = new ApiLibFile(relFile, source, this.projectDirOf(workspaceRoot, relFile));
119
+ return this.sitesIn(file)
120
+ .filter((site) => changedLines === undefined || changedLines.has(site.line))
121
+ .filter((site) => !this.disabled(lines, site.line))
122
+ .map((site) => new FoundSite(relFile, site));
123
+ }
124
+ /** A non-test `.ts` file, not under `allowedPaths`, owned by a `role:api-lib` project. */
125
+ inScope(workspaceRoot, relFile) {
126
+ if (!relFile.endsWith('.ts') || relFile.endsWith('.d.ts'))
127
+ return false;
128
+ if (/\.(spec|test)\.ts$/.test(relFile) || relFile.includes('__tests__/'))
129
+ return false;
130
+ if ((0, rules_config_1.isPathExcluded)(relFile, this.config.allowedPaths ?? []))
131
+ return false;
132
+ if (!fs.existsSync(path.join(workspaceRoot, relFile)))
133
+ return false;
134
+ return this.roleResolver.roleOf(workspaceRoot, relFile) === API_LIB_ROLE;
135
+ }
136
+ /** `// webpieces-disable <rule> -- <reason>` on the site's line or the line above. */
137
+ disabled(lines, line) {
138
+ return (0, rules_config_1.hasDisable)(lines[line - 1] ?? '', this.name) || (0, rules_config_1.hasDisable)(lines[line - 2] ?? '', this.name);
139
+ }
140
+ /** The nearest ancestor of `relFile` holding a project.json, absolute. */
141
+ projectDirOf(workspaceRoot, relFile) {
142
+ let dir = path.dirname(path.join(workspaceRoot, relFile));
143
+ while (!fs.existsSync(path.join(dir, 'project.json')) && path.dirname(dir) !== dir) {
144
+ dir = path.dirname(dir);
145
+ }
146
+ return dir;
147
+ }
148
+ failure(found) {
149
+ const message = `${found.length} site(s) in a role:api-lib project: ${this.why()}\n` +
150
+ found.map((each) => ` ${each.relFile}:${each.site.line} — ${each.site.what}\n ${each.site.snippet}`).join('\n') +
151
+ `\n Last resort, per site: // webpieces-disable ${this.name} -- <reason>`;
152
+ return new rules_config_1.RuleFailError(this.name, message, undefined, undefined, found.map((each) => new rules_config_1.Option(`${each.relFile}:${each.site.line}: ${each.site.cure}`, true)));
153
+ }
154
+ }
155
+ exports.ApiLibSourceRule = ApiLibSourceRule;
156
+ //# sourceMappingURL=api-lib-source-rule.js.map
@@ -0,0 +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;;;;;;;;;;;;;GAaG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,uDAAiC;AACjC,0DASiC;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,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC;IAC1F,CAAC;IAED,wDAAwD;IACxD,IAAI,CAAC,IAAa,EAAE,IAAY,EAAE,IAAY;QAC1C,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;QACnE,OAAO,IAAI,UAAU,CAA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AC3G,CAAC;IACN,CAAC;CACJ;AA9FD,4CA8FC","sourcesContent":["/**\n * The shared half of the two `role:api-lib` spelling rules (#1023): `no-inline-import-in-api-lib` and\n * `one-enum-spelling-in-api-lib`.\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 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;\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`, owned by a `role:api-lib` project. */\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.roleResolver.roleOf(workspaceRoot, relFile) === API_LIB_ROLE;\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 a role:api-lib project: ${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"]}
@@ -34,5 +34,7 @@ exports.CONFIG_BINDINGS = [
34
34
  [rules_config_1.FrameworkTagConfig, 'framework-tag'],
35
35
  [rules_config_1.RoleTagConfig, 'role-tag'],
36
36
  [rules_config_1.EnsureWeAreSecureConfig, 'ensure-we-are-secure'],
37
+ [rules_config_1.NoInlineImportInApiLibConfig, 'no-inline-import-in-api-lib'],
38
+ [rules_config_1.OneEnumSpellingInApiLibConfig, 'one-enum-spelling-in-api-lib'],
37
39
  ];
38
40
  //# sourceMappingURL=code-rules-config-table.js.map