@memberjunction/standards 6.1.4 → 6.2.0-edge.1

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,1124 @@
1
+ /**
2
+ * @fileoverview The naming-convention standard.
3
+ *
4
+ * Enforces the convention documented in the MJ repo's `.claude/rules/typescript-style.md`, which is
5
+ * deliberately inverted from ordinary TypeScript style:
6
+ *
7
+ * public class members PascalCase `public IsLoading`, `@Input() QueryId`
8
+ * private class members camelCase `private destroy$`, `private _internalState`
9
+ * exported functions PascalCase `export function EscapeSQLString()`
10
+ * exported types PascalCase classes, interfaces, type aliases, enums
11
+ *
12
+ * ## Why an AST and not a regex
13
+ *
14
+ * The rule keys off information only a parser has. Visibility is the obvious part — TypeScript's
15
+ * default is *public*, so `foo()` with no modifier is a public member and must be PascalCase, which
16
+ * no regex can tell from a local function. But the exemptions matter more: whether a member
17
+ * implements a framework contract depends on its class's heritage clause, and whether it carries
18
+ * `@HostListener` depends on its decorators. A text-matching gate gets those wrong in both
19
+ * directions, and a gate with false positives gets switched off.
20
+ *
21
+ * Parsing is syntax-only — `createSourceFile` per file, no `Program`, no type checker. There is no
22
+ * root tsconfig in MJ that could build a repo-wide `Program` (the two at the root are bare
23
+ * `compilerOptions` bases with no `include`/`references`), and a `Program` per package tsconfig
24
+ * across 300+ packages is far too slow for a PR gate. Everything this rule needs is syntactic, so a
25
+ * full-repo pass over ~7,900 files runs in well under a minute (about 44s on a developer laptop),
26
+ * against the many minutes a type-aware pass would take.
27
+ *
28
+ * ## What it deliberately does not check
29
+ *
30
+ * - **`protected` members.** MJ's own base classes declare PascalCase protected extension points —
31
+ * `BaseAction.InternalRunAction` (overridden 300+ times), `BaseEngine.AdditionalLoading`,
32
+ * `BaseResourceComponent.OnQueryParamsChanged`, `ProviderToUse`. That is the template-method
33
+ * pattern, it is load-bearing, and subclasses cannot deviate from the parent's casing. The
34
+ * documented "camelCase for private/protected" rule is simply wrong for the protected half.
35
+ *
36
+ * Constructor parameter properties and interface / type-literal members WERE on this list while the
37
+ * rule was being rolled out. Both are checked now — `checkParameterProperties` and
38
+ * `checkTypeMembers` — and both are covered by tests.
39
+ *
40
+ * @module @memberjunction/standards
41
+ */
42
+ import { existsSync, readFileSync, statSync } from 'node:fs';
43
+ import { dirname, join, relative, resolve } from 'node:path';
44
+ import { HasMarkerNear } from '../lib/markers.js';
45
+ import { FindPackageDirs, FindSourceFiles } from '../lib/walk.js';
46
+ // ─────────────────────────────────────────────────────────────────────────────
47
+ // The parser, as an optional peer dependency
48
+ // ─────────────────────────────────────────────────────────────────────────────
49
+ let typeScriptLoad;
50
+ /**
51
+ * Resolve `typescript`, or `null` if the host repo does not have it.
52
+ *
53
+ * A dynamic import under category 2 of the repo's dynamic-import rule — an **optional peer
54
+ * dependency**, declared as such in this package's `package.json`. This package is installed into
55
+ * client repos to run in their CI, and pinning a hard `typescript` version there is exactly the
56
+ * dependency conflict the "no runtime dependencies" design note exists to avoid. Every repo that
57
+ * has TypeScript source already has the compiler; one that does not has nothing for this check to
58
+ * read, so a clean skip is the right answer rather than a failed install.
59
+ *
60
+ * Memoized, so a run parses the module once rather than per file.
61
+ */
62
+ function loadTypeScript() {
63
+ typeScriptLoad ??= import('typescript')
64
+ .then((mod) => (mod.default ?? mod))
65
+ .catch(() => null);
66
+ return typeScriptLoad;
67
+ }
68
+ // ─────────────────────────────────────────────────────────────────────────────
69
+ // What gets read
70
+ // ─────────────────────────────────────────────────────────────────────────────
71
+ const SOURCE_EXTENSIONS = ['.ts', '.tsx', '.mts', '.cts'];
72
+ /**
73
+ * The parse mode for a file, by extension.
74
+ *
75
+ * A `.tsx` file parsed as plain TS does not fail — it silently misparses. `<Rect x={3} y={3} />`
76
+ * becomes a chain of comparison and type-assertion expressions, and the attribute names surface as
77
+ * declarations the check then reports: `exported const "y" is neither PascalCase nor
78
+ * SCREAMING_SNAKE_CASE`, at a line holding no declaration at all. Every such finding is a false
79
+ * positive, and no marker can silence one, because there is nothing there to mark.
80
+ */
81
+ function scriptKindFor(ts, file) {
82
+ return file.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
83
+ }
84
+ /**
85
+ * Directories never descended into.
86
+ *
87
+ * `generated` and `.claude` are the two that actually matter here. Committed CodeGen output is
88
+ * regenerated from a template, so a finding in it is unfixable in place — the fix belongs in the
89
+ * generator — and `mj codegen` would revert any edit on its next run. `.claude/worktrees` holds
90
+ * full duplicate checkouts of the repo, which would double every count.
91
+ */
92
+ const SKIP_DIRS = new Set([
93
+ 'node_modules',
94
+ 'dist',
95
+ 'build',
96
+ '.git',
97
+ '.angular',
98
+ 'coverage',
99
+ 'generated',
100
+ '.claude',
101
+ '.turbo',
102
+ ]);
103
+ const ALLOW_MARKER = 'case-violation-ok-legacy-back-compat';
104
+ const DECLARATION_FILE = /\.d\.[mc]?ts$/;
105
+ const TEST_FILE = /\.(test|spec)\.[mc]?tsx?$/;
106
+ const TEST_DIR = /[\\/]__tests__[\\/]/;
107
+ // ─────────────────────────────────────────────────────────────────────────────
108
+ // Name shapes
109
+ // ─────────────────────────────────────────────────────────────────────────────
110
+ /** `Foo`, `FooBar`, `HTTPClient` — an initial capital and nothing but letters and digits after. */
111
+ export function IsPascalCase(name) {
112
+ return /^[A-Z][A-Za-z0-9]*$/.test(name);
113
+ }
114
+ /**
115
+ * `MAX_ROWS`, `PREFS_KEY`, `URL` — a constant, not a misnamed member.
116
+ *
117
+ * Accepted wherever a capital would otherwise be a violation, because SCREAMING_SNAKE for constants
118
+ * is universal and MJ uses it heavily: 419 private `static readonly` fields and 700+ exported
119
+ * `const`s. A literal reading of "private members are camelCase" would flag every one of them, and
120
+ * that alone would have made the rule unadoptable.
121
+ */
122
+ export function IsScreamingSnake(name) {
123
+ return (/^[A-Z][A-Z0-9_]*$/.test(name) && name.includes('_')) || /^[A-Z][A-Z0-9]{1,}$/.test(name);
124
+ }
125
+ /**
126
+ * The PascalCase form of a name, for the "rename to …" half of a message.
127
+ *
128
+ * Splits on `_` and `-` so `output_config` suggests `OutputConfig` rather than `Output_config`,
129
+ * which is what a naive first-character uppercase produces and which is not PascalCase at all — a
130
+ * suggestion that is itself a violation teaches the reader the wrong rule.
131
+ */
132
+ export function SuggestPascalCase(name) {
133
+ const parts = name.replace(/^[^A-Za-z0-9]+/, '').split(/[_-]+/).filter(Boolean);
134
+ if (parts.length === 0)
135
+ return name;
136
+ return parts.map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join('');
137
+ }
138
+ /**
139
+ * Is this name owned by a spec or framework that uses a `$` sigil?
140
+ *
141
+ * `$schema` is the JSON Schema keyword; `$`-prefixed members are conventional in several ecosystems.
142
+ * The sigil is not a casing choice, and PascalCasing it would break the thing that reads it.
143
+ */
144
+ function isSigilName(name) {
145
+ return name.startsWith('$');
146
+ }
147
+ /**
148
+ * `destroy$`, `_internalState` — the shape a private member must have.
149
+ *
150
+ * The optional leading underscore is deliberate: `private _config` paired with `public get Config()`
151
+ * is the documented backing-field idiom and appears ~1,960 times. Both it and the bare form are
152
+ * correct; this check does not try to normalise between them.
153
+ */
154
+ export function IsPrivateShaped(name) {
155
+ return /^_*[a-z$]/.test(name);
156
+ }
157
+ // ─────────────────────────────────────────────────────────────────────────────
158
+ // Framework contracts — names whose casing is not ours to choose
159
+ // ─────────────────────────────────────────────────────────────────────────────
160
+ /** `ngOnInit`, `ngOnDestroy`, `ngAfterViewInit`, … — Angular calls these by name. */
161
+ const ANGULAR_LIFECYCLE = /^ng[A-Z]/;
162
+ /** Members a JS runtime, the DOM, or a framework invokes by an exact lowercase name. */
163
+ const PLATFORM_CONTRACT = new Set([
164
+ // JS / JSON protocols
165
+ 'toJSON', 'toString', 'valueOf',
166
+ // Angular ControlValueAccessor + PipeTransform
167
+ 'writeValue', 'registerOnChange', 'registerOnTouched', 'setDisabledState', 'transform',
168
+ // Angular guards / interceptors
169
+ 'canActivate', 'intercept',
170
+ // Custom elements / Lit
171
+ 'connectedCallback', 'disconnectedCallback', 'attributeChangedCallback', 'observedAttributes', 'render',
172
+ // Disposable
173
+ 'dispose',
174
+ // Node stream internals. Node calls these by exact name on the instance, so a `@deprecated`
175
+ // stub still works — but it makes the deprecated member the load-bearing one, which inverts
176
+ // what the tag means. `Transform`/`Flush`/`Read` are ordinary MJ names and stay checked; only
177
+ // the underscore protocol hooks are the contract.
178
+ '_transform', '_flush', '_read', '_write', '_writev', '_final', '_destroy', '_construct',
179
+ ]);
180
+ /**
181
+ * React calls these by exact name. The two statics are the dangerous ones: React reads them
182
+ * into a local and calls them UNBOUND (`var f = fiber.type.getDerivedStateFromError; f(error)`),
183
+ * so a `@deprecated` stub forwarding through `this` throws instead of delegating — and for
184
+ * `getDerivedStateFromError` it throws while handling a child's error, unmounting the tree.
185
+ *
186
+ * These are exempt unconditionally rather than behind a `React.Component` heritage test, because
187
+ * a boundary built against an injected React (`extends (React as any).Component`) has no typed
188
+ * base class for the contract index to see.
189
+ */
190
+ const REACT_LIFECYCLE = new Set([
191
+ // Statics — invoked unbound, so a delegating stub cannot work at all
192
+ 'getDerivedStateFromError', 'getDerivedStateFromProps',
193
+ // Instance lifecycle
194
+ 'componentDidCatch', 'componentDidMount', 'componentDidUpdate', 'componentWillUnmount',
195
+ 'shouldComponentUpdate', 'getSnapshotBeforeUpdate',
196
+ // Legacy lifecycle, still honoured by React
197
+ 'componentWillMount', 'componentWillReceiveProps', 'componentWillUpdate',
198
+ 'UNSAFE_componentWillMount', 'UNSAFE_componentWillReceiveProps', 'UNSAFE_componentWillUpdate',
199
+ // Statics React reads off the class
200
+ 'defaultProps', 'displayName', 'contextType', 'contextTypes', 'propTypes',
201
+ ]);
202
+ /** oclif reads these off a `Command` subclass, and calls `run()` by name. */
203
+ const OCLIF_MEMBERS = new Set([
204
+ 'run', 'flags', 'args', 'description', 'examples', 'topic', 'aliases',
205
+ 'hidden', 'strict', 'usage', 'baseFlags', 'summary', 'enableJsonFlag',
206
+ ]);
207
+ /** `Error` subclasses inherit these; renaming one breaks `instanceof` reporting. */
208
+ const ERROR_MEMBERS = new Set(['name', 'message', 'stack', 'cause']);
209
+ /** Decorators that let a framework bind a member under a name of its own choosing. */
210
+ const EXEMPT_MEMBER_DECORATORS = new Set(['HostListener', 'HostBinding']);
211
+ /** MJ's own generated system columns. Their casing comes from the database, not from style. */
212
+ const MJ_SYSTEM_PREFIX = '__mj_';
213
+ /**
214
+ * Every line that carries the NAME of a `@deprecated` declaration.
215
+ *
216
+ * This is the exclusion that makes the cleanup possible. The fix for a violating public symbol is
217
+ * to rename it and leave the old name behind as a deprecated stub delegating to the new one — so
218
+ * the old name is *supposed* to keep its old casing, and flagging it would make the fix itself a
219
+ * violation. MJ already writes exactly this shim (`SQLServerDataProvider.ts:424` is a literal
220
+ * camelCase/PascalCase deprecated pair), so the tag is the natural marker.
221
+ *
222
+ * Collected per file up front rather than tested per finding, because the tag sits on a node the
223
+ * finding does not carry — a `VariableStatement`'s JSDoc governs names declared one level below it.
224
+ *
225
+ * NOTE: `ts.getJSDocTags` reads `node.jsDoc`, which is only populated when the file was parsed with
226
+ * `setParentNodes: true`. Parsing without it returns an empty tag list for every node — silently,
227
+ * which would turn this whole exclusion into a no-op.
228
+ */
229
+ function deprecatedNameLines(ts, source) {
230
+ const lines = new Set();
231
+ const isDeprecated = (node) => {
232
+ try {
233
+ return ts.getJSDocTags(node).some((tag) => tag.tagName.text === 'deprecated');
234
+ }
235
+ catch {
236
+ return false;
237
+ }
238
+ };
239
+ const visit = (node) => {
240
+ if (isDeprecated(node)) {
241
+ if (ts.isVariableStatement(node)) {
242
+ // The tag is on the statement; the names are on its declarations.
243
+ for (const declaration of node.declarationList.declarations) {
244
+ if (ts.isIdentifier(declaration.name))
245
+ lines.add(lineOf(source, declaration.name));
246
+ }
247
+ }
248
+ else {
249
+ const named = node;
250
+ if (named.name && ts.isIdentifier(named.name))
251
+ lines.add(lineOf(source, named.name));
252
+ }
253
+ }
254
+ ts.forEachChild(node, visit);
255
+ };
256
+ ts.forEachChild(source, visit);
257
+ return lines;
258
+ }
259
+ // ─────────────────────────────────────────────────────────────────────────────
260
+ // Pass 1 — the inherited-contract index
261
+ // ─────────────────────────────────────────────────────────────────────────────
262
+ /** Walk every class declaration/expression in a source file. */
263
+ function forEachClass(ts, source, visit) {
264
+ const walk = (node) => {
265
+ if (ts.isClassDeclaration(node) || ts.isClassExpression(node))
266
+ visit(node);
267
+ ts.forEachChild(node, walk);
268
+ };
269
+ ts.forEachChild(source, walk);
270
+ }
271
+ /** `Foo<Bar>` / `ns.Foo` → `Foo`. */
272
+ function heritageName(type, source) {
273
+ return type.expression.getText(source).replace(/<[\s\S]*$/, '').split('.').pop() ?? '';
274
+ }
275
+ /** The `extends` names of a class or interface, unqualified. */
276
+ function extendsNames(ts, node, source) {
277
+ const names = [];
278
+ for (const clause of node.heritageClauses ?? []) {
279
+ if (clause.token !== ts.SyntaxKind.ExtendsKeyword)
280
+ continue;
281
+ for (const type of clause.types)
282
+ names.push(heritageName(type, source));
283
+ }
284
+ return names;
285
+ }
286
+ /** The `implements` names of a class, unqualified. */
287
+ function implementsNames(ts, node, source) {
288
+ const names = [];
289
+ for (const clause of node.heritageClauses ?? []) {
290
+ if (clause.token !== ts.SyntaxKind.ImplementsKeyword)
291
+ continue;
292
+ for (const type of clause.types)
293
+ names.push(heritageName(type, source));
294
+ }
295
+ return names;
296
+ }
297
+ /**
298
+ * Every member name declared by a class that something else in the repo `extends`.
299
+ *
300
+ * This is what stands in for a type checker. A subclass member that matches a name its base class
301
+ * declares is honouring a contract, not choosing a name — and renaming it would break the override.
302
+ * Roughly 1,580 members in MJ are in this position.
303
+ *
304
+ * `override` alone is not enough to detect them: only ~130 of those 1,580 carry the keyword, because
305
+ * TypeScript does not require it unless `noImplicitOverride` is on. So the index is built by name,
306
+ * which over-exempts slightly (a subclass coining a name that coincides with an unrelated base
307
+ * class's member) in exchange for not producing ~1,450 unfixable findings. That trade is the right
308
+ * way round: a gate that cries wolf gets disabled, and the marker is there for the rest.
309
+ */
310
+ function buildIndexes(ts, parsedFiles) {
311
+ const inherited = new Set();
312
+ const implemented = new Set();
313
+ const membersByType = new Map();
314
+ const record = (name, members) => {
315
+ const names = [];
316
+ for (const member of members) {
317
+ if (member.name && ts.isIdentifier(member.name))
318
+ names.push(member.name.text);
319
+ }
320
+ membersByType.set(name, names);
321
+ };
322
+ for (const source of parsedFiles) {
323
+ forEachClass(ts, source, (node) => {
324
+ // `implements` counts as well as `extends`: an interface a class implements dictates
325
+ // that class's member names just as firmly as a base class does.
326
+ for (const name of extendsNames(ts, node, source))
327
+ inherited.add(name);
328
+ for (const name of implementsNames(ts, node, source)) {
329
+ inherited.add(name);
330
+ implemented.add(name);
331
+ }
332
+ if (node.name)
333
+ record(node.name.text, node.members);
334
+ });
335
+ // Interfaces are indexed too, so `interface B extends A` lets B inherit A's names.
336
+ for (const statement of source.statements) {
337
+ if (!ts.isInterfaceDeclaration(statement))
338
+ continue;
339
+ for (const name of extendsNames(ts, statement, source))
340
+ inherited.add(name);
341
+ record(statement.name.text, statement.members);
342
+ }
343
+ }
344
+ const contract = new Set();
345
+ for (const [typeName, names] of membersByType) {
346
+ if (!inherited.has(typeName))
347
+ continue;
348
+ for (const name of names)
349
+ contract.add(name);
350
+ }
351
+ return { Contract: contract, Implemented: implemented };
352
+ }
353
+ // ─────────────────────────────────────────────────────────────────────────────
354
+ // Pass 2 — the rules
355
+ // ─────────────────────────────────────────────────────────────────────────────
356
+ /** Modifier kinds on a node, or an empty list where modifiers are not possible. */
357
+ function modifierKinds(ts, node) {
358
+ if (!ts.canHaveModifiers(node))
359
+ return [];
360
+ return (ts.getModifiers(node) ?? []).map((m) => m.kind);
361
+ }
362
+ /** Decorator names on a node — `@Input()` and `@Input` both yield `Input`. */
363
+ function decoratorNames(ts, node, source) {
364
+ if (!ts.canHaveDecorators(node))
365
+ return [];
366
+ return (ts.getDecorators(node) ?? []).map((d) => d.expression.getText(source).replace(/[(<][\s\S]*$/, ''));
367
+ }
368
+ /** 1-based line of a node. */
369
+ function lineOf(source, node) {
370
+ return source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;
371
+ }
372
+ /** Repo-level additions to the built-in allowlist. */
373
+ function isRepoAllowed(name, context) {
374
+ return context.AllowedNames.has(name) || context.AllowedPrefixes.some((p) => name.startsWith(p));
375
+ }
376
+ /**
377
+ * Is this member's name dictated by something other than MJ style?
378
+ *
379
+ * Every branch here corresponds to a measured false-positive class in the MJ repo, not a
380
+ * hypothetical one — the counts are in `guides/NAMING_CONVENTIONS_GUIDE.md`.
381
+ */
382
+ function isContractName(name, member, classContext, context) {
383
+ const { Ts: ts, Source: source } = context;
384
+ if (ANGULAR_LIFECYCLE.test(name))
385
+ return true;
386
+ if (PLATFORM_CONTRACT.has(name))
387
+ return true;
388
+ if (REACT_LIFECYCLE.has(name))
389
+ return true;
390
+ if (name.startsWith(MJ_SYSTEM_PREFIX))
391
+ return true;
392
+ if (classContext.IsOclifCommand && OCLIF_MEMBERS.has(name))
393
+ return true;
394
+ if (classContext.IsErrorSubclass && ERROR_MEMBERS.has(name))
395
+ return true;
396
+ if (decoratorNames(ts, member, source).some((d) => EXEMPT_MEMBER_DECORATORS.has(d)))
397
+ return true;
398
+ if (isRepoAllowed(name, context))
399
+ return true;
400
+ // Honouring a base class's name. The `override` keyword is the explicit signal; the index
401
+ // catches the ~92% of real overrides that omit it.
402
+ const kinds = modifierKinds(ts, member);
403
+ if (kinds.includes(ts.SyntaxKind.OverrideKeyword))
404
+ return true;
405
+ const hasHeritage = classContext.Extends.length > 0 || classContext.Implements.length > 0;
406
+ return hasHeritage && context.Contract.has(name);
407
+ }
408
+ /** Members that carry a name we could judge. Constructors and index signatures do not. */
409
+ function isNamedMember(ts, member) {
410
+ if (ts.isConstructorDeclaration(member))
411
+ return false;
412
+ // A non-`Identifier` name is computed, a string literal, or `[Symbol.iterator]` — in every case
413
+ // the name is not a style choice, so there is nothing to enforce.
414
+ return !!member.name && ts.isIdentifier(member.name);
415
+ }
416
+ /** Judge one class member. Returns a message, or `null` when it is fine or exempt. */
417
+ function checkMember(member, classContext, context) {
418
+ const ts = context.Ts;
419
+ const kinds = modifierKinds(ts, member);
420
+ const name = member.name.text;
421
+ // `protected` is not checked at all — see the file header.
422
+ if (kinds.includes(ts.SyntaxKind.ProtectedKeyword))
423
+ return null;
424
+ if (kinds.includes(ts.SyntaxKind.PrivateKeyword)) {
425
+ if (IsPrivateShaped(name) || IsScreamingSnake(name.replace(/^_+/, '')))
426
+ return null;
427
+ if (isRepoAllowed(name, context))
428
+ return null;
429
+ const suggestion = name.replace(/^(_*)([A-Z])/, (_, u, c) => u + c.toLowerCase());
430
+ return `private member "${name}" is PascalCase — private members are camelCase; rename to "${suggestion}"`;
431
+ }
432
+ // Everything else is public: TypeScript's default visibility is public, so a member with no
433
+ // access modifier is part of the class's API surface just as much as an explicit `public` one.
434
+ if (IsPascalCase(name) || IsScreamingSnake(name) || isSigilName(name))
435
+ return null;
436
+ if (isContractName(name, member, classContext, context))
437
+ return null;
438
+ return `public member "${name}" is not PascalCase — rename to "${SuggestPascalCase(name)}"`;
439
+ }
440
+ /** Judge every member of one class. */
441
+ function checkClass(node, context) {
442
+ const ts = context.Ts;
443
+ const extendsList = extendsNames(ts, node, context.Source);
444
+ const classContext = {
445
+ Extends: extendsList,
446
+ Implements: implementsNames(ts, node, context.Source),
447
+ IsOclifCommand: extendsList.some((e) => /Command$/.test(e)),
448
+ IsErrorSubclass: extendsList.some((e) => /Error$/.test(e)),
449
+ };
450
+ const findings = [];
451
+ const record = (node2, message) => {
452
+ if (!message)
453
+ return;
454
+ const line = lineOf(context.Source, node2);
455
+ if (HasMarkerNear(context.Lines, line, ALLOW_MARKER))
456
+ return;
457
+ findings.push({ Line: line, Message: message });
458
+ };
459
+ for (const member of node.members) {
460
+ if (ts.isConstructorDeclaration(member)) {
461
+ findings.push(...checkParameterProperties(member, classContext, context));
462
+ continue;
463
+ }
464
+ if (!isNamedMember(ts, member))
465
+ continue;
466
+ record(member.name, checkMember(member, classContext, context));
467
+ }
468
+ return findings;
469
+ }
470
+ /**
471
+ * Judge `constructor(public Foo: X, private bar: Y)`.
472
+ *
473
+ * A parameter property declares a class member, so it follows the member rule — a `public` one is
474
+ * part of the class's API surface exactly as a field is. A parameter with no access modifier is an
475
+ * ordinary parameter, not a member, and is left alone.
476
+ */
477
+ function checkParameterProperties(constructorNode, classContext, context) {
478
+ const ts = context.Ts;
479
+ const findings = [];
480
+ for (const parameter of constructorNode.parameters) {
481
+ const kinds = modifierKinds(ts, parameter);
482
+ if (kinds.length === 0)
483
+ continue;
484
+ if (!ts.isIdentifier(parameter.name))
485
+ continue;
486
+ const name = parameter.name.text;
487
+ let message = null;
488
+ if (kinds.includes(ts.SyntaxKind.ProtectedKeyword)) {
489
+ message = null;
490
+ }
491
+ else if (kinds.includes(ts.SyntaxKind.PrivateKeyword)) {
492
+ if (!IsPrivateShaped(name) && !IsScreamingSnake(name.replace(/^_+/, '')) && !isRepoAllowed(name, context)) {
493
+ const suggestion = name.replace(/^(_*)([A-Z])/, (_, u, c) => u + c.toLowerCase());
494
+ message = `private parameter property "${name}" is PascalCase — private members are camelCase; rename to "${suggestion}"`;
495
+ }
496
+ }
497
+ else if (!IsPascalCase(name) && !IsScreamingSnake(name) && !isSigilName(name)) {
498
+ const hasHeritage = classContext.Extends.length > 0 || classContext.Implements.length > 0;
499
+ const exempt = isRepoAllowed(name, context) || (hasHeritage && context.Contract.has(name));
500
+ if (!exempt) {
501
+ message = `public parameter property "${name}" is not PascalCase — rename to "${SuggestPascalCase(name)}"`;
502
+ }
503
+ }
504
+ if (!message)
505
+ continue;
506
+ const line = lineOf(context.Source, parameter.name);
507
+ if (HasMarkerNear(context.Lines, line, ALLOW_MARKER))
508
+ continue;
509
+ findings.push({ Line: line, Message: message });
510
+ }
511
+ return findings;
512
+ }
513
+ /**
514
+ * Judge the members of an exported interface, type literal, or enum.
515
+ *
516
+ * An exported type's members ARE the package's API surface — a consumer writes
517
+ * `params.maxTokens`, and the property name is as much a published contract as a class's public
518
+ * field. So the same PascalCase rule applies. Only **exported** types are judged: an internal
519
+ * `interface Options` nobody outside the module can name is an implementation detail, and the
520
+ * public-API-surface principle the whole convention rests on does not reach it.
521
+ *
522
+ * `SCREAMING_SNAKE` is accepted for the same reason it is on a class — constants. Enum members are
523
+ * overwhelmingly one or the other already.
524
+ */
525
+ function checkTypeMembers(members, kindLabel, hasHeritage, context, ownerName) {
526
+ const ts = context.Ts;
527
+ const findings = [];
528
+ for (const member of members) {
529
+ // Index signatures, computed keys and string-literal keys carry no name we could judge.
530
+ if (!member.name || !ts.isIdentifier(member.name))
531
+ continue;
532
+ const name = member.name.text;
533
+ if (IsPascalCase(name) || IsScreamingSnake(name) || isSigilName(name))
534
+ continue;
535
+ if (name.startsWith(MJ_SYSTEM_PREFIX))
536
+ continue;
537
+ if (PLATFORM_CONTRACT.has(name))
538
+ continue;
539
+ if (isRepoAllowed(name, context))
540
+ continue;
541
+ // `interface B extends A` must keep A's names, exactly as a subclass must.
542
+ if (hasHeritage && context.Contract.has(name))
543
+ continue;
544
+ const line = lineOf(context.Source, member.name);
545
+ if (HasMarkerNear(context.Lines, line, ALLOW_MARKER))
546
+ continue;
547
+ // An interface a class implements HAS a runtime carrier: the class can hold both the old and
548
+ // the new name, so renaming the interface member is fixable without breaking anyone. A plain
549
+ // data shape has no such carrier, which is what `DataShapeOwner` marks.
550
+ const isDataShape = !ownerName || !context.Implemented.has(ownerName);
551
+ findings.push({
552
+ Line: line,
553
+ Message: `exported ${kindLabel} member "${name}" is not PascalCase — rename to "${SuggestPascalCase(name)}"`,
554
+ ...(isDataShape && ownerName ? { DataShapeOwner: ownerName } : {}),
555
+ });
556
+ }
557
+ return findings;
558
+ }
559
+ /** Every object-literal type reachable inside an exported type alias, including nested ones. */
560
+ function collectTypeLiterals(ts, node) {
561
+ const found = [];
562
+ const walk = (current) => {
563
+ if (ts.isTypeLiteralNode(current))
564
+ found.push(current);
565
+ ts.forEachChild(current, walk);
566
+ };
567
+ walk(node);
568
+ return found;
569
+ }
570
+ /**
571
+ * Judge an `export { Foo, bar }` list.
572
+ *
573
+ * A named export list publishes a name under the module's API surface just as `export function`
574
+ * does, so the same rule applies. This is a distinct AST node with no `export` modifier of its own,
575
+ * which is why it needs its own branch rather than falling out of the modifier check.
576
+ *
577
+ * Re-exports (`export { x } from './y'`) are skipped: the name belongs to the module it came from
578
+ * and is judged there, and a barrel file cannot fix it.
579
+ */
580
+ function checkExportList(statement, context) {
581
+ const ts = context.Ts;
582
+ if (statement.moduleSpecifier)
583
+ return [];
584
+ if (!statement.exportClause || !ts.isNamedExports(statement.exportClause))
585
+ return [];
586
+ const findings = [];
587
+ for (const element of statement.exportClause.elements) {
588
+ const name = element.name.text;
589
+ if (IsPascalCase(name) || IsScreamingSnake(name) || isSigilName(name) || isRepoAllowed(name, context))
590
+ continue;
591
+ const line = lineOf(context.Source, element.name);
592
+ if (HasMarkerNear(context.Lines, line, ALLOW_MARKER))
593
+ continue;
594
+ findings.push({
595
+ Line: line,
596
+ Message: `exported name "${name}" is not PascalCase — rename to "${SuggestPascalCase(name)}"`,
597
+ });
598
+ }
599
+ return findings;
600
+ }
601
+ /**
602
+ * Judge one exported module-scope declaration.
603
+ *
604
+ * Exported *functions* are the rule this settles: MJ was split 1,388 PascalCase to 2,047 camelCase
605
+ * with nothing written down either way, so the public-API-surface-is-PascalCase reading wins for
606
+ * consistency with class members. A `const` holding an arrow function is a function by any useful
607
+ * definition and follows the same rule; a `const` holding a value may be PascalCase or
608
+ * SCREAMING_SNAKE, which is what 96% of them already are.
609
+ */
610
+ function checkExportedStatement(statement, context) {
611
+ const ts = context.Ts;
612
+ // An `export { ... }` list has no export MODIFIER, so it is handled before the modifier gate.
613
+ if (ts.isExportDeclaration(statement))
614
+ return checkExportList(statement, context);
615
+ if (!modifierKinds(ts, statement).includes(ts.SyntaxKind.ExportKeyword))
616
+ return [];
617
+ const findings = [];
618
+ const flag = (node, message) => {
619
+ const line = lineOf(context.Source, node);
620
+ if (HasMarkerNear(context.Lines, line, ALLOW_MARKER))
621
+ return;
622
+ findings.push({ Line: line, Message: message });
623
+ };
624
+ const pascalize = SuggestPascalCase;
625
+ if (ts.isFunctionDeclaration(statement) && statement.name && !IsPascalCase(statement.name.text)) {
626
+ const name = statement.name.text;
627
+ if (!isRepoAllowed(name, context) && !isSigilName(name)) {
628
+ flag(statement.name, `exported function "${name}" is not PascalCase — rename to "${pascalize(name)}"`);
629
+ }
630
+ }
631
+ const typeDeclaration = (ts.isClassDeclaration(statement) && 'class') ||
632
+ (ts.isInterfaceDeclaration(statement) && 'interface') ||
633
+ (ts.isTypeAliasDeclaration(statement) && 'type') ||
634
+ (ts.isEnumDeclaration(statement) && 'enum');
635
+ if (typeDeclaration && statement.name && ts.isIdentifier(statement.name) && !IsPascalCase(statement.name.text)) {
636
+ const name = statement.name.text;
637
+ if (!isRepoAllowed(name, context)) {
638
+ flag(statement.name, `exported ${typeDeclaration} "${name}" is not PascalCase — rename to "${pascalize(name)}"`);
639
+ }
640
+ }
641
+ if (ts.isInterfaceDeclaration(statement)) {
642
+ const hasHeritage = extendsNames(ts, statement, context.Source).length > 0;
643
+ findings.push(...checkTypeMembers(statement.members, 'interface', hasHeritage, context, statement.name.text));
644
+ }
645
+ if (ts.isTypeAliasDeclaration(statement)) {
646
+ for (const literal of collectTypeLiterals(ts, statement.type)) {
647
+ findings.push(...checkTypeMembers(literal.members, 'type', false, context, statement.name.text));
648
+ }
649
+ }
650
+ if (ts.isEnumDeclaration(statement)) {
651
+ findings.push(...checkTypeMembers(statement.members, 'enum', false, context, statement.name.text));
652
+ }
653
+ if (ts.isVariableStatement(statement)) {
654
+ const keyword = (statement.declarationList.flags & ts.NodeFlags.Const) !== 0 ? 'const' : 'binding';
655
+ for (const declaration of statement.declarationList.declarations) {
656
+ if (!ts.isIdentifier(declaration.name))
657
+ continue;
658
+ const name = declaration.name.text;
659
+ if (isRepoAllowed(name, context))
660
+ continue;
661
+ const initializer = declaration.initializer;
662
+ const isFunction = !!initializer && (ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer));
663
+ if (isFunction) {
664
+ if (!IsPascalCase(name)) {
665
+ flag(declaration.name, `exported function "${name}" is not PascalCase — rename to "${pascalize(name)}"`);
666
+ }
667
+ }
668
+ else if (!IsPascalCase(name) && !IsScreamingSnake(name)) {
669
+ flag(declaration.name, `exported ${keyword} "${name}" is neither PascalCase nor SCREAMING_SNAKE_CASE`);
670
+ }
671
+ }
672
+ }
673
+ return findings;
674
+ }
675
+ /** Judge one file. */
676
+ export function CheckSourceFile(context) {
677
+ const findings = [];
678
+ forEachClass(context.Ts, context.Source, (node) => findings.push(...checkClass(node, context)));
679
+ for (const statement of context.Source.statements)
680
+ findings.push(...checkExportedStatement(statement, context));
681
+ // A `@deprecated` declaration is a back-compat stub keeping an old name alive on purpose. Its
682
+ // casing is the whole point, so it is not a violation. Counted by the caller so the number of
683
+ // suppressions stays visible rather than becoming a quiet hiding place.
684
+ const deprecated = deprecatedNameLines(context.Ts, context.Source);
685
+ context.DeprecatedSuppressed.Count += findings.filter((f) => deprecated.has(f.Line)).length;
686
+ // A message that suggests renaming a name to itself is noise at best and teaches the wrong rule
687
+ // at worst. It means the name is one this check cannot express an opinion about, so drop it.
688
+ return findings
689
+ .filter((f) => !deprecated.has(f.Line))
690
+ .filter((f) => !/rename to "([^"]+)"$/.test(f.Message) || !isNoOpSuggestion(f.Message))
691
+ .sort((a, b) => a.Line - b.Line);
692
+ }
693
+ /**
694
+ * Does a `rename to "X"` message suggest the name it is already complaining about?
695
+ *
696
+ * Read as two anchored halves rather than one pattern spanning the middle. A single
697
+ * `"([^"]+)" is .*rename to "([^"]+)"$` puts an unbounded `.*` between two character classes and an
698
+ * end anchor, which backtracks polynomially — the message is assembled from source identifiers, so
699
+ * its length is not something this check controls.
700
+ */
701
+ function isNoOpSuggestion(message) {
702
+ const declared = /^[^"]*"([^"]+)" is /.exec(message);
703
+ if (!declared)
704
+ return false;
705
+ const suggested = /rename to "([^"]+)"$/.exec(message);
706
+ return !!suggested && declared[1] === suggested[1];
707
+ }
708
+ // ─────────────────────────────────────────────────────────────────────────────
709
+ // What a package actually publishes
710
+ // ─────────────────────────────────────────────────────────────────────────────
711
+ /** Every string that looks like a module path inside an `exports` subtree. */
712
+ function collectExportTargets(node, out) {
713
+ if (typeof node === 'string') {
714
+ out.push(node);
715
+ return;
716
+ }
717
+ if (Array.isArray(node)) {
718
+ for (const item of node)
719
+ collectExportTargets(item, out);
720
+ return;
721
+ }
722
+ if (node && typeof node === 'object') {
723
+ for (const value of Object.values(node))
724
+ collectExportTargets(value, out);
725
+ }
726
+ }
727
+ /**
728
+ * The source files a package's published entry points are built from.
729
+ *
730
+ * `main`/`types` point into `dist`, which this check never reads — it works on source — so each
731
+ * published path is mapped back to its `src` counterpart.
732
+ *
733
+ * **Every** entry counts, not just the root one. A package with an `exports` map publishes one
734
+ * module per subpath, and a type reachable only from `"./forms"` is every bit as public as one
735
+ * reachable from `"."` — consumers import it as `@scope/pkg/forms`. Reading only `types`/`main`
736
+ * declares those types unpublished and therefore free to rename, which is exactly backwards.
737
+ */
738
+ function resolveEntrySources(packageDir) {
739
+ let manifest;
740
+ try {
741
+ manifest = JSON.parse(readFileSync(join(packageDir, 'package.json'), 'utf8'));
742
+ }
743
+ catch {
744
+ return { Entries: [], Private: false };
745
+ }
746
+ const isPrivate = manifest.private === true;
747
+ const raw = [];
748
+ for (const field of [manifest.types, manifest.typings, manifest.main]) {
749
+ if (typeof field === 'string')
750
+ raw.push(field);
751
+ }
752
+ collectExportTargets(manifest.exports, raw);
753
+ const candidates = raw.map((field) => field.replace(/^\.\//, '').replace(/^dist\//, 'src/').replace(/\.d\.ts$|\.js$/, '.ts'));
754
+ const entries = [];
755
+ const seen = new Set();
756
+ const take = (candidate) => {
757
+ const full = join(packageDir, candidate);
758
+ if (seen.has(full))
759
+ return;
760
+ if (existsSync(full) && statSync(full).isFile()) {
761
+ seen.add(full);
762
+ entries.push(full);
763
+ }
764
+ };
765
+ for (const candidate of candidates)
766
+ take(candidate);
767
+ if (entries.length === 0) {
768
+ for (const fallback of ['src/index.ts', 'src/public-api.ts', 'src/public_api.ts', 'index.ts'])
769
+ take(fallback);
770
+ }
771
+ return { Entries: entries, Private: isPrivate };
772
+ }
773
+ /** Resolve a relative module specifier to a source file on disk. */
774
+ function resolveRelativeImport(fromFile, specifier) {
775
+ if (!specifier.startsWith('.'))
776
+ return null;
777
+ const base = resolve(dirname(fromFile), specifier).replace(/\.js$/, '');
778
+ for (const candidate of [`${base}.ts`, `${base}.tsx`, join(base, 'index.ts')]) {
779
+ if (existsSync(candidate) && statSync(candidate).isFile())
780
+ return candidate;
781
+ }
782
+ return null;
783
+ }
784
+ /**
785
+ * Every symbol name a package publishes, reached transitively from its entry points.
786
+ *
787
+ * This is what separates "exported from its file" from "exported from the package" — and the two
788
+ * are very different for this rule. A type no consumer can name can be renamed outright; one the
789
+ * package publishes cannot, because an interface has no runtime carrier to hold both names. Only
790
+ * the second kind is a compatibility problem.
791
+ *
792
+ * Follows `export * from './x'` into the target file. A named re-export contributes both its
793
+ * exported name and, when it is aliased, the source name the declaration actually carries.
794
+ * A re-export from another *package* is not followed: that name belongs to the package it came
795
+ * from and is judged there.
796
+ */
797
+ function collectPublicSymbols(ts, entryFiles, sourceOf) {
798
+ const names = new Set();
799
+ const seen = new Set();
800
+ const queue = [...entryFiles];
801
+ while (queue.length > 0) {
802
+ const file = queue.shift();
803
+ if (seen.has(file))
804
+ continue;
805
+ seen.add(file);
806
+ const source = sourceOf(file);
807
+ if (!source)
808
+ continue;
809
+ for (const statement of source.statements) {
810
+ if (ts.isExportDeclaration(statement)) {
811
+ const specifier = statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier)
812
+ ? statement.moduleSpecifier.text
813
+ : null;
814
+ if (statement.exportClause && ts.isNamedExports(statement.exportClause)) {
815
+ for (const element of statement.exportClause.elements) {
816
+ // Both halves of `export { Source as Alias }`. Consumers import the ALIAS,
817
+ // so it is published — but a finding on a member carries the name of the
818
+ // DECLARATION that owns it (`DataShapeOwner`), which is the source half.
819
+ // Recording only the alias makes `severityFor` miss the match and return
820
+ // `error`, and an `error` type member is what the rename pass selects —
821
+ // so a published member would be renamed with no stub possible.
822
+ names.add(element.name.text);
823
+ if (element.propertyName)
824
+ names.add(element.propertyName.text);
825
+ }
826
+ }
827
+ else if (!statement.exportClause && specifier) {
828
+ const target = resolveRelativeImport(file, specifier);
829
+ if (target)
830
+ queue.push(target);
831
+ }
832
+ continue;
833
+ }
834
+ if (!modifierKinds(ts, statement).includes(ts.SyntaxKind.ExportKeyword))
835
+ continue;
836
+ if (ts.isVariableStatement(statement)) {
837
+ for (const declaration of statement.declarationList.declarations) {
838
+ if (ts.isIdentifier(declaration.name))
839
+ names.add(declaration.name.text);
840
+ }
841
+ }
842
+ else {
843
+ const named = statement;
844
+ if (named.name && ts.isIdentifier(named.name))
845
+ names.add(named.name.text);
846
+ }
847
+ }
848
+ }
849
+ return names;
850
+ }
851
+ // ─────────────────────────────────────────────────────────────────────────────
852
+ // Options
853
+ // ─────────────────────────────────────────────────────────────────────────────
854
+ function stringArrayOption(options, key) {
855
+ const raw = options[key];
856
+ if (!Array.isArray(raw))
857
+ return [];
858
+ return raw.filter((v) => typeof v === 'string');
859
+ }
860
+ /** Normalise a repo-relative path for prefix comparison on any platform. */
861
+ function toPosix(path) {
862
+ return path.split('\\').join('/');
863
+ }
864
+ // ─────────────────────────────────────────────────────────────────────────────
865
+ // The check
866
+ // ─────────────────────────────────────────────────────────────────────────────
867
+ /** The registered naming-convention standard. */
868
+ export const NamingConventionsCheck = {
869
+ Id: 'naming-conventions',
870
+ Title: 'Public class members and exported symbols are PascalCase; private members are camelCase',
871
+ Since: '6.2.0',
872
+ DefaultSeverity: 'warn',
873
+ DocsUrl: 'https://github.com/MemberJunction/MJ/blob/next/guides/NAMING_CONVENTIONS_GUIDE.md',
874
+ Description: 'MJ inverts the usual TypeScript convention: public class members and exported symbols are PascalCase, ' +
875
+ 'private members are camelCase (a leading underscore is fine). Framework contracts — Angular lifecycle ' +
876
+ 'hooks, oclif command members, base-class override points, SCREAMING_SNAKE constants — are exempt. ' +
877
+ 'Severity follows whether a compatible fix exists: anything a @deprecated delegating stub can fix is an ' +
878
+ 'error; members of an exported data shape are a warn, since an interface has no runtime carrier for a stub.',
879
+ DefaultRoots: ['packages'],
880
+ DefaultOptions: {
881
+ /**
882
+ * Promote data-shape findings from `warn` to `error`.
883
+ *
884
+ * Off by default because those findings have **no compatible fix** — see the severity model
885
+ * in `Run`. Turning it on accepts a **breaking change** to this repo's published types:
886
+ * every external consumer naming one of those properties stops compiling, and no stub can
887
+ * carry the old name because an interface has no runtime carrier.
888
+ *
889
+ * It exists for a repository whose types are internal, or that is pre-1.0 and willing to
890
+ * take the break. A repo with published consumers should leave it off.
891
+ */
892
+ enforceTypeMembers: false,
893
+ /** Include `*.test.ts` / `*.spec.ts` / `__tests__`. Off: tests mimic third-party APIs on purpose. */
894
+ includeTests: false,
895
+ /** Exact member/export names this repo accepts regardless of shape. */
896
+ allowedNames: [],
897
+ /** Name prefixes this repo accepts regardless of shape, e.g. `__mj_`. */
898
+ allowedPrefixes: [],
899
+ },
900
+ /**
901
+ * ## The severity model
902
+ *
903
+ * Severity is derived from **whether a finding can be fixed without breaking a consumer**, not
904
+ * from which package it is in. That is the only axis that makes a hard-failing gate honest here.
905
+ *
906
+ * Almost everything is fixable: a class member, an exported function, an exported const — all
907
+ * of them have a runtime object that can carry the new name *and* keep the old one as a
908
+ * `@deprecated` stub delegating to it. Those are `error`.
909
+ *
910
+ * The exception is a member of an **exported data shape** — an interface, type literal or enum
911
+ * that no class implements. An interface is erased at compile time, so there is no carrier and
912
+ * no stub: renaming the member simply breaks anyone who names it. Keeping both members does not
913
+ * help either, because making them optional to stay compatible is what destroys the type safety
914
+ * the interface existed for. Those are `warn` — visible, counted, but not something the build
915
+ * can demand — unless `enforceTypeMembers` says otherwise.
916
+ */
917
+ async Run(context) {
918
+ const ts = await loadTypeScript();
919
+ if (!ts) {
920
+ return {
921
+ Violations: [],
922
+ Notes: ['typescript could not be resolved — naming-conventions skipped. Install it to enable this check.'],
923
+ };
924
+ }
925
+ const includeTests = context.Options['includeTests'] === true;
926
+ const enforceTypeMembers = context.Options['enforceTypeMembers'] === true;
927
+ const allowedNames = new Set(stringArrayOption(context.Options, 'allowedNames'));
928
+ const allowedPrefixes = stringArrayOption(context.Options, 'allowedPrefixes');
929
+ const isExcludedFile = (file) => {
930
+ if (DECLARATION_FILE.test(file))
931
+ return true;
932
+ if (includeTests)
933
+ return false;
934
+ return TEST_FILE.test(file) || TEST_DIR.test(toPosix(file));
935
+ };
936
+ // Collect every file first, so pass 1 can index base classes that live in other packages.
937
+ const packages = [];
938
+ for (const root of context.Roots) {
939
+ for (const dir of FindPackageDirs(join(context.RepoRoot, root), { SkipDirs: SKIP_DIRS })) {
940
+ const files = FindSourceFiles(dir, {
941
+ SkipDirs: SKIP_DIRS,
942
+ Extensions: SOURCE_EXTENSIONS,
943
+ Exclude: isExcludedFile,
944
+ });
945
+ if (files.length > 0)
946
+ packages.push({ Dir: dir, Rel: toPosix(relative(context.RepoRoot, dir)), Files: files, Public: null, Private: false });
947
+ }
948
+ }
949
+ // A file can sit in more than one package's walk when packages nest, and parsing it twice
950
+ // would report it twice. The innermost package wins, which is the one that owns the file.
951
+ const ownerByFile = new Map();
952
+ for (const pkg of packages) {
953
+ for (const file of pkg.Files) {
954
+ const current = ownerByFile.get(file);
955
+ if (!current || pkg.Rel.length > current.length)
956
+ ownerByFile.set(file, pkg.Rel);
957
+ }
958
+ }
959
+ // `setParentNodes: true` is required, not incidental: `ts.getJSDocTags` reads `node.jsDoc`,
960
+ // which the parser only attaches when it is on. Without it the `@deprecated` exclusion
961
+ // silently matches nothing. Measured cost over ~7,500 files: 2.1s -> 2.5s.
962
+ const sources = new Map();
963
+ const parsed = [];
964
+ for (const file of ownerByFile.keys()) {
965
+ let text;
966
+ try {
967
+ text = readFileSync(file, 'utf8');
968
+ }
969
+ catch {
970
+ continue;
971
+ }
972
+ const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, scriptKindFor(ts, file));
973
+ sources.set(file, source);
974
+ parsed.push({ File: file, Source: source, Lines: text.split('\n') });
975
+ }
976
+ const sourceOf = (file) => {
977
+ const cached = sources.get(file);
978
+ if (cached)
979
+ return cached;
980
+ try {
981
+ const source = ts.createSourceFile(file, readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true, scriptKindFor(ts, file));
982
+ sources.set(file, source);
983
+ return source;
984
+ }
985
+ catch {
986
+ return null;
987
+ }
988
+ };
989
+ let packagesWithoutEntry = 0;
990
+ for (const pkg of packages) {
991
+ const { Entries, Private } = resolveEntrySources(pkg.Dir);
992
+ pkg.Private = Private;
993
+ if (Entries.length === 0) {
994
+ if (!Private)
995
+ packagesWithoutEntry++;
996
+ continue;
997
+ }
998
+ pkg.Public = collectPublicSymbols(ts, Entries, sourceOf);
999
+ }
1000
+ const packageByRel = new Map(packages.map((p) => [p.Rel, p]));
1001
+ const { Contract, Implemented } = buildIndexes(ts, parsed.map((p) => p.Source));
1002
+ const deprecatedSuppressed = { Count: 0 };
1003
+ /**
1004
+ * A data-shape finding is only a compatibility problem when the owning type is actually
1005
+ * published. When the package has no resolvable entry we cannot prove it is unpublished, so
1006
+ * it is treated as published — the conservative direction, since the cost of being wrong is
1007
+ * demanding a rename that does break someone.
1008
+ */
1009
+ const severityFor = (finding, pkgRel) => {
1010
+ if (!finding.DataShapeOwner || enforceTypeMembers)
1011
+ return 'error';
1012
+ const pkg = pkgRel ? packageByRel.get(pkgRel) : undefined;
1013
+ if (!pkg)
1014
+ return 'warn';
1015
+ // A private package is published to nobody. Nothing outside the repo can name its types,
1016
+ // so there is no compatibility to preserve and the rename is free.
1017
+ if (pkg.Private)
1018
+ return 'error';
1019
+ if (pkg.Public === null)
1020
+ return 'warn';
1021
+ return pkg.Public.has(finding.DataShapeOwner) ? 'warn' : 'error';
1022
+ };
1023
+ const violations = [];
1024
+ for (const { File, Source, Lines } of parsed) {
1025
+ const pkgRel = ownerByFile.get(File);
1026
+ const rel = toPosix(relative(context.RepoRoot, File));
1027
+ const findings = CheckSourceFile({
1028
+ Ts: ts,
1029
+ Source,
1030
+ Lines,
1031
+ Contract,
1032
+ Implemented,
1033
+ DeprecatedSuppressed: deprecatedSuppressed,
1034
+ AllowedNames: allowedNames,
1035
+ AllowedPrefixes: allowedPrefixes,
1036
+ });
1037
+ for (const finding of findings) {
1038
+ violations.push({
1039
+ File: rel,
1040
+ Line: finding.Line,
1041
+ Message: finding.Message,
1042
+ ...(pkgRel ? { Package: pkgRel } : {}),
1043
+ Severity: severityFor(finding, pkgRel),
1044
+ });
1045
+ }
1046
+ }
1047
+ return { Violations: violations, Notes: buildNotes(violations, parsed.length, packages.length, packagesWithoutEntry, deprecatedSuppressed.Count) };
1048
+ },
1049
+ };
1050
+ /**
1051
+ * The summary a reader actually needs when there are tens of thousands of findings.
1052
+ *
1053
+ * A per-package table, because the work is done package by package and a total tells you nothing
1054
+ * about where to start. Capped, because the tail is long and the point is orientation.
1055
+ */
1056
+ function buildNotes(violations, fileCount, packageCount, packagesWithoutEntry, deprecatedSuppressed) {
1057
+ const errors = violations.filter((v) => v.Severity === 'error');
1058
+ const warnings = violations.length - errors.length;
1059
+ const notes = [
1060
+ `${fileCount} file(s) in ${packageCount} package(s) scanned — ${errors.length} failing, ${warnings} reported`,
1061
+ `${warnings} are members of exported data shapes: an interface has no runtime carrier, so there is no ` +
1062
+ 'deprecated-stub form for them and no fix that keeps consumers compiling. Renaming them is a ' +
1063
+ 'breaking change; "enforceTypeMembers" opts into that and is off by default.',
1064
+ ];
1065
+ if (deprecatedSuppressed > 0) {
1066
+ notes.push(`${deprecatedSuppressed} finding(s) suppressed by an @deprecated tag — back-compat stubs, working as intended.`);
1067
+ }
1068
+ if (packagesWithoutEntry > 0) {
1069
+ notes.push(`${packagesWithoutEntry} package(s) have no resolvable entry point; their data shapes are treated as published.`);
1070
+ }
1071
+ if (errors.length === 0)
1072
+ return notes;
1073
+ const byPackage = new Map();
1074
+ for (const violation of errors) {
1075
+ const key = violation.Package ?? '(unattributed)';
1076
+ byPackage.set(key, (byPackage.get(key) ?? 0) + 1);
1077
+ }
1078
+ const ranked = [...byPackage.entries()].sort((a, b) => b[1] - a[1]);
1079
+ notes.push(`failing findings span ${ranked.length} package(s); the heaviest:`);
1080
+ for (const [name, count] of ranked.slice(0, PACKAGE_TABLE_LIMIT)) {
1081
+ notes.push(` ${String(count).padStart(6)} ${name}`);
1082
+ }
1083
+ if (ranked.length > PACKAGE_TABLE_LIMIT) {
1084
+ notes.push(` … and ${ranked.length - PACKAGE_TABLE_LIMIT} more package(s)`);
1085
+ }
1086
+ return notes;
1087
+ }
1088
+ /** How many packages the summary table names before it stops. */
1089
+ const PACKAGE_TABLE_LIMIT = 15;
1090
+ // ─────────────────────────────────────────────────────────────────────────────
1091
+ // Adoption support
1092
+ // ─────────────────────────────────────────────────────────────────────────────
1093
+ /**
1094
+ * Packages that currently have zero violations.
1095
+ *
1096
+ * Progress tracking for a cleanup campaign: which packages are done. Answers it by running the
1097
+ * rules, never by writing to the repo and reverting — the same discipline as
1098
+ * `ProbeUndeclaredPackages` in `ui-layers`.
1099
+ */
1100
+ export async function FindCleanPackages(repoRoot, roots) {
1101
+ const summary = await NamingConventionsCheck.Run({ RepoRoot: repoRoot, Roots: roots, Options: {} });
1102
+ const dirty = new Set();
1103
+ for (const violation of summary.Violations)
1104
+ if (violation.Package)
1105
+ dirty.add(violation.Package);
1106
+ const ts = await loadTypeScript();
1107
+ if (!ts)
1108
+ return [];
1109
+ const clean = [];
1110
+ for (const root of roots) {
1111
+ for (const dir of FindPackageDirs(join(repoRoot, root), { SkipDirs: SKIP_DIRS })) {
1112
+ const rel = toPosix(relative(repoRoot, dir));
1113
+ const files = FindSourceFiles(dir, {
1114
+ SkipDirs: SKIP_DIRS,
1115
+ Extensions: SOURCE_EXTENSIONS,
1116
+ Exclude: (f) => DECLARATION_FILE.test(f) || TEST_FILE.test(f) || TEST_DIR.test(toPosix(f)),
1117
+ });
1118
+ if (files.length > 0 && !dirty.has(rel))
1119
+ clean.push(rel);
1120
+ }
1121
+ }
1122
+ return clean.sort();
1123
+ }
1124
+ //# sourceMappingURL=naming-conventions.js.map