Repository navigation
Expand file tree
/
Copy patheslint-local-rules.mjs
More file actions
2135 lines (2071 loc) · 85 KB
/
Copy patheslint-local-rules.mjs
File metadata and controls
2135 lines (2071 loc) · 85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import path from "node:path";
import ts from "typescript";
/**
* Shared helpers for the rules ported from anti-slop
* (https://github.com/dmmulroy/anti-slop). The common theme: values whose
* types are syntactically evident (literals, typed bindings) must not flow
* into explicitly broad types (`unknown`, `object`, `Record<string, ...>`)
* that discard that evidence — push type information into the compiler
* instead of re-deriving it at runtime or re-asserting it later.
*
* Differences from upstream (which targets oxlint's ESTree): typescript-eslint
* does not emit ParenthesizedExpression/TSParenthesizedType nodes, and the
* module-level type-alias/interface environment resolution is omitted — it
* only adds catches (alias-of-Record etc.), so skipping it cannot introduce
* false positives. An AST census (2026-08) showed the omission has zero
* effect here: only 4 broad aliases existed repo-wide (UnknownRecord,
* LogFields, JsonRecord, MetaRecord), every assertion through them sat on
* un-evident values (JSON.parse/fetch results) where the rules stay silent
* by design, and upstream's resolution is file-local anyway so cross-file
* aliases would remain invisible even with the full port. Revisit only if
* broad local aliases become common.
*/
/**
* Unwrap only the transparent wrappers (non-null, satisfies) while keeping
* assertions intact — for walks that must see assertion nodes themselves.
*/
function unwrapPassthroughWrappers(expression) {
let current = expression;
while (current.type === "TSNonNullExpression" || current.type === "TSSatisfiesExpression") {
current = current.expression;
}
return current;
}
/** Unwrap assertion-like wrappers to reach the underlying value expression. */
function unwrapAssertions(expression) {
let current = expression;
while (
current.type === "TSAsExpression" ||
current.type === "TSTypeAssertion" ||
current.type === "TSNonNullExpression" ||
current.type === "TSSatisfiesExpression"
) {
current = current.expression;
}
return current;
}
/** Expressions whose type is syntactically established at the use site. */
function isKnownEvidenceExpression(expression) {
const current = unwrapAssertions(expression);
return (
current.type === "ObjectExpression" ||
current.type === "ArrayExpression" ||
current.type === "ArrowFunctionExpression" ||
current.type === "ClassExpression" ||
current.type === "FunctionExpression" ||
current.type === "NewExpression" ||
current.type === "Literal" ||
current.type === "TemplateLiteral" ||
current.type === "UnaryExpression"
);
}
function isEmptyObjectExpression(expression) {
const current = unwrapAssertions(expression);
return current.type === "ObjectExpression" && current.properties.length === 0;
}
function resolveVariable(sourceCode, identifier) {
let scope = sourceCode.getScope(identifier);
while (scope !== null) {
const variable = scope.set.get(identifier.name);
if (variable !== undefined) {
return variable;
}
scope = scope.upper;
}
return null;
}
function variableDeclarator(variable) {
if (variable.defs.length !== 1) {
return null;
}
const definition = variable.defs[0];
return definition.type === "Variable" && definition.node.type === "VariableDeclarator"
? definition.node
: null;
}
/** A `const` binding that is never reassigned after initialization. */
function isStableConstVariable(variable, declarator) {
return (
declarator.parent.type === "VariableDeclaration" &&
declarator.parent.kind === "const" &&
variable.references.every((reference) => reference.init || !reference.isWrite())
);
}
/** True when the expression's type is syntactically known, tracing through stable consts. */
function hasKnownEvidence(sourceCode, expression, visitedVariables = new Set()) {
if (isKnownEvidenceExpression(expression)) {
return true;
}
const unwrapped = unwrapAssertions(expression);
if (unwrapped.type !== "Identifier") {
return false;
}
const variable = resolveVariable(sourceCode, unwrapped);
if (variable === null || visitedVariables.has(variable)) {
return false;
}
const declarator = variableDeclarator(variable);
if (
declarator === null ||
declarator.init === null ||
!isStableConstVariable(variable, declarator)
) {
return false;
}
visitedVariables.add(variable);
return hasKnownEvidence(sourceCode, declarator.init, visitedVariables);
}
const TRANSPARENT_TYPE_WRAPPERS = new Set(["Readonly", "Partial", "Required", "NonNullable"]);
function typeReferenceName(type) {
return type.type === "TSTypeReference" && type.typeName.type === "Identifier"
? type.typeName.name
: null;
}
function typeArgumentsOf(typeReference) {
// typescript-eslint v8 uses typeArguments; older versions used typeParameters.
return (typeReference.typeArguments ?? typeReference.typeParameters)?.params ?? [];
}
function unwrapReadonlyOperator(type) {
let current = type;
while (current.type === "TSTypeOperator" && current.operator === "readonly") {
current = current.typeAnnotation;
}
return current;
}
/**
* Classify explicitly broad target types that discard evidence when a known
* value flows into them. Returns a human-readable kind or null.
*/
function classifyWideningTarget(type) {
const unwrapped = unwrapReadonlyOperator(type);
if (unwrapped.type === "TSUnknownKeyword") {
return "unknown";
}
if (unwrapped.type === "TSObjectKeyword") {
return "object";
}
if (unwrapped.type === "TSTypeLiteral") {
// Upstream also classifies non-empty literals without an index signature
// ("anonymous object"), but inline object annotations are idiomatic here
// (296 prod sites) and the assertion case is already restricted by
// @typescript-eslint/consistent-type-assertions, so we treat them as safe.
return unwrapped.members.some((member) => member.type === "TSIndexSignature")
? "open dictionary"
: null;
}
if (unwrapped.type === "TSMappedType") {
return "open dictionary";
}
const name = typeReferenceName(unwrapped);
if (name === null) {
return null;
}
if (TRANSPARENT_TYPE_WRAPPERS.has(name)) {
const [inner] = typeArgumentsOf(unwrapped);
return inner === undefined ? null : classifyWideningTarget(inner);
}
return name === "Record" ? "open dictionary" : null;
}
function isBroadRecordKeyType(type) {
if (
type.type === "TSStringKeyword" ||
type.type === "TSNumberKeyword" ||
type.type === "TSSymbolKeyword"
) {
return true;
}
if (type.type === "TSUnionType") {
return type.types.every(isBroadRecordKeyType);
}
return typeReferenceName(type) === "PropertyKey";
}
function isUnknownOrAnyType(type) {
return type.type === "TSUnknownKeyword" || type.type === "TSAnyKeyword";
}
/** `Record<broad-key, unknown|any>` or an index-signature-only literal of the same shape. */
function isBroadRecordType(type) {
const unwrapped = unwrapReadonlyOperator(type);
const name = typeReferenceName(unwrapped);
if (name === "Readonly") {
const [inner] = typeArgumentsOf(unwrapped);
return inner !== undefined && isBroadRecordType(inner);
}
if (name === "Record") {
const parameters = typeArgumentsOf(unwrapped);
return (
parameters.length === 2 &&
isBroadRecordKeyType(parameters[0]) &&
isUnknownOrAnyType(parameters[1])
);
}
if (unwrapped.type !== "TSTypeLiteral" || unwrapped.members.length !== 1) {
return false;
}
const [member] = unwrapped.members;
return (
member.type === "TSIndexSignature" &&
member.parameters.length === 1 &&
isBroadRecordKeyType(member.parameters[0].typeAnnotation.typeAnnotation) &&
isUnknownOrAnyType(member.typeAnnotation.typeAnnotation)
);
}
/** Broad-type kinds used by no-widen-then-assert. */
function broadTypeKind(type) {
const unwrapped = unwrapReadonlyOperator(type);
if (unwrapped.type === "TSUnknownKeyword" || unwrapped.type === "TSAnyKeyword") {
return "top";
}
if (unwrapped.type === "TSObjectKeyword") {
return "object";
}
return isBroadRecordType(unwrapped) ? "record" : null;
}
const FUNCTION_BOUNDARY_TYPES = new Set([
"ArrowFunctionExpression",
"FunctionDeclaration",
"FunctionExpression",
"TSDeclareFunction",
"TSEmptyBodyFunctionExpression",
]);
function functionBoundary(node) {
let current = node.parent;
while (current != null && current.type !== "Program") {
if (FUNCTION_BOUNDARY_TYPES.has(current.type)) {
return current;
}
current = current.parent;
}
return null;
}
/**
* The repo's custom `local/*` rules. eslint.config.mjs registers them for ESLint, and
* .oxlintrc.json loads them as an oxlint JS plugin.
*/
const localPlugin = {
meta: { name: "local" },
rules: {
"no-required-member-typeof-guard": {
meta: {
type: "problem",
docs: {
description:
'Disallow `typeof x.member === "function"` guards on members the type declares as required methods',
},
messages: {
required:
"`{{member}}` is a required method of `{{owner}}`, so this typeof guard can only fire for an incomplete test double. Complete the double (or make the member optional in the interface if it really is optional).",
},
},
create(context) {
// Production code gets real instances through DI; a typeof guard on a member the type
// requires is dead there and hides wiring bugs by silently skipping work. Such guards
// kept reappearing to tolerate partial test doubles (#4531, #4557).
const services = context.sourceCode.parserServices;
if (services?.program == null || services.esTreeNodeToTSNodeMap == null) {
return {};
}
const checker = services.program.getTypeChecker();
const isAlwaysCallable = (type) => {
const parts = type.isUnion() ? type.types : [type];
return parts.every(
(part) =>
(part.flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Null | ts.TypeFlags.Void)) ===
0 && part.getCallSignatures().length > 0
);
};
return {
BinaryExpression(node) {
if (!["===", "!==", "==", "!="].includes(node.operator)) return;
const typeofSide = node.left.type === "UnaryExpression" ? node.left : node.right;
const literalSide = typeofSide === node.left ? node.right : node.left;
if (typeofSide.type !== "UnaryExpression" || typeofSide.operator !== "typeof") return;
if (literalSide.type !== "Literal" || literalSide.value !== "function") return;
const member = typeofSide.argument;
if (
member.type !== "MemberExpression" ||
member.computed ||
member.optional ||
member.property.type !== "Identifier"
) {
return;
}
// Only injected dependencies (`this.<dep>[.<dep>...].<method>`): feature detection on
// runtime/library objects (timers, fetch, streams) stays legitimate.
// Also covers the widening-cast alias `const maybe = this.<dep> as Dep & { m?: ... }`.
const isThisRooted = (expression) => {
let current = expression;
while (current.type === "MemberExpression" && !current.computed) {
current = current.object;
}
return current.type === "ThisExpression" && expression.type !== "ThisExpression";
};
let receiverRooted = isThisRooted(member.object);
if (!receiverRooted && member.object.type === "Identifier") {
const variable = context.sourceCode
.getScope(node)
.references.concat(context.sourceCode.getScope(node).through)
.find((reference) => reference.identifier === member.object)?.resolved;
const init = variable?.defs[0]?.node?.init;
receiverRooted = init?.type === "TSAsExpression" && isThisRooted(init.expression);
}
if (!receiverRooted) return;
const objectType = checker.getTypeAtLocation(
services.esTreeNodeToTSNodeMap.get(member.object)
);
// Untyped or loose receivers (any/unknown/index signatures) make the check meaningful.
if (objectType.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) return;
const symbol = checker.getPropertyOfType(objectType, member.property.name);
if (symbol == null || (symbol.flags & ts.SymbolFlags.Optional) !== 0) return;
const memberType = checker.getTypeOfSymbolAtLocation(
symbol,
services.esTreeNodeToTSNodeMap.get(member.property)
);
if (!isAlwaysCallable(memberType)) return;
context.report({
node,
messageId: "required",
data: {
member: member.property.name,
owner: checker.typeToString(objectType),
},
});
},
};
},
},
"no-unsafe-child-process": {
meta: {
type: "problem",
docs: {
description: "Prevent unsafe child_process usage that can cause zombie processes",
},
messages: {
unsafePromisifyExec:
"Do not use promisify(exec) directly. Use DisposableExec wrapper with 'using' declaration to prevent zombie processes.",
},
},
create(context) {
return {
CallExpression(node) {
// Ban promisify(exec)
if (
node.callee.type === "Identifier" &&
node.callee.name === "promisify" &&
node.arguments.length > 0 &&
node.arguments[0].type === "Identifier" &&
node.arguments[0].name === "exec"
) {
context.report({
node,
messageId: "unsafePromisifyExec",
});
}
},
};
},
},
"no-sync-fs-methods": {
meta: {
type: "problem",
docs: {
description: "Prevent synchronous filesystem operations",
},
messages: {
syncFsMethod:
"Do not use synchronous fs methods ({{method}}). Use async version instead: {{asyncMethod}}",
},
},
create(context) {
// Map of sync methods to their async equivalents
const syncMethods = {
statSync: "stat",
readFileSync: "readFile",
writeFileSync: "writeFile",
readdirSync: "readdir",
mkdirSync: "mkdir",
unlinkSync: "unlink",
rmdirSync: "rmdir",
existsSync: "access or stat",
accessSync: "access",
copyFileSync: "copyFile",
renameSync: "rename",
chmodSync: "chmod",
chownSync: "chown",
lstatSync: "lstat",
linkSync: "link",
symlinkSync: "symlink",
readlinkSync: "readlink",
realpathSync: "realpath",
truncateSync: "truncate",
fstatSync: "fstat",
appendFileSync: "appendFile",
};
return {
MemberExpression(node) {
// Only flag if it's a property access on 'fs' or imported fs methods
if (
node.property &&
node.property.type === "Identifier" &&
syncMethods[node.property.name] &&
node.object &&
node.object.type === "Identifier" &&
(node.object.name === "fs" || node.object.name === "fsPromises")
) {
context.report({
node,
messageId: "syncFsMethod",
data: {
method: node.property.name,
asyncMethod: syncMethods[node.property.name],
},
});
}
},
};
},
},
"no-cross-boundary-imports": {
meta: {
type: "problem",
docs: {
description: "Enforce folder boundaries to prevent architectural violations",
},
messages: {
browserToNode:
"browser/ cannot import from node/. Move shared code to common/ or use IPC.",
nodeToDesktop:
"node/ cannot import from desktop/. Move shared code to common/ or use dependency injection.",
nodeToCli: "node/ cannot import from cli/. Move shared code to common/.",
cliToBrowser: "cli/ cannot import from browser/. Move shared code to common/.",
desktopToBrowser: "desktop/ cannot import from browser/. Move shared code to common/.",
},
},
create(context) {
return {
ImportDeclaration(node) {
// Allow type-only imports (for DI patterns)
if (node.importKind === "type") {
return;
}
const sourceFile = context.filename;
const importPath = node.source.value;
// Extract folder from source file (browser, node, desktop, cli, common)
const sourceFolderMatch = sourceFile.match(
/\/src\/(browser|node|desktop|cli|common)\//
);
if (!sourceFolderMatch) return;
const sourceFolder = sourceFolderMatch[1];
// Extract folder from import target
// Handle relative imports (e.g., '../node/...')
let targetFolder = null;
if (importPath.startsWith("../")) {
const targetMatch = importPath.match(/\.\.\/(browser|node|desktop|cli|common)\//);
if (targetMatch) {
targetFolder = targetMatch[1];
}
} else if (importPath.startsWith("@/")) {
// Handle alias imports (e.g., '@/node/...')
const targetMatch = importPath.match(/@\/(browser|node|desktop|cli|common)\//);
if (targetMatch) {
targetFolder = targetMatch[1];
}
}
if (!targetFolder) return;
// Allow imports from common
if (targetFolder === "common") return;
// Check for violations
if (sourceFolder === "browser" && targetFolder === "node") {
context.report({
node,
messageId: "browserToNode",
});
} else if (sourceFolder === "node" && targetFolder === "desktop") {
context.report({
node,
messageId: "nodeToDesktop",
});
} else if (sourceFolder === "node" && targetFolder === "cli") {
context.report({
node,
messageId: "nodeToCli",
});
} else if (sourceFolder === "cli" && targetFolder === "browser") {
context.report({
node,
messageId: "cliToBrowser",
});
} else if (sourceFolder === "desktop" && targetFolder === "browser") {
context.report({
node,
messageId: "desktopToBrowser",
});
}
},
};
},
},
"no-module-query-copy": {
meta: {
type: "problem",
docs: {
description:
'Disallow loading a second copy of a repo module with a query specifier (`require("./x?real=1")`)',
},
schema: [
{
type: "object",
properties: {
// Repo-relative test path -> query specifiers it may still load.
allow: {
type: "object",
additionalProperties: { type: "array", items: { type: "string" } },
},
},
additionalProperties: false,
},
],
messages: {
copy: "\"{{specifier}}\" loads a second copy of a repo module. Bun's LCOV keeps only the last-loaded copy of a file, so in a shared CI shard this copy can replace the coverage that the module's own tests recorded (#6339). To get the real exports past a module mock, snapshot `{ ...RealModule }` from a static `import * as RealModule` at file scope, before the mock.module call.",
},
},
create(context) {
const allowed = new Set(
context.options[0]?.allow?.[
path.relative(context.cwd, context.filename).split(path.sep).join("/")
] ?? []
);
// Package specifiers (react-dnd?real=1) stay allowed: their coverage is not reported.
// Asset loader queries (logo.svg?react) are the module's only specifier, not a copy.
const isRepoQueryCopy = (specifier) => {
const queryStart = specifier.indexOf("?");
return (
(specifier.startsWith("@/") ||
specifier.startsWith("@shared/") ||
specifier.startsWith(".")) &&
queryStart !== -1 &&
!/\.(svg|png|jpe?g|gif|webp|avif|ico|css|json|txt|md|html|wasm|woff2?|ttf)$/.test(
specifier.slice(0, queryStart)
)
);
};
const check = (node, source) => {
if (
source?.type === "Literal" &&
typeof source.value === "string" &&
isRepoQueryCopy(source.value) &&
!allowed.has(source.value)
) {
context.report({ node, messageId: "copy", data: { specifier: source.value } });
}
};
return {
CallExpression(node) {
if (node.callee.type === "Identifier" && node.callee.name === "require") {
check(node, node.arguments[0]);
}
},
ImportExpression(node) {
check(node, node.source);
},
// Type-only imports and exports load nothing at runtime, whether the declaration
// (`import type`) or every specifier (`import { type A, type B }`) is type-only.
ImportDeclaration(node) {
const typeOnly =
node.importKind === "type" ||
(node.specifiers.length > 0 &&
node.specifiers.every((specifier) => specifier.importKind === "type"));
if (!typeOnly) check(node, node.source);
},
ExportNamedDeclaration(node) {
const typeOnly =
node.exportKind === "type" ||
(node.specifiers.length > 0 &&
node.specifiers.every((specifier) => specifier.exportKind === "type"));
if (!typeOnly) check(node, node.source);
},
ExportAllDeclaration(node) {
if (node.exportKind !== "type") check(node, node.source);
},
};
},
},
"no-clear-dom-global": {
meta: {
type: "problem",
docs: {
description: "Disallow clearing DOM globals (globalThis.window = undefined) in tests",
},
messages: {
clear:
"Clearing globalThis.{{name}} leaks into every later test file in the same bun process: tests/ui/dom installs the DOM globals only once per process (#5084). Call saveDomGlobals() from tests/ui/domGlobals in beforeEach, before replacing them, and restoreDomGlobals() in afterEach.",
},
},
create(context) {
// Must match DOM_GLOBAL_KEYS in tests/ui/domGlobals.ts (scripts/noClearDomGlobal.test.ts
// checks that every key there is reported).
const DOM_GLOBALS = new Set([
"window",
"document",
"navigator",
"localStorage",
"CustomEvent",
"DocumentFragment",
"Element",
"HTMLInputElement",
"HTMLElement",
"NodeFilter",
"Node",
"Image",
"requestAnimationFrame",
"cancelAnimationFrame",
"getComputedStyle",
"ResizeObserver",
"IntersectionObserver",
"MutationObserver",
]);
const unwrap = (node) => {
while (
node.type === "TSAsExpression" ||
node.type === "TSTypeAssertion" ||
node.type === "TSNonNullExpression" ||
node.type === "TSSatisfiesExpression"
) {
node = node.expression;
}
return node;
};
// Returns the DOM global name for `globalThis.X` / `(globalThis as T).X` / `global["X"]`.
const domGlobalName = (member) => {
if (member.type !== "MemberExpression") {
return null;
}
const object = unwrap(member.object);
if (object.type !== "Identifier" || !["globalThis", "global"].includes(object.name)) {
return null;
}
const name = member.computed
? member.property.type === "Literal"
? member.property.value
: null
: member.property.name;
return DOM_GLOBALS.has(name) ? name : null;
};
// `delete globalThis.X` is not reported: tests also use it to put back a global that
// was absent before (`if (original) { restore } else { delete }`), and telling the
// two apart needs flow analysis.
const isUndefined = (node) => {
node = unwrap(node);
return (
(node.type === "Identifier" && node.name === "undefined") ||
(node.type === "UnaryExpression" && node.operator === "void")
);
};
return {
AssignmentExpression(node) {
const name = domGlobalName(node.left);
if (node.operator === "=" && name != null && isUndefined(node.right)) {
context.report({ node, messageId: "clear", data: { name } });
}
},
};
},
},
"require-module-mock-restore": {
meta: {
type: "problem",
docs: {
description:
"Require every bun `mock.module` registration in a test to be restored after the suite",
},
schema: [
{
type: "object",
properties: {
// Repo-relative test path -> specifiers whose mock may stay unrestored.
allow: {
type: "object",
additionalProperties: { type: "array", items: { type: "string" } },
},
},
additionalProperties: false,
},
],
messages: {
unrestored:
'mock.module("{{specifier}}") leaks into every later test file in the same bun process (`mock.restore()` does not undo module mocks). Restore it with `restoreModulesAfterSuite([["{{specifier}}", { ...realModule }]])` from tests/ui/moduleMocks, re-register the real exports in `afterAll`/`afterEach`, or inject the dependency instead of mocking the module. Restores that may not run (conditional, in helpers passed as values, in `afterEach` of an all-skipped suite) or come from a mutated list do not count.',
dynamicSpecifier:
"mock.module needs a statically known specifier (a string literal, a `const` string, or a loop over a `const` array of them) so its restore can be verified.",
},
},
create(context) {
// bun registers mock.module process-wide and never unregisters it, so a mock silently
// replaces the module for every test file that runs later in the same shard, whether it
// was registered at file scope, from a hook, a test body or a helper. That made
// unrelated suites fail only for certain CI shard orders (#4524, #3359, #4639).
//
// A registration is a restore when it runs only from teardown: inside an
// `afterAll`/`afterEach` callback, or inside a same-file function whose every use is a
// call from teardown code (or its registration as the hook callback itself). A helper
// that setup code also calls is an installer. `restoreModulesAfterSuite` entries are
// restores too. A restore covers installs in the `describe` block (or file) its hook
// runs in, including nested blocks; load-time installs run before every test, so any
// restore that runs covers them. Skipped suites and never-called helpers do not run.
// This is a flow-insensitive lint heuristic for the repo's idioms, not a proof, so it
// errs in one direction (#4660): installs over-approximate and restores
// under-approximate (a restore that may not run, or may not cover a specifier, counts
// as none).
const allowed = new Set(
context.options[0]?.allow?.[
path.relative(context.cwd, context.filename).split(path.sep).join("/")
] ?? []
);
const RESTORE_HOOKS = new Set(["afterAll", "afterEach"]);
const { sourceCode } = context;
const mockCalls = [];
const restoreListCalls = [];
const allCalls = [];
const exitStatements = [];
const isFunctionNode = (node) =>
node?.type === "ArrowFunctionExpression" ||
node?.type === "FunctionExpression" ||
node?.type === "FunctionDeclaration";
const isMockModuleCall = (node) =>
node.callee.type === "MemberExpression" &&
!node.callee.computed &&
node.callee.object.type === "Identifier" &&
node.callee.object.name === "mock" &&
node.callee.property.type === "Identifier" &&
node.callee.property.name === "module";
const unwrapTypeAssertions = (node) => {
let current = node;
while (current?.type === "TSAsExpression" || current?.type === "TSSatisfiesExpression") {
current = current.expression;
}
return current;
};
const findVariable = (identifier) => {
for (let scope = sourceCode.getScope(identifier); scope; scope = scope.upper) {
const variable = scope.set.get(identifier.name);
if (variable) {
return variable;
}
}
return null;
};
// Only the real helper registers an afterAll; a local look-alike does not.
const isRestoreListHelper = (callee) => {
const def = callee.type === "Identifier" ? findVariable(callee)?.defs[0] : null;
return (
callee.name === "restoreModulesAfterSuite" &&
def?.type === "ImportBinding" &&
String(def.parent.source.value).endsWith("/moduleMocks")
);
};
// A loop leaves the elements alone when it destructures each one
// (`for (const [p, real] of entries)`) or never reaches into or hands off its variable
// except to mock.module; `for (const entry of entries) entry[0] = "b"` rewrites the list.
const loopKeepsElements = (loop) => {
const declarator =
loop.left.type === "VariableDeclaration" ? loop.left.declarations[0] : null;
if (declarator?.id.type === "ArrayPattern") {
return declarator.id.elements.every((e) => e == null || e.type === "Identifier");
}
return (
declarator?.id.type === "Identifier" &&
sourceCode.getDeclaredVariables(declarator)[0].references.every(({ identifier }) => {
const parent = identifier.parent;
return parent.type === "CallExpression" || parent.type === "NewExpression"
? isMockModuleCall(parent) && parent.arguments[0] === identifier
: !(parent.type === "MemberExpression" && parent.object === identifier);
})
);
};
// A `const` array still holds its literal elements only when every use reads it
// whole: looping over it, spreading it into a copy, or handing it to
// restoreModulesAfterSuite. Any other use (`entries.length = 0`, `.push`, passing it
// elsewhere, exporting it) may change what it holds by the time it is read.
const isSealedArray = (variable) =>
variable.defs[0].parent.parent?.type !== "ExportNamedDeclaration" &&
variable.references.every((reference) => {
if (reference.init) {
return true;
}
let node = reference.identifier;
while (
node.parent.type === "TSAsExpression" ||
node.parent.type === "TSSatisfiesExpression" ||
node.parent.type === "TSNonNullExpression"
) {
node = node.parent;
}
const parent = node.parent;
return (
(parent.type === "ForOfStatement" &&
parent.right === node &&
loopKeepsElements(parent)) ||
(parent.type === "SpreadElement" && parent.parent.type === "ArrayExpression") ||
(parent.type === "CallExpression" &&
parent.arguments[0] === node &&
isRestoreListHelper(parent.callee))
);
});
// Element nodes of a statically known array: an array literal (spreads of other known
// arrays included) or a sealed `const` bound to one.
const resolveArrayElements = (rawNode, depth = 0) => {
const node = unwrapTypeAssertions(rawNode);
if (depth > 5 || node == null) {
return null;
}
if (node.type === "Identifier") {
const variable = findVariable(node);
const def = variable?.defs[0];
return def?.type === "Variable" &&
def.parent.kind === "const" &&
isSealedArray(variable)
? resolveArrayElements(def.node.init, depth + 1)
: null;
}
if (node.type !== "ArrayExpression") {
return null;
}
const elements = [];
for (const element of node.elements) {
if (element?.type === "SpreadElement") {
const spread = resolveArrayElements(element.argument, depth + 1);
if (spread == null) {
return null;
}
elements.push(...spread);
} else if (element != null) {
elements.push(element);
}
}
return elements;
};
// Every specifier string an expression can evaluate to, or null when not static. Covers
// literals, `const` strings, and loop variables over known arrays (`for (const p of
// PATHS)`, `for (const [p, exports] of realModules)`), so looped installs and restores
// stay checkable.
const resolveSpecifiers = (rawNode, depth = 0) => {
const node = unwrapTypeAssertions(rawNode);
if (depth > 5 || node == null) {
return null;
}
if (node.type === "Literal") {
return typeof node.value === "string" ? [node.value] : null;
}
if (node.type === "TemplateLiteral") {
return node.expressions.length === 0 ? [node.quasis[0].value.cooked] : null;
}
if (node.type !== "Identifier") {
return null;
}
const def = findVariable(node)?.defs[0];
if (def?.type !== "Variable") {
return null;
}
const declarator = def.node;
const declaration = def.parent;
if (
declaration.parent?.type === "ForOfStatement" &&
declaration.parent.left === declaration
) {
const elements = resolveArrayElements(declaration.parent.right, depth + 1);
if (elements == null) {
return null;
}
let pick;
if (declarator.id.type === "Identifier") {
pick = (element) => element;
} else if (
declarator.id.type === "ArrayPattern" &&
declarator.id.elements[0]?.type === "Identifier" &&
declarator.id.elements[0].name === node.name
) {
pick = (element) => (element.type === "ArrayExpression" ? element.elements[0] : null);
} else {
return null;
}
const specifiers = [];
for (const element of elements) {
const resolved = resolveSpecifiers(pick(element), depth + 1);
if (resolved == null) {
return null;
}
specifiers.push(...resolved);
}
return specifiers;
}
return declaration.kind === "const" && declarator.id.type === "Identifier"
? resolveSpecifiers(declarator.init, depth + 1)
: null;
};
const getCalleeRootName = (callee) => {
let current = callee;
while (current.type === "MemberExpression" || current.type === "CallExpression") {
current = current.type === "MemberExpression" ? current.object : current.callee;
}
return current.type === "Identifier" ? current.name : null;
};
const SUITE_CALLS = new Set(["describe", "xdescribe"]);
const HOOK_CALLS = new Set(["beforeAll", "beforeEach", "afterAll", "afterEach"]);
const TEST_CALLS = new Set(["test", "it", "xtest", "xit"]);
// Whether the callee chain uses one of `names`, e.g. `test.skip.each(rows)(...)`.
const calleeUses = (call, names) => {
for (
let callee = call.callee;
callee.type === "MemberExpression" || callee.type === "CallExpression";
callee = callee.type === "MemberExpression" ? callee.object : callee.callee
) {
if (
callee.type === "MemberExpression" &&
!callee.computed &&
callee.property.type === "Identifier" &&
names.has(callee.property.name)
) {
return true;
}
}
return false;
};
const SKIP_MODIFIERS = new Set(["skip", "todo"]);
const CONDITIONAL_MODIFIERS = new Set(["if", "skipIf", "todoIf"]);
// `describe.skip(...)`, `test.todo(...)`, `xit(...)`: the callback never runs.
const isSkippedCall = (call) =>
getCalleeRootName(call.callee)?.startsWith("x") || calleeUses(call, SKIP_MODIFIERS);
const isFunctionContext = (node) => isFunctionNode(node) || node.type === "Program";
const enclosingContext = (node) =>
sourceCode.getAncestors(node).findLast((ancestor) => isFunctionContext(ancestor));
// The function a variable names: `function f() {}` or `const f = () => {}`.
const functionOfVariable = (variable) => {
const def = variable?.defs[0];
if (def?.type === "FunctionName") {
return def.node;
}
return def?.type === "Variable" && isFunctionNode(def.node.init) ? def.node.init : null;
};
const variableOfFunction = (fn) => {
const id =
fn.type === "FunctionDeclaration"
? fn.id
: fn.parent?.type === "VariableDeclarator"
? fn.parent.id
: null;
return id?.type === "Identifier" ? findVariable(id) : null;
};
const suiteIsWithin = (inner, outer) =>
outer === null ||
(inner !== null && outer.range[0] <= inner.range[0] && inner.range[1] <= outer.range[1]);
const LOOPS = new Set([
"ForStatement",
"ForInStatement",
"ForOfStatement",
"WhileStatement",
"DoWhileStatement",
]);
// Whether `node` can be skipped while its enclosing function runs: it sits in a branch
// (`if (p === "a") mock.module(p, ...)` in a loop), a return/throw precedes it, or a
// return/throw/break/continue sits in a loop around it.
const runsConditionally = (node) => {
const fn = enclosingContext(node);
const loops = [];