@terreno/test 57.17.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,517 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.runHygieneRules = exports.resolvesToBarrel = exports.DEFAULT_SLEEP_CALLEES = exports.HYGIENE_RULE_IDS = void 0;
7
+ /**
8
+ * AST rules for the test-hygiene checker. Each rule targets a Bun test pattern that causes
9
+ * order-dependent or timing-dependent failures:
10
+ *
11
+ * - `no-module-scope-mock-module`: `mock.module()` is process-wide and has no undo, so a call
12
+ * that runs at module load leaks into every later file in the process. Register mocks from a
13
+ * helper called in `beforeEach`/`beforeAll`/`describe` instead.
14
+ * - `no-direct-barrel-mock`: mocking a shared barrel by one specifier (an alias like `@hooks`)
15
+ * leaves the other cache key (`hooks/index.ts`) bound to the real module. Route barrel mocks
16
+ * through helpers that register both keys.
17
+ * - `no-sleep`: fixed sleeps are either too short on slow CI or waste time locally. Poll the
18
+ * real condition instead.
19
+ * - `no-cache-busted-import`: `import("./x?bust")` creates a new module identity, so
20
+ * `mock.module()` registrations for `./x` no longer apply.
21
+ * - `no-late-real-capture`: capturing the real barrel inside the mock factory can re-enter the
22
+ * in-progress registration and bind a partial module. Capture real exports at module scope.
23
+ * - `no-component-snapshot`: `expect(ImportedComponent).toMatchSnapshot()` snapshots a function
24
+ * reference, not rendered output.
25
+ *
26
+ * Uses the TypeScript compiler API (not regex) so scope detection is reliable.
27
+ */
28
+ const node_path_1 = __importDefault(require("node:path"));
29
+ const typescript_1 = __importDefault(require("typescript"));
30
+ const collectFiles_1 = require("./collectFiles");
31
+ exports.HYGIENE_RULE_IDS = [
32
+ "no-module-scope-mock-module",
33
+ "no-direct-barrel-mock",
34
+ "no-sleep",
35
+ "no-cache-busted-import",
36
+ "no-late-real-capture",
37
+ "no-component-snapshot",
38
+ ];
39
+ exports.DEFAULT_SLEEP_CALLEES = ["Bun.sleep"];
40
+ const stripExtension = (filePath) => filePath.replace(/\.(tsx?|jsx?|mjs|cjs)$/u, "");
41
+ /** Whether `specifier` is `entry` exactly or ends with `/entry` (ignoring a file extension). */
42
+ const specifierMatchesModule = ({ specifier, modules, }) => {
43
+ const stripped = stripExtension(specifier);
44
+ return modules.some((entry) => stripped === entry || stripped.endsWith(`/${entry}`));
45
+ };
46
+ /** Determines whether a `mock.module()`/`require()`/`import()` specifier targets a shared barrel. */
47
+ const resolvesToBarrel = ({ config, fromFile, specifier, }) => {
48
+ if (!specifier.startsWith(".")) {
49
+ return (0, collectFiles_1.matchesAnyGlob)({ filePath: specifier, globs: config.barrelAliases ?? [] });
50
+ }
51
+ const barrelPaths = config.barrelPaths ?? [];
52
+ if (barrelPaths.length === 0) {
53
+ return false;
54
+ }
55
+ const resolved = stripExtension(node_path_1.default.resolve(node_path_1.default.dirname(fromFile), specifier));
56
+ const relativeToRoot = (0, collectFiles_1.toPosixPath)(node_path_1.default.relative(config.rootDir, resolved));
57
+ const candidates = [relativeToRoot];
58
+ if (relativeToRoot.endsWith("/index")) {
59
+ candidates.push(relativeToRoot.slice(0, -"/index".length));
60
+ }
61
+ return candidates.some((candidate) => (0, collectFiles_1.matchesAnyGlob)({ filePath: candidate, globs: barrelPaths }));
62
+ };
63
+ exports.resolvesToBarrel = resolvesToBarrel;
64
+ const isMockModuleCallee = (expression) => typescript_1.default.isPropertyAccessExpression(expression) &&
65
+ typescript_1.default.isIdentifier(expression.expression) &&
66
+ expression.expression.text === "mock" &&
67
+ expression.name.text === "module";
68
+ const isMockModuleCall = (node) => typescript_1.default.isCallExpression(node) && isMockModuleCallee(node.expression);
69
+ const isFunctionLike = (node) => typescript_1.default.isFunctionDeclaration(node) ||
70
+ typescript_1.default.isFunctionExpression(node) ||
71
+ typescript_1.default.isArrowFunction(node) ||
72
+ typescript_1.default.isMethodDeclaration(node) ||
73
+ typescript_1.default.isConstructorDeclaration(node) ||
74
+ typescript_1.default.isGetAccessorDeclaration(node) ||
75
+ typescript_1.default.isSetAccessorDeclaration(node);
76
+ /** Whether `node` runs at module load (no enclosing function). */
77
+ const isAtModuleScope = (node) => {
78
+ let current = node.parent;
79
+ while (current) {
80
+ if (isFunctionLike(current)) {
81
+ return false;
82
+ }
83
+ current = current.parent;
84
+ }
85
+ return true;
86
+ };
87
+ const makeViolation = ({ sourceFile, node, ruleId, message, }) => {
88
+ const { line } = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile));
89
+ return { file: sourceFile.fileName, line: line + 1, message, ruleId };
90
+ };
91
+ /** Calls `visitor` for every node in `root`, depth first. */
92
+ const walk = (root, visitor) => {
93
+ const visit = (node) => {
94
+ visitor(node);
95
+ typescript_1.default.forEachChild(node, visit);
96
+ };
97
+ visit(root);
98
+ };
99
+ /** Collects named functions (`function foo() {}` and `const foo = () => {}`) in the file. */
100
+ const collectNamedFunctions = (sourceFile) => {
101
+ const namedFunctions = new Map();
102
+ walk(sourceFile, (node) => {
103
+ if (typescript_1.default.isFunctionDeclaration(node) && node.name) {
104
+ namedFunctions.set(node.name.text, node);
105
+ }
106
+ else if (typescript_1.default.isVariableDeclaration(node) &&
107
+ typescript_1.default.isIdentifier(node.name) &&
108
+ node.initializer &&
109
+ (typescript_1.default.isArrowFunction(node.initializer) || typescript_1.default.isFunctionExpression(node.initializer))) {
110
+ namedFunctions.set(node.name.text, node.initializer);
111
+ }
112
+ });
113
+ return namedFunctions;
114
+ };
115
+ /** Collects local names of named imports whose module specifier matches `modules`. */
116
+ const collectNamedImportsFrom = ({ sourceFile, modules, namePattern, }) => {
117
+ const names = new Set();
118
+ if (modules.length === 0) {
119
+ return names;
120
+ }
121
+ for (const statement of sourceFile.statements) {
122
+ if (!typescript_1.default.isImportDeclaration(statement) ||
123
+ !typescript_1.default.isStringLiteral(statement.moduleSpecifier) ||
124
+ !specifierMatchesModule({ modules, specifier: statement.moduleSpecifier.text })) {
125
+ continue;
126
+ }
127
+ const bindings = statement.importClause?.namedBindings;
128
+ if (!bindings || !typescript_1.default.isNamedImports(bindings)) {
129
+ continue;
130
+ }
131
+ for (const element of bindings.elements) {
132
+ if (!namePattern || namePattern.test(element.name.text)) {
133
+ names.add(element.name.text);
134
+ }
135
+ }
136
+ }
137
+ return names;
138
+ };
139
+ /** Whether `fn` transitively (through same-file named functions) calls `mock.module()` or a helper. */
140
+ const createMockRegistrationDetector = ({ sourceFile, mockHelperNames, }) => {
141
+ const namedFunctions = collectNamedFunctions(sourceFile);
142
+ const memo = new Map();
143
+ const visiting = new Set();
144
+ const registersMock = (fn) => {
145
+ const cached = memo.get(fn);
146
+ if (cached !== undefined) {
147
+ return cached;
148
+ }
149
+ if (visiting.has(fn)) {
150
+ return false;
151
+ }
152
+ visiting.add(fn);
153
+ let found = false;
154
+ const visit = (node) => {
155
+ if (found) {
156
+ return;
157
+ }
158
+ if (isMockModuleCall(node)) {
159
+ found = true;
160
+ return;
161
+ }
162
+ if (typescript_1.default.isCallExpression(node) && typescript_1.default.isIdentifier(node.expression)) {
163
+ const name = node.expression.text;
164
+ const target = namedFunctions.get(name);
165
+ if (mockHelperNames.has(name) || (target && registersMock(target))) {
166
+ found = true;
167
+ return;
168
+ }
169
+ }
170
+ typescript_1.default.forEachChild(node, visit);
171
+ };
172
+ visit(fn.body ?? fn);
173
+ visiting.delete(fn);
174
+ memo.set(fn, found);
175
+ return found;
176
+ };
177
+ return registersMock;
178
+ };
179
+ const findModuleScopeMockViolations = ({ sourceFile, mockHelperNames, }) => {
180
+ const namedFunctions = collectNamedFunctions(sourceFile);
181
+ const registersMock = createMockRegistrationDetector({ mockHelperNames, sourceFile });
182
+ const violations = [];
183
+ walk(sourceFile, (node) => {
184
+ if (!typescript_1.default.isCallExpression(node) || !isAtModuleScope(node)) {
185
+ return;
186
+ }
187
+ if (isMockModuleCallee(node.expression)) {
188
+ violations.push(makeViolation({
189
+ message: "mock.module() executes at module load; wrap it in a helper called from beforeEach/beforeAll/describe.",
190
+ node,
191
+ ruleId: "no-module-scope-mock-module",
192
+ sourceFile,
193
+ }));
194
+ return;
195
+ }
196
+ if (!typescript_1.default.isIdentifier(node.expression)) {
197
+ return;
198
+ }
199
+ const name = node.expression.text;
200
+ if (mockHelperNames.has(name)) {
201
+ violations.push(makeViolation({
202
+ message: `${name}() registers mock.module() and is invoked at module scope; call it from beforeEach/beforeAll/describe instead.`,
203
+ node,
204
+ ruleId: "no-module-scope-mock-module",
205
+ sourceFile,
206
+ }));
207
+ return;
208
+ }
209
+ const target = namedFunctions.get(name);
210
+ if (target && registersMock(target)) {
211
+ violations.push(makeViolation({
212
+ message: `${name}() registers mock.module() and is invoked at module scope; call it from beforeEach/beforeAll/describe instead.`,
213
+ node,
214
+ ruleId: "no-module-scope-mock-module",
215
+ sourceFile,
216
+ }));
217
+ }
218
+ });
219
+ return violations;
220
+ };
221
+ const findDirectBarrelMockViolations = ({ sourceFile, config, relativeFile, }) => {
222
+ if ((0, collectFiles_1.matchesAnyGlob)({ filePath: relativeFile, globs: config.barrelMockAllowlist ?? [] })) {
223
+ return [];
224
+ }
225
+ const violations = [];
226
+ walk(sourceFile, (node) => {
227
+ if (!isMockModuleCall(node)) {
228
+ return;
229
+ }
230
+ const [specifierArg] = node.arguments;
231
+ if (specifierArg &&
232
+ typescript_1.default.isStringLiteralLike(specifierArg) &&
233
+ (0, exports.resolvesToBarrel)({ config, fromFile: sourceFile.fileName, specifier: specifierArg.text })) {
234
+ violations.push(makeViolation({
235
+ message: `mock.module("${specifierArg.text}") targets a shared barrel directly; use a helper that registers every specifier the barrel resolves under.`,
236
+ node,
237
+ ruleId: "no-direct-barrel-mock",
238
+ sourceFile,
239
+ }));
240
+ }
241
+ });
242
+ return violations;
243
+ };
244
+ /** Whether `node` is `setTimeout(resolve, N)` (optionally as a statement or return value). */
245
+ const isSetTimeoutOnResolve = ({ node, resolveName, }) => {
246
+ let expr = node;
247
+ if (typescript_1.default.isExpressionStatement(node)) {
248
+ expr = node.expression;
249
+ }
250
+ else if (typescript_1.default.isReturnStatement(node) && node.expression) {
251
+ expr = node.expression;
252
+ }
253
+ if (!typescript_1.default.isCallExpression(expr) ||
254
+ !typescript_1.default.isIdentifier(expr.expression) ||
255
+ expr.expression.text !== "setTimeout") {
256
+ return false;
257
+ }
258
+ const [firstArg] = expr.arguments;
259
+ return Boolean(firstArg && typescript_1.default.isIdentifier(firstArg) && firstArg.text === resolveName);
260
+ };
261
+ /** Whether `node` is `new Promise((resolve) => setTimeout(resolve, N))` with no other logic. */
262
+ const isBareSleepPromise = (node) => {
263
+ if (!typescript_1.default.isNewExpression(node) ||
264
+ !typescript_1.default.isIdentifier(node.expression) ||
265
+ node.expression.text !== "Promise") {
266
+ return false;
267
+ }
268
+ const [executor] = node.arguments ?? [];
269
+ if (!executor || !(typescript_1.default.isArrowFunction(executor) || typescript_1.default.isFunctionExpression(executor))) {
270
+ return false;
271
+ }
272
+ const [resolveParam] = executor.parameters;
273
+ if (!resolveParam || !typescript_1.default.isIdentifier(resolveParam.name)) {
274
+ return false;
275
+ }
276
+ const statements = typescript_1.default.isBlock(executor.body)
277
+ ? executor.body.statements
278
+ : [executor.body];
279
+ return (statements.length === 1 &&
280
+ isSetTimeoutOnResolve({ node: statements[0], resolveName: resolveParam.name.text }));
281
+ };
282
+ /** Returns `a.b.c` for identifier/property-access callees, otherwise undefined. */
283
+ const getCalleeText = (expr) => {
284
+ if (typescript_1.default.isIdentifier(expr)) {
285
+ return expr.text;
286
+ }
287
+ if (typescript_1.default.isPropertyAccessExpression(expr)) {
288
+ const left = getCalleeText(expr.expression);
289
+ return left ? `${left}.${expr.name.text}` : undefined;
290
+ }
291
+ return undefined;
292
+ };
293
+ const findSleepViolations = ({ sourceFile, config }) => {
294
+ const sleepCallees = new Set(config.sleepCallees ?? exports.DEFAULT_SLEEP_CALLEES);
295
+ const violations = [];
296
+ walk(sourceFile, (node) => {
297
+ if (isBareSleepPromise(node)) {
298
+ violations.push(makeViolation({
299
+ message: "Bare setTimeout sleep; poll the actual condition (e.g. waitFor) instead.",
300
+ node,
301
+ ruleId: "no-sleep",
302
+ sourceFile,
303
+ }));
304
+ return;
305
+ }
306
+ if (!typescript_1.default.isCallExpression(node)) {
307
+ return;
308
+ }
309
+ const callee = getCalleeText(node.expression);
310
+ if (callee && sleepCallees.has(callee)) {
311
+ violations.push(makeViolation({
312
+ message: `${callee}() sleeps for a fixed time; poll the actual condition (e.g. waitFor) instead.`,
313
+ node,
314
+ ruleId: "no-sleep",
315
+ sourceFile,
316
+ }));
317
+ }
318
+ });
319
+ return violations;
320
+ };
321
+ /** Whether a string/template/concatenation expression contains a literal `?`. */
322
+ const containsQuestionMark = (node) => {
323
+ if (typescript_1.default.isStringLiteralLike(node)) {
324
+ return node.text.includes("?");
325
+ }
326
+ if (typescript_1.default.isTemplateExpression(node)) {
327
+ return (node.head.text.includes("?") ||
328
+ node.templateSpans.some((span) => span.literal.text.includes("?")));
329
+ }
330
+ if (typescript_1.default.isBinaryExpression(node)) {
331
+ return containsQuestionMark(node.left) || containsQuestionMark(node.right);
332
+ }
333
+ if (typescript_1.default.isParenthesizedExpression(node)) {
334
+ return containsQuestionMark(node.expression);
335
+ }
336
+ return false;
337
+ };
338
+ const isDynamicImportCall = (node) => typescript_1.default.isCallExpression(node) && node.expression.kind === typescript_1.default.SyntaxKind.ImportKeyword;
339
+ const isRequireCall = (node) => typescript_1.default.isCallExpression(node) &&
340
+ typescript_1.default.isIdentifier(node.expression) &&
341
+ node.expression.text === "require";
342
+ const findCacheBustedImportViolations = ({ sourceFile }) => {
343
+ const violations = [];
344
+ walk(sourceFile, (node) => {
345
+ if (!isDynamicImportCall(node)) {
346
+ return;
347
+ }
348
+ const [arg] = node.arguments;
349
+ if (arg && containsQuestionMark(arg)) {
350
+ violations.push(makeViolation({
351
+ message: "Dynamic import specifier contains a cache-busting '?'; module identity must stay stable for mock.module to apply.",
352
+ node,
353
+ ruleId: "no-cache-busted-import",
354
+ sourceFile,
355
+ }));
356
+ }
357
+ });
358
+ return violations;
359
+ };
360
+ const getMockFactory = ({ node, mockHelperNames, }) => {
361
+ let factory;
362
+ if (isMockModuleCall(node)) {
363
+ factory = node.arguments[1];
364
+ }
365
+ else if (typescript_1.default.isCallExpression(node) &&
366
+ typescript_1.default.isIdentifier(node.expression) &&
367
+ mockHelperNames.has(node.expression.text)) {
368
+ factory = node.arguments[0];
369
+ }
370
+ if (factory && (typescript_1.default.isArrowFunction(factory) || typescript_1.default.isFunctionExpression(factory))) {
371
+ return factory;
372
+ }
373
+ return undefined;
374
+ };
375
+ const findLateRealCaptureViolations = ({ sourceFile, config, mockHelperNames, }) => {
376
+ const getterNames = collectNamedImportsFrom({
377
+ modules: config.realExportGetterModules ?? [],
378
+ namePattern: config.realExportGetterNamePattern
379
+ ? new RegExp(config.realExportGetterNamePattern, "u")
380
+ : undefined,
381
+ sourceFile,
382
+ });
383
+ const violations = [];
384
+ const checkFactoryNode = (node) => {
385
+ if (isRequireCall(node) || isDynamicImportCall(node)) {
386
+ const [specifierArg] = node.arguments;
387
+ if (specifierArg &&
388
+ typescript_1.default.isStringLiteralLike(specifierArg) &&
389
+ (0, exports.resolvesToBarrel)({ config, fromFile: sourceFile.fileName, specifier: specifierArg.text })) {
390
+ violations.push(makeViolation({
391
+ message: `Captures the real "${specifierArg.text}" barrel inside a mock factory; capture it at module scope before mock registration instead.`,
392
+ node,
393
+ ruleId: "no-late-real-capture",
394
+ sourceFile,
395
+ }));
396
+ }
397
+ return;
398
+ }
399
+ if (typescript_1.default.isCallExpression(node) &&
400
+ typescript_1.default.isIdentifier(node.expression) &&
401
+ getterNames.has(node.expression.text)) {
402
+ violations.push(makeViolation({
403
+ message: `Calls ${node.expression.text}() inside a mock factory; call it at module scope before mock registration instead.`,
404
+ node,
405
+ ruleId: "no-late-real-capture",
406
+ sourceFile,
407
+ }));
408
+ }
409
+ };
410
+ walk(sourceFile, (node) => {
411
+ const factory = getMockFactory({ mockHelperNames, node });
412
+ if (factory) {
413
+ walk(factory.body, checkFactoryNode);
414
+ }
415
+ });
416
+ return violations;
417
+ };
418
+ const addBindingNames = ({ name, out }) => {
419
+ if (typescript_1.default.isIdentifier(name)) {
420
+ out.add(name.text);
421
+ return;
422
+ }
423
+ for (const element of name.elements) {
424
+ if (typescript_1.default.isBindingElement(element)) {
425
+ addBindingNames({ name: element.name, out });
426
+ }
427
+ }
428
+ };
429
+ /** Names bound to module imports: static imports plus `const {X} = await import()/require()`. */
430
+ const collectImportedNames = (sourceFile) => {
431
+ const importedNames = new Set();
432
+ walk(sourceFile, (node) => {
433
+ if (typescript_1.default.isImportDeclaration(node) && node.importClause) {
434
+ const { importClause } = node;
435
+ if (importClause.name) {
436
+ importedNames.add(importClause.name.text);
437
+ }
438
+ const bindings = importClause.namedBindings;
439
+ if (bindings && typescript_1.default.isNamedImports(bindings)) {
440
+ for (const element of bindings.elements) {
441
+ importedNames.add(element.name.text);
442
+ }
443
+ }
444
+ else if (bindings && typescript_1.default.isNamespaceImport(bindings)) {
445
+ importedNames.add(bindings.name.text);
446
+ }
447
+ return;
448
+ }
449
+ if (typescript_1.default.isVariableDeclaration(node) && node.initializer) {
450
+ const init = typescript_1.default.isAwaitExpression(node.initializer)
451
+ ? node.initializer.expression
452
+ : node.initializer;
453
+ if (isDynamicImportCall(init) || isRequireCall(init)) {
454
+ addBindingNames({ name: node.name, out: importedNames });
455
+ }
456
+ }
457
+ });
458
+ return importedNames;
459
+ };
460
+ const findComponentSnapshotViolations = ({ sourceFile }) => {
461
+ const importedNames = collectImportedNames(sourceFile);
462
+ const violations = [];
463
+ walk(sourceFile, (node) => {
464
+ if (!typescript_1.default.isCallExpression(node) ||
465
+ !typescript_1.default.isPropertyAccessExpression(node.expression) ||
466
+ node.expression.name.text !== "toMatchSnapshot") {
467
+ return;
468
+ }
469
+ const receiver = node.expression.expression;
470
+ if (!typescript_1.default.isCallExpression(receiver) ||
471
+ !typescript_1.default.isIdentifier(receiver.expression) ||
472
+ receiver.expression.text !== "expect") {
473
+ return;
474
+ }
475
+ const [arg] = receiver.arguments;
476
+ if (arg && typescript_1.default.isIdentifier(arg) && importedNames.has(arg.text)) {
477
+ violations.push(makeViolation({
478
+ message: `expect(${arg.text}).toMatchSnapshot() snapshots the imported reference, not rendered output; render it first.`,
479
+ node,
480
+ ruleId: "no-component-snapshot",
481
+ sourceFile,
482
+ }));
483
+ }
484
+ });
485
+ return violations;
486
+ };
487
+ const RULES = {
488
+ "no-cache-busted-import": findCacheBustedImportViolations,
489
+ "no-component-snapshot": findComponentSnapshotViolations,
490
+ "no-direct-barrel-mock": findDirectBarrelMockViolations,
491
+ "no-late-real-capture": findLateRealCaptureViolations,
492
+ "no-module-scope-mock-module": findModuleScopeMockViolations,
493
+ "no-sleep": findSleepViolations,
494
+ };
495
+ /**
496
+ * Runs the enabled rules against one parsed file. Pure and filesystem free. Returned violations
497
+ * carry the root-relative path and are not yet suppression filtered.
498
+ */
499
+ const runHygieneRules = ({ fileName, sourceText, config, rules = exports.HYGIENE_RULE_IDS, }) => {
500
+ const isJsx = /\.[jt]sx$/u.test(fileName);
501
+ const sourceFile = typescript_1.default.createSourceFile(fileName, sourceText, typescript_1.default.ScriptTarget.Latest, true, isJsx ? typescript_1.default.ScriptKind.TSX : typescript_1.default.ScriptKind.TS);
502
+ const context = {
503
+ config,
504
+ mockHelperNames: collectNamedImportsFrom({
505
+ modules: config.mockHelperModules ?? [],
506
+ sourceFile,
507
+ }),
508
+ relativeFile: (0, collectFiles_1.toPosixPath)(node_path_1.default.relative(config.rootDir, fileName)),
509
+ sourceFile,
510
+ };
511
+ const violations = rules
512
+ .flatMap((ruleId) => RULES[ruleId](context))
513
+ .map((violation) => ({ ...violation, file: context.relativeFile }))
514
+ .sort((a, b) => a.line - b.line || a.ruleId.localeCompare(b.ruleId));
515
+ return { violations };
516
+ };
517
+ exports.runHygieneRules = runHygieneRules;
@@ -0,0 +1,155 @@
1
+ /** Process granularity for the files in one shard. */
2
+ declare const PROCESS_PER: {
3
+ readonly dir: "dir";
4
+ readonly file: "file";
5
+ readonly shard: "shard";
6
+ };
7
+ export type ProcessPer = (typeof PROCESS_PER)[keyof typeof PROCESS_PER];
8
+ interface WeightedFile {
9
+ file: string;
10
+ weight: number;
11
+ }
12
+ export interface Shard {
13
+ files: string[];
14
+ weight: number;
15
+ }
16
+ export interface ProcessGroup {
17
+ /** Label for progress and summary output. */
18
+ name: string;
19
+ /** `cwd`-relative POSIX paths run together in one `bun test` process. */
20
+ files: string[];
21
+ }
22
+ interface ProcessGroupResult {
23
+ group: ProcessGroup;
24
+ success: boolean;
25
+ durationMs: number;
26
+ }
27
+ export interface RunProcessGroupsOutcome {
28
+ results: ProcessGroupResult[];
29
+ /** Groups never started because an earlier group failed under `failFast`. */
30
+ skipped: ProcessGroup[];
31
+ allPassed: boolean;
32
+ }
33
+ /** Runs one command to completion and reports its exit code. Injectable for tests. */
34
+ export type SpawnCommand = (options: {
35
+ cmd: string[];
36
+ cwd: string;
37
+ }) => {
38
+ exitCode: number;
39
+ };
40
+ export interface CliLogger {
41
+ info: (message: string) => void;
42
+ error: (message: string) => void;
43
+ }
44
+ /** Counts `it(`/`test(` calls (including `.only`, `.each`, etc.) that start a line. */
45
+ export declare const countTests: ({ source }: {
46
+ source: string;
47
+ }) => {
48
+ testCount: number;
49
+ };
50
+ /** Estimates a file's relative runtime as `lines + linesPerTest * testCount`. */
51
+ export declare const estimateTestWeight: ({ source, linesPerTest, }: {
52
+ source: string;
53
+ linesPerTest?: number;
54
+ }) => {
55
+ weight: number;
56
+ };
57
+ /**
58
+ * Assigns files to `total` shards, heaviest first, always filling the lightest shard next. Ties
59
+ * break on file name and lowest shard index so every CI node computes the same assignment.
60
+ */
61
+ export declare const buildShards: ({ files, total }: {
62
+ files: WeightedFile[];
63
+ total: number;
64
+ }) => Shard[];
65
+ /** Parses a 1-based `<index>/<total>` shard spec such as `2/4`. */
66
+ export declare const parseShardSpec: ({ spec, }: {
67
+ spec: string;
68
+ }) => {
69
+ index: number;
70
+ total: number;
71
+ } | {
72
+ error: string;
73
+ };
74
+ /**
75
+ * Splits one shard's files into `bun test` processes. Files matching an `isolate` glob always get
76
+ * a process of their own; the rest share one process (`shard`), one per directory prefix of
77
+ * `dirDepth` segments (`dir`), or one each (`file`).
78
+ */
79
+ export declare const planProcessGroups: ({ files, processPer, isolate, dirDepth, }: {
80
+ files: string[];
81
+ processPer?: ProcessPer;
82
+ isolate?: readonly string[];
83
+ dirDepth?: number;
84
+ }) => ProcessGroup[];
85
+ /**
86
+ * Builds the `bun test` argv for a group. Paths are `./`-prefixed because Bun treats bare
87
+ * positional arguments as substring filters (a bare `tests` also matches every `__tests__`).
88
+ */
89
+ export declare const buildBunTestCommand: ({ files, bunArgs, }: {
90
+ files: string[];
91
+ bunArgs?: readonly string[];
92
+ }) => {
93
+ cmd: string[];
94
+ };
95
+ /** Runs each group in its own `bun test` process, optionally stopping at the first failure. */
96
+ export declare const runProcessGroups: ({ groups, cwd, bunArgs, failFast, spawn, logger, }: {
97
+ groups: ProcessGroup[];
98
+ cwd: string;
99
+ bunArgs?: readonly string[];
100
+ failFast?: boolean;
101
+ spawn?: SpawnCommand;
102
+ logger?: CliLogger;
103
+ }) => RunProcessGroupsOutcome;
104
+ /** Formats the PASS/FAIL/SKIP block printed after a multi-process run. */
105
+ export declare const formatRunSummary: ({ results, skipped }: RunProcessGroupsOutcome) => {
106
+ text: string;
107
+ };
108
+ /** Reads newline-separated globs, ignoring blank lines and `#` comments. */
109
+ export declare const parseGlobList: ({ text }: {
110
+ text: string;
111
+ }) => {
112
+ globs: string[];
113
+ };
114
+ export interface TestShardCliOptions {
115
+ shard: {
116
+ index: number;
117
+ total: number;
118
+ };
119
+ paths: string[];
120
+ patterns: string[];
121
+ exclude: string[];
122
+ excludeDirs: string[];
123
+ isolate: string[];
124
+ isolateFiles: string[];
125
+ processPer: ProcessPer;
126
+ dirDepth: number;
127
+ linesPerTest: number;
128
+ isListOnly: boolean;
129
+ failFast: boolean;
130
+ cwd: string;
131
+ bunArgs: string[];
132
+ isHelp: boolean;
133
+ }
134
+ /** Parses CLI arguments; returns `{error}` with a message on invalid input. */
135
+ export declare const parseTestShardArgs: ({ argv, cwd, }: {
136
+ argv: string[];
137
+ cwd: string;
138
+ }) => {
139
+ options: TestShardCliOptions;
140
+ } | {
141
+ error: string;
142
+ };
143
+ /**
144
+ * CLI entry point: discovers files, balances them into shards, prints the selected shard, and
145
+ * (unless `--list`) runs it. Returns the process exit code instead of exiting so it is testable.
146
+ */
147
+ export declare const runTestShardCli: ({ argv, cwd, spawn, logger, }: {
148
+ argv: string[];
149
+ cwd?: string;
150
+ spawn?: SpawnCommand;
151
+ logger?: CliLogger;
152
+ }) => {
153
+ exitCode: number;
154
+ };
155
+ export {};