@terreno/test 57.18.0 → 57.19.2

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.
Files changed (115) hide show
  1. package/CHANGELOG.md +1681 -0
  2. package/README.md +6 -0
  3. package/dist/assertions/expectAPIError.d.ts +18 -0
  4. package/dist/assertions/expectAPIError.js +33 -0
  5. package/dist/assertions/strictResponseProperties.d.ts +14 -0
  6. package/dist/assertions/strictResponseProperties.js +37 -0
  7. package/dist/cache/mongoTestCache.js +2 -2
  8. package/dist/cli/collectFiles.d.ts +38 -0
  9. package/dist/cli/collectFiles.js +73 -0
  10. package/dist/cli/testHygiene.d.ts +134 -0
  11. package/dist/cli/testHygiene.js +357 -0
  12. package/dist/cli/testHygieneCli.d.ts +2 -0
  13. package/dist/cli/testHygieneCli.js +5 -0
  14. package/dist/cli/testHygieneRules.d.ts +58 -0
  15. package/dist/cli/testHygieneRules.js +517 -0
  16. package/dist/cli/testShard.d.ts +155 -0
  17. package/dist/cli/testShard.js +377 -0
  18. package/dist/cli/testShardCli.d.ts +2 -0
  19. package/dist/cli/testShardCli.js +5 -0
  20. package/dist/expo/authTokenStorage.d.ts +76 -0
  21. package/dist/expo/authTokenStorage.js +160 -0
  22. package/dist/expo/expoModuleMocks.d.ts +24 -0
  23. package/dist/expo/expoModuleMocks.js +456 -0
  24. package/dist/expo/libraryModuleMocks.d.ts +17 -0
  25. package/dist/expo/libraryModuleMocks.js +347 -0
  26. package/dist/expo/mockHelpers.d.ts +39 -0
  27. package/dist/expo/mockHelpers.js +45 -0
  28. package/dist/expo/mockModuleAliases.d.ts +50 -0
  29. package/dist/expo/mockModuleAliases.js +174 -0
  30. package/dist/expo/reactNativeMock.d.ts +39 -0
  31. package/dist/expo/reactNativeMock.js +421 -0
  32. package/dist/expo/registerExpoTestEnvironment.d.ts +69 -0
  33. package/dist/expo/registerExpoTestEnvironment.js +163 -0
  34. package/dist/expo/renderWithTerreno.d.ts +47 -0
  35. package/dist/expo/renderWithTerreno.js +47 -0
  36. package/dist/http/authWithToken.d.ts +20 -0
  37. package/dist/http/authWithToken.js +30 -0
  38. package/dist/index.d.ts +14 -1
  39. package/dist/index.js +33 -1
  40. package/dist/logging/silenceLogs.js +0 -2
  41. package/dist/mocks/aiSdk.d.ts +77 -0
  42. package/dist/mocks/aiSdk.js +102 -0
  43. package/dist/mocks/cloudTasks.d.ts +91 -0
  44. package/dist/mocks/cloudTasks.js +197 -0
  45. package/dist/mocks/expoPush.d.ts +53 -0
  46. package/dist/mocks/expoPush.js +57 -0
  47. package/dist/mocks/gcs.d.ts +101 -0
  48. package/dist/mocks/gcs.js +162 -0
  49. package/dist/mocks/googleAuth.d.ts +69 -0
  50. package/dist/mocks/googleAuth.js +55 -0
  51. package/dist/mocks/mockGroup.d.ts +11 -0
  52. package/dist/mocks/mockGroup.js +21 -0
  53. package/dist/mocks/notifiers.d.ts +21 -0
  54. package/dist/mocks/notifiers.js +26 -0
  55. package/dist/mocks/sendgrid.d.ts +22 -0
  56. package/dist/mocks/sendgrid.js +32 -0
  57. package/dist/mocks/twilio.d.ts +72 -0
  58. package/dist/mocks/twilio.js +64 -0
  59. package/dist/preload/registerBackendPreload.js +4 -1
  60. package/dist/time/freezeTime.d.ts +16 -0
  61. package/dist/time/freezeTime.js +49 -0
  62. package/dist/transaction/testTransaction.d.ts +43 -6
  63. package/dist/transaction/testTransaction.js +371 -92
  64. package/dist/utils/waitUntil.d.ts +22 -0
  65. package/dist/utils/waitUntil.js +34 -0
  66. package/package.json +53 -8
  67. package/src/assertions/expectAPIError.ts +51 -0
  68. package/src/assertions/strictResponseProperties.ts +42 -0
  69. package/src/cache/mongoTestCache.ts +2 -2
  70. package/src/cli/collectFiles.ts +115 -0
  71. package/src/cli/testHygiene.ts +539 -0
  72. package/src/cli/testHygieneCli.ts +4 -0
  73. package/src/cli/testHygieneRules.ts +719 -0
  74. package/src/cli/testShard.ts +532 -0
  75. package/src/cli/testShardCli.ts +4 -0
  76. package/src/expo/authTokenStorage.ts +198 -0
  77. package/src/expo/expoModuleMocks.ts +503 -0
  78. package/src/expo/libraryModuleMocks.ts +411 -0
  79. package/src/expo/mockHelpers.ts +73 -0
  80. package/src/expo/mockModuleAliases.ts +252 -0
  81. package/src/expo/reactNativeMock.ts +534 -0
  82. package/src/expo/registerExpoTestEnvironment.ts +260 -0
  83. package/src/expo/renderWithTerreno.ts +79 -0
  84. package/src/http/authWithToken.ts +38 -0
  85. package/src/index.ts +82 -1
  86. package/src/logging/silenceLogs.ts +0 -2
  87. package/src/mocks/aiSdk.ts +199 -0
  88. package/src/mocks/cloudTasks.ts +323 -0
  89. package/src/mocks/expoPush.ts +134 -0
  90. package/src/mocks/gcs.ts +305 -0
  91. package/src/mocks/googleAuth.ts +136 -0
  92. package/src/mocks/mockGroup.ts +32 -0
  93. package/src/mocks/notifiers.ts +36 -0
  94. package/src/mocks/sendgrid.ts +57 -0
  95. package/src/mocks/twilio.ts +143 -0
  96. package/src/preload/registerBackendPreload.ts +4 -1
  97. package/src/time/freezeTime.ts +61 -0
  98. package/src/transaction/testTransaction.ts +456 -124
  99. package/src/utils/waitUntil.ts +47 -0
  100. package/biome.jsonc +0 -20
  101. package/bunfig.toml +0 -16
  102. package/src/cache/mongoTestCache.test.ts +0 -103
  103. package/src/env/setTerrenoTestEnv.test.ts +0 -26
  104. package/src/http/authAsUser.test.ts +0 -40
  105. package/src/http/getBaseServer.test.ts +0 -45
  106. package/src/logging/setupEnvironment.test.ts +0 -24
  107. package/src/logging/silenceLogs.test.ts +0 -52
  108. package/src/logging/testLogger.test.ts +0 -58
  109. package/src/mocks/sentryBun.test.ts +0 -230
  110. package/src/mongo/connection.test.ts +0 -43
  111. package/src/mongo/mongoServer.test.ts +0 -99
  112. package/src/preload/registerBackendPreload.test.ts +0 -10
  113. package/src/transaction/testTransaction.test.ts +0 -64
  114. package/src/utils/helpers.test.ts +0 -46
  115. package/tsconfig.json +0 -18
@@ -0,0 +1,539 @@
1
+ /**
2
+ * Test-hygiene checker: runs the AST rules in `testHygieneRules.ts` over a tree of test files,
3
+ * honors suppression comments, and compares against a committed baseline so only new
4
+ * violations fail CI.
5
+ *
6
+ * - Suppress one finding with `// test-hygiene-disable-next-line <rule-id>[, <rule-id>] -- reason`
7
+ * on the line before it.
8
+ * - A baseline is a JSON array of `{file, rule, count}`. For each file/rule pair the first
9
+ * `count` violations (by line) are tolerated; regenerate it with `--update-baseline`.
10
+ */
11
+ import {existsSync, readFileSync, writeFileSync} from "node:fs";
12
+ import path from "node:path";
13
+ import {parseArgs} from "node:util";
14
+
15
+ import {collectFiles, DEFAULT_EXCLUDED_DIRS, DEFAULT_TEST_PATTERNS} from "./collectFiles";
16
+ import {
17
+ DEFAULT_SLEEP_CALLEES,
18
+ HYGIENE_RULE_IDS,
19
+ type HygieneRuleConfig,
20
+ type HygieneRuleId,
21
+ type HygieneViolation,
22
+ runHygieneRules,
23
+ } from "./testHygieneRules";
24
+
25
+ const SUPPRESSION_DIRECTIVE = "test-hygiene-disable-next-line";
26
+
27
+ /** Config file looked up in the working directory when `--config` is not passed. */
28
+ const DEFAULT_CONFIG_FILE = "test-hygiene.config.json";
29
+
30
+ /** Baseline file, relative to the root, used when the config does not name one. */
31
+ const DEFAULT_BASELINE_FILE = "test-hygiene-baseline.json";
32
+
33
+ export interface BaselineEntry {
34
+ file: string;
35
+ rule: HygieneRuleId;
36
+ count: number;
37
+ }
38
+
39
+ /** JSON config file shape. Relative paths resolve against the config file's directory. */
40
+ export interface TestHygieneConfigFile {
41
+ /** Directory scanned, reported against, and used for barrel paths (default: config dir). */
42
+ root?: string;
43
+ /** Files or directories to scan, relative to `root` (default: `["."]`). */
44
+ paths?: string[];
45
+ /** Test file globs relative to `root`. */
46
+ include?: string[];
47
+ /** Root-relative globs to skip. */
48
+ exclude?: string[];
49
+ /** Directory names skipped at any depth, added to the defaults. */
50
+ excludeDirs?: string[];
51
+ /** Baseline path. */
52
+ baseline?: string;
53
+ /** Rule toggles; omitted rules stay on. */
54
+ rules?: Partial<Record<HygieneRuleId, boolean>>;
55
+ barrels?: {
56
+ aliases?: string[];
57
+ paths?: string[];
58
+ allowMockIn?: string[];
59
+ };
60
+ mockHelperModules?: string[];
61
+ realExportGetters?: {
62
+ modules?: string[];
63
+ namePattern?: string;
64
+ };
65
+ sleepCallees?: string[];
66
+ }
67
+
68
+ export interface ResolvedHygieneConfig {
69
+ rootDir: string;
70
+ paths: string[];
71
+ include: string[];
72
+ exclude: string[];
73
+ excludeDirs: string[];
74
+ baselinePath: string;
75
+ rules: HygieneRuleId[];
76
+ ruleConfig: HygieneRuleConfig;
77
+ }
78
+
79
+ const isHygieneRuleId = (value: string): value is HygieneRuleId =>
80
+ (HYGIENE_RULE_IDS as readonly string[]).includes(value);
81
+
82
+ /**
83
+ * Drops violations whose preceding line carries a matching suppression directive. The directive
84
+ * accepts a comma-separated rule list, followed by an optional `-- reason`.
85
+ */
86
+ export const applySuppressions = ({
87
+ sourceText,
88
+ violations,
89
+ }: {
90
+ sourceText: string;
91
+ violations: HygieneViolation[];
92
+ }): {violations: HygieneViolation[]} => {
93
+ const lines = sourceText.split("\n");
94
+ const directive = new RegExp(`${SUPPRESSION_DIRECTIVE}\\s+([\\w-]+(?:\\s*,\\s*[\\w-]+)*)`, "u");
95
+ return {
96
+ violations: violations.filter((violation) => {
97
+ const precedingLine = lines[violation.line - 2];
98
+ const match = precedingLine?.match(directive);
99
+ if (!match) {
100
+ return true;
101
+ }
102
+ const suppressed = match[1].split(",").map((rule) => rule.trim());
103
+ return !suppressed.includes(violation.ruleId);
104
+ }),
105
+ };
106
+ };
107
+
108
+ /** Parses, runs the enabled rules on, and suppression-filters one file. Filesystem free. */
109
+ export const checkTestSource = ({
110
+ fileName,
111
+ sourceText,
112
+ config,
113
+ rules,
114
+ }: {
115
+ fileName: string;
116
+ sourceText: string;
117
+ config: HygieneRuleConfig;
118
+ rules?: readonly HygieneRuleId[];
119
+ }): {violations: HygieneViolation[]} => {
120
+ const {violations} = runHygieneRules({config, fileName, rules, sourceText});
121
+ return applySuppressions({sourceText, violations});
122
+ };
123
+
124
+ const baselineKey = ({file, rule}: {file: string; rule: string}): string => `${file}::${rule}`;
125
+
126
+ /** Counts violations per file/rule pair, sorted by file then rule for stable diffs. */
127
+ export const buildBaseline = ({
128
+ violations,
129
+ }: {
130
+ violations: HygieneViolation[];
131
+ }): {entries: BaselineEntry[]} => {
132
+ const counts = new Map<string, BaselineEntry>();
133
+ for (const violation of violations) {
134
+ const key = baselineKey({file: violation.file, rule: violation.ruleId});
135
+ const entry = counts.get(key) ?? {count: 0, file: violation.file, rule: violation.ruleId};
136
+ entry.count += 1;
137
+ counts.set(key, entry);
138
+ }
139
+ const entries = [...counts.values()].sort(
140
+ (a, b) => a.file.localeCompare(b.file) || a.rule.localeCompare(b.rule)
141
+ );
142
+ return {entries};
143
+ };
144
+
145
+ /**
146
+ * Splits violations into new ones (beyond the baseline count for their file/rule pair) and
147
+ * reports baseline entries whose count is now higher than reality, so the baseline can ratchet.
148
+ */
149
+ export const diffAgainstBaseline = ({
150
+ violations,
151
+ baseline,
152
+ }: {
153
+ violations: HygieneViolation[];
154
+ baseline: BaselineEntry[];
155
+ }): {newViolations: HygieneViolation[]; staleEntries: BaselineEntry[]} => {
156
+ const grouped = new Map<string, HygieneViolation[]>();
157
+ for (const violation of violations) {
158
+ const key = baselineKey({file: violation.file, rule: violation.ruleId});
159
+ grouped.set(key, [...(grouped.get(key) ?? []), violation]);
160
+ }
161
+ const allowed = new Map(baseline.map((entry) => [baselineKey(entry), entry.count]));
162
+
163
+ const newViolations: HygieneViolation[] = [];
164
+ for (const [key, list] of grouped) {
165
+ const sorted = [...list].sort((a, b) => a.line - b.line);
166
+ newViolations.push(...sorted.slice(allowed.get(key) ?? 0));
167
+ }
168
+ const staleEntries = baseline.filter(
169
+ (entry) => (grouped.get(baselineKey(entry))?.length ?? 0) < entry.count
170
+ );
171
+ return {
172
+ newViolations: newViolations.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line),
173
+ staleEntries,
174
+ };
175
+ };
176
+
177
+ /** Parses and validates baseline JSON. */
178
+ export const parseBaseline = ({
179
+ text,
180
+ }: {
181
+ text: string;
182
+ }): {entries: BaselineEntry[]} | {error: string} => {
183
+ let data: unknown;
184
+ try {
185
+ data = JSON.parse(text);
186
+ } catch (error) {
187
+ return {error: `Baseline is not valid JSON: ${(error as Error).message}`};
188
+ }
189
+ if (!Array.isArray(data)) {
190
+ return {error: "Baseline must be a JSON array of {file, rule, count}"};
191
+ }
192
+ const entries: BaselineEntry[] = [];
193
+ for (const item of data as unknown[]) {
194
+ const entry = item as Partial<BaselineEntry>;
195
+ if (
196
+ typeof entry?.file !== "string" ||
197
+ typeof entry.rule !== "string" ||
198
+ !isHygieneRuleId(entry.rule) ||
199
+ typeof entry.count !== "number"
200
+ ) {
201
+ return {error: `Invalid baseline entry: ${JSON.stringify(item)}`};
202
+ }
203
+ entries.push({count: entry.count, file: entry.file, rule: entry.rule});
204
+ }
205
+ return {entries};
206
+ };
207
+
208
+ /** Counts violations per rule, including rules with zero findings, in rule order. */
209
+ export const countByRule = ({
210
+ violations,
211
+ rules = HYGIENE_RULE_IDS,
212
+ }: {
213
+ violations: HygieneViolation[];
214
+ rules?: readonly HygieneRuleId[];
215
+ }): {counts: Record<string, number>} => {
216
+ const counts: Record<string, number> = Object.fromEntries(rules.map((rule) => [rule, 0]));
217
+ for (const violation of violations) {
218
+ counts[violation.ruleId] = (counts[violation.ruleId] ?? 0) + 1;
219
+ }
220
+ return {counts};
221
+ };
222
+
223
+ /** Applies defaults and resolves config-file paths against `configDir`. */
224
+ export const resolveHygieneConfig = ({
225
+ file = {},
226
+ configDir,
227
+ }: {
228
+ file?: TestHygieneConfigFile;
229
+ configDir: string;
230
+ }): {config: ResolvedHygieneConfig} => {
231
+ const rootDir = path.resolve(configDir, file.root ?? ".");
232
+ const rules = HYGIENE_RULE_IDS.filter((rule) => file.rules?.[rule] !== false);
233
+ return {
234
+ config: {
235
+ baselinePath: file.baseline
236
+ ? path.resolve(configDir, file.baseline)
237
+ : path.join(rootDir, DEFAULT_BASELINE_FILE),
238
+ exclude: file.exclude ?? [],
239
+ excludeDirs: [...DEFAULT_EXCLUDED_DIRS, ...(file.excludeDirs ?? [])],
240
+ include: file.include ?? [...DEFAULT_TEST_PATTERNS],
241
+ paths: file.paths ?? ["."],
242
+ rootDir,
243
+ ruleConfig: {
244
+ barrelAliases: file.barrels?.aliases ?? [],
245
+ barrelMockAllowlist: file.barrels?.allowMockIn ?? [],
246
+ barrelPaths: file.barrels?.paths ?? [],
247
+ mockHelperModules: file.mockHelperModules ?? [],
248
+ realExportGetterModules: file.realExportGetters?.modules ?? [],
249
+ realExportGetterNamePattern: file.realExportGetters?.namePattern,
250
+ rootDir,
251
+ sleepCallees: file.sleepCallees ?? [...DEFAULT_SLEEP_CALLEES],
252
+ },
253
+ rules,
254
+ },
255
+ };
256
+ };
257
+
258
+ const TEST_HYGIENE_USAGE = `Usage: terreno-test-hygiene [options] [path ...]
259
+
260
+ Checks Bun test files for mock-isolation and timing hazards. Paths default to the root.
261
+
262
+ Options:
263
+ --config <file> JSON config (default: ./${DEFAULT_CONFIG_FILE} when present).
264
+ --root <dir> Root that paths, globs, and barrel paths are relative to.
265
+ --include <glob> Test file glob, root relative (repeatable).
266
+ Default: ${DEFAULT_TEST_PATTERNS.join(", ")}
267
+ --exclude <glob> Skip files matching this root-relative glob (repeatable).
268
+ --exclude-dir <name> Skip directories with this name at any depth (repeatable).
269
+ --baseline <file> Baseline JSON (default: <root>/${DEFAULT_BASELINE_FILE}).
270
+ --update-baseline Write current violations to the baseline and exit 0.
271
+ --no-baseline Ignore any baseline; report every violation.
272
+ --rule <id> Run only these rules (repeatable).
273
+ --disable-rule <id> Turn a rule off (repeatable).
274
+ --barrel-alias <glob> Bare specifier that names a shared barrel, e.g. @hooks (repeatable).
275
+ --barrel-path <glob> Root-relative module path of a shared barrel, e.g. hooks (repeatable).
276
+ --mock-helper <module> Module whose named imports register mock.module (repeatable).
277
+ --sleep-callee <name> Extra sleep callee to flag, e.g. timeout (repeatable).
278
+ --format <text|json> Output format (default text).
279
+ -h, --help Show this help.
280
+
281
+ Rules: ${HYGIENE_RULE_IDS.join(", ")}
282
+ Suppress one finding: // ${SUPPRESSION_DIRECTIVE} <rule-id> -- reason
283
+
284
+ Exit code: 0 when no violations beyond the baseline, 1 otherwise, 2 on usage errors.`;
285
+
286
+ interface HygieneFlagValues {
287
+ baseline?: string;
288
+ "barrel-alias"?: string[];
289
+ "barrel-path"?: string[];
290
+ config?: string;
291
+ "disable-rule"?: string[];
292
+ exclude?: string[];
293
+ "exclude-dir"?: string[];
294
+ format?: string;
295
+ help?: boolean;
296
+ include?: string[];
297
+ "mock-helper"?: string[];
298
+ "no-baseline"?: boolean;
299
+ root?: string;
300
+ rule?: string[];
301
+ "sleep-callee"?: string[];
302
+ "update-baseline"?: boolean;
303
+ }
304
+
305
+ /** Throws on unknown flags or missing flag values (strict mode). */
306
+ const parseHygieneFlags = (args: string[]): {values: HygieneFlagValues; positionals: string[]} =>
307
+ parseArgs({
308
+ allowPositionals: true,
309
+ args,
310
+ options: {
311
+ "barrel-alias": {multiple: true, type: "string"},
312
+ "barrel-path": {multiple: true, type: "string"},
313
+ baseline: {type: "string"},
314
+ config: {type: "string"},
315
+ "disable-rule": {multiple: true, type: "string"},
316
+ exclude: {multiple: true, type: "string"},
317
+ "exclude-dir": {multiple: true, type: "string"},
318
+ format: {type: "string"},
319
+ help: {short: "h", type: "boolean"},
320
+ include: {multiple: true, type: "string"},
321
+ "mock-helper": {multiple: true, type: "string"},
322
+ "no-baseline": {type: "boolean"},
323
+ root: {type: "string"},
324
+ rule: {multiple: true, type: "string"},
325
+ "sleep-callee": {multiple: true, type: "string"},
326
+ "update-baseline": {type: "boolean"},
327
+ },
328
+ strict: true,
329
+ });
330
+
331
+ export interface TestHygieneCliOptions {
332
+ config: ResolvedHygieneConfig;
333
+ format: "json" | "text";
334
+ isHelp: boolean;
335
+ isUpdateBaseline: boolean;
336
+ useBaseline: boolean;
337
+ }
338
+
339
+ /** Merges the config file (if any) with CLI flags. Flags win; list flags extend the config. */
340
+ export const parseTestHygieneArgs = ({
341
+ argv,
342
+ cwd,
343
+ readFile = (filePath: string): string | undefined =>
344
+ existsSync(filePath) ? readFileSync(filePath, "utf-8") : undefined,
345
+ }: {
346
+ argv: string[];
347
+ cwd: string;
348
+ readFile?: (filePath: string) => string | undefined;
349
+ }): {options: TestHygieneCliOptions} | {error: string} => {
350
+ let parsed: {values: HygieneFlagValues; positionals: string[]};
351
+ try {
352
+ parsed = parseHygieneFlags(argv);
353
+ } catch (error) {
354
+ return {error: (error as Error).message};
355
+ }
356
+ const {values, positionals} = parsed;
357
+
358
+ const configPath = path.resolve(cwd, values.config ?? DEFAULT_CONFIG_FILE);
359
+ const configText = readFile(configPath);
360
+ if (values.config && configText === undefined) {
361
+ return {error: `Config file not found: ${configPath}`};
362
+ }
363
+ let file: TestHygieneConfigFile = {};
364
+ if (configText !== undefined) {
365
+ try {
366
+ file = JSON.parse(configText) as TestHygieneConfigFile;
367
+ } catch (error) {
368
+ return {error: `Config ${configPath} is not valid JSON: ${(error as Error).message}`};
369
+ }
370
+ }
371
+ const configDir = configText === undefined ? cwd : path.dirname(configPath);
372
+
373
+ const ruleFlags = [...(values.rule ?? []), ...(values["disable-rule"] ?? [])];
374
+ const unknownRule = ruleFlags.find((rule) => !isHygieneRuleId(rule));
375
+ if (unknownRule) {
376
+ return {error: `Unknown rule "${unknownRule}". Rules: ${HYGIENE_RULE_IDS.join(", ")}`};
377
+ }
378
+ const format = values.format ?? "text";
379
+ if (format !== "text" && format !== "json") {
380
+ return {error: `--format must be text or json, got "${format}"`};
381
+ }
382
+
383
+ const merged: TestHygieneConfigFile = {
384
+ ...file,
385
+ barrels: {
386
+ ...file.barrels,
387
+ aliases: [...(file.barrels?.aliases ?? []), ...(values["barrel-alias"] ?? [])],
388
+ paths: [...(file.barrels?.paths ?? []), ...(values["barrel-path"] ?? [])],
389
+ },
390
+ exclude: [...(file.exclude ?? []), ...(values.exclude ?? [])],
391
+ excludeDirs: [...(file.excludeDirs ?? []), ...(values["exclude-dir"] ?? [])],
392
+ include: values.include ?? file.include,
393
+ mockHelperModules: [...(file.mockHelperModules ?? []), ...(values["mock-helper"] ?? [])],
394
+ sleepCallees: [
395
+ ...(file.sleepCallees ?? DEFAULT_SLEEP_CALLEES),
396
+ ...(values["sleep-callee"] ?? []),
397
+ ],
398
+ };
399
+ // CLI --root/--baseline/paths are relative to the cwd, not to the config file.
400
+ if (values.root) {
401
+ merged.root = path.resolve(cwd, values.root);
402
+ }
403
+ if (values.baseline) {
404
+ merged.baseline = path.resolve(cwd, values.baseline);
405
+ }
406
+ if (positionals.length > 0) {
407
+ const rootForPaths = path.resolve(configDir, merged.root ?? ".");
408
+ merged.paths = positionals.map((p) => path.relative(rootForPaths, path.resolve(cwd, p)) || ".");
409
+ }
410
+
411
+ const {config} = resolveHygieneConfig({configDir, file: merged});
412
+ const onlyRules = values.rule ?? [];
413
+ const disabled = new Set(values["disable-rule"] ?? []);
414
+ config.rules = config.rules.filter(
415
+ (rule) => (onlyRules.length === 0 || onlyRules.includes(rule)) && !disabled.has(rule)
416
+ );
417
+
418
+ return {
419
+ options: {
420
+ config,
421
+ format,
422
+ isHelp: values.help ?? false,
423
+ isUpdateBaseline: values["update-baseline"] ?? false,
424
+ useBaseline: !(values["no-baseline"] ?? false),
425
+ },
426
+ };
427
+ };
428
+
429
+ export interface HygieneLogger {
430
+ info: (message: string) => void;
431
+ error: (message: string) => void;
432
+ }
433
+
434
+ const formatCounts = ({counts}: {counts: Record<string, number>}): string =>
435
+ Object.entries(counts)
436
+ .map(([rule, count]) => ` ${rule}: ${count}`)
437
+ .join("\n");
438
+
439
+ /**
440
+ * CLI entry point: scans test files, applies the baseline, prints findings and per-rule counts,
441
+ * and returns the exit code instead of exiting so it is testable.
442
+ */
443
+ export const runTestHygieneCli = ({
444
+ argv,
445
+ cwd = process.cwd(),
446
+ logger = console,
447
+ }: {
448
+ argv: string[];
449
+ cwd?: string;
450
+ logger?: HygieneLogger;
451
+ }): {exitCode: number} => {
452
+ const parsed = parseTestHygieneArgs({argv, cwd});
453
+ if ("error" in parsed) {
454
+ logger.error(`${parsed.error}\n\n${TEST_HYGIENE_USAGE}`);
455
+ return {exitCode: 2};
456
+ }
457
+ const {options} = parsed;
458
+ if (options.isHelp) {
459
+ logger.info(TEST_HYGIENE_USAGE);
460
+ return {exitCode: 0};
461
+ }
462
+ const {config} = options;
463
+
464
+ const {files, missingPaths} = collectFiles({
465
+ cwd: config.rootDir,
466
+ exclude: config.exclude,
467
+ excludeDirs: config.excludeDirs,
468
+ paths: config.paths,
469
+ patterns: config.include,
470
+ });
471
+ if (missingPaths.length > 0) {
472
+ logger.error(`Path(s) do not exist under ${config.rootDir}: ${missingPaths.join(", ")}`);
473
+ return {exitCode: 2};
474
+ }
475
+
476
+ const violations = files.flatMap(
477
+ (file) =>
478
+ checkTestSource({
479
+ config: config.ruleConfig,
480
+ fileName: path.join(config.rootDir, file),
481
+ rules: config.rules,
482
+ sourceText: readFileSync(path.join(config.rootDir, file), "utf-8"),
483
+ }).violations
484
+ );
485
+
486
+ if (options.isUpdateBaseline) {
487
+ const {entries} = buildBaseline({violations});
488
+ writeFileSync(config.baselinePath, `${JSON.stringify(entries, null, 2)}\n`, "utf-8");
489
+ logger.info(
490
+ `Wrote ${config.baselinePath}: ${violations.length} violation(s) across ${entries.length} file/rule pair(s).`
491
+ );
492
+ return {exitCode: 0};
493
+ }
494
+
495
+ let baseline: BaselineEntry[] = [];
496
+ if (options.useBaseline && existsSync(config.baselinePath)) {
497
+ const parsedBaseline = parseBaseline({text: readFileSync(config.baselinePath, "utf-8")});
498
+ if ("error" in parsedBaseline) {
499
+ logger.error(`${config.baselinePath}: ${parsedBaseline.error}`);
500
+ return {exitCode: 2};
501
+ }
502
+ baseline = parsedBaseline.entries;
503
+ }
504
+ const {newViolations, staleEntries} = diffAgainstBaseline({baseline, violations});
505
+ const exitCode = newViolations.length === 0 ? 0 : 1;
506
+
507
+ if (options.format === "json") {
508
+ logger.info(
509
+ JSON.stringify(
510
+ {
511
+ baselined: violations.length - newViolations.length,
512
+ countsByRule: countByRule({rules: config.rules, violations}).counts,
513
+ filesChecked: files.length,
514
+ newCountsByRule: countByRule({rules: config.rules, violations: newViolations}).counts,
515
+ newViolations,
516
+ staleBaselineEntries: staleEntries,
517
+ },
518
+ null,
519
+ 2
520
+ )
521
+ );
522
+ return {exitCode};
523
+ }
524
+
525
+ for (const violation of newViolations) {
526
+ logger.error(`${violation.file}:${violation.line} ${violation.ruleId} ${violation.message}`);
527
+ }
528
+ logger.info(
529
+ `\nChecked ${files.length} file(s) under ${config.rootDir}: ${violations.length} violation(s), ` +
530
+ `${violations.length - newViolations.length} baselined, ${newViolations.length} new.`
531
+ );
532
+ logger.info(formatCounts(countByRule({rules: config.rules, violations: newViolations})));
533
+ if (staleEntries.length > 0) {
534
+ logger.info(
535
+ `${staleEntries.length} baseline entr(ies) are higher than current counts; run --update-baseline to ratchet.`
536
+ );
537
+ }
538
+ return {exitCode};
539
+ };
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env bun
2
+ import {runTestHygieneCli} from "./testHygiene";
3
+
4
+ process.exitCode = runTestHygieneCli({argv: process.argv.slice(2)}).exitCode;