@interfere/landmines 0.0.0-stage → 0.1.0

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,1481 @@
1
+ import { definePlugin, defineRule } from "@oxlint/plugins";
2
+ import { z } from "zod";
3
+ // src/lib/allowlist.ts
4
+ const allowlistSchema = [{
5
+ type: "object",
6
+ properties: { allow: {
7
+ type: "object",
8
+ additionalProperties: {
9
+ type: "integer",
10
+ minimum: 1
11
+ }
12
+ } },
13
+ additionalProperties: false
14
+ }];
15
+ const allowlistOptions = z.tuple([z.object({ allow: z.record(z.string(), z.int().min(1)) })]).or(z.tuple([]));
16
+ function allowance(context) {
17
+ const filename = context.physicalFilename.replaceAll("\\", "/");
18
+ const [options] = allowlistOptions.parse(context.options);
19
+ return Object.entries(options?.allow ?? {}).find(([path]) => filename === path || filename.endsWith(`/${path}`));
20
+ }
21
+ function reportAllowed(context, program, violations, messageId) {
22
+ const [path, count] = allowance(context) ?? ["", 0];
23
+ if (violations.length < count) {
24
+ context.report({
25
+ node: program,
26
+ messageId: "stale",
27
+ data: {
28
+ path,
29
+ count: String(violations.length)
30
+ }
31
+ });
32
+ return;
33
+ }
34
+ if (violations.length === count) return;
35
+ for (const node of violations) context.report({
36
+ node,
37
+ messageId
38
+ });
39
+ }
40
+ // src/rules/no-fixed-sleep.ts
41
+ const testCallees = /* @__PURE__ */ new Set([
42
+ "test",
43
+ "it",
44
+ "beforeEach",
45
+ "afterEach",
46
+ "beforeAll",
47
+ "afterAll"
48
+ ]);
49
+ const timerModules = /* @__PURE__ */ new Set(["node:timers/promises", "timers/promises"]);
50
+ function isMember(node, object, property) {
51
+ return node.type === "MemberExpression" && node.object.type === "Identifier" && node.object.name === object && node.property.type === "Identifier" && !node.computed && node.property.name === property;
52
+ }
53
+ function isSetTimeout(node) {
54
+ return node.type === "Identifier" && node.name === "setTimeout" || isMember(node, "globalThis", "setTimeout") || isMember(node, "window", "setTimeout");
55
+ }
56
+ const calleeRoot = (node) => {
57
+ if (node.type === "CallExpression") return calleeRoot(node.callee);
58
+ if (node.type === "MemberExpression") return calleeRoot(node.object);
59
+ if (node.type === "TaggedTemplateExpression") return calleeRoot(node.tag);
60
+ return node.type === "Identifier" ? node.name : void 0;
61
+ };
62
+ function inTestBody(node) {
63
+ let current = node.parent;
64
+ while (current && current.type !== "ArrowFunctionExpression" && current.type !== "FunctionExpression" && current.type !== "FunctionDeclaration") current = current.parent;
65
+ const call = current?.parent;
66
+ return call?.type === "CallExpression" && testCallees.has(calleeRoot(call.callee) ?? "");
67
+ }
68
+ function scheduled(body) {
69
+ if (body?.type !== "BlockStatement") return body;
70
+ const [statement, ...rest] = body.body;
71
+ return statement?.type === "ExpressionStatement" && rest.length === 0 ? statement.expression : null;
72
+ }
73
+ function resolvesAfterTimeout(node) {
74
+ const [executor] = node.arguments;
75
+ if (!executor || executor.type !== "ArrowFunctionExpression" && executor.type !== "FunctionExpression") return false;
76
+ const [resolve] = executor.params;
77
+ if (resolve?.type !== "Identifier") return false;
78
+ const call = scheduled(executor.body);
79
+ if (call?.type !== "CallExpression" || !isSetTimeout(call.callee)) return false;
80
+ const [handler] = call.arguments;
81
+ if (handler?.type === "Identifier") return handler.name === resolve.name;
82
+ return handler?.type === "ArrowFunctionExpression" && handler.body.type === "CallExpression" && handler.body.callee.type === "Identifier" && handler.body.callee.name === resolve.name;
83
+ }
84
+ const noFixedSleep = defineRule({
85
+ meta: {
86
+ type: "problem",
87
+ schema: allowlistSchema,
88
+ docs: { description: "Disallow awaiting a fixed real-time sleep in a test or hook body." },
89
+ messages: {
90
+ sleep: "Replace this fixed sleep with a signal: await the operation itself or a promise its handler resolves. To move time, use vi.useFakeTimers() and advance it. A sleep guesses how long real work takes and fails under CPU load.",
91
+ stale: "This file now has {{count}} fixed sleeps; lower its no-fixed-sleep allowlist entry for {{path}} in .oxlintrc.jsonc to {{count}}, or remove the entry at 0."
92
+ }
93
+ },
94
+ create(context) {
95
+ const timers = /* @__PURE__ */ new Set();
96
+ const sleeps = [];
97
+ let fakeTimers = false;
98
+ function isSleep(node) {
99
+ if (node.type === "NewExpression") return node.callee.type === "Identifier" && node.callee.name === "Promise" && resolvesAfterTimeout(node);
100
+ if (node.type !== "CallExpression") return false;
101
+ return node.callee.type === "Identifier" && timers.has(node.callee.name) || isMember(node.callee, "scheduler", "wait") || isMember(node.callee, "Bun", "sleep");
102
+ }
103
+ return {
104
+ ImportDeclaration(node) {
105
+ if (!timerModules.has(node.source.value)) return;
106
+ for (const specifier of node.specifiers) if (specifier.type === "ImportSpecifier" && specifier.imported.type === "Identifier" && specifier.imported.name === "setTimeout") timers.add(specifier.local.name);
107
+ },
108
+ CallExpression(node) {
109
+ if (isMember(node.callee, "vi", "useFakeTimers")) fakeTimers = true;
110
+ },
111
+ AwaitExpression(node) {
112
+ if (isSleep(node.argument) && inTestBody(node)) sleeps.push(node);
113
+ },
114
+ "Program:exit"(program) {
115
+ reportAllowed(context, program, fakeTimers ? [] : sleeps, "sleep");
116
+ }
117
+ };
118
+ }
119
+ });
120
+ // src/rules/no-flake-masking.ts
121
+ const testFunctions = /* @__PURE__ */ new Set([
122
+ "test",
123
+ "it",
124
+ "describe",
125
+ "suite"
126
+ ]);
127
+ const configTimeouts = /* @__PURE__ */ new Set(["testTimeout", "hookTimeout"]);
128
+ const testTimeouts = /* @__PURE__ */ new Set(["timeout"]);
129
+ function keyName(property) {
130
+ if (property.type !== "Property" || property.computed) return null;
131
+ if (property.key.type === "Identifier") return property.key.name;
132
+ return property.key.type === "Literal" ? String(property.key.value) : null;
133
+ }
134
+ function rootName(initial) {
135
+ let node = initial;
136
+ while (node.type === "MemberExpression" || node.type === "CallExpression") node = node.type === "MemberExpression" ? node.object : node.callee;
137
+ return node.type === "Identifier" ? node.name : null;
138
+ }
139
+ function memberName(node) {
140
+ return node.type === "MemberExpression" && !node.computed && node.property.type === "Identifier" ? node.property.name : null;
141
+ }
142
+ function testCall(node) {
143
+ const name = rootName(node.callee);
144
+ const member = memberName(node.callee);
145
+ return name !== null && testFunctions.has(name) && member !== "each" && member !== "for" && member !== "extend" && member !== "scoped" && member !== "override";
146
+ }
147
+ function configCall(node) {
148
+ return node.callee.type === "MemberExpression" && node.callee.object.type === "Identifier" && node.callee.object.name === "vi" && memberName(node.callee) === "setConfig";
149
+ }
150
+ const noFlakeMasking = defineRule({
151
+ meta: {
152
+ type: "problem",
153
+ schema: allowlistSchema,
154
+ docs: { description: "Fix flaky tests at their cause instead of retrying them or raising their timeouts." },
155
+ messages: {
156
+ retry: "Do not retry tests. A test that passes on rerun is a flake: wait on the event it depends on and file the failure under the flaky-test tracker.",
157
+ timeout: "Do not raise a test's timeout. Wait on the event the test depends on, or move slow shared setup into a beforeAll hook.",
158
+ stale: "This file now has {{count}} test timeout bumps; lower its no-flake-masking allowlist entry for {{path}} in .oxlintrc.jsonc to {{count}}, or remove the entry at 0."
159
+ }
160
+ },
161
+ create(context) {
162
+ const timeouts = [];
163
+ function inspect(node, keys) {
164
+ if (node?.type !== "ObjectExpression") return;
165
+ for (const property of node.properties) {
166
+ const key = keyName(property);
167
+ if (key === "retry") context.report({
168
+ node: property,
169
+ messageId: "retry"
170
+ });
171
+ else if (key !== null && keys.has(key)) timeouts.push(property);
172
+ }
173
+ }
174
+ return {
175
+ CallExpression(node) {
176
+ if (configCall(node)) {
177
+ inspect(node.arguments[0], configTimeouts);
178
+ return;
179
+ }
180
+ if (!testCall(node)) return;
181
+ const [, second, third] = node.arguments;
182
+ inspect(second, testTimeouts);
183
+ inspect(third, testTimeouts);
184
+ if (third !== void 0 && second?.type !== "ObjectExpression" && third.type !== "ObjectExpression" && third.type !== "ArrowFunctionExpression" && third.type !== "FunctionExpression") timeouts.push(third);
185
+ },
186
+ "Program:exit"(program) {
187
+ reportAllowed(context, program, timeouts, "timeout");
188
+ },
189
+ Property(node) {
190
+ if (keyName(node) === "test" && node.value.type === "ObjectExpression") {
191
+ for (const property of node.value.properties) if (keyName(property) === "retry") context.report({
192
+ node: property,
193
+ messageId: "retry"
194
+ });
195
+ }
196
+ }
197
+ };
198
+ }
199
+ });
200
+ // src/rules/no-test-doubles.ts
201
+ const replacements = /* @__PURE__ */ new Set([
202
+ "mockImplementation",
203
+ "mockImplementationOnce",
204
+ "mockReturnValue",
205
+ "mockReturnValueOnce",
206
+ "mockResolvedValue",
207
+ "mockResolvedValueOnce",
208
+ "mockRejectedValue",
209
+ "mockRejectedValueOnce",
210
+ "mockReturnThis",
211
+ "withImplementation",
212
+ "mockStepResult",
213
+ "mockStepError"
214
+ ]);
215
+ const tauriMockMethods = /* @__PURE__ */ new Set([
216
+ "mockIPC",
217
+ "mockWindows",
218
+ "mockConvertFileSrc"
219
+ ]);
220
+ const frameworkReplacements = /* @__PURE__ */ new Set([
221
+ "stubGlobal",
222
+ "mock",
223
+ "doMock",
224
+ "unstable_mockModule",
225
+ "importMock",
226
+ "mockObject",
227
+ "createMockFromModule",
228
+ "genMockFromModule",
229
+ "setMock",
230
+ "replaceProperty",
231
+ "enableAutomock"
232
+ ]);
233
+ const replacementGlobals = /* @__PURE__ */ new Set([
234
+ "AbortController",
235
+ "AbortSignal",
236
+ "fetch",
237
+ "isTauri",
238
+ "__TAURI_INTERNALS__",
239
+ "document",
240
+ "CSS",
241
+ "scrollTo",
242
+ "scrollBy",
243
+ "visualViewport",
244
+ "addEventListener",
245
+ "removeEventListener",
246
+ "dispatchEvent",
247
+ "CompressionStream",
248
+ "DecompressionStream",
249
+ "Worker",
250
+ "SharedWorker",
251
+ "WebSocket",
252
+ "XMLHttpRequest",
253
+ "ResizeObserver",
254
+ "IntersectionObserver",
255
+ "MutationObserver",
256
+ "requestIdleCallback",
257
+ "cancelIdleCallback",
258
+ "requestAnimationFrame",
259
+ "cancelAnimationFrame",
260
+ "localStorage",
261
+ "sessionStorage",
262
+ "navigator",
263
+ "Notification",
264
+ "matchMedia",
265
+ "open",
266
+ "performance",
267
+ "screen",
268
+ "crypto",
269
+ "Date",
270
+ "FileReader",
271
+ "BroadcastChannel",
272
+ "innerWidth",
273
+ "innerHeight",
274
+ "devicePixelRatio"
275
+ ]);
276
+ const documentReplacements = /* @__PURE__ */ new Set([
277
+ "querySelector",
278
+ "querySelectorAll",
279
+ "getElementById",
280
+ "createElement",
281
+ "addEventListener",
282
+ "removeEventListener",
283
+ "dispatchEvent",
284
+ "visibilityState",
285
+ "hidden",
286
+ "hasFocus",
287
+ "modelContext"
288
+ ]);
289
+ const navigatorReplacements = /* @__PURE__ */ new Set([
290
+ "clipboard",
291
+ "permissions",
292
+ "storage",
293
+ "serviceWorker",
294
+ "gpu",
295
+ "credentials",
296
+ "userAgent",
297
+ "userAgentData",
298
+ "webdriver",
299
+ "platform",
300
+ "onLine",
301
+ "modelContext"
302
+ ]);
303
+ const storageReplacements = /* @__PURE__ */ new Set([
304
+ "getItem",
305
+ "setItem",
306
+ "removeItem",
307
+ "clear",
308
+ "key",
309
+ "length"
310
+ ]);
311
+ const nestedReplacements = /* @__PURE__ */ new Map([
312
+ ["FileReader.prototype", /* @__PURE__ */ new Set([
313
+ "abort",
314
+ "readAsArrayBuffer",
315
+ "readAsBinaryString",
316
+ "readAsDataURL",
317
+ "readAsText"
318
+ ])],
319
+ ["IntersectionObserver.prototype", /* @__PURE__ */ new Set([
320
+ "observe",
321
+ "unobserve",
322
+ "disconnect",
323
+ "takeRecords"
324
+ ])],
325
+ ["ResizeObserver.prototype", /* @__PURE__ */ new Set([
326
+ "observe",
327
+ "unobserve",
328
+ "disconnect"
329
+ ])],
330
+ ["MutationObserver.prototype", /* @__PURE__ */ new Set([
331
+ "observe",
332
+ "disconnect",
333
+ "takeRecords"
334
+ ])],
335
+ ["AbortController.prototype", /* @__PURE__ */ new Set(["abort", "signal"])],
336
+ ["AbortSignal", /* @__PURE__ */ new Set([
337
+ "abort",
338
+ "any",
339
+ "timeout"
340
+ ])],
341
+ ["AbortSignal.prototype", /* @__PURE__ */ new Set([
342
+ "aborted",
343
+ "reason",
344
+ "throwIfAborted"
345
+ ])],
346
+ ["Date", /* @__PURE__ */ new Set(["now"])],
347
+ ["Math", /* @__PURE__ */ new Set(["random"])],
348
+ ["performance", /* @__PURE__ */ new Set(["now"])],
349
+ ["crypto", /* @__PURE__ */ new Set(["randomUUID", "getRandomValues"])],
350
+ ["history", /* @__PURE__ */ new Set([
351
+ "pushState",
352
+ "replaceState",
353
+ "go",
354
+ "back",
355
+ "forward"
356
+ ])],
357
+ ["Storage.prototype", storageReplacements],
358
+ ["localStorage", storageReplacements],
359
+ ["sessionStorage", storageReplacements],
360
+ ["navigator.clipboard", /* @__PURE__ */ new Set([
361
+ "read",
362
+ "readText",
363
+ "write",
364
+ "writeText"
365
+ ])],
366
+ ["navigator.credentials", /* @__PURE__ */ new Set([
367
+ "get",
368
+ "create",
369
+ "store",
370
+ "preventSilentAccess"
371
+ ])],
372
+ ["navigator.permissions", /* @__PURE__ */ new Set(["query"])],
373
+ ["navigator.storage", /* @__PURE__ */ new Set([
374
+ "estimate",
375
+ "persist",
376
+ "persisted",
377
+ "getDirectory"
378
+ ])],
379
+ ["navigator.userAgentData", /* @__PURE__ */ new Set(["getHighEntropyValues", "toJSON"])]
380
+ ]);
381
+ function propertyName$1(source, node) {
382
+ if (node.type !== "MemberExpression") return null;
383
+ if (!node.computed && node.property.type === "Identifier") return node.property.name;
384
+ return node.computed ? literalKey(source, node.property) : null;
385
+ }
386
+ function initializedOnce(variable) {
387
+ return variable.defs.length === 1 && variable.references.every((reference) => !reference.isWrite() || reference.init);
388
+ }
389
+ function constantValue(source, node) {
390
+ if (node.type !== "Identifier") return null;
391
+ for (let scope = source.getScope(node); scope !== null; scope = scope.upper) {
392
+ const variable = scope.set.get(node.name);
393
+ if (!variable || variable.defs.length === 0) continue;
394
+ for (const { node: definition, parent, type } of variable.defs) {
395
+ if (type === "FunctionName" && definition.type === "FunctionDeclaration" && initializedOnce(variable)) return definition;
396
+ if (definition.type === "VariableDeclarator" && definition.id.type === "Identifier" && parent?.type === "VariableDeclaration" && initializedOnce(variable)) return definition.init;
397
+ }
398
+ break;
399
+ }
400
+ return null;
401
+ }
402
+ function lexicalVariable(source, node) {
403
+ if (node.type !== "Identifier") return null;
404
+ for (let scope = source.getScope(node); scope !== null; scope = scope.upper) {
405
+ const variable = scope.set.get(node.name);
406
+ if (variable) return variable;
407
+ }
408
+ return null;
409
+ }
410
+ function sameMember(source, left, right) {
411
+ let first = resolvedConstant(source, left);
412
+ let second = resolvedConstant(source, right);
413
+ const seen = /* @__PURE__ */ new Set();
414
+ while (!seen.has(first)) {
415
+ seen.add(first);
416
+ if (first === second) return true;
417
+ if (first.type === "Identifier" && second.type === "Identifier") return first.name === second.name && lexicalVariable(source, first) === lexicalVariable(source, second);
418
+ if (first.type !== "MemberExpression" || second.type !== "MemberExpression") return false;
419
+ const key = propertyName$1(source, first);
420
+ if (key === null || key !== propertyName$1(source, second)) return false;
421
+ first = resolvedConstant(source, first.object);
422
+ second = resolvedConstant(source, second.object);
423
+ }
424
+ return false;
425
+ }
426
+ function delegatesSavedMember(source, initial, saved) {
427
+ const node = resolvedConstant(source, initial);
428
+ if (node.type !== "FunctionExpression" && node.type !== "FunctionDeclaration" || node.async || node.generator || node.body?.type !== "BlockStatement") return false;
429
+ const [parameter] = node.params;
430
+ if (node.params.length !== 1 || parameter?.type !== "RestElement" || parameter.argument.type !== "Identifier") return false;
431
+ const statements = node.body.body;
432
+ const last = statements.at(-1);
433
+ if (last?.type !== "ReturnStatement" || statements.slice(0, -1).some((statement) => {
434
+ if (statement.type !== "ExpressionStatement" || statement.expression.type !== "CallExpression") return true;
435
+ const { callee, args } = invokedFunction(source, statement.expression);
436
+ if (callee.type === "MemberExpression" && sameMember(source, callee.object, parameter.argument)) return true;
437
+ const path = nativePropertyPath(source, callee);
438
+ const [target] = args;
439
+ return [
440
+ "Reflect.set",
441
+ "Reflect.defineProperty",
442
+ "Reflect.deleteProperty",
443
+ "Object.assign",
444
+ "Object.defineProperty",
445
+ "Object.defineProperties"
446
+ ].includes(path ?? "") && target !== void 0 && target !== null && sameMember(source, target, parameter.argument);
447
+ })) return false;
448
+ const result = last.argument;
449
+ if (result?.type !== "CallExpression") return false;
450
+ const callee = resolvedConstant(source, result.callee);
451
+ if (callee.type !== "MemberExpression" || propertyName$1(source, callee) !== "apply" || callee.object.type !== "Identifier" || callee.object.name !== "Reflect" || !unshadowed(source, callee.object)) return false;
452
+ const [original, receiver, args] = result.arguments;
453
+ return result.arguments.length === 3 && original?.type === "Identifier" && lexicalVariable(source, original) === saved && receiver?.type === "ThisExpression" && args?.type === "Identifier" && lexicalVariable(source, parameter.argument) === lexicalVariable(source, args);
454
+ }
455
+ function destructuredReference(source, node) {
456
+ if (node.type !== "Identifier") return null;
457
+ for (let scope = source.getScope(node); scope !== null; scope = scope.upper) {
458
+ const variable = scope.set.get(node.name);
459
+ if (!variable || variable.defs.length === 0) continue;
460
+ for (const { node: definition, parent } of variable.defs) {
461
+ if (definition.type !== "VariableDeclarator" || definition.id.type !== "ObjectPattern" || parent?.type !== "VariableDeclaration" || !initializedOnce(variable) || !definition.init) continue;
462
+ const property = definition.id.properties.find((value) => value.type === "Property" && value.value.type === "Identifier" && value.value.name === node.name);
463
+ if (property?.type !== "Property") continue;
464
+ if (!property.computed && property.key.type === "Identifier") return {
465
+ object: definition.init,
466
+ property: property.key.name
467
+ };
468
+ const key = literalKey(source, property.key);
469
+ if (key !== null) return {
470
+ object: definition.init,
471
+ property: key
472
+ };
473
+ }
474
+ break;
475
+ }
476
+ return null;
477
+ }
478
+ function resolvedConstant(source, initial) {
479
+ const visited = /* @__PURE__ */ new Set();
480
+ let node = initial;
481
+ while (!visited.has(node)) {
482
+ visited.add(node);
483
+ if (node.type === "TSAsExpression" || node.type === "TSTypeAssertion" || node.type === "TSNonNullExpression" || node.type === "TSSatisfiesExpression") {
484
+ node = node.expression;
485
+ continue;
486
+ }
487
+ const value = constantValue(source, node);
488
+ if (!value) break;
489
+ node = value;
490
+ }
491
+ return node;
492
+ }
493
+ function literalKey(source, initial) {
494
+ const node = initial ? resolvedConstant(source, initial) : void 0;
495
+ if (node?.type === "TemplateLiteral" && node.expressions.length === 0) return node.quasis[0]?.value.cooked ?? null;
496
+ return node?.type === "Literal" ? String(node.value) : null;
497
+ }
498
+ function namespaceImport(source, initial, specifier) {
499
+ const node = resolvedConstant(source, initial);
500
+ if (node.type !== "Identifier") return false;
501
+ for (let scope = source.getScope(node); scope !== null; scope = scope.upper) {
502
+ const variable = scope.set.get(node.name);
503
+ if (variable === void 0 || variable.defs.length === 0) continue;
504
+ return variable.defs.some(({ node: definition, parent }) => definition.type === "ImportNamespaceSpecifier" && parent?.type === "ImportDeclaration" && (specifier === void 0 ? parent.source.value === "vitest" || parent.source.value === "@jest/globals" : parent.source.value === specifier));
505
+ }
506
+ return false;
507
+ }
508
+ function framework(source, initial) {
509
+ const node = resolvedConstant(source, initial);
510
+ if (node.type === "MemberExpression" && [
511
+ "vi",
512
+ "vitest",
513
+ "jest"
514
+ ].includes(String(propertyName$1(source, node)))) return namespaceImport(source, node.object);
515
+ const reference = destructuredReference(source, node);
516
+ if (reference && [
517
+ "vi",
518
+ "vitest",
519
+ "jest"
520
+ ].includes(reference.property)) return namespaceImport(source, reference.object);
521
+ if (node.type !== "Identifier") return false;
522
+ for (let scope = source.getScope(node); scope !== null; scope = scope.upper) {
523
+ const variable = scope.set.get(node.name);
524
+ if (variable === void 0 || variable.defs.length === 0) continue;
525
+ return variable.defs.some(({ node: definition, parent }) => {
526
+ if (parent?.type !== "ImportDeclaration" || definition.type !== "ImportSpecifier") return false;
527
+ const name = definition.imported.type === "Identifier" ? definition.imported.name : definition.imported.value;
528
+ return parent.source.value === "vitest" && (name === "vi" || name === "vitest") || parent.source.value === "@jest/globals" && name === "jest";
529
+ });
530
+ }
531
+ return [
532
+ "vi",
533
+ "vitest",
534
+ "jest"
535
+ ].includes(node.name);
536
+ }
537
+ function jestFramework(source, callee) {
538
+ const target = resolvedConstant(source, callee);
539
+ if (target.type !== "MemberExpression") return false;
540
+ const node = resolvedConstant(source, target.object);
541
+ if (node.type !== "Identifier") return false;
542
+ for (let scope = source.getScope(node); scope !== null; scope = scope.upper) {
543
+ const variable = scope.set.get(node.name);
544
+ if (variable === void 0 || variable.defs.length === 0) continue;
545
+ return variable.defs.some(({ parent }) => parent?.type === "ImportDeclaration" && parent.source.value === "@jest/globals");
546
+ }
547
+ return node.name === "jest";
548
+ }
549
+ function replacementMethod(source, node) {
550
+ const visited = /* @__PURE__ */ new Set();
551
+ let target = node;
552
+ while (!visited.has(target)) {
553
+ visited.add(target);
554
+ if (target.type === "MemberExpression") {
555
+ const method = propertyName$1(source, target);
556
+ return method !== null && (replacements.has(method) || framework(source, target.object)) ? method : null;
557
+ }
558
+ const reference = destructuredReference(source, target);
559
+ if (reference && (replacements.has(reference.property) || framework(source, reference.object))) return reference.property;
560
+ if (target.type !== "Identifier") return null;
561
+ let initializer;
562
+ for (let scope = source.getScope(target); scope !== null; scope = scope.upper) {
563
+ const variable = scope.set.get(target.name);
564
+ if (!variable || variable.defs.length === 0) continue;
565
+ for (const { node: definition, parent } of variable.defs) {
566
+ if (definition.type !== "VariableDeclarator" || parent?.type !== "VariableDeclaration" || !initializedOnce(variable) || !definition.init) continue;
567
+ if (definition.id.type === "Identifier") {
568
+ initializer = definition.init;
569
+ break;
570
+ }
571
+ if (definition.id.type === "ObjectPattern" && framework(source, definition.init)) {
572
+ const { name } = target;
573
+ const property = definition.id.properties.find((value) => value.type === "Property" && value.value.type === "Identifier" && value.value.name === name);
574
+ if (property?.type === "Property") {
575
+ if (!property.computed && property.key.type === "Identifier") return property.key.name;
576
+ return literalKey(source, property.key);
577
+ }
578
+ }
579
+ }
580
+ break;
581
+ }
582
+ if (!initializer) return null;
583
+ target = initializer;
584
+ }
585
+ return null;
586
+ }
587
+ function globalObject(source, initial) {
588
+ const node = resolvedConstant(source, initial);
589
+ return node.type === "Identifier" && [
590
+ "globalThis",
591
+ "window",
592
+ "global",
593
+ "self"
594
+ ].includes(node.name) && unshadowed(source, node);
595
+ }
596
+ function unshadowed(source, node) {
597
+ if (node.type !== "Identifier") return false;
598
+ for (let scope = source.getScope(node); scope !== null; scope = scope.upper) {
599
+ const variable = scope.set.get(node.name);
600
+ if (variable !== void 0 && variable.defs.length > 0) return false;
601
+ }
602
+ return true;
603
+ }
604
+ function nativePropertyPath(source, initial) {
605
+ let node = resolvedConstant(source, initial);
606
+ const seen = /* @__PURE__ */ new Set();
607
+ const path = [];
608
+ while (!seen.has(node)) {
609
+ seen.add(node);
610
+ const reference = destructuredReference(source, node);
611
+ if (reference) {
612
+ path.unshift(reference.property);
613
+ if (globalObject(source, reference.object)) return path.join(".");
614
+ node = resolvedConstant(source, reference.object);
615
+ continue;
616
+ }
617
+ if (node.type === "Identifier" && unshadowed(source, node)) return [node.name, ...path].join(".");
618
+ if (node.type !== "MemberExpression") return null;
619
+ const property = propertyName$1(source, node);
620
+ if (property === null) return null;
621
+ path.unshift(property);
622
+ if (globalObject(source, node.object)) return path.join(".");
623
+ node = resolvedConstant(source, node.object);
624
+ }
625
+ return null;
626
+ }
627
+ function protectedProperties(source, initial) {
628
+ if (globalObject(source, initial)) return replacementGlobals;
629
+ const name = nativePropertyPath(source, initial);
630
+ if (name === "document" || name === "Document.prototype") return documentReplacements;
631
+ return name === "navigator" || name === "Navigator.prototype" ? navigatorReplacements : nestedReplacements.get(name ?? "");
632
+ }
633
+ function cloudflareImport(source, initial, name, specifier = "cloudflare:workers") {
634
+ const node = resolvedConstant(source, initial);
635
+ if (node.type !== "Identifier") return false;
636
+ for (let scope = source.getScope(node); scope !== null; scope = scope.upper) {
637
+ const variable = scope.set.get(node.name);
638
+ if (variable === void 0 || variable.defs.length === 0) continue;
639
+ return variable.defs.some(({ node: definition, parent }) => definition.type === "ImportSpecifier" && parent?.type === "ImportDeclaration" && parent.source.value === specifier && (definition.imported.type === "Identifier" ? definition.imported.name : definition.imported.value) === name);
640
+ }
641
+ return false;
642
+ }
643
+ function nativeFetchType(source, initial) {
644
+ const pending = [initial];
645
+ const seen = /* @__PURE__ */ new Set();
646
+ while (pending.length > 0) {
647
+ const node = pending.pop();
648
+ if (!node || seen.has(node)) continue;
649
+ seen.add(node);
650
+ if (node.type === "TSTypeQuery") {
651
+ const name = node.exprName;
652
+ if (name.type === "Identifier" && nativePropertyPath(source, name) === "fetch") return true;
653
+ if (name.type === "TSQualifiedName" && name.right.name === "fetch" && globalObject(source, name.left)) return true;
654
+ }
655
+ if (node.type === "TSTypeReference") {
656
+ for (const definition of lexicalVariable(source, node.typeName)?.defs ?? []) if (definition.node.type === "TSTypeAliasDeclaration") pending.push(definition.node.typeAnnotation);
657
+ }
658
+ }
659
+ return false;
660
+ }
661
+ function knockConstructor(source, initial) {
662
+ const specifier = "@knocklabs/node";
663
+ const node = resolvedConstant(source, initial);
664
+ if (cloudflareImport(source, node, "Knock", specifier)) return true;
665
+ const reference = destructuredReference(source, node);
666
+ if (reference) return ["default", "Knock"].includes(reference.property) && namespaceImport(source, reference.object, specifier);
667
+ if (node.type === "MemberExpression") return ["default", "Knock"].includes(propertyName$1(source, node) ?? "") && namespaceImport(source, node.object, specifier);
668
+ return lexicalVariable(source, node)?.defs.some(({ node: definition, parent }) => definition.type === "ImportDefaultSpecifier" && parent?.type === "ImportDeclaration" && parent.source.value === specifier) ?? false;
669
+ }
670
+ const effectiveOption = (source, initial, name, ancestors = /* @__PURE__ */ new Set()) => {
671
+ const node = resolvedConstant(source, initial);
672
+ if (node.type !== "ObjectExpression" || ancestors.has(node)) return null;
673
+ const seen = /* @__PURE__ */ new Set([...ancestors, node]);
674
+ for (const property of node.properties.toReversed()) {
675
+ if (property.type === "SpreadElement") {
676
+ const value = effectiveOption(source, property.argument, name, seen);
677
+ if (value !== false) return value;
678
+ continue;
679
+ }
680
+ const key = !property.computed && property.key.type === "Identifier" ? property.key.name : literalKey(source, property.key);
681
+ if (key === null) return null;
682
+ if (key === name) return property.value;
683
+ }
684
+ return false;
685
+ };
686
+ function tauriMockImport(source, initial) {
687
+ const specifier = "@tauri-apps/api/mocks";
688
+ const node = resolvedConstant(source, initial);
689
+ for (const name of tauriMockMethods) if (cloudflareImport(source, node, name, specifier)) return true;
690
+ if (node.type === "MemberExpression") return tauriMockMethods.has(propertyName$1(source, node) ?? "") && namespaceImport(source, node.object, specifier);
691
+ const reference = destructuredReference(source, node);
692
+ return reference !== null && tauriMockMethods.has(reference.property) && namespaceImport(source, reference.object, specifier);
693
+ }
694
+ function durableParameter(source, node) {
695
+ if (node.type !== "Identifier") return false;
696
+ for (let scope = source.getScope(node); scope !== null; scope = scope.upper) {
697
+ const variable = scope.set.get(node.name);
698
+ if (!variable || variable.defs.length === 0) continue;
699
+ return variable.defs.some((definition) => {
700
+ const callback = definition.node;
701
+ if (definition.type !== "Parameter" || callback.type !== "ArrowFunctionExpression" && callback.type !== "FunctionExpression" || !callback.params.slice(0, 2).some((parameter) => parameter.type === "Identifier" && parameter.name === node.name) || callback.parent.type !== "CallExpression") return false;
702
+ const { callee, args } = invokedFunction(source, callback.parent);
703
+ return args[1] === callback && cloudflareImport(source, callee, "runInDurableObject", "cloudflare:test");
704
+ });
705
+ }
706
+ return false;
707
+ }
708
+ function playwrightType(source, node, names) {
709
+ return lexicalVariable(source, node)?.identifiers.some((identifier) => {
710
+ const annotation = identifier.typeAnnotation?.typeAnnotation;
711
+ return annotation?.type === "TSTypeReference" && [
712
+ "@playwright/test",
713
+ "playwright",
714
+ "playwright-core"
715
+ ].some((specifier) => names.some((name) => cloudflareImport(source, annotation.typeName, name, specifier)));
716
+ }) ?? false;
717
+ }
718
+ function playwrightObject(source, initial) {
719
+ if (playwrightType(source, initial, [
720
+ "Page",
721
+ "BrowserContext",
722
+ "Browser",
723
+ "BrowserType"
724
+ ])) return true;
725
+ const pending = [initial];
726
+ const seen = /* @__PURE__ */ new Set();
727
+ while (pending.length > 0) {
728
+ const current = pending.pop();
729
+ if (!current) continue;
730
+ const node = resolvedConstant(source, current);
731
+ if (seen.has(node)) continue;
732
+ seen.add(node);
733
+ if (playwrightType(source, node, [
734
+ "Page",
735
+ "BrowserContext",
736
+ "Browser",
737
+ "BrowserType"
738
+ ])) return true;
739
+ if ([
740
+ "@playwright/test",
741
+ "playwright",
742
+ "playwright-core"
743
+ ].some((specifier) => [
744
+ "chromium",
745
+ "firefox",
746
+ "webkit"
747
+ ].some((name) => cloudflareImport(source, node, name, specifier)))) return true;
748
+ if (node.type === "AwaitExpression") pending.push(node.argument);
749
+ else if (node.type === "ConditionalExpression") pending.push(node.consequent, node.alternate);
750
+ else if (node.type === "CallExpression") {
751
+ const { callee } = invokedFunction(source, node);
752
+ if (callee.type === "MemberExpression" && [
753
+ "launch",
754
+ "launchPersistentContext",
755
+ "connect",
756
+ "connectOverCDP",
757
+ "newContext",
758
+ "newPage"
759
+ ].includes(propertyName$1(source, callee) ?? "")) pending.push(callee.object);
760
+ }
761
+ }
762
+ return false;
763
+ }
764
+ function playwrightRoute(source, initial) {
765
+ if (playwrightType(source, initial, ["Route"])) return true;
766
+ const variable = lexicalVariable(source, resolvedConstant(source, initial));
767
+ return variable?.defs.some((definition) => {
768
+ const callback = definition.node;
769
+ if (definition.type !== "Parameter" || callback.type !== "ArrowFunctionExpression" && callback.type !== "FunctionExpression" || callback.params[0]?.type !== "Identifier" || lexicalVariable(source, callback.params[0]) !== variable || callback.parent.type !== "CallExpression") return false;
770
+ const { callee, args } = invokedFunction(source, callback.parent);
771
+ return args[1] === callback && callee.type === "MemberExpression" && propertyName$1(source, callee) === "route" && playwrightObject(source, callee.object);
772
+ }) ?? false;
773
+ }
774
+ function staticRouteResponse(source, initial) {
775
+ const pending = [{
776
+ node: initial,
777
+ field: false
778
+ }];
779
+ const seenObjects = /* @__PURE__ */ new Set();
780
+ const seenValues = /* @__PURE__ */ new Set();
781
+ while (pending.length > 0) {
782
+ const next = pending.pop();
783
+ if (!next) continue;
784
+ const node = resolvedConstant(source, next.node);
785
+ const seen = next.field ? seenValues : seenObjects;
786
+ if (seen.has(node)) continue;
787
+ seen.add(node);
788
+ if (node.type === "ConditionalExpression") {
789
+ pending.push({
790
+ node: node.consequent,
791
+ field: next.field
792
+ }, {
793
+ node: node.alternate,
794
+ field: next.field
795
+ });
796
+ continue;
797
+ }
798
+ if (node.type === "LogicalExpression") {
799
+ pending.push({
800
+ node: node.left,
801
+ field: next.field
802
+ }, {
803
+ node: node.right,
804
+ field: next.field
805
+ });
806
+ continue;
807
+ }
808
+ if (next.field && [
809
+ "Literal",
810
+ "TemplateLiteral",
811
+ "ObjectExpression",
812
+ "ArrayExpression"
813
+ ].includes(node.type)) return true;
814
+ if (node.type !== "ObjectExpression") continue;
815
+ for (const property of node.properties) {
816
+ if (property.type === "SpreadElement") {
817
+ pending.push({
818
+ node: property.argument,
819
+ field: false
820
+ });
821
+ continue;
822
+ }
823
+ const key = !property.computed && property.key.type === "Identifier" ? property.key.name : literalKey(source, property.key);
824
+ if ([
825
+ "body",
826
+ "json",
827
+ "status",
828
+ "contentType"
829
+ ].includes(key ?? "")) pending.push({
830
+ node: property.value,
831
+ field: true
832
+ });
833
+ }
834
+ }
835
+ return false;
836
+ }
837
+ function workerBinding(source, initial) {
838
+ let node = resolvedConstant(source, initial);
839
+ const seen = /* @__PURE__ */ new Set();
840
+ while (!seen.has(node)) {
841
+ seen.add(node);
842
+ if (cloudflareImport(source, node, "env") || durableParameter(source, node)) return true;
843
+ const reference = destructuredReference(source, node);
844
+ if (reference) {
845
+ node = resolvedConstant(source, reference.object);
846
+ continue;
847
+ }
848
+ if (node.type !== "MemberExpression") return false;
849
+ node = resolvedConstant(source, node.object);
850
+ }
851
+ return false;
852
+ }
853
+ function containsFunction(source, initial) {
854
+ const pending = [initial];
855
+ const seen = /* @__PURE__ */ new Set();
856
+ while (pending.length > 0) {
857
+ const next = pending.pop();
858
+ if (!next) continue;
859
+ const node = resolvedConstant(source, next);
860
+ if (seen.has(node)) continue;
861
+ seen.add(node);
862
+ if (node.type === "ArrowFunctionExpression" || node.type === "FunctionExpression" || node.type === "FunctionDeclaration") return true;
863
+ if (node.type === "CallExpression") {
864
+ const callee = resolvedConstant(source, node.callee);
865
+ if (callee.type === "MemberExpression" && propertyName$1(source, callee) === "bind") {
866
+ const receiver = resolvedConstant(source, callee.object);
867
+ if (receiver.type !== "ObjectExpression") pending.push(receiver);
868
+ }
869
+ }
870
+ if (node.type === "ObjectExpression") for (const property of node.properties) pending.push(property.type === "SpreadElement" ? property.argument : property.value);
871
+ if (node.type === "ConditionalExpression") pending.push(node.consequent, node.alternate);
872
+ if (node.type === "LogicalExpression") pending.push(node.left, node.right);
873
+ if (node.type === "SequenceExpression") {
874
+ const result = node.expressions.at(-1);
875
+ if (result) pending.push(result);
876
+ }
877
+ }
878
+ return false;
879
+ }
880
+ function localResults(source, initial) {
881
+ const pending = [{
882
+ node: initial,
883
+ path: [],
884
+ ancestors: /* @__PURE__ */ new Set()
885
+ }];
886
+ const visited = /* @__PURE__ */ new Map();
887
+ const results = [];
888
+ while (pending.length > 0) {
889
+ const next = pending.pop();
890
+ if (!next) continue;
891
+ const node = resolvedConstant(source, next.node);
892
+ const key = JSON.stringify(next.path);
893
+ const paths = visited.get(node) ?? /* @__PURE__ */ new Set();
894
+ if (paths.has(key) || next.ancestors.has(node)) continue;
895
+ paths.add(key);
896
+ visited.set(node, paths);
897
+ const push = (value, path = next.path) => {
898
+ pending.push({
899
+ node: value,
900
+ path,
901
+ ancestors: /* @__PURE__ */ new Set([...next.ancestors, node])
902
+ });
903
+ };
904
+ const reference = destructuredReference(source, node);
905
+ if (reference) {
906
+ push(reference.object, [reference.property, ...next.path]);
907
+ continue;
908
+ }
909
+ if (node.type === "CallExpression") {
910
+ const { callee } = invokedFunction(source, node);
911
+ if (callee.type === "FunctionDeclaration" || callee.type === "FunctionExpression" || callee.type === "ArrowFunctionExpression") {
912
+ if (callee.body?.type === "BlockStatement") {
913
+ for (const statement of callee.body.body) if (statement.type === "ReturnStatement" && statement.argument) push(statement.argument);
914
+ } else if (callee.body) push(callee.body);
915
+ continue;
916
+ }
917
+ }
918
+ if (node.type === "MemberExpression") {
919
+ const property = propertyName$1(source, node);
920
+ if (property !== null) push(node.object, [property, ...next.path]);
921
+ continue;
922
+ }
923
+ if (node.type === "ConditionalExpression") {
924
+ push(node.consequent);
925
+ push(node.alternate);
926
+ continue;
927
+ }
928
+ if (node.type === "ObjectExpression" && next.path.length > 0) {
929
+ const [property, ...rest] = next.path;
930
+ for (const field of node.properties) if (field.type === "SpreadElement") push(field.argument);
931
+ else if ((!field.computed && field.key.type === "Identifier" ? field.key.name : literalKey(source, field.key)) === property) push(field.value, rest);
932
+ continue;
933
+ }
934
+ const variable = lexicalVariable(source, node);
935
+ for (const definition of variable?.defs ?? []) {
936
+ const owner = definition.node;
937
+ if (definition.type !== "Parameter" || owner.type !== "FunctionDeclaration" || !owner.id) continue;
938
+ const index = owner.params.findIndex((parameter) => lexicalVariable(source, parameter) === variable);
939
+ for (const call of lexicalVariable(source, owner.id)?.references ?? []) {
940
+ const { parent } = call.identifier;
941
+ if (parent.type === "CallExpression" && parent.callee === call.identifier) {
942
+ const argument = parent.arguments[index];
943
+ if (argument && argument.type !== "SpreadElement") push(argument);
944
+ }
945
+ }
946
+ }
947
+ if (next.path.length === 0) results.push(node);
948
+ }
949
+ return results;
950
+ }
951
+ function honoReceiver(source, initial, filename) {
952
+ const pending = [initial];
953
+ const seen = /* @__PURE__ */ new Set();
954
+ while (pending.length > 0) {
955
+ const next = pending.pop();
956
+ if (!next) continue;
957
+ for (const node of localResults(source, next)) {
958
+ if (seen.has(node)) continue;
959
+ seen.add(node);
960
+ if (node.type === "NewExpression" && (cloudflareImport(source, node.callee, "Hono", "hono") || cloudflareImport(source, node.callee, "OpenAPIHono", "@hono/zod-openapi"))) return true;
961
+ if (node.type === "CallExpression") {
962
+ const { callee } = invokedFunction(source, node);
963
+ if (callee.type === "CallExpression") pending.push(callee);
964
+ else if (callee.type === "MemberExpression" && [
965
+ "use",
966
+ "route",
967
+ "get",
968
+ "post",
969
+ "put",
970
+ "patch",
971
+ "delete",
972
+ "all",
973
+ "on",
974
+ "basePath",
975
+ "notFound",
976
+ "onError"
977
+ ].includes(propertyName$1(source, callee) ?? "")) pending.push(callee.object);
978
+ }
979
+ if (/(?:^|\/)src\/workers\/[^/]+\/(?:tests?|__tests__)\//u.test(filename.replaceAll("\\", "/")) && lexicalVariable(source, node)?.defs.some(({ node: definition, parent }) => definition.type === "ImportDefaultSpecifier" && parent?.type === "ImportDeclaration" && /^(?:\.\.\/)+src(?:\/index(?:\.[cm]?[jt]s)?)?$/u.test(parent.source.value))) return true;
980
+ }
981
+ }
982
+ return false;
983
+ }
984
+ function handwrittenBindings(source, initial) {
985
+ const pending = [initial];
986
+ const seen = /* @__PURE__ */ new Set();
987
+ const objects = [];
988
+ while (pending.length > 0) {
989
+ const next = pending.pop();
990
+ if (!next) continue;
991
+ for (const node of localResults(source, next)) {
992
+ if (seen.has(node) || node.type !== "ObjectExpression") continue;
993
+ seen.add(node);
994
+ for (const property of node.properties) {
995
+ if (property.type === "SpreadElement") {
996
+ pending.push(property.argument);
997
+ continue;
998
+ }
999
+ const key = !property.computed && property.key.type === "Identifier" ? property.key.name : literalKey(source, property.key);
1000
+ if (key && /^[A-Z][A-Z0-9_]*$/u.test(key) && containsFunction(source, property.value)) {
1001
+ objects.push(node);
1002
+ break;
1003
+ }
1004
+ }
1005
+ }
1006
+ }
1007
+ return objects;
1008
+ }
1009
+ function definesReplacementGlobal(source, initial, properties) {
1010
+ const pending = initial ? [initial] : [];
1011
+ const visited = /* @__PURE__ */ new Set();
1012
+ while (pending.length > 0) {
1013
+ const next = pending.pop();
1014
+ const node = next ? resolvedConstant(source, next) : void 0;
1015
+ if (!node || visited.has(node)) continue;
1016
+ visited.add(node);
1017
+ if (node.type === "ConditionalExpression") pending.push(node.consequent, node.alternate);
1018
+ if (node.type === "LogicalExpression") pending.push(node.left, node.right);
1019
+ if (node.type === "SequenceExpression") {
1020
+ const result = node.expressions.at(-1);
1021
+ if (result) pending.push(result);
1022
+ }
1023
+ if (node.type !== "ObjectExpression") continue;
1024
+ for (const property of node.properties) {
1025
+ if (property.type === "SpreadElement") {
1026
+ pending.push(property.argument);
1027
+ continue;
1028
+ }
1029
+ const key = !property.computed && property.key.type === "Identifier" ? property.key.name : literalKey(source, property.key);
1030
+ if (key !== null && properties.has(key)) return true;
1031
+ }
1032
+ }
1033
+ return false;
1034
+ }
1035
+ function observationOptions(node) {
1036
+ return node?.type === "ObjectExpression" && node.properties.length === 1 && node.properties.some((property) => property.type === "Property" && !property.computed && (property.key.type === "Identifier" && property.key.name === "spy" || property.key.type === "Literal" && property.key.value === "spy") && property.value.type === "Literal" && property.value.value === true);
1037
+ }
1038
+ function invokedFunction(source, node) {
1039
+ let target = resolvedConstant(source, node.callee);
1040
+ let args = [...node.arguments];
1041
+ const visited = /* @__PURE__ */ new Set();
1042
+ while (!visited.has(target)) {
1043
+ visited.add(target);
1044
+ if (target.type === "CallExpression") {
1045
+ const bound = resolvedConstant(source, target.callee);
1046
+ if (bound.type !== "MemberExpression" || propertyName$1(source, bound) !== "bind") break;
1047
+ args.unshift(...target.arguments.slice(1));
1048
+ target = resolvedConstant(source, bound.object);
1049
+ continue;
1050
+ }
1051
+ if (nativePropertyPath(source, target) === "Reflect.apply") {
1052
+ const [fn, , list] = args;
1053
+ if (!fn) break;
1054
+ const values = list ? resolvedConstant(source, list) : null;
1055
+ args = values?.type === "ArrayExpression" ? [...values.elements] : [];
1056
+ target = resolvedConstant(source, fn);
1057
+ continue;
1058
+ }
1059
+ if (target.type !== "MemberExpression") break;
1060
+ const method = propertyName$1(source, target);
1061
+ if (method === "call") args = args.slice(1);
1062
+ else if (method === "apply") {
1063
+ const [, list] = args;
1064
+ const values = list ? resolvedConstant(source, list) : null;
1065
+ args = values?.type === "ArrayExpression" ? [...values.elements] : [];
1066
+ } else break;
1067
+ target = resolvedConstant(source, target.object);
1068
+ }
1069
+ return {
1070
+ callee: target,
1071
+ args
1072
+ };
1073
+ }
1074
+ function mswResponseConstructor(source, initial) {
1075
+ const node = resolvedConstant(source, initial);
1076
+ return cloudflareImport(source, node, "HttpResponse", "msw") || node.type === "MemberExpression" && propertyName$1(source, node) === "HttpResponse" && namespaceImport(source, node.object, "msw");
1077
+ }
1078
+ function rawResponse(source, initial, includeMsw = false) {
1079
+ const pending = [initial];
1080
+ const visited = /* @__PURE__ */ new Set();
1081
+ while (pending.length > 0) {
1082
+ const next = pending.pop();
1083
+ if (!next) continue;
1084
+ const node = resolvedConstant(source, next);
1085
+ if (visited.has(node)) continue;
1086
+ visited.add(node);
1087
+ switch (node.type) {
1088
+ case "NewExpression":
1089
+ if (nativePropertyPath(source, node.callee) === "Response" || includeMsw && mswResponseConstructor(source, node.callee)) return true;
1090
+ break;
1091
+ case "CallExpression": {
1092
+ const { callee, args } = invokedFunction(source, node);
1093
+ const path = nativePropertyPath(source, callee);
1094
+ if (path === "Promise.resolve" && args[0]) pending.push(args[0]);
1095
+ if (includeMsw && callee.type === "MemberExpression" && [
1096
+ "json",
1097
+ "text",
1098
+ "html",
1099
+ "xml",
1100
+ "arrayBuffer",
1101
+ "formData",
1102
+ "error",
1103
+ "redirect",
1104
+ "bytes"
1105
+ ].includes(propertyName$1(source, callee) ?? "") && mswResponseConstructor(source, callee.object)) return true;
1106
+ if (path && [
1107
+ "Response.json",
1108
+ "Response.redirect",
1109
+ "Response.error"
1110
+ ].includes(path)) return true;
1111
+ if ((callee.type === "FunctionDeclaration" || callee.type === "FunctionExpression" || callee.type === "ArrowFunctionExpression") && callee.body) pending.push(callee.body);
1112
+ break;
1113
+ }
1114
+ case "FunctionDeclaration":
1115
+ case "FunctionExpression":
1116
+ case "ArrowFunctionExpression":
1117
+ if (node.body) pending.push(node.body);
1118
+ break;
1119
+ case "BlockStatement":
1120
+ pending.push(...node.body.filter((statement) => statement.type !== "FunctionDeclaration"));
1121
+ break;
1122
+ case "ReturnStatement":
1123
+ if (node.argument) pending.push(node.argument);
1124
+ break;
1125
+ case "AwaitExpression":
1126
+ pending.push(node.argument);
1127
+ break;
1128
+ case "IfStatement":
1129
+ pending.push(node.consequent);
1130
+ if (node.alternate) pending.push(node.alternate);
1131
+ break;
1132
+ case "ConditionalExpression":
1133
+ pending.push(node.consequent, node.alternate);
1134
+ break;
1135
+ case "LogicalExpression":
1136
+ pending.push(node.left, node.right);
1137
+ break;
1138
+ case "SequenceExpression": {
1139
+ const result = node.expressions.at(-1);
1140
+ if (result) pending.push(result);
1141
+ break;
1142
+ }
1143
+ case "SwitchStatement":
1144
+ pending.push(...node.cases.flatMap((branch) => branch.consequent));
1145
+ break;
1146
+ case "TryStatement":
1147
+ pending.push(node.block);
1148
+ if (node.handler) pending.push(node.handler.body);
1149
+ if (node.finalizer) pending.push(node.finalizer);
1150
+ }
1151
+ }
1152
+ return false;
1153
+ }
1154
+ function rawServiceBindings(source, initial) {
1155
+ const pending = [initial];
1156
+ const visited = /* @__PURE__ */ new Set();
1157
+ while (pending.length > 0) {
1158
+ const next = pending.pop();
1159
+ if (!next) continue;
1160
+ const node = resolvedConstant(source, next);
1161
+ if (visited.has(node) || node.type !== "ObjectExpression") continue;
1162
+ visited.add(node);
1163
+ for (const property of node.properties) if (property.type === "SpreadElement") pending.push(property.argument);
1164
+ else if (rawResponse(source, property.value)) return true;
1165
+ }
1166
+ return false;
1167
+ }
1168
+ const noTestDoubles = defineRule({
1169
+ meta: {
1170
+ type: "problem",
1171
+ schema: [],
1172
+ docs: { description: "Keep real implementations in tests; intercept network requests with MSW and allow observation-only spies." },
1173
+ messages: { replacement: "Do not replace test dependency behavior. Use the real implementation and MSW for network responses; spies must only observe." }
1174
+ },
1175
+ create(context) {
1176
+ const source = context.sourceCode;
1177
+ const testCode = /(?:^|\/)(?:__tests__|tests?|testing|test-utils)(?:\/|$)|(?:^|[/.])(?:test|spec|fixture|mock|setup|commands)(?:\.[^/]*)?$/u.test(context.filename.replaceAll("\\", "/")) || source.ast.body.some((node) => node.type === "ImportDeclaration" && /^(?:vitest(?:\/|$)|@jest\/globals$|node:test$)/u.test(node.source.value));
1178
+ const vitestConfig = /(?:^|\/)vitest(?:\.[\w-]+)*\.config\.[cm]?[jt]s$/u.test(context.filename.replaceAll("\\", "/"));
1179
+ const reportedBindings = /* @__PURE__ */ new Set();
1180
+ const savedMembers = [];
1181
+ const assignments = [];
1182
+ return {
1183
+ VariableDeclarator(node) {
1184
+ if (testCode && node.id.type === "Identifier" && node.init?.type === "MemberExpression") savedMembers.push(node);
1185
+ if (testCode && node.id.type === "Identifier" && node.init) {
1186
+ const annotation = node.id.typeAnnotation?.typeAnnotation;
1187
+ const implementation = resolvedConstant(source, node.init);
1188
+ if (annotation && nativeFetchType(source, annotation) && rawResponse(source, implementation, true) && !reportedBindings.has(implementation)) {
1189
+ reportedBindings.add(implementation);
1190
+ context.report({
1191
+ node: node.init,
1192
+ messageId: "replacement"
1193
+ });
1194
+ }
1195
+ }
1196
+ },
1197
+ "Program:exit"() {
1198
+ for (const assignment of assignments) {
1199
+ const replacement = resolvedConstant(source, assignment.right);
1200
+ if (assignment.left.type !== "MemberExpression" || replacement.type !== "ArrowFunctionExpression" && replacement.type !== "FunctionExpression" && replacement.type !== "FunctionDeclaration") continue;
1201
+ const property = propertyName$1(source, assignment.left);
1202
+ const { object } = assignment.left;
1203
+ if (workerBinding(source, assignment.left) || protectedProperties(source, object)?.has(property ?? "") || property?.startsWith("on") && (globalObject(source, object) || nativePropertyPath(source, object) === "document")) continue;
1204
+ if (savedMembers.some((declaration) => {
1205
+ if (declaration.id.type !== "Identifier" || !declaration.init || declaration.range[0] >= assignment.range[0] || !sameMember(source, declaration.init, assignment.left)) return false;
1206
+ const variable = lexicalVariable(source, declaration.id);
1207
+ return variable !== null && initializedOnce(variable) && !delegatesSavedMember(source, replacement, variable) && assignments.some((restore) => restore.range[0] > assignment.range[0] && restore.right.type === "Identifier" && lexicalVariable(source, restore.right) === variable && sameMember(source, restore.left, assignment.left));
1208
+ })) context.report({
1209
+ node: assignment,
1210
+ messageId: "replacement"
1211
+ });
1212
+ }
1213
+ },
1214
+ NewExpression(node) {
1215
+ if (!testCode || !knockConstructor(source, node.callee)) return;
1216
+ const [options] = node.arguments;
1217
+ if (!options || options.type === "SpreadElement") return;
1218
+ for (const value of localResults(source, options)) {
1219
+ const transport = effectiveOption(source, value, "fetch");
1220
+ if (transport !== null && transport !== false && rawResponse(source, transport, true)) {
1221
+ const implementation = resolvedConstant(source, transport);
1222
+ if (!reportedBindings.has(implementation)) {
1223
+ reportedBindings.add(implementation);
1224
+ context.report({
1225
+ node: transport,
1226
+ messageId: "replacement"
1227
+ });
1228
+ }
1229
+ break;
1230
+ }
1231
+ }
1232
+ },
1233
+ ObjectExpression(node) {
1234
+ if (node.parent.type === "CallExpression" && cloudflareImport(source, invokedFunction(source, node.parent).callee, "withEnv")) return;
1235
+ if (testCode && node.properties.some((property) => property.type === "SpreadElement" && workerBinding(source, property.argument)) && containsFunction(source, node) && !reportedBindings.has(node)) {
1236
+ reportedBindings.add(node);
1237
+ context.report({
1238
+ node,
1239
+ messageId: "replacement"
1240
+ });
1241
+ }
1242
+ },
1243
+ Property(node) {
1244
+ if (!vitestConfig) return;
1245
+ const key = !node.computed && node.key.type === "Identifier" ? node.key.name : literalKey(source, node.key);
1246
+ if (key === "outboundService" && rawResponse(source, node.value) || key === "serviceBindings" && rawServiceBindings(source, node.value)) context.report({
1247
+ node,
1248
+ messageId: "replacement"
1249
+ });
1250
+ },
1251
+ CallExpression(node) {
1252
+ const { callee, args } = invokedFunction(source, node);
1253
+ if (testCode && callee.type === "MemberExpression" && propertyName$1(source, callee) === "request" && args[2] && honoReceiver(source, callee.object, context.filename)) {
1254
+ for (const binding of handwrittenBindings(source, args[2])) if (!reportedBindings.has(binding)) {
1255
+ reportedBindings.add(binding);
1256
+ context.report({
1257
+ node: binding,
1258
+ messageId: "replacement"
1259
+ });
1260
+ }
1261
+ }
1262
+ if (testCode && callee.type === "MemberExpression" && propertyName$1(source, callee) === "fulfill" && playwrightRoute(source, callee.object) && args[0] && staticRouteResponse(source, args[0])) context.report({
1263
+ node,
1264
+ messageId: "replacement"
1265
+ });
1266
+ const replacement = replacementMethod(source, callee);
1267
+ if (tauriMockImport(source, callee)) context.report({
1268
+ node,
1269
+ messageId: "replacement"
1270
+ });
1271
+ if (replacement !== null && (replacements.has(replacement) || frameworkReplacements.has(replacement) && !([
1272
+ "mock",
1273
+ "doMock",
1274
+ "mockObject"
1275
+ ].includes(replacement) && args.length === 2 && !jestFramework(source, callee) && observationOptions(args[1] ?? void 0)) || replacement === "fn" && args[0] !== null && args[0] !== void 0 && !(args[0].type === "Identifier" && args[0].name === "undefined" && unshadowed(source, args[0])))) context.report({
1276
+ node,
1277
+ messageId: "replacement"
1278
+ });
1279
+ const mutation = nativePropertyPath(source, callee);
1280
+ if (testCode) {
1281
+ const [target] = args;
1282
+ let candidates = [];
1283
+ if (cloudflareImport(source, callee, "withEnv")) candidates = args.slice(0, 1);
1284
+ else if (target && workerBinding(source, target)) switch (mutation) {
1285
+ case "Object.assign":
1286
+ candidates = args.slice(1);
1287
+ break;
1288
+ case "Object.defineProperty":
1289
+ case "Reflect.defineProperty":
1290
+ case "Reflect.set":
1291
+ candidates = args.slice(2, 3);
1292
+ break;
1293
+ case "Object.defineProperties": candidates = args.slice(1, 2);
1294
+ }
1295
+ if (candidates.some((value) => value && containsFunction(source, value))) context.report({
1296
+ node,
1297
+ messageId: "replacement"
1298
+ });
1299
+ }
1300
+ if (testCode && mutation !== null && args[0] !== null && args[0] !== void 0) {
1301
+ const properties = protectedProperties(source, args[0]);
1302
+ if (!properties) return;
1303
+ const [, argument] = args;
1304
+ if ([
1305
+ "Object.defineProperty",
1306
+ "Reflect.defineProperty",
1307
+ "Reflect.set",
1308
+ "Reflect.deleteProperty"
1309
+ ].includes(mutation) && properties.has(literalKey(source, argument ?? void 0) ?? "") || mutation === "Object.defineProperties" && definesReplacementGlobal(source, argument ?? void 0, properties) || mutation === "Object.assign" && args.slice(1).some((value) => definesReplacementGlobal(source, value ?? void 0, properties))) context.report({
1310
+ node,
1311
+ messageId: "replacement"
1312
+ });
1313
+ }
1314
+ },
1315
+ UnaryExpression(node) {
1316
+ if (testCode && node.operator === "delete" && node.argument.type === "MemberExpression" && protectedProperties(source, node.argument.object)?.has(String(propertyName$1(source, node.argument)))) context.report({
1317
+ node,
1318
+ messageId: "replacement"
1319
+ });
1320
+ },
1321
+ AssignmentExpression(node) {
1322
+ if (!testCode) return;
1323
+ if (node.operator === "=") assignments.push(node);
1324
+ const target = node.left;
1325
+ if (workerBinding(source, target) && containsFunction(source, node.right)) context.report({
1326
+ node,
1327
+ messageId: "replacement"
1328
+ });
1329
+ if (target.type === "Identifier" && replacementGlobals.has(target.name) && unshadowed(source, target) || target.type === "MemberExpression" && protectedProperties(source, target.object)?.has(String(propertyName$1(source, target)))) context.report({
1330
+ node,
1331
+ messageId: "replacement"
1332
+ });
1333
+ }
1334
+ };
1335
+ }
1336
+ });
1337
+ // src/rules/no-unsignaled-poll.ts
1338
+ const spyMatchers = /^(?:toHaveBeenCalled|toHaveBeenCalledOnce|toHaveBeenCalledTimes|toHaveBeenCalledWith|toHaveBeenCalledExactlyOnceWith|toHaveBeenLastCalledWith|toHaveBeenNthCalledWith|toHaveReturned|toHaveReturnedTimes|toHaveReturnedWith|toHaveLastReturnedWith|toHaveNthReturnedWith|toHaveResolved|toHaveResolvedTimes|toHaveResolvedWith|toHaveLastResolvedWith|toHaveNthResolvedWith)$/u;
1339
+ function propertyName(node) {
1340
+ return node.property.type === "Identifier" && !node.computed ? node.property.name : void 0;
1341
+ }
1342
+ function isCall(node, object, property) {
1343
+ return node.type === "MemberExpression" && node.object.type === "Identifier" && node.object.name === object && propertyName(node) === property;
1344
+ }
1345
+ const path = (node) => {
1346
+ if (node.type === "ChainExpression") return path(node.expression);
1347
+ if (node.type === "Identifier") return [node.name];
1348
+ if (node.type !== "MemberExpression") return null;
1349
+ const object = path(node.object);
1350
+ return object && [...object, propertyName(node) ?? "[]"];
1351
+ };
1352
+ function readsRecorder(node) {
1353
+ const names = path(node);
1354
+ if (!names || names.includes("current")) return false;
1355
+ const last = names.at(-1);
1356
+ return names.includes("mock") || names.length > 1 && (last === "length" || last === "size");
1357
+ }
1358
+ function polledValue(callback) {
1359
+ if (callback.type !== "ArrowFunctionExpression" && callback.type !== "FunctionExpression") return null;
1360
+ if (!callback.body) return null;
1361
+ if (callback.body.type !== "BlockStatement") return callback.body;
1362
+ const [statement, ...rest] = callback.body.body;
1363
+ if (rest.length > 0) return null;
1364
+ if (statement?.type === "ReturnStatement") return statement.argument;
1365
+ return statement?.type === "ExpressionStatement" ? statement.expression : null;
1366
+ }
1367
+ function assertsRecorder(node) {
1368
+ if (node.type !== "CallExpression" || node.callee.type !== "MemberExpression") return false;
1369
+ const matcher = propertyName(node.callee) ?? "";
1370
+ const subject = node.callee.object.type === "MemberExpression" && propertyName(node.callee.object) === "not" ? node.callee.object.object : node.callee.object;
1371
+ if (subject.type !== "CallExpression" || subject.callee.type !== "Identifier" || subject.callee.name !== "expect") return false;
1372
+ const [target] = subject.arguments;
1373
+ if (!target || target.type === "SpreadElement") return false;
1374
+ if (readsRecorder(target)) return true;
1375
+ const names = path(target);
1376
+ return names !== null && !names.includes("current") && (spyMatchers.test(matcher) || matcher === "toHaveLength");
1377
+ }
1378
+ function pollsLength(node, value) {
1379
+ const { parent } = node;
1380
+ const names = path(value);
1381
+ return parent.type === "MemberExpression" && propertyName(parent) === "toHaveLength" && names !== null && !names.includes("current");
1382
+ }
1383
+ const noUnsignaledPoll = defineRule({
1384
+ meta: {
1385
+ type: "problem",
1386
+ schema: allowlistSchema,
1387
+ docs: { description: "Disallow expect.poll and vi.waitFor on request recorders and spy state, which race a deadline instead of awaiting a signal." },
1388
+ messages: {
1389
+ poll: "Await a signal instead of polling a request recorder or spy: resolve a Promise.withResolvers() deferred from the handler or callback that records it, then await its promise, or await the operation's own completion. A deadline-bound poll on a counter fails under CPU load, and a longer timeout only hides that.",
1390
+ stale: "This file now has {{count}} unsignaled polls; lower its no-unsignaled-poll allowlist entry for {{path}} in .oxlintrc.jsonc to {{count}}, or remove the entry at 0."
1391
+ }
1392
+ },
1393
+ create(context) {
1394
+ const violations = [];
1395
+ return {
1396
+ CallExpression(node) {
1397
+ const poll = isCall(node.callee, "expect", "poll");
1398
+ if (!poll && !isCall(node.callee, "vi", "waitFor")) return;
1399
+ const [callback] = node.arguments;
1400
+ const value = callback && polledValue(callback);
1401
+ if (!value) return;
1402
+ if (readsRecorder(value) || (poll ? pollsLength(node, value) : assertsRecorder(value))) violations.push(node);
1403
+ },
1404
+ "Program:exit"(program) {
1405
+ reportAllowed(context, program, violations, "poll");
1406
+ }
1407
+ };
1408
+ }
1409
+ });
1410
+ // src/rules/strict-msw.ts
1411
+ const starters = /* @__PURE__ */ new Map([["setupServer", "listen"], ["setupWorker", "start"]]);
1412
+ function variableOf(source, node, name) {
1413
+ for (let scope = source.getScope(node); scope !== null; scope = scope.upper) {
1414
+ const variable = scope.set.get(name);
1415
+ if (variable) return variable;
1416
+ }
1417
+ return null;
1418
+ }
1419
+ function mswFactory(source, node) {
1420
+ if (node?.type !== "CallExpression" || node.callee.type !== "Identifier") return null;
1421
+ for (const { node: definition, parent } of variableOf(source, node.callee, node.callee.name)?.defs ?? []) if (definition.type === "ImportSpecifier" && parent?.type === "ImportDeclaration" && /^msw(?:\/|$)/u.test(parent.source.value)) {
1422
+ const name = definition.imported.type === "Identifier" ? definition.imported.name : definition.imported.value;
1423
+ return starters.has(name) ? name : null;
1424
+ }
1425
+ return null;
1426
+ }
1427
+ function assignedValues(variable) {
1428
+ return variable.references.flatMap((reference) => reference.isWrite() && reference.writeExpr ? [reference.writeExpr] : []);
1429
+ }
1430
+ function serverFactory(source, node) {
1431
+ if (node.type !== "Identifier") return mswFactory(source, node);
1432
+ const variable = variableOf(source, node, node.name);
1433
+ if (!variable) return null;
1434
+ const factories = new Set(assignedValues(variable).flatMap((value) => {
1435
+ const factory = mswFactory(source, value);
1436
+ return factory === null ? [] : [factory];
1437
+ }));
1438
+ const [factory] = factories;
1439
+ return factories.size === 1 && factory !== void 0 ? factory : null;
1440
+ }
1441
+ function strict(node) {
1442
+ return node?.type === "ObjectExpression" && node.properties.some((property) => property.type === "Property" && !property.computed && property.key.type === "Identifier" && property.key.name === "onUnhandledRequest" && (property.value.type === "Literal" && property.value.value === "error" || property.value.type === "ArrowFunctionExpression" || property.value.type === "FunctionExpression"));
1443
+ }
1444
+ const strictMsw = defineRule({
1445
+ meta: {
1446
+ type: "problem",
1447
+ schema: allowlistSchema,
1448
+ docs: { description: "Fail tests on requests that no MSW handler covers instead of letting them reach the network." },
1449
+ messages: {
1450
+ lenient: "Start MSW with { onUnhandledRequest: \"error\" }. Add a handler for every request the test makes, with passthrough() for local origins the test owns.",
1451
+ stale: "This file now has {{count}} lenient MSW starts; lower its strict-msw allowlist entry for {{path}} in .oxlintrc.jsonc to {{count}}, or remove the entry at 0."
1452
+ }
1453
+ },
1454
+ create(context) {
1455
+ const source = context.sourceCode;
1456
+ const lenientStarts = [];
1457
+ return {
1458
+ CallExpression(node) {
1459
+ const { callee } = node;
1460
+ if (callee.type !== "MemberExpression" || callee.computed || callee.property.type !== "Identifier") return;
1461
+ const factory = serverFactory(source, callee.object);
1462
+ if (factory !== null && starters.get(factory) === callee.property.name && !strict(node.arguments[0])) lenientStarts.push(node);
1463
+ },
1464
+ "Program:exit"(program) {
1465
+ reportAllowed(context, program, lenientStarts, "lenient");
1466
+ }
1467
+ };
1468
+ }
1469
+ });
1470
+ // src/plugins/testing.ts
1471
+ const plugin = definePlugin({
1472
+ meta: { name: "landmines-testing" },
1473
+ rules: {
1474
+ "no-fixed-sleep": noFixedSleep,
1475
+ "no-flake-masking": noFlakeMasking,
1476
+ "no-test-doubles": noTestDoubles,
1477
+ "no-unsignaled-poll": noUnsignaledPoll,
1478
+ "strict-msw": strictMsw
1479
+ }
1480
+ });
1481
+ export { plugin as default };