vitest-native 0.15.0 → 0.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,4 @@
1
+ import { t as placeSetupFiles } from "./setup-files-C6-77IIs.mjs";
1
2
  import { n as ignorePattern, r as packageOfRequest, t as findNodeModuleMocks } from "./root-mocks-DP95ncxD.mjs";
2
3
  import { createRequire, isBuiltin } from "node:module";
3
4
  import { fileURLToPath } from "node:url";
@@ -16,6 +17,9 @@ const WITH_FACTORY = /* @__PURE__ */ new Set(["mock", "doMock"]);
16
17
  const UNMOCK = /* @__PURE__ */ new Set(["unmock", "doUnmock"]);
17
18
  const TRANSFORMABLE = /\.(?:[cm]?[jt]sx?)$/;
18
19
  const HAS_JEST_MOCK = /\bjest\s*\.\s*(?:mock|unmock|doMock|doUnmock)\s*\(/;
20
+ const NAMES_JEST = /\bjest\b/;
21
+ const NAMES_MOCK_METHOD = /\b(?:mock|unmock|doMock|doUnmock)\b(?!\s*\.)/;
22
+ const JEST_SOURCES = /* @__PURE__ */ new Set(["@jest/globals", "vitest-native/jest-compat/jest-globals"]);
19
23
  const SETUP = "__vn_jest_compat__";
20
24
  /** Prepended to a file whose mock factories use the setup. Exported for tests. */
21
25
  const SETUP_ACCESSOR = `const ${SETUP} = vi.hoisted(() => (name) => {\n if (typeof globalThis[name] === "function") return globalThis[name];\n throw Object.assign(new Error("[vitest-native] jest.mock() factories need the jest-compat setup, which this test run does not load. " +\n "Add jestCompatSetup from 'vitest-native/jest-compat' to test.setupFiles, ahead of any setup file that calls jest.mock()."),\n { name: "VitestNativeError", code: "JEST_COMPAT_SETUP_MISSING" });\n});\n`;
@@ -34,6 +38,160 @@ function walk(node, fn) {
34
38
  } else if (child && typeof child.type === "string") walk(child, fn);
35
39
  }
36
40
  }
41
+ /** Whether `node` is a `require('<literal>')` of one of JEST_SOURCES. */
42
+ function jestSourceOf(node) {
43
+ const spec = node?.type === "CallExpression" ? requireSpec(node) : null;
44
+ return spec !== null && JEST_SOURCES.has(spec);
45
+ }
46
+ function propertyName(node) {
47
+ if (node?.type === "Identifier") return node.name;
48
+ if (node?.type === "Literal" && typeof node.value === "string") return node.value;
49
+ return null;
50
+ }
51
+ /** The names a declaration pattern binds. */
52
+ function patternNames(pattern, into = []) {
53
+ if (!pattern) return into;
54
+ if (pattern.type === "Identifier") into.push(pattern.name);
55
+ else if (pattern.type === "ObjectPattern") for (const property of pattern.properties) patternNames(property.type === "RestElement" ? property.argument : property.value, into);
56
+ else if (pattern.type === "ArrayPattern") for (const element of pattern.elements) patternNames(element, into);
57
+ else if (pattern.type === "AssignmentPattern") patternNames(pattern.left, into);
58
+ else if (pattern.type === "RestElement") patternNames(pattern.argument, into);
59
+ return into;
60
+ }
61
+ /** The `var` names a function body declares, outside its nested functions. */
62
+ function varNames(body) {
63
+ const found = [];
64
+ walk(body, (node) => {
65
+ if (FUNCTION.has(node.type) || node.type === "ClassBody") return false;
66
+ if (node.type === "VariableDeclaration" && node.kind === "var") for (const declarator of node.declarations) patternNames(declarator.id, found);
67
+ });
68
+ return found;
69
+ }
70
+ /** The names a block's own statements declare with let, const, class or function. */
71
+ function blockNames(statements) {
72
+ const found = [];
73
+ for (const statement of statements) {
74
+ const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
75
+ if (declaration?.type === "VariableDeclaration" && declaration.kind !== "var") for (const declarator of declaration.declarations) patternNames(declarator.id, found);
76
+ else if ((declaration?.type === "FunctionDeclaration" || declaration?.type === "ClassDeclaration") && declaration.id) found.push(declaration.id.name);
77
+ }
78
+ return found;
79
+ }
80
+ /**
81
+ * The identifiers named in `watched` that a scope inside the Program declares again (a
82
+ * parameter, a local, a catch binding): those refer to the local, not to the
83
+ * Program-level binding of that name.
84
+ */
85
+ function shadowedIdentifiers(ast, watched) {
86
+ const shadowed = /* @__PURE__ */ new WeakSet();
87
+ const scopes = [];
88
+ const visit = (node) => {
89
+ if (!node || typeof node.type !== "string") return;
90
+ let scope = null;
91
+ if (FUNCTION.has(node.type)) {
92
+ const declared = node.params.flatMap((param) => patternNames(param));
93
+ if (node.type === "FunctionExpression" && node.id) declared.push(node.id.name);
94
+ if (node.body.type === "BlockStatement") declared.push(...varNames(node.body), ...blockNames(node.body.body));
95
+ scope = declared;
96
+ } else if (node.type === "BlockStatement" || node.type === "StaticBlock") scope = blockNames(node.body);
97
+ else if (node.type === "CatchClause") scope = patternNames(node.param);
98
+ else if ((node.type === "ForStatement" || node.type === "ForInStatement" || node.type === "ForOfStatement") && (node.init ?? node.left)?.type === "VariableDeclaration" && (node.init ?? node.left).kind !== "var") scope = (node.init ?? node.left).declarations.flatMap((d) => patternNames(d.id));
99
+ const pushed = scope !== null && scope.some((name) => watched.has(name));
100
+ if (pushed) scopes.push(new Set(scope));
101
+ if (node.type === "Identifier" && watched.has(node.name)) {
102
+ if (scopes.some((names) => names.has(node.name))) shadowed.add(node);
103
+ }
104
+ for (const key in node) {
105
+ if (key === "type" || key === "start" || key === "end" || key === "loc") continue;
106
+ const child = node[key];
107
+ if (Array.isArray(child)) for (const c of child) visit(c);
108
+ else if (child && typeof child.type === "string") visit(child);
109
+ }
110
+ if (pushed) scopes.pop();
111
+ };
112
+ visit(ast);
113
+ return shadowed;
114
+ }
115
+ /**
116
+ * The file's jest bindings. A Program-level further name for a jest object (`const j =
117
+ * mockJest`) or for one of its hoisted methods (`const { mock } = jest`) that a mock call
118
+ * then goes through is one Jest would not hoist either, and this transform would leave
119
+ * unapplied without a word, so it fails, naming the binding and its line. A name a scope
120
+ * declares again, or that is reassigned, is not that binding and is left alone, and so is
121
+ * `requireActual` under any name: it is never hoisted and works at run time as it is.
122
+ */
123
+ function jestBindings(ast, code, id) {
124
+ const names = /* @__PURE__ */ new Set(["jest"]);
125
+ const namespaces = /* @__PURE__ */ new Set();
126
+ const program = ast.body.map((statement) => statement.type === "ExportNamedDeclaration" && statement.declaration ? statement.declaration : statement);
127
+ for (const statement of program) if (statement.type === "ImportDeclaration") {
128
+ const fromJest = JEST_SOURCES.has(statement.source.value);
129
+ for (const specifier of statement.specifiers) if (!fromJest) {
130
+ if (specifier.local.name === "jest") names.delete("jest");
131
+ } else if (specifier.type === "ImportNamespaceSpecifier") namespaces.add(specifier.local.name);
132
+ else if (specifier.type === "ImportSpecifier" && propertyName(specifier.imported) === "jest") names.add(specifier.local.name);
133
+ } else if (statement.type === "VariableDeclaration") for (const declarator of statement.declarations) {
134
+ const init = declarator.init;
135
+ if (!init) continue;
136
+ if (jestSourceOf(init)) {
137
+ if (declarator.id.type === "Identifier") namespaces.add(declarator.id.name);
138
+ else if (declarator.id.type === "ObjectPattern") {
139
+ for (const property of declarator.id.properties) if (property.type === "Property" && propertyName(property.key) === "jest" && property.value.type === "Identifier") names.add(property.value.name);
140
+ }
141
+ } else if (init.type === "MemberExpression" && jestSourceOf(init.object) && propertyName(init.property) === "jest" && declarator.id.type === "Identifier") names.add(declarator.id.name);
142
+ }
143
+ const aliases = /* @__PURE__ */ new Map();
144
+ const methodAliases = /* @__PURE__ */ new Map();
145
+ const plainJest = (node) => node?.type === "Identifier" && names.has(node.name) || node?.type === "MemberExpression" && node.object?.type === "Identifier" && namespaces.has(node.object.name) && propertyName(node.property) === "jest";
146
+ for (const statement of program) {
147
+ if (statement.type !== "VariableDeclaration") continue;
148
+ for (const declarator of statement.declarations) {
149
+ const [target, value] = [declarator.id, declarator.init];
150
+ if (!value) continue;
151
+ if (plainJest(value)) {
152
+ if (target.type === "Identifier" && !names.has(target.name)) aliases.set(target.name, declarator);
153
+ if (target.type === "ObjectPattern") for (const property of target.properties) {
154
+ const name = property.type === "Property" ? propertyName(property.key) : null;
155
+ if (name && HOISTABLE.has(name) && property.value.type === "Identifier") methodAliases.set(property.value.name, declarator);
156
+ }
157
+ } else if (value.type === "MemberExpression" && plainJest(value.object) && HOISTABLE.has(propertyName(value.property) ?? "") && target.type === "Identifier") methodAliases.set(target.name, declarator);
158
+ }
159
+ }
160
+ const watched = /* @__PURE__ */ new Set([
161
+ ...names,
162
+ ...namespaces,
163
+ ...aliases.keys(),
164
+ ...methodAliases.keys()
165
+ ]);
166
+ watched.delete("jest");
167
+ const shadowed = watched.size > 0 ? shadowedIdentifiers(ast, watched) : /* @__PURE__ */ new WeakSet();
168
+ const isJest = (node) => node?.type === "Identifier" && names.has(node.name) && (node.name === "jest" || !shadowed.has(node)) || node?.type === "MemberExpression" && node.object?.type === "Identifier" && namespaces.has(node.object.name) && !shadowed.has(node.object) && propertyName(node.property) === "jest" && (!node.computed || node.property.type === "Literal");
169
+ if (aliases.size === 0 && methodAliases.size === 0) return { isJest };
170
+ walk(ast, (node) => {
171
+ const target = node.type === "AssignmentExpression" ? node.left : node.type === "UpdateExpression" ? node.argument : null;
172
+ if (target?.type === "Identifier" && !shadowed.has(target)) {
173
+ aliases.delete(target.name);
174
+ methodAliases.delete(target.name);
175
+ }
176
+ });
177
+ walk(ast, (node) => {
178
+ if (node.type !== "CallExpression") return;
179
+ const callee = node.callee;
180
+ let binding = null;
181
+ let name = "";
182
+ if (callee?.type === "MemberExpression" && callee.object?.type === "Identifier" && aliases.has(callee.object.name) && !shadowed.has(callee.object) && HOISTABLE.has(propertyName(callee.property) ?? "")) {
183
+ binding = aliases.get(callee.object.name);
184
+ name = `${callee.object.name}.${propertyName(callee.property)}`;
185
+ } else if (callee?.type === "Identifier" && methodAliases.has(callee.name) && !shadowed.has(callee)) {
186
+ binding = methodAliases.get(callee.name);
187
+ name = callee.name;
188
+ }
189
+ if (!binding) return;
190
+ const line = (at) => code.slice(0, at).split("\n").length;
191
+ throw new VitestNativeError("JEST_BINDING_NOT_FOLLOWED", `[vitest-native] jestMockTransform cannot follow \`${code.slice(binding.start, binding.end)}\` (${id.split("?")[0]}:${line(binding.start)}), so the \`${name}(…)\` call on line ${line(node.start)} would not be hoisted or registered. Jest does not hoist it either. Call it on the jest object itself: \`jest\`, or the name it is imported as from '@jest/globals'.`);
192
+ });
193
+ return { isJest };
194
+ }
37
195
  const FUNCTION = /* @__PURE__ */ new Set([
38
196
  "FunctionExpression",
39
197
  "ArrowFunctionExpression",
@@ -42,11 +200,11 @@ const FUNCTION = /* @__PURE__ */ new Set([
42
200
  const NODE_MODULES = /[\\/]node_modules[\\/]/;
43
201
  const SOURCE_FILE = /\.[cm]?[jt]sx?$/;
44
202
  /** The string specifier of a `jest.requireActual('<literal>')` call, or null. */
45
- function requireActualSpec(node) {
203
+ function requireActualSpec(node, jest) {
46
204
  if (node.type !== "CallExpression" || node.arguments.length !== 1) return null;
47
205
  const callee = node.callee;
48
206
  if (callee?.type !== "MemberExpression" || callee.computed) return null;
49
- if (callee.object?.type !== "Identifier" || callee.object.name !== "jest") return null;
207
+ if (!jest.isJest(callee.object)) return null;
50
208
  if (callee.property?.type !== "Identifier" || callee.property.name !== "requireActual") return null;
51
209
  return literalSpec(node.arguments[0]);
52
210
  }
@@ -68,11 +226,11 @@ const BINDS_REQUIRE = /\b(?:const|let|var|function|class)\s+require\b|\bimport\s
68
226
  * its own body, not in a nested function or a class body (where `await` is not allowed
69
227
  * either). `mocked` is the specifier the factory mocks, whose own require stays as is.
70
228
  */
71
- function ownLoadCalls(factory, mocked, requireIsGlobal) {
229
+ function ownLoadCalls(factory, mocked, requireIsGlobal, jest) {
72
230
  const calls = [];
73
231
  walk(factory.body, (node) => {
74
232
  if (FUNCTION.has(node.type) || node.type === "ClassBody") return false;
75
- const actual = requireActualSpec(node);
233
+ const actual = requireActualSpec(node, jest);
76
234
  if (actual !== null) return void calls.push({
77
235
  node,
78
236
  spec: actual,
@@ -175,14 +333,7 @@ function jestMockTransform(options = {}) {
175
333
  root,
176
334
  ...found
177
335
  });
178
- const setupFiles = Array.isArray(test.setupFiles) ? [...test.setupFiles] : test.setupFiles ? [test.setupFiles] : [];
179
- if (setupFiles.includes(id)) return;
180
- let compat = -1;
181
- setupFiles.forEach((file, index) => {
182
- if (JEST_COMPAT_SETUP.test(file)) compat = index;
183
- });
184
- setupFiles.splice(compat + 1, 0, id);
185
- test.setupFiles = setupFiles;
336
+ placeSetupFiles(test, [id], (file) => JEST_COMPAT_SETUP.test(file));
186
337
  },
187
338
  configResolved(config) {
188
339
  const native = config.plugins.find((plugin) => plugin.name === "vitest-native");
@@ -221,7 +372,7 @@ function jestMockTransform(options = {}) {
221
372
  if (id.includes("/node_modules/")) return null;
222
373
  const file = id.split("?")[0];
223
374
  if (!TRANSFORMABLE.test(file)) return null;
224
- if (!HAS_JEST_MOCK.test(code)) return null;
375
+ if (!HAS_JEST_MOCK.test(code) && !(NAMES_JEST.test(code) && NAMES_MOCK_METHOD.test(code))) return null;
225
376
  const owner = rootMockModules.has(file) ? projectsByRoot.get(rootMockModules.get(file).root) ?? project : project;
226
377
  let module;
227
378
  const spelled = path.isAbsolute(file) ? viteId(file) : file;
@@ -374,15 +525,16 @@ function adapt(ctx, code, id, project, manualMockFor = () => null, automockable
374
525
  } catch {
375
526
  return null;
376
527
  }
528
+ const jest = jestBindings(ast, code, id);
377
529
  const candidates = /* @__PURE__ */ new Map();
378
530
  const requireIsGlobal = !BINDS_REQUIRE.test(code);
379
531
  walk(ast, (node) => {
380
- const factory = mockFactoryOf(node);
532
+ const factory = mockFactoryOf(node, jest);
381
533
  if (!factory || factory.generator) return;
382
- const calls = ownLoadCalls(factory, literalSpec(node.arguments[0]), requireIsGlobal);
534
+ const calls = ownLoadCalls(factory, literalSpec(node.arguments[0]), requireIsGlobal, jest);
383
535
  if (calls.length > 0) candidates.set(factory, calls);
384
536
  });
385
- if (candidates.size === 0) return rewrite(code, ast, /* @__PURE__ */ new Map(), manualMockFor, automockable);
537
+ if (candidates.size === 0) return rewrite(code, ast, jest, /* @__PURE__ */ new Map(), manualMockFor, automockable);
386
538
  const specs = new Set([...candidates.values()].flat().map((call) => call.spec));
387
539
  return Promise.all([...specs].map(async (spec) => {
388
540
  try {
@@ -397,15 +549,15 @@ function adapt(ctx, code, id, project, manualMockFor = () => null, automockable
397
549
  const moved = calls.filter((call) => owned.has(call.spec));
398
550
  if (moved.length > 0) toAsync.set(factory, moved);
399
551
  }
400
- return rewrite(code, ast, toAsync, manualMockFor, automockable);
552
+ return rewrite(code, ast, jest, toAsync, manualMockFor, automockable);
401
553
  });
402
554
  }
403
555
  /** The factory of a `jest.mock`/`jest.doMock` call with an inline function factory. */
404
- function mockFactoryOf(node) {
556
+ function mockFactoryOf(node, jest) {
405
557
  if (node.type !== "CallExpression" || node.arguments.length < 2) return null;
406
558
  const callee = node.callee;
407
559
  if (callee?.type !== "MemberExpression" || callee.computed) return null;
408
- if (callee.object?.type !== "Identifier" || callee.object.name !== "jest") return null;
560
+ if (!jest.isJest(callee.object)) return null;
409
561
  if (callee.property?.type !== "Identifier" || !WITH_FACTORY.has(callee.property.name)) return null;
410
562
  const factory = node.arguments[1];
411
563
  return factory.type === "ArrowFunctionExpression" || factory.type === "FunctionExpression" ? factory : null;
@@ -414,7 +566,7 @@ function mockFactoryOf(node) {
414
566
  * The transform itself. `toAsync` maps a factory to the `jest.requireActual` calls that
415
567
  * load through Vite instead (see "`jest.requireActual` of project source" above).
416
568
  */
417
- function rewrite(code, ast, toAsync, manualMockFor = () => null, automockable = () => false) {
569
+ function rewrite(code, ast, jest, toAsync, manualMockFor = () => null, automockable = () => false) {
418
570
  const s = new MagicString(code);
419
571
  let changed = false;
420
572
  const topLevel = /* @__PURE__ */ new Map();
@@ -442,7 +594,7 @@ function rewrite(code, ast, toAsync, manualMockFor = () => null, automockable =
442
594
  if (!callee || callee.type !== "MemberExpression" || callee.computed) return;
443
595
  const obj = callee.object;
444
596
  const prop = callee.property;
445
- if (!obj || obj.type !== "Identifier" || obj.name !== "jest") return;
597
+ if (!jest.isJest(obj)) return;
446
598
  if (!prop || prop.type !== "Identifier" || !HOISTABLE.has(prop.name)) return;
447
599
  s.overwrite(obj.start, obj.end, "vi");
448
600
  changed = true;
@@ -447,11 +447,42 @@ const EXPO_DEV_STUBS = {
447
447
  };
448
448
  const EXPO_SUFFIXES = Object.keys(EXPO_DEV_STUBS);
449
449
 
450
+ /**
451
+ * expo-modules-core's `createSnapshotFriendlyRef` (src/Refs.ts) is React's `createRef`.
452
+ * Expo modules pass refs made with it to their native views as props: expo-image's
453
+ * `nativeViewRef` and `containerViewRef`. A snapshot then printed the host instance and
454
+ * React's fiber tree behind them, thousands of lines with render timings that differ on
455
+ * every run. jest-expo serves a ref that prints as "[React.ref]" (src/preset/setup.js),
456
+ * and this is that ref: `{ current: null }` with a non-enumerable `toJSON`.
457
+ */
458
+ const SNAPSHOT_FRIENDLY_REF = `
459
+ exports.createSnapshotFriendlyRef = function createSnapshotFriendlyRef() {
460
+ const ref = { current: null };
461
+ Object.defineProperty(ref, "toJSON", { value: () => "[React.ref]" });
462
+ return ref;
463
+ };
464
+ `;
465
+ const EXPO_MODULES_CORE_STUBS = {
466
+ "build/Refs.js": SNAPSHOT_FRIENDLY_REF,
467
+ "src/Refs.ts": SNAPSHOT_FRIENDLY_REF,
468
+ };
469
+ const EXPO_MODULES_CORE_SUFFIXES = Object.keys(EXPO_MODULES_CORE_STUBS);
470
+
471
+ /**
472
+ * The stand-ins for files outside react-native, by package directory. The registry keys
473
+ * on them, so a changed stand-in is not served from a registry built with the old one.
474
+ */
475
+ export const PACKAGE_STUBS = {
476
+ expo: EXPO_DEV_STUBS,
477
+ "expo-modules-core": EXPO_MODULES_CORE_STUBS,
478
+ };
479
+
450
480
  /** Normalised-path test: is this a native-boundary module? */
451
481
  export function isBoundary(normPath) {
452
482
  return (
453
483
  SUFFIXES.some((s) => normPath.endsWith("/react-native/" + s)) ||
454
- EXPO_SUFFIXES.some((s) => normPath.endsWith("/expo/" + s))
484
+ EXPO_SUFFIXES.some((s) => normPath.endsWith("/expo/" + s)) ||
485
+ EXPO_MODULES_CORE_SUFFIXES.some((s) => normPath.endsWith("/expo-modules-core/" + s))
455
486
  );
456
487
  }
457
488
 
@@ -466,5 +497,8 @@ export function boundarySourceFor(normPath, platform = "ios", version = "0.0.0")
466
497
  for (const s of EXPO_SUFFIXES) {
467
498
  if (normPath.endsWith("/expo/" + s)) return EXPO_DEV_STUBS[s];
468
499
  }
500
+ for (const s of EXPO_MODULES_CORE_SUFFIXES) {
501
+ if (normPath.endsWith("/expo-modules-core/" + s)) return EXPO_MODULES_CORE_STUBS[s];
502
+ }
469
503
  return null;
470
504
  }
@@ -2,11 +2,15 @@
2
2
  //
3
3
  // Expensive toolchain/configuration modules must not become permanent members of
4
4
  // Vite's main process merely because their result is needed once at startup. The
5
- // child receives one JSON value on stdin and returns one JSON value over fd 3;
5
+ // child receives one JSON value in a file named by its first argument (readInput) and
6
+ // returns one JSON value over fd 3;
6
7
  // stdout/stderr remain available to arbitrary user/toolchain code without being
7
8
  // able to corrupt the protocol.
8
9
  import { spawn } from "node:child_process";
10
+ import crypto from "node:crypto";
11
+ import fs from "node:fs";
9
12
  import os from "node:os";
13
+ import path from "node:path";
10
14
  import { suspendedNote, suspensionTracker } from "./suspension.mjs";
11
15
 
12
16
  // The protocol channel carries the one answer and is capped strictly. stdout/stderr
@@ -29,9 +33,73 @@ export function lowerPriority(pid, priority, setPriority = os.setPriority) {
29
33
  }
30
34
  }
31
35
 
36
+ /** The helper's side: the JSON value its parent wrote for it. */
37
+ export function readInput(argv = process.argv) {
38
+ return JSON.parse(fs.readFileSync(argv[2], "utf8"));
39
+ }
40
+
41
+ /**
42
+ * Writes a helper's input to a file of its own in `dir`, read by the helper by path.
43
+ *
44
+ * Not stdin: the parent would end it with a write and a shutdown request, and a pending
45
+ * request holds this process's event loop open. On Windows a pipe's shutdown is a flush
46
+ * that waits until the reader has drained the pipe or is gone, and closing the pipe does
47
+ * not cancel it: a helper stopped before it read its input (one still starting on a
48
+ * loaded machine) kept a cancelled run from exiting for seconds. A file involves no
49
+ * request to the child. Created exclusively under a random name, so concurrent workers
50
+ * never share one.
51
+ */
52
+ function writeInput(dir, label, input) {
53
+ const inputDir = path.join(dir, "helper-input");
54
+ fs.mkdirSync(inputDir, { recursive: true });
55
+ removeOrphanedInputs(inputDir);
56
+ const file = path.join(
57
+ inputDir,
58
+ [slugOf(label), HOST, process.pid, crypto.randomUUID(), "json"].join("."),
59
+ );
60
+ fs.writeFileSync(file, JSON.stringify(input), { flag: "wx", mode: 0o600 });
61
+ return file;
62
+ }
63
+
64
+ const slugOf = (text) => text.replace(/[^a-z0-9]+/gi, "-").toLowerCase() || "x";
65
+ // Input files are named <label>.<host>.<pid>.<uuid>.json.
66
+ const HOST = slugOf(os.hostname());
67
+ // A helper reads its input within seconds of starting.
68
+ const ORPHAN_AGE_MS = 10 * 60_000;
69
+
70
+ /**
71
+ * Removes input files whose writer has died: a run killed outright (SIGKILL, a closed
72
+ * terminal) cannot run the removal its helper's end would have. Only this host's files,
73
+ * and only old ones: a process id means nothing on another machine or container sharing
74
+ * the directory (a mounted project in CI), and a recent file may still be read. A process
75
+ * that exists but cannot be signalled (EPERM) is alive.
76
+ */
77
+ function removeOrphanedInputs(inputDir) {
78
+ // writeInput has just created the directory: an unreadable one fails that write, and
79
+ // runBoundedProcess reports it.
80
+ const now = Date.now();
81
+ for (const name of fs.readdirSync(inputDir)) {
82
+ const [, host, pidText] = name.split(".");
83
+ const pid = Number(pidText);
84
+ if (host !== HOST || !Number.isInteger(pid) || pid <= 0 || pid === process.pid) continue;
85
+ const file = path.join(inputDir, name);
86
+ try {
87
+ if (now - fs.statSync(file).mtimeMs < ORPHAN_AGE_MS) continue;
88
+ process.kill(pid, 0);
89
+ } catch (error) {
90
+ if (error?.code === "ESRCH") removeInput(file);
91
+ }
92
+ }
93
+ }
94
+
95
+ function removeInput(file) {
96
+ // A helper killed on Windows may still hold it for a moment.
97
+ fs.rmSync(file, { force: true, maxRetries: 5, retryDelay: 50 });
98
+ }
99
+
32
100
  function attempt(
33
101
  entryFile,
34
- input,
102
+ inputFile,
35
103
  heapMb,
36
104
  spawnProcess,
37
105
  timeoutMs,
@@ -47,10 +115,11 @@ function attempt(
47
115
  }
48
116
  let child;
49
117
  try {
50
- child = spawnProcess(process.execPath, [`--max-old-space-size=${heapMb}`, entryFile], {
51
- stdio: ["pipe", "pipe", "pipe", "pipe"],
52
- windowsHide: true,
53
- });
118
+ child = spawnProcess(
119
+ process.execPath,
120
+ [`--max-old-space-size=${heapMb}`, entryFile, inputFile],
121
+ { stdio: ["ignore", "pipe", "pipe", "pipe"], windowsHide: true },
122
+ );
54
123
  } catch (error) {
55
124
  resolve({
56
125
  ok: false,
@@ -147,9 +216,6 @@ function attempt(
147
216
  child.on("error", (error) => {
148
217
  finish({ ok: false, oom: false, error: error.message, heapMb });
149
218
  });
150
- // A helper may exit before draining input. EPIPE is emitted asynchronously;
151
- // catching stdin.end() does not catch it. The close event reports the cause.
152
- child.stdin?.on("error", () => {});
153
219
  child.on("close", (code, exitSignal) => {
154
220
  if (settled) return;
155
221
  const oom = OOM_RE.test(stderr);
@@ -188,17 +254,6 @@ function attempt(
188
254
  });
189
255
  }, pollMs);
190
256
  timer.unref?.();
191
- try {
192
- child.stdin?.end(JSON.stringify(input));
193
- } catch (error) {
194
- child.kill("SIGKILL");
195
- finish({
196
- ok: false,
197
- oom: false,
198
- heapMb,
199
- error: error instanceof Error ? error.message : String(error),
200
- });
201
- }
202
257
  });
203
258
  }
204
259
 
@@ -218,16 +273,44 @@ export async function runBoundedProcess(
218
273
  priority,
219
274
  // Let this process exit while the child runs (the child's timer is unref'd too).
220
275
  unref = false,
276
+ // Where the input file is written: the project's cache directory (cacheRootFor), on
277
+ // the project's volume rather than the system temporary directory.
278
+ inputDir = os.tmpdir(),
221
279
  },
222
280
  ) {
223
- const run = (heapMb) =>
224
- attempt(entryFile, input, heapMb, spawnProcess, timeoutMs, label, signal, priority, unref);
225
- const first = await run(initialHeapMb);
226
- if (first.ok || !first.oom || retryHeapMb <= initialHeapMb) {
227
- return { ...first, attempts: 1 };
281
+ let inputFile;
282
+ try {
283
+ inputFile = writeInput(inputDir, label, input);
284
+ } catch (error) {
285
+ return {
286
+ ok: false,
287
+ oom: false,
288
+ error: `${label} input could not be written: ${error instanceof Error ? error.message : String(error)}`,
289
+ attempts: 0,
290
+ };
291
+ }
292
+ try {
293
+ const run = (heapMb) =>
294
+ attempt(
295
+ entryFile,
296
+ inputFile,
297
+ heapMb,
298
+ spawnProcess,
299
+ timeoutMs,
300
+ label,
301
+ signal,
302
+ priority,
303
+ unref,
304
+ );
305
+ const first = await run(initialHeapMb);
306
+ if (first.ok || !first.oom || retryHeapMb <= initialHeapMb) {
307
+ return { ...first, attempts: 1 };
308
+ }
309
+ const retry = await run(retryHeapMb);
310
+ return { ...retry, attempts: 2 };
311
+ } finally {
312
+ removeInput(inputFile);
228
313
  }
229
- const retry = await run(retryHeapMb);
230
- return { ...retry, attempts: 2 };
231
314
  }
232
315
 
233
316
  export const boundedProcessDefaults = Object.freeze({
@@ -0,0 +1,148 @@
1
+ // Gesture Handler 3's buttons, pressable from Testing Library under the native engine.
2
+ //
3
+ // The package's jestSetup.js mocks its native module, its legacy buttons and its gesture
4
+ // detector host, but leaves the native button host (components/GestureHandlerButton)
5
+ // real, which v3's Touchable, RectButton, BorderlessButton and Pressable render. That host
6
+ // takes `onButtonPress*` callbacks, which only the device's native view calls, and
7
+ // RectButton and BorderlessButton press through a native gesture's state changes instead.
8
+ // So in a test nothing could press them: userEvent found no handler, and fireEvent reached
9
+ // Touchable's composite `onPress` even while disabled (#351).
10
+ //
11
+ // The package already has a convention for this: its own Pressable gives the button host
12
+ // `testOnly_onPress` (and the other press events) in a test environment, which Testing
13
+ // Library's event lookup reads. Two mocks follow it, registered after the package's
14
+ // jestSetup.js with the same Jest semantics (library-jest.mjs), so they live and reset
15
+ // with the package's own:
16
+ //
17
+ // - the button host is the real host component with its props as given, plus a
18
+ // `testOnly_*` handler for each `onButton*` callback it has, called with the button's
19
+ // own event shape. A disabled button (`enabled={false}`) takes the press and does
20
+ // nothing, as the native view does, so it no longer reaches a parent's handler. A
21
+ // `testOnly_*` the caller passed (Pressable's) is kept as it is;
22
+ // - the gesture detector host is jestSetup.js's own View, and, around such a button
23
+ // with no press handler of its own (RectButton, BorderlessButton), it gives the button
24
+ // a press that plays the tap a device sends its native gesture (began, active, end)
25
+ // through the package's own Jest utilities (fireGestureHandler), so the button's own
26
+ // onBegin/onFinalize decide what is pressed.
27
+
28
+ /** The package's setup file, as LIBRARY_SETUP_FILES (preset-map.ts) lists it. */
29
+ export const GESTURE_HANDLER_SETUP = "react-native-gesture-handler/jestSetup.js";
30
+
31
+ /** The button host and detector mocks, registered from the package's jestSetup.js. */
32
+ // `support` is the library's `jest`, under another name: the project's jestMockTransform
33
+ // rewrites a `jest.mock(...)` call in any module Vite compiles, this one included.
34
+ export function registerGestureHandlerButtons(support) {
35
+ for (const base of ["./src", "./lib/module"]) {
36
+ const buttonSpec = `${base}/components/GestureHandlerButton`;
37
+ support.mock(buttonSpec, () => buttonModule(support, support.requireActual(buttonSpec)));
38
+ support.mock(`${base}/v3/detectors/HostGestureDetector`, () => detectorModule(support, base));
39
+ }
40
+ }
41
+
42
+ const IS_BUTTON = Symbol.for("vitest-native.gestureHandlerButton");
43
+
44
+ /** The press events Testing Library dispatches, and the button callbacks they reach. */
45
+ const PRESS_EVENTS = [
46
+ ["testOnly_onPressIn", "onButtonPressIn"],
47
+ ["testOnly_onPressOut", "onButtonPressOut"],
48
+ ["testOnly_onLongPress", "onButtonLongPress"],
49
+ ["testOnly_onPress", "onButtonPress"],
50
+ ];
51
+
52
+ function noop() {}
53
+
54
+ /** The button's own event (specs/RNGestureHandlerButtonNativeComponent ButtonEvent). */
55
+ function buttonEvent(event) {
56
+ const touch = event?.nativeEvent ?? {};
57
+ const x = touch.locationX ?? 0;
58
+ const y = touch.locationY ?? 0;
59
+ return {
60
+ nativeEvent: {
61
+ pointerInside: true,
62
+ x,
63
+ y,
64
+ absoluteX: touch.pageX ?? x,
65
+ absoluteY: touch.pageY ?? y,
66
+ numberOfPointers: 1,
67
+ pointerType: 0,
68
+ },
69
+ };
70
+ }
71
+
72
+ function buttonModule(support, actual) {
73
+ const React = support.requireActual("react");
74
+ const Host = actual.default ?? actual.ButtonComponent;
75
+ function GestureHandlerButton(props) {
76
+ const handlers = {};
77
+ for (const [testOnly, callback] of PRESS_EVENTS) {
78
+ if (props[testOnly] !== undefined) continue;
79
+ if (props.enabled === false) {
80
+ handlers[testOnly] = noop;
81
+ continue;
82
+ }
83
+ const call = props[callback];
84
+ if (typeof call !== "function") continue;
85
+ handlers[testOnly] = (event) => {
86
+ const own = buttonEvent(event);
87
+ call(own);
88
+ // A device ends every interaction with this event, after its press or press-out.
89
+ if (callback === "onButtonPress") props.onButtonInteractionFinished?.(own);
90
+ };
91
+ }
92
+ return React.createElement(Host, { ...props, ...handlers });
93
+ }
94
+ GestureHandlerButton[IS_BUTTON] = true;
95
+ return {
96
+ ...actual,
97
+ __esModule: true,
98
+ default: GestureHandlerButton,
99
+ ButtonComponent: GestureHandlerButton,
100
+ };
101
+ }
102
+
103
+ /** Whether a button host's own props already handle a press. */
104
+ function handlesPress(props) {
105
+ return PRESS_EVENTS.some(
106
+ ([testOnly, callback]) =>
107
+ props[testOnly] !== undefined || typeof props[callback] === "function",
108
+ );
109
+ }
110
+
111
+ function detectorModule(support, base) {
112
+ const React = support.requireActual("react");
113
+ const { View } = support.requireActual("react-native");
114
+ function HostGestureDetector(props) {
115
+ const child = React.Children.toArray(props.children);
116
+ const button = child.length === 1 ? child[0] : null;
117
+ if (
118
+ button === null ||
119
+ !button.type?.[IS_BUTTON] ||
120
+ button.props.enabled === false ||
121
+ handlesPress(button.props) ||
122
+ typeof props.onGestureHandlerStateChange !== "function"
123
+ ) {
124
+ return React.createElement(View, props);
125
+ }
126
+ // The button's native gesture, as the package's Jest utilities take a v3 gesture.
127
+ const gesture = {
128
+ type: "NativeViewGestureHandler",
129
+ handlerTag: props.handlerTags?.[0],
130
+ config: { enabled: true },
131
+ detectorCallbacks: { jsEventHandler: props.onGestureHandlerStateChange },
132
+ };
133
+ const tap = () => {
134
+ const { fireGestureHandler } = support.requireActual(`${base}/jestUtils`);
135
+ const { State } = support.requireActual(`${base}/State`);
136
+ fireGestureHandler(gesture, [
137
+ { state: State.BEGAN },
138
+ { state: State.ACTIVE },
139
+ { state: State.END },
140
+ ]);
141
+ };
142
+ // The detector is `pointerEvents="box-none"`, which a press passes through, so the
143
+ // button it wraps is what takes it.
144
+ const pressable = React.cloneElement(button, { testOnly_onPress: tap });
145
+ return React.createElement(View, { ...props, children: pressable });
146
+ }
147
+ return { __esModule: true, default: HostGestureDetector };
148
+ }