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.
- package/dist/cli.mjs +169 -27
- package/dist/errors.d.mts +2 -0
- package/dist/hang-watch.d.mts +2 -0
- package/dist/hang-watch.mjs +60 -3
- package/dist/{host-TAGjG56H.mjs → host-BY3RaLPW.mjs} +1 -1
- package/dist/{index-BpZ0E2eJ.d.mts → index-DQz6guT5.d.mts} +17 -3
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +88 -80
- package/dist/jest-compat.cjs +193 -21
- package/dist/jest-compat.mjs +173 -21
- package/dist/native/boundary.mjs +35 -1
- package/dist/native/bounded-process.mjs +110 -27
- package/dist/native/gesture-handler-buttons.mjs +148 -0
- package/dist/native/hot-diagnostic.mjs +7 -0
- package/dist/native/loader.mjs +108 -1
- package/dist/native/metro-profile-compiler.mjs +2 -1
- package/dist/native/metro-profile.mjs +2 -0
- package/dist/native/registry-compiler.mjs +3 -2
- package/dist/native/registry-process.mjs +2 -0
- package/dist/native/registry.mjs +6 -1
- package/dist/native/reset.mjs +51 -26
- package/dist/native/setup.mjs +15 -2
- package/dist/native/state-manifest.mjs +2 -3
- package/dist/native/transform.mjs +122 -1
- package/dist/native/worker.mjs +3 -4
- package/dist/preset-react.d.mts +11 -0
- package/dist/preset-react.mjs +104 -0
- package/dist/{presets-DLH7uRGA.mjs → presets-cQiD0YHw.mjs} +836 -520
- package/dist/presets.d.mts +1 -1
- package/dist/presets.mjs +1 -1
- package/dist/setup-files-C6-77IIs.mjs +22 -0
- package/dist/setup.mjs +15 -13
- package/package.json +12 -5
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { A as
|
|
3
|
-
import {
|
|
1
|
+
import { n as runSetupFilesInOrder, t as placeSetupFiles } from "./setup-files-C6-77IIs.mjs";
|
|
2
|
+
import { A as PEER_REQUIREMENTS, D as validateOptions, F as unsupportedExpoSdkMessage, I as unsupportedReactNativeMessage, M as belowRecommendedMessage, N as installedExpoVersion, O as validatePeerDependency, P as isBelowSupportedReactNative, S as shouldDefaultFsModuleCache, a as runningVite, b as readProjectSource, c as detectEcosystemPackages, d as detectEngine, f as createProjectBabel, j as SUPPORTED_EXPO_SDKS, k as warnUnknownOptions, m as missingBabelCoreNotice, n as assertHotWorkerLoadsRunningVitest, p as isProjectSourceFile, s as aliasReachedPaths, t as assertHostResolvesRunningVitest, w as assertSupportedNode, x as fsModuleCacheKey, y as installedManifest } from "./host-BY3RaLPW.mjs";
|
|
3
|
+
import { N as BUILT_IN_PRESET, t as presets_exports } from "./presets-cQiD0YHw.mjs";
|
|
4
|
+
import { a as PRESET_MODULES, d as presetForInstalled, i as LIBRARY_SETUP_FILES, r as DEFAULT_ASSET_EXTS, s as autoDetectedPresetApplies, t as AUTO_DETECT_PRESETS, u as libraryRegistryEntries } from "./preset-map-DdAexIwz.mjs";
|
|
4
5
|
import { t as workerVitestMismatch } from "./worker-vitest-CILPFeRX.mjs";
|
|
5
6
|
import { createRequire } from "node:module";
|
|
6
7
|
import { extensionsFor, firstExact, platformSubpathFile } from "./native/resolve.mjs";
|
|
@@ -12,16 +13,16 @@ import flowRemoveTypes from "flow-remove-types";
|
|
|
12
13
|
import { VitestNativeError, VitestNativeTypeError } from "./errors.mjs";
|
|
13
14
|
import { docsUrl } from "./docs-url.mjs";
|
|
14
15
|
import { presetFromModule } from "./preset-modules.mjs";
|
|
15
|
-
import { CONTEXT_ENV, ensureProjectContext, projectContext, writeProjectContext } from "./context.mjs";
|
|
16
16
|
import { serializableAliases } from "./jest-compat/aliases.mjs";
|
|
17
17
|
import { tsconfigPathAliases } from "./native/tsconfig-paths.mjs";
|
|
18
18
|
import { aliasList, checkResolverInputs, conditionsIn, createSharedResolver, identityKey, nodeDefaultConditions, nodeOptionsList, ownershipShadowFile, resolverInputsHash, serializeResolutionAliases } from "./native/shared-resolver.mjs";
|
|
19
19
|
import { knownNativeModulesFor, nativeModuleSpecsFor } from "./native/native-modules.mjs";
|
|
20
20
|
import { createNativeOwnershipPolicy, findNativeInlineConflicts, findNativeOwnershipConflict, formatNativeOwnershipManifest } from "./native/ownership.mjs";
|
|
21
21
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
22
|
-
import { transformWithOxc } from "vite";
|
|
22
|
+
import { parseAst, transformWithOxc } from "vite";
|
|
23
23
|
import { containsPath, dependencyDirOf, isPackageEntryFile, memoizePackageDirOf, packageDirOf } from "./native/match.mjs";
|
|
24
24
|
import { OWNERSHIP_META_KEY, OWNERSHIP_ROUTES, viteMarkerFor } from "./native/ownership-ledger.mjs";
|
|
25
|
+
import { CONTEXT_ENV, ensureProjectContext, projectContext, writeProjectContext } from "./context.mjs";
|
|
25
26
|
import { cacheRootFor } from "./native/transform.mjs";
|
|
26
27
|
import { HangWatch, debugging, hangTimeoutFor } from "./hang-watch.mjs";
|
|
27
28
|
import inspector from "node:inspector";
|
|
@@ -42,53 +43,6 @@ function getPlatformExtensions(platform) {
|
|
|
42
43
|
function getConfiguredPlatformExtensions(platform, sourceExts) {
|
|
43
44
|
return extensionsFor(platform, sourceExts);
|
|
44
45
|
}
|
|
45
|
-
// src/fresh-runtime-presets.ts
|
|
46
|
-
/**
|
|
47
|
-
* The presets whose module, as served, uses React through vitest-native's own dist (a
|
|
48
|
-
* module-scope `import React`). The hot runtime keeps that dist resident, so under
|
|
49
|
-
* `hotRuntime.freshRuntime`, where React is evaluated again for each file, these modules
|
|
50
|
-
* keep the first file's React, and later files fail with "Invalid hook call" or read a
|
|
51
|
-
* default (#719). While one is active, freshRuntime declines and React stays resident.
|
|
52
|
-
*
|
|
53
|
-
* reanimated corrects even the library's own mock with React-using helpers, and
|
|
54
|
-
* bottomSheet serves the names the library's mock lacks from its built-in module, so
|
|
55
|
-
* both count whichever module they serve.
|
|
56
|
-
*
|
|
57
|
-
* Temporary: removed when the preset factories take React from the file's own require.
|
|
58
|
-
*/
|
|
59
|
-
const HOLD_REACT = /* @__PURE__ */ new Set([
|
|
60
|
-
"bottomSheet",
|
|
61
|
-
"expo",
|
|
62
|
-
"flashList",
|
|
63
|
-
"gestureHandler",
|
|
64
|
-
"keyboardController",
|
|
65
|
-
"mmkv",
|
|
66
|
-
"navigation",
|
|
67
|
-
"reanimated",
|
|
68
|
-
"safeAreaContext",
|
|
69
|
-
"screens",
|
|
70
|
-
"svg",
|
|
71
|
-
"unistyles",
|
|
72
|
-
"vectorIcons",
|
|
73
|
-
"webview"
|
|
74
|
-
]);
|
|
75
|
-
/** Presets that serve the library's own Jest mock, which does not use the preset's React, when it is installed. */
|
|
76
|
-
const NOT_WITH_OWN_MOCK = {
|
|
77
|
-
safeAreaContext: SAFE_AREA_MOCK,
|
|
78
|
-
keyboardController: KEYBOARD_CONTROLLER_MOCK
|
|
79
|
-
};
|
|
80
|
-
/** The active presets, by name, whose served module holds React per worker. */
|
|
81
|
-
function presetsHoldingReact(presetNames, projectRoot) {
|
|
82
|
-
return presetNames.filter((name) => {
|
|
83
|
-
if (!HOLD_REACT.has(name)) return false;
|
|
84
|
-
const mock = NOT_WITH_OWN_MOCK[name];
|
|
85
|
-
return mock === void 0 || libraryMockDir(mock, projectRoot) === null;
|
|
86
|
-
});
|
|
87
|
-
}
|
|
88
|
-
/** The one line printed when freshRuntime declines. */
|
|
89
|
-
function freshRuntimeDeclinedNotice(names) {
|
|
90
|
-
return `[vitest-native] hotRuntime.freshRuntime declined: ${names.join(", ")} ${names.length === 1 ? "holds" : "hold"} React per worker (#719). React stays resident, as without freshRuntime.`;
|
|
91
|
-
}
|
|
92
46
|
// src/native/apply.ts
|
|
93
47
|
/**
|
|
94
48
|
* Vite/Vitest config fragment for the native engine.
|
|
@@ -213,7 +167,9 @@ function nativeEngineConfig(setupFilePath, fields, extensions, transformPkgs = [
|
|
|
213
167
|
* Vite's import analysis cannot parse.
|
|
214
168
|
*
|
|
215
169
|
* Only files outside `node_modules`: packages are compiled by their own path (the native
|
|
216
|
-
* engine's Babel transform, or the mock engine's Flow strip and Vite's pipeline).
|
|
170
|
+
* engine's Babel transform, or the mock engine's Flow strip and Vite's pipeline). The one
|
|
171
|
+
* exception is loadPackageJsx below: a package's `.js` file that Vite serves uncompiled and
|
|
172
|
+
* cannot parse.
|
|
217
173
|
*/
|
|
218
174
|
/** The Oxc options for a project `.js` file, or undefined when Oxc is turned off. */
|
|
219
175
|
function projectJsxOptions(oxc) {
|
|
@@ -271,6 +227,72 @@ async function loadProjectJsx(id, options, config, chain, log) {
|
|
|
271
227
|
map: result.map
|
|
272
228
|
};
|
|
273
229
|
}
|
|
230
|
+
/**
|
|
231
|
+
* A `.js` file inside `node_modules`: the plain file, no query. The native engine compiles
|
|
232
|
+
* the packages it detects in Node, so such a file reaching Vite's load belongs to a package
|
|
233
|
+
* nothing compiles.
|
|
234
|
+
*/
|
|
235
|
+
function isPackageJsFile(id) {
|
|
236
|
+
return id.endsWith(".js") && !id.includes("?") && path.isAbsolute(id) && NODE_MODULES.test(id);
|
|
237
|
+
}
|
|
238
|
+
/** The package a `node_modules` path belongs to, `@scope/name` or `name`, or null. */
|
|
239
|
+
function packageOfFile(id) {
|
|
240
|
+
const parts = id.split(/[\\/]/);
|
|
241
|
+
const at = parts.lastIndexOf("node_modules");
|
|
242
|
+
if (at < 0 || at + 1 >= parts.length) return null;
|
|
243
|
+
const first = parts[at + 1];
|
|
244
|
+
return first.startsWith("@") && at + 2 < parts.length ? `${first}/${parts[at + 2]}` : first;
|
|
245
|
+
}
|
|
246
|
+
/** Whether Vite's parser accepts the code: Vite's import analysis fails on what it rejects. */
|
|
247
|
+
function parses(code) {
|
|
248
|
+
try {
|
|
249
|
+
parseAst(code);
|
|
250
|
+
return true;
|
|
251
|
+
} catch {
|
|
252
|
+
return false;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
const warnedPackages = /* @__PURE__ */ new Set();
|
|
256
|
+
/**
|
|
257
|
+
* A package's `.js` file with JSX that nothing compiles, compiled as JSX, or undefined to
|
|
258
|
+
* leave the file as it is (#763).
|
|
259
|
+
*
|
|
260
|
+
* Under the native engine a package the engine does not detect (one that declares no
|
|
261
|
+
* `react-native` dependency or peer, such as react-native-calendars, whose `main` is
|
|
262
|
+
* `src/index.ts`) can be served by Vite. Oxc compiles its `.ts` files and skips its `.js`
|
|
263
|
+
* ones, so JSX in a `.js` file failed Vite's import analysis. The file is compiled here
|
|
264
|
+
* exactly as a project `.js` file is, and stays in Vite: no package changes owner.
|
|
265
|
+
*
|
|
266
|
+
* Only a file Vite's parser rejects is touched, so every file that loads today loads the
|
|
267
|
+
* same. Another plugin's load still wins, as for project files, and later transforms still
|
|
268
|
+
* run on the result. When Oxc cannot compile it either (Flow, say), the file is served as
|
|
269
|
+
* it is, Vite reports its own parse error, and one warning names the package and the fix.
|
|
270
|
+
*/
|
|
271
|
+
async function loadPackageJsx(id, options, config, chain, log, warn = console.warn) {
|
|
272
|
+
if (!options || !isPackageJsFile(id) || asking.getStore() === id) return void 0;
|
|
273
|
+
const code = await readProjectSource(id);
|
|
274
|
+
if (code === null || !MAY_HAVE_JSX.test(code) || parses(code)) return void 0;
|
|
275
|
+
if (chain) {
|
|
276
|
+
const other = await asking.run(id, () => chain.load(id));
|
|
277
|
+
if (other != null) return other;
|
|
278
|
+
}
|
|
279
|
+
const pkg = packageOfFile(id) ?? id;
|
|
280
|
+
let result;
|
|
281
|
+
try {
|
|
282
|
+
result = await transformWithOxc(code, id, options, void 0, config);
|
|
283
|
+
} catch {
|
|
284
|
+
if (!warnedPackages.has(pkg)) {
|
|
285
|
+
warnedPackages.add(pkg);
|
|
286
|
+
warn(`[vitest-native] ${pkg} ships source Vite cannot parse (${id}), and nothing compiles the package. Add it to reactNative({ transform: ['${pkg}'] }). See https://github.com/danfry1/vitest-native/issues/763.`);
|
|
287
|
+
}
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
log?.(`[vitest-native] compiled JSX in ${id}: ${pkg} is served by Vite uncompiled (#763).`);
|
|
291
|
+
return {
|
|
292
|
+
code: result.code,
|
|
293
|
+
map: result.map
|
|
294
|
+
};
|
|
295
|
+
}
|
|
274
296
|
// src/plugin.ts
|
|
275
297
|
function uniqueExtensions(values) {
|
|
276
298
|
const seen = /* @__PURE__ */ new Set();
|
|
@@ -637,7 +659,6 @@ async function startRegistryFor(options) {
|
|
|
637
659
|
}
|
|
638
660
|
/** Recommended-floor warnings already printed in this process. */
|
|
639
661
|
const warnedRecommended = /* @__PURE__ */ new Set();
|
|
640
|
-
const freshRuntimeNotices = /* @__PURE__ */ new Set();
|
|
641
662
|
/** Vitest instances whose close already settles the background registry builds. */
|
|
642
663
|
const registrySettlers = /* @__PURE__ */ new WeakSet();
|
|
643
664
|
/** Load declarative Metro data without retaining Metro/Expo in Vite's process. */
|
|
@@ -1210,25 +1231,22 @@ function pinInlineProjectRoots(test, declaringRoot) {
|
|
|
1210
1231
|
return pinned;
|
|
1211
1232
|
}
|
|
1212
1233
|
/**
|
|
1213
|
-
* Run React Native's setup before the user's own setup files.
|
|
1214
|
-
*
|
|
1215
|
-
*
|
|
1216
|
-
*
|
|
1217
|
-
*
|
|
1218
|
-
* `
|
|
1219
|
-
*
|
|
1220
|
-
* by installing the hooks at worker boot; every other run broke. Jest has the same
|
|
1221
|
-
* ordering contract: a preset's `setupFiles` run before the project's
|
|
1222
|
-
* `setupFilesAfterEnv`. Moving the entries into the user's list (and out of the merged
|
|
1223
|
-
* result) keeps a single copy of each at the front, in order.
|
|
1234
|
+
* Run React Native's setup before the user's own setup files (placeSetupFiles). A user
|
|
1235
|
+
* setup that imports `@testing-library/react-native` or `react-native` otherwise reached
|
|
1236
|
+
* Node before the require hooks existed and failed on React Native's Flow source
|
|
1237
|
+
* ("Unexpected token 'typeof'"). The hot runtime hid this by installing the hooks at
|
|
1238
|
+
* worker boot; every other run broke. Jest has the same ordering contract: a preset's
|
|
1239
|
+
* `setupFiles` run before the project's `setupFilesAfterEnv`. The entries move into the
|
|
1240
|
+
* user's list and out of the merged result, so a single copy of each runs, first.
|
|
1224
1241
|
*/
|
|
1225
1242
|
function prependSetupFile(userConfig, contributed) {
|
|
1226
|
-
const ours = contributed.setupFiles;
|
|
1227
1243
|
const userTest = userConfig.test ??= {};
|
|
1228
1244
|
const existing = userTest.setupFiles;
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1245
|
+
if (existing == null || Array.isArray(existing) && existing.length === 0) {
|
|
1246
|
+
runSetupFilesInOrder(userTest);
|
|
1247
|
+
return;
|
|
1248
|
+
}
|
|
1249
|
+
placeSetupFiles(userTest, contributed.setupFiles);
|
|
1232
1250
|
contributed.setupFiles = [];
|
|
1233
1251
|
}
|
|
1234
1252
|
function sameDirectory(a, b) {
|
|
@@ -1804,17 +1822,6 @@ function reactNative(options) {
|
|
|
1804
1822
|
const selection = selectPresets(options?.presets, resolvedRoot);
|
|
1805
1823
|
const nativePresetNames = selection.listed ? selection.listed.map((p) => p.name) : autoDetectPresetNames(resolvedRoot, diagnostics).filter((n) => !disabledNative.has(n) && autoDetectedPresetApplies(n, "native", options?.presets));
|
|
1806
1824
|
if (nativePresetNames.length > 0) fields.presetNames = nativePresetNames;
|
|
1807
|
-
if (fields.hotFreshRuntime === true) {
|
|
1808
|
-
const holding = presetsHoldingReact(nativePresetNames, resolvedRoot);
|
|
1809
|
-
if (holding.length > 0) {
|
|
1810
|
-
delete fields.hotFreshRuntime;
|
|
1811
|
-
const notice = freshRuntimeDeclinedNotice(holding);
|
|
1812
|
-
if (!freshRuntimeNotices.has(notice)) {
|
|
1813
|
-
freshRuntimeNotices.add(notice);
|
|
1814
|
-
console.warn(notice);
|
|
1815
|
-
}
|
|
1816
|
-
}
|
|
1817
|
-
}
|
|
1818
1825
|
if (options?.experimental?.nodeMocks === true || ownershipModel === "resolution") fields.nodeMocks = true;
|
|
1819
1826
|
let ownJestSupport = [];
|
|
1820
1827
|
if (!selection.listed) {
|
|
@@ -2161,6 +2168,7 @@ function reactNative(options) {
|
|
|
2161
2168
|
const projectBabel = projectBabelFor(this.environment?.config?.root);
|
|
2162
2169
|
if (projectBabel && isProjectSourceFile(id)) return projectBabel.load(id, chain).then((compiled) => compiled == null && projectJsx && isProjectJsFile(id) ? jsx() : compiled);
|
|
2163
2170
|
if (projectJsx && isProjectJsFile(id)) return jsx();
|
|
2171
|
+
if (engine === "native" && projectJsx && isPackageJsFile(id)) return loadPackageJsx(id, projectJsx, viteConfig, chain, diagnostics ? console.log : void 0);
|
|
2164
2172
|
if (id === "\0virtual:rn-facade" && rnFacadeExports !== null) {
|
|
2165
2173
|
const cached = virtualCodeCache.get(id);
|
|
2166
2174
|
if (cached) return cached;
|
package/dist/jest-compat.cjs
CHANGED
|
@@ -28,6 +28,27 @@ let node_path = require("node:path");
|
|
|
28
28
|
node_path = __toESM(node_path, 1);
|
|
29
29
|
let node_url = require("node:url");
|
|
30
30
|
let magic_string = require("magic-string");
|
|
31
|
+
// src/setup-files.ts
|
|
32
|
+
/**
|
|
33
|
+
* Inserts `files` into `test.setupFiles` in place: at the front, or straight after the
|
|
34
|
+
* last entry `after` matches. Entries already listed are moved, not repeated. Under
|
|
35
|
+
* `sequence.setupFiles: 'parallel'`, the project's setup files then run in order.
|
|
36
|
+
*/
|
|
37
|
+
function placeSetupFiles(test, files, after) {
|
|
38
|
+
const existing = test.setupFiles;
|
|
39
|
+
const list = (Array.isArray(existing) ? existing : existing == null ? [] : [existing]).filter((entry) => !files.includes(entry));
|
|
40
|
+
let at = 0;
|
|
41
|
+
if (after) list.forEach((entry, index) => {
|
|
42
|
+
if (typeof entry === "string" && after(entry)) at = index + 1;
|
|
43
|
+
});
|
|
44
|
+
list.splice(at, 0, ...files);
|
|
45
|
+
test.setupFiles = list;
|
|
46
|
+
runSetupFilesInOrder(test);
|
|
47
|
+
}
|
|
48
|
+
/** Under `sequence.setupFiles: 'parallel'`, the project's setup files run in order. */
|
|
49
|
+
function runSetupFilesInOrder(test) {
|
|
50
|
+
if (test.sequence?.setupFiles === "parallel") test.sequence.setupFiles = "list";
|
|
51
|
+
}
|
|
31
52
|
// src/jest-compat/root-mocks.ts
|
|
32
53
|
/**
|
|
33
54
|
* Jest's automatic manual mocks for node_modules packages, registered as Jest 29.7
|
|
@@ -190,6 +211,9 @@ const WITH_FACTORY = /* @__PURE__ */ new Set(["mock", "doMock"]);
|
|
|
190
211
|
const UNMOCK = /* @__PURE__ */ new Set(["unmock", "doUnmock"]);
|
|
191
212
|
const TRANSFORMABLE = /\.(?:[cm]?[jt]sx?)$/;
|
|
192
213
|
const HAS_JEST_MOCK = /\bjest\s*\.\s*(?:mock|unmock|doMock|doUnmock)\s*\(/;
|
|
214
|
+
const NAMES_JEST = /\bjest\b/;
|
|
215
|
+
const NAMES_MOCK_METHOD = /\b(?:mock|unmock|doMock|doUnmock)\b(?!\s*\.)/;
|
|
216
|
+
const JEST_SOURCES = /* @__PURE__ */ new Set(["@jest/globals", "vitest-native/jest-compat/jest-globals"]);
|
|
193
217
|
const SETUP = "__vn_jest_compat__";
|
|
194
218
|
/** Prepended to a file whose mock factories use the setup. Exported for tests. */
|
|
195
219
|
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`;
|
|
@@ -208,6 +232,160 @@ function walk(node, fn) {
|
|
|
208
232
|
} else if (child && typeof child.type === "string") walk(child, fn);
|
|
209
233
|
}
|
|
210
234
|
}
|
|
235
|
+
/** Whether `node` is a `require('<literal>')` of one of JEST_SOURCES. */
|
|
236
|
+
function jestSourceOf(node) {
|
|
237
|
+
const spec = node?.type === "CallExpression" ? requireSpec(node) : null;
|
|
238
|
+
return spec !== null && JEST_SOURCES.has(spec);
|
|
239
|
+
}
|
|
240
|
+
function propertyName(node) {
|
|
241
|
+
if (node?.type === "Identifier") return node.name;
|
|
242
|
+
if (node?.type === "Literal" && typeof node.value === "string") return node.value;
|
|
243
|
+
return null;
|
|
244
|
+
}
|
|
245
|
+
/** The names a declaration pattern binds. */
|
|
246
|
+
function patternNames(pattern, into = []) {
|
|
247
|
+
if (!pattern) return into;
|
|
248
|
+
if (pattern.type === "Identifier") into.push(pattern.name);
|
|
249
|
+
else if (pattern.type === "ObjectPattern") for (const property of pattern.properties) patternNames(property.type === "RestElement" ? property.argument : property.value, into);
|
|
250
|
+
else if (pattern.type === "ArrayPattern") for (const element of pattern.elements) patternNames(element, into);
|
|
251
|
+
else if (pattern.type === "AssignmentPattern") patternNames(pattern.left, into);
|
|
252
|
+
else if (pattern.type === "RestElement") patternNames(pattern.argument, into);
|
|
253
|
+
return into;
|
|
254
|
+
}
|
|
255
|
+
/** The `var` names a function body declares, outside its nested functions. */
|
|
256
|
+
function varNames(body) {
|
|
257
|
+
const found = [];
|
|
258
|
+
walk(body, (node) => {
|
|
259
|
+
if (FUNCTION.has(node.type) || node.type === "ClassBody") return false;
|
|
260
|
+
if (node.type === "VariableDeclaration" && node.kind === "var") for (const declarator of node.declarations) patternNames(declarator.id, found);
|
|
261
|
+
});
|
|
262
|
+
return found;
|
|
263
|
+
}
|
|
264
|
+
/** The names a block's own statements declare with let, const, class or function. */
|
|
265
|
+
function blockNames(statements) {
|
|
266
|
+
const found = [];
|
|
267
|
+
for (const statement of statements) {
|
|
268
|
+
const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
|
|
269
|
+
if (declaration?.type === "VariableDeclaration" && declaration.kind !== "var") for (const declarator of declaration.declarations) patternNames(declarator.id, found);
|
|
270
|
+
else if ((declaration?.type === "FunctionDeclaration" || declaration?.type === "ClassDeclaration") && declaration.id) found.push(declaration.id.name);
|
|
271
|
+
}
|
|
272
|
+
return found;
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* The identifiers named in `watched` that a scope inside the Program declares again (a
|
|
276
|
+
* parameter, a local, a catch binding): those refer to the local, not to the
|
|
277
|
+
* Program-level binding of that name.
|
|
278
|
+
*/
|
|
279
|
+
function shadowedIdentifiers(ast, watched) {
|
|
280
|
+
const shadowed = /* @__PURE__ */ new WeakSet();
|
|
281
|
+
const scopes = [];
|
|
282
|
+
const visit = (node) => {
|
|
283
|
+
if (!node || typeof node.type !== "string") return;
|
|
284
|
+
let scope = null;
|
|
285
|
+
if (FUNCTION.has(node.type)) {
|
|
286
|
+
const declared = node.params.flatMap((param) => patternNames(param));
|
|
287
|
+
if (node.type === "FunctionExpression" && node.id) declared.push(node.id.name);
|
|
288
|
+
if (node.body.type === "BlockStatement") declared.push(...varNames(node.body), ...blockNames(node.body.body));
|
|
289
|
+
scope = declared;
|
|
290
|
+
} else if (node.type === "BlockStatement" || node.type === "StaticBlock") scope = blockNames(node.body);
|
|
291
|
+
else if (node.type === "CatchClause") scope = patternNames(node.param);
|
|
292
|
+
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));
|
|
293
|
+
const pushed = scope !== null && scope.some((name) => watched.has(name));
|
|
294
|
+
if (pushed) scopes.push(new Set(scope));
|
|
295
|
+
if (node.type === "Identifier" && watched.has(node.name)) {
|
|
296
|
+
if (scopes.some((names) => names.has(node.name))) shadowed.add(node);
|
|
297
|
+
}
|
|
298
|
+
for (const key in node) {
|
|
299
|
+
if (key === "type" || key === "start" || key === "end" || key === "loc") continue;
|
|
300
|
+
const child = node[key];
|
|
301
|
+
if (Array.isArray(child)) for (const c of child) visit(c);
|
|
302
|
+
else if (child && typeof child.type === "string") visit(child);
|
|
303
|
+
}
|
|
304
|
+
if (pushed) scopes.pop();
|
|
305
|
+
};
|
|
306
|
+
visit(ast);
|
|
307
|
+
return shadowed;
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* The file's jest bindings. A Program-level further name for a jest object (`const j =
|
|
311
|
+
* mockJest`) or for one of its hoisted methods (`const { mock } = jest`) that a mock call
|
|
312
|
+
* then goes through is one Jest would not hoist either, and this transform would leave
|
|
313
|
+
* unapplied without a word, so it fails, naming the binding and its line. A name a scope
|
|
314
|
+
* declares again, or that is reassigned, is not that binding and is left alone, and so is
|
|
315
|
+
* `requireActual` under any name: it is never hoisted and works at run time as it is.
|
|
316
|
+
*/
|
|
317
|
+
function jestBindings(ast, code, id) {
|
|
318
|
+
const names = /* @__PURE__ */ new Set(["jest"]);
|
|
319
|
+
const namespaces = /* @__PURE__ */ new Set();
|
|
320
|
+
const program = ast.body.map((statement) => statement.type === "ExportNamedDeclaration" && statement.declaration ? statement.declaration : statement);
|
|
321
|
+
for (const statement of program) if (statement.type === "ImportDeclaration") {
|
|
322
|
+
const fromJest = JEST_SOURCES.has(statement.source.value);
|
|
323
|
+
for (const specifier of statement.specifiers) if (!fromJest) {
|
|
324
|
+
if (specifier.local.name === "jest") names.delete("jest");
|
|
325
|
+
} else if (specifier.type === "ImportNamespaceSpecifier") namespaces.add(specifier.local.name);
|
|
326
|
+
else if (specifier.type === "ImportSpecifier" && propertyName(specifier.imported) === "jest") names.add(specifier.local.name);
|
|
327
|
+
} else if (statement.type === "VariableDeclaration") for (const declarator of statement.declarations) {
|
|
328
|
+
const init = declarator.init;
|
|
329
|
+
if (!init) continue;
|
|
330
|
+
if (jestSourceOf(init)) {
|
|
331
|
+
if (declarator.id.type === "Identifier") namespaces.add(declarator.id.name);
|
|
332
|
+
else if (declarator.id.type === "ObjectPattern") {
|
|
333
|
+
for (const property of declarator.id.properties) if (property.type === "Property" && propertyName(property.key) === "jest" && property.value.type === "Identifier") names.add(property.value.name);
|
|
334
|
+
}
|
|
335
|
+
} else if (init.type === "MemberExpression" && jestSourceOf(init.object) && propertyName(init.property) === "jest" && declarator.id.type === "Identifier") names.add(declarator.id.name);
|
|
336
|
+
}
|
|
337
|
+
const aliases = /* @__PURE__ */ new Map();
|
|
338
|
+
const methodAliases = /* @__PURE__ */ new Map();
|
|
339
|
+
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";
|
|
340
|
+
for (const statement of program) {
|
|
341
|
+
if (statement.type !== "VariableDeclaration") continue;
|
|
342
|
+
for (const declarator of statement.declarations) {
|
|
343
|
+
const [target, value] = [declarator.id, declarator.init];
|
|
344
|
+
if (!value) continue;
|
|
345
|
+
if (plainJest(value)) {
|
|
346
|
+
if (target.type === "Identifier" && !names.has(target.name)) aliases.set(target.name, declarator);
|
|
347
|
+
if (target.type === "ObjectPattern") for (const property of target.properties) {
|
|
348
|
+
const name = property.type === "Property" ? propertyName(property.key) : null;
|
|
349
|
+
if (name && HOISTABLE.has(name) && property.value.type === "Identifier") methodAliases.set(property.value.name, declarator);
|
|
350
|
+
}
|
|
351
|
+
} else if (value.type === "MemberExpression" && plainJest(value.object) && HOISTABLE.has(propertyName(value.property) ?? "") && target.type === "Identifier") methodAliases.set(target.name, declarator);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
const watched = /* @__PURE__ */ new Set([
|
|
355
|
+
...names,
|
|
356
|
+
...namespaces,
|
|
357
|
+
...aliases.keys(),
|
|
358
|
+
...methodAliases.keys()
|
|
359
|
+
]);
|
|
360
|
+
watched.delete("jest");
|
|
361
|
+
const shadowed = watched.size > 0 ? shadowedIdentifiers(ast, watched) : /* @__PURE__ */ new WeakSet();
|
|
362
|
+
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");
|
|
363
|
+
if (aliases.size === 0 && methodAliases.size === 0) return { isJest };
|
|
364
|
+
walk(ast, (node) => {
|
|
365
|
+
const target = node.type === "AssignmentExpression" ? node.left : node.type === "UpdateExpression" ? node.argument : null;
|
|
366
|
+
if (target?.type === "Identifier" && !shadowed.has(target)) {
|
|
367
|
+
aliases.delete(target.name);
|
|
368
|
+
methodAliases.delete(target.name);
|
|
369
|
+
}
|
|
370
|
+
});
|
|
371
|
+
walk(ast, (node) => {
|
|
372
|
+
if (node.type !== "CallExpression") return;
|
|
373
|
+
const callee = node.callee;
|
|
374
|
+
let binding = null;
|
|
375
|
+
let name = "";
|
|
376
|
+
if (callee?.type === "MemberExpression" && callee.object?.type === "Identifier" && aliases.has(callee.object.name) && !shadowed.has(callee.object) && HOISTABLE.has(propertyName(callee.property) ?? "")) {
|
|
377
|
+
binding = aliases.get(callee.object.name);
|
|
378
|
+
name = `${callee.object.name}.${propertyName(callee.property)}`;
|
|
379
|
+
} else if (callee?.type === "Identifier" && methodAliases.has(callee.name) && !shadowed.has(callee)) {
|
|
380
|
+
binding = methodAliases.get(callee.name);
|
|
381
|
+
name = callee.name;
|
|
382
|
+
}
|
|
383
|
+
if (!binding) return;
|
|
384
|
+
const line = (at) => code.slice(0, at).split("\n").length;
|
|
385
|
+
throw new src_errors_mjs.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'.`);
|
|
386
|
+
});
|
|
387
|
+
return { isJest };
|
|
388
|
+
}
|
|
211
389
|
const FUNCTION = /* @__PURE__ */ new Set([
|
|
212
390
|
"FunctionExpression",
|
|
213
391
|
"ArrowFunctionExpression",
|
|
@@ -216,11 +394,11 @@ const FUNCTION = /* @__PURE__ */ new Set([
|
|
|
216
394
|
const NODE_MODULES = /[\\/]node_modules[\\/]/;
|
|
217
395
|
const SOURCE_FILE = /\.[cm]?[jt]sx?$/;
|
|
218
396
|
/** The string specifier of a `jest.requireActual('<literal>')` call, or null. */
|
|
219
|
-
function requireActualSpec(node) {
|
|
397
|
+
function requireActualSpec(node, jest) {
|
|
220
398
|
if (node.type !== "CallExpression" || node.arguments.length !== 1) return null;
|
|
221
399
|
const callee = node.callee;
|
|
222
400
|
if (callee?.type !== "MemberExpression" || callee.computed) return null;
|
|
223
|
-
if (
|
|
401
|
+
if (!jest.isJest(callee.object)) return null;
|
|
224
402
|
if (callee.property?.type !== "Identifier" || callee.property.name !== "requireActual") return null;
|
|
225
403
|
return literalSpec(node.arguments[0]);
|
|
226
404
|
}
|
|
@@ -242,11 +420,11 @@ const BINDS_REQUIRE = /\b(?:const|let|var|function|class)\s+require\b|\bimport\s
|
|
|
242
420
|
* its own body, not in a nested function or a class body (where `await` is not allowed
|
|
243
421
|
* either). `mocked` is the specifier the factory mocks, whose own require stays as is.
|
|
244
422
|
*/
|
|
245
|
-
function ownLoadCalls(factory, mocked, requireIsGlobal) {
|
|
423
|
+
function ownLoadCalls(factory, mocked, requireIsGlobal, jest) {
|
|
246
424
|
const calls = [];
|
|
247
425
|
walk(factory.body, (node) => {
|
|
248
426
|
if (FUNCTION.has(node.type) || node.type === "ClassBody") return false;
|
|
249
|
-
const actual = requireActualSpec(node);
|
|
427
|
+
const actual = requireActualSpec(node, jest);
|
|
250
428
|
if (actual !== null) return void calls.push({
|
|
251
429
|
node,
|
|
252
430
|
spec: actual,
|
|
@@ -349,14 +527,7 @@ function jestMockTransform(options = {}) {
|
|
|
349
527
|
root,
|
|
350
528
|
...found
|
|
351
529
|
});
|
|
352
|
-
|
|
353
|
-
if (setupFiles.includes(id)) return;
|
|
354
|
-
let compat = -1;
|
|
355
|
-
setupFiles.forEach((file, index) => {
|
|
356
|
-
if (JEST_COMPAT_SETUP.test(file)) compat = index;
|
|
357
|
-
});
|
|
358
|
-
setupFiles.splice(compat + 1, 0, id);
|
|
359
|
-
test.setupFiles = setupFiles;
|
|
530
|
+
placeSetupFiles(test, [id], (file) => JEST_COMPAT_SETUP.test(file));
|
|
360
531
|
},
|
|
361
532
|
configResolved(config) {
|
|
362
533
|
const native = config.plugins.find((plugin) => plugin.name === "vitest-native");
|
|
@@ -395,7 +566,7 @@ function jestMockTransform(options = {}) {
|
|
|
395
566
|
if (id.includes("/node_modules/")) return null;
|
|
396
567
|
const file = id.split("?")[0];
|
|
397
568
|
if (!TRANSFORMABLE.test(file)) return null;
|
|
398
|
-
if (!HAS_JEST_MOCK.test(code)) return null;
|
|
569
|
+
if (!HAS_JEST_MOCK.test(code) && !(NAMES_JEST.test(code) && NAMES_MOCK_METHOD.test(code))) return null;
|
|
399
570
|
const owner = rootMockModules.has(file) ? projectsByRoot.get(rootMockModules.get(file).root) ?? project : project;
|
|
400
571
|
let module;
|
|
401
572
|
const spelled = node_path.default.isAbsolute(file) ? viteId(file) : file;
|
|
@@ -548,15 +719,16 @@ function adapt(ctx, code, id, project, manualMockFor = () => null, automockable
|
|
|
548
719
|
} catch {
|
|
549
720
|
return null;
|
|
550
721
|
}
|
|
722
|
+
const jest = jestBindings(ast, code, id);
|
|
551
723
|
const candidates = /* @__PURE__ */ new Map();
|
|
552
724
|
const requireIsGlobal = !BINDS_REQUIRE.test(code);
|
|
553
725
|
walk(ast, (node) => {
|
|
554
|
-
const factory = mockFactoryOf(node);
|
|
726
|
+
const factory = mockFactoryOf(node, jest);
|
|
555
727
|
if (!factory || factory.generator) return;
|
|
556
|
-
const calls = ownLoadCalls(factory, literalSpec(node.arguments[0]), requireIsGlobal);
|
|
728
|
+
const calls = ownLoadCalls(factory, literalSpec(node.arguments[0]), requireIsGlobal, jest);
|
|
557
729
|
if (calls.length > 0) candidates.set(factory, calls);
|
|
558
730
|
});
|
|
559
|
-
if (candidates.size === 0) return rewrite(code, ast, /* @__PURE__ */ new Map(), manualMockFor, automockable);
|
|
731
|
+
if (candidates.size === 0) return rewrite(code, ast, jest, /* @__PURE__ */ new Map(), manualMockFor, automockable);
|
|
560
732
|
const specs = new Set([...candidates.values()].flat().map((call) => call.spec));
|
|
561
733
|
return Promise.all([...specs].map(async (spec) => {
|
|
562
734
|
try {
|
|
@@ -571,15 +743,15 @@ function adapt(ctx, code, id, project, manualMockFor = () => null, automockable
|
|
|
571
743
|
const moved = calls.filter((call) => owned.has(call.spec));
|
|
572
744
|
if (moved.length > 0) toAsync.set(factory, moved);
|
|
573
745
|
}
|
|
574
|
-
return rewrite(code, ast, toAsync, manualMockFor, automockable);
|
|
746
|
+
return rewrite(code, ast, jest, toAsync, manualMockFor, automockable);
|
|
575
747
|
});
|
|
576
748
|
}
|
|
577
749
|
/** The factory of a `jest.mock`/`jest.doMock` call with an inline function factory. */
|
|
578
|
-
function mockFactoryOf(node) {
|
|
750
|
+
function mockFactoryOf(node, jest) {
|
|
579
751
|
if (node.type !== "CallExpression" || node.arguments.length < 2) return null;
|
|
580
752
|
const callee = node.callee;
|
|
581
753
|
if (callee?.type !== "MemberExpression" || callee.computed) return null;
|
|
582
|
-
if (
|
|
754
|
+
if (!jest.isJest(callee.object)) return null;
|
|
583
755
|
if (callee.property?.type !== "Identifier" || !WITH_FACTORY.has(callee.property.name)) return null;
|
|
584
756
|
const factory = node.arguments[1];
|
|
585
757
|
return factory.type === "ArrowFunctionExpression" || factory.type === "FunctionExpression" ? factory : null;
|
|
@@ -588,7 +760,7 @@ function mockFactoryOf(node) {
|
|
|
588
760
|
* The transform itself. `toAsync` maps a factory to the `jest.requireActual` calls that
|
|
589
761
|
* load through Vite instead (see "`jest.requireActual` of project source" above).
|
|
590
762
|
*/
|
|
591
|
-
function rewrite(code, ast, toAsync, manualMockFor = () => null, automockable = () => false) {
|
|
763
|
+
function rewrite(code, ast, jest, toAsync, manualMockFor = () => null, automockable = () => false) {
|
|
592
764
|
const s = new magic_string.MagicString(code);
|
|
593
765
|
let changed = false;
|
|
594
766
|
const topLevel = /* @__PURE__ */ new Map();
|
|
@@ -616,7 +788,7 @@ function rewrite(code, ast, toAsync, manualMockFor = () => null, automockable =
|
|
|
616
788
|
if (!callee || callee.type !== "MemberExpression" || callee.computed) return;
|
|
617
789
|
const obj = callee.object;
|
|
618
790
|
const prop = callee.property;
|
|
619
|
-
if (!
|
|
791
|
+
if (!jest.isJest(obj)) return;
|
|
620
792
|
if (!prop || prop.type !== "Identifier" || !HOISTABLE.has(prop.name)) return;
|
|
621
793
|
s.overwrite(obj.start, obj.end, "vi");
|
|
622
794
|
changed = true;
|