vitest 0.18.0 → 0.19.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.
Files changed (36) hide show
  1. package/LICENSE.md +6 -6
  2. package/dist/browser.d.ts +1850 -0
  3. package/dist/browser.mjs +20 -0
  4. package/dist/{chunk-api-setup.63babd7c.mjs → chunk-api-setup.0cf2c96a.mjs} +37 -11
  5. package/dist/{chunk-constants.8eb2ed35.mjs → chunk-constants.38b43a44.mjs} +3 -3
  6. package/dist/{chunk-env-node.26c72624.mjs → chunk-defaults.ed196a9a.mjs} +458 -455
  7. package/dist/{chunk-install-pkg.2dcb2c04.mjs → chunk-install-pkg.6c6dc0c2.mjs} +11 -10
  8. package/dist/chunk-integrations-globals.1018e651.mjs +24 -0
  9. package/dist/chunk-node-git.9058b82a.mjs +1139 -0
  10. package/dist/chunk-runtime-chain.f2e00f4c.mjs +2039 -0
  11. package/dist/{vendor-entry.78de67ab.mjs → chunk-runtime-error.606e0393.mjs} +167 -183
  12. package/dist/{chunk-runtime-chain.eb764dff.mjs → chunk-runtime-hooks.d4cadf47.mjs} +33 -2012
  13. package/dist/{chunk-runtime-mocker.79ccc3de.mjs → chunk-runtime-mocker.dfdfd57b.mjs} +70 -22
  14. package/dist/{chunk-runtime-rpc.cc6a06a2.mjs → chunk-runtime-rpc.45d8ee19.mjs} +1 -1
  15. package/dist/{chunk-utils-global.1b22c4fd.mjs → chunk-utils-global.2aa95025.mjs} +11 -6
  16. package/dist/{chunk-utils-source-map.957e7756.mjs → chunk-utils-source-map.8b066ce2.mjs} +2 -2
  17. package/dist/{chunk-vite-node-externalize.0791f2ed.mjs → chunk-vite-node-externalize.e9af6472.mjs} +105 -1174
  18. package/dist/chunk-vite-node-utils.ad73f2ab.mjs +1433 -0
  19. package/dist/cli.mjs +9 -11
  20. package/dist/config.cjs +4 -1
  21. package/dist/config.d.ts +1 -0
  22. package/dist/config.mjs +4 -1
  23. package/dist/entry.mjs +54 -10
  24. package/dist/index.d.ts +56 -27
  25. package/dist/index.mjs +12 -9
  26. package/dist/node.d.ts +37 -18
  27. package/dist/node.mjs +10 -12
  28. package/dist/spy.mjs +102 -2
  29. package/dist/suite.mjs +13 -0
  30. package/dist/vendor-index.61438b77.mjs +335 -0
  31. package/dist/{vendor-index.4bf9c627.mjs → vendor-index.62ce5c33.mjs} +11 -343
  32. package/dist/worker.mjs +6 -6
  33. package/package.json +20 -12
  34. package/dist/chunk-integrations-globals.61e4d6ae.mjs +0 -26
  35. package/dist/chunk-integrations-spy.674b628e.mjs +0 -102
  36. package/dist/chunk-vite-node-utils.af8ead96.mjs +0 -9195
@@ -0,0 +1,1433 @@
1
+ import { builtinModules, createRequire } from 'module';
2
+ import { pathToFileURL, fileURLToPath as fileURLToPath$1, URL as URL$1 } from 'url';
3
+ import vm from 'vm';
4
+ import { C as resolve$1, d as dirname, F as isAbsolute$1, S as extname$1 } from './chunk-utils-global.2aa95025.mjs';
5
+ import path from 'path';
6
+ import fs, { promises, statSync, existsSync, realpathSync, Stats } from 'fs';
7
+ import assert from 'assert';
8
+ import { format, inspect } from 'util';
9
+ import createDebug from 'debug';
10
+
11
+ function normalizeWindowsPath(input = "") {
12
+ if (!input.includes("\\")) {
13
+ return input;
14
+ }
15
+ return input.replace(/\\/g, "/");
16
+ }
17
+
18
+ const _UNC_REGEX = /^[/][/]/;
19
+ const _UNC_DRIVE_REGEX = /^[/][/]([.]{1,2}[/])?([a-zA-Z]):[/]/;
20
+ const _IS_ABSOLUTE_RE = /^\/|^\\|^[a-zA-Z]:[/\\]/;
21
+ const normalize = function(path) {
22
+ if (path.length === 0) {
23
+ return ".";
24
+ }
25
+ path = normalizeWindowsPath(path);
26
+ const isUNCPath = path.match(_UNC_REGEX);
27
+ const hasUNCDrive = isUNCPath && path.match(_UNC_DRIVE_REGEX);
28
+ const isPathAbsolute = isAbsolute(path);
29
+ const trailingSeparator = path[path.length - 1] === "/";
30
+ path = normalizeString(path, !isPathAbsolute);
31
+ if (path.length === 0) {
32
+ if (isPathAbsolute) {
33
+ return "/";
34
+ }
35
+ return trailingSeparator ? "./" : ".";
36
+ }
37
+ if (trailingSeparator) {
38
+ path += "/";
39
+ }
40
+ if (isUNCPath) {
41
+ if (hasUNCDrive) {
42
+ return `//./${path}`;
43
+ }
44
+ return `//${path}`;
45
+ }
46
+ return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path;
47
+ };
48
+ const join = function(...args) {
49
+ if (args.length === 0) {
50
+ return ".";
51
+ }
52
+ let joined;
53
+ for (let i = 0; i < args.length; ++i) {
54
+ const arg = args[i];
55
+ if (arg.length > 0) {
56
+ if (joined === void 0) {
57
+ joined = arg;
58
+ } else {
59
+ joined += `/${arg}`;
60
+ }
61
+ }
62
+ }
63
+ if (joined === void 0) {
64
+ return ".";
65
+ }
66
+ return normalize(joined.replace(/\/\/+/g, "/"));
67
+ };
68
+ const resolve = function(...args) {
69
+ args = args.map((arg) => normalizeWindowsPath(arg));
70
+ let resolvedPath = "";
71
+ let resolvedAbsolute = false;
72
+ for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
73
+ const path = i >= 0 ? args[i] : process.cwd();
74
+ if (path.length === 0) {
75
+ continue;
76
+ }
77
+ resolvedPath = `${path}/${resolvedPath}`;
78
+ resolvedAbsolute = isAbsolute(path);
79
+ }
80
+ resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
81
+ if (resolvedAbsolute && !isAbsolute(resolvedPath)) {
82
+ return `/${resolvedPath}`;
83
+ }
84
+ return resolvedPath.length > 0 ? resolvedPath : ".";
85
+ };
86
+ function normalizeString(path, allowAboveRoot) {
87
+ let res = "";
88
+ let lastSegmentLength = 0;
89
+ let lastSlash = -1;
90
+ let dots = 0;
91
+ let char = null;
92
+ for (let i = 0; i <= path.length; ++i) {
93
+ if (i < path.length) {
94
+ char = path[i];
95
+ } else if (char === "/") {
96
+ break;
97
+ } else {
98
+ char = "/";
99
+ }
100
+ if (char === "/") {
101
+ if (lastSlash === i - 1 || dots === 1) ; else if (dots === 2) {
102
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
103
+ if (res.length > 2) {
104
+ const lastSlashIndex = res.lastIndexOf("/");
105
+ if (lastSlashIndex === -1) {
106
+ res = "";
107
+ lastSegmentLength = 0;
108
+ } else {
109
+ res = res.slice(0, lastSlashIndex);
110
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
111
+ }
112
+ lastSlash = i;
113
+ dots = 0;
114
+ continue;
115
+ } else if (res.length !== 0) {
116
+ res = "";
117
+ lastSegmentLength = 0;
118
+ lastSlash = i;
119
+ dots = 0;
120
+ continue;
121
+ }
122
+ }
123
+ if (allowAboveRoot) {
124
+ res += res.length > 0 ? "/.." : "..";
125
+ lastSegmentLength = 2;
126
+ }
127
+ } else {
128
+ if (res.length > 0) {
129
+ res += `/${path.slice(lastSlash + 1, i)}`;
130
+ } else {
131
+ res = path.slice(lastSlash + 1, i);
132
+ }
133
+ lastSegmentLength = i - lastSlash - 1;
134
+ }
135
+ lastSlash = i;
136
+ dots = 0;
137
+ } else if (char === "." && dots !== -1) {
138
+ ++dots;
139
+ } else {
140
+ dots = -1;
141
+ }
142
+ }
143
+ return res;
144
+ }
145
+ const isAbsolute = function(p) {
146
+ return _IS_ABSOLUTE_RE.test(p);
147
+ };
148
+ const _EXTNAME_RE = /(?<!^)\.[^/.]+$/;
149
+ const extname = function(p) {
150
+ const match = _EXTNAME_RE.exec(normalizeWindowsPath(p));
151
+ return match && match[0] || "";
152
+ };
153
+
154
+ /*---------------------------------------------------------------------------------------------
155
+ * Copyright (c) Microsoft Corporation. All rights reserved.
156
+ * Licensed under the MIT License. See License.txt in the project root for license information.
157
+ *--------------------------------------------------------------------------------------------*/
158
+ var ParseOptions;
159
+ (function (ParseOptions) {
160
+ ParseOptions.DEFAULT = {
161
+ allowTrailingComma: false
162
+ };
163
+ })(ParseOptions || (ParseOptions = {}));
164
+
165
+ const defaultFindOptions = {
166
+ startingFrom: ".",
167
+ rootPattern: /^node_modules$/,
168
+ test: (filePath) => {
169
+ try {
170
+ if (statSync(filePath).isFile()) {
171
+ return true;
172
+ }
173
+ } catch {
174
+ }
175
+ return null;
176
+ }
177
+ };
178
+ async function findNearestFile(filename, _options = {}) {
179
+ const options = { ...defaultFindOptions, ..._options };
180
+ const basePath = resolve(options.startingFrom);
181
+ const leadingSlash = basePath[0] === "/";
182
+ const segments = basePath.split("/").filter(Boolean);
183
+ if (leadingSlash) {
184
+ segments[0] = "/" + segments[0];
185
+ }
186
+ let root = segments.findIndex((r) => r.match(options.rootPattern));
187
+ if (root === -1)
188
+ root = 0;
189
+ for (let i = segments.length; i > root; i--) {
190
+ const filePath = join(...segments.slice(0, i), filename);
191
+ if (await options.test(filePath)) {
192
+ return filePath;
193
+ }
194
+ }
195
+ throw new Error(`Cannot find matching ${filename} in ${options.startingFrom} or parent directories`);
196
+ }
197
+ async function readPackageJSON(id, opts = {}) {
198
+ const resolvedPath = await resolvePackageJSON(id, opts);
199
+ const blob = await promises.readFile(resolvedPath, "utf-8");
200
+ return JSON.parse(blob);
201
+ }
202
+ async function resolvePackageJSON(id = process.cwd(), opts = {}) {
203
+ const resolvedPath = isAbsolute(id) ? id : await resolvePath(id, opts);
204
+ return findNearestFile("package.json", { startingFrom: resolvedPath, ...opts });
205
+ }
206
+
207
+ const BUILTIN_MODULES = new Set(builtinModules);
208
+ function normalizeSlash(str) {
209
+ return str.replace(/\\/g, "/");
210
+ }
211
+ function pcall(fn, ...args) {
212
+ try {
213
+ return Promise.resolve(fn(...args)).catch((err) => perr(err));
214
+ } catch (err) {
215
+ return perr(err);
216
+ }
217
+ }
218
+ function perr(_err) {
219
+ const err = new Error(_err);
220
+ err.code = _err.code;
221
+ Error.captureStackTrace(err, pcall);
222
+ return Promise.reject(err);
223
+ }
224
+
225
+ function fileURLToPath(id) {
226
+ if (typeof id === "string" && !id.startsWith("file://")) {
227
+ return normalizeSlash(id);
228
+ }
229
+ return normalizeSlash(fileURLToPath$1(id));
230
+ }
231
+ function normalizeid(id) {
232
+ if (typeof id !== "string") {
233
+ id = id.toString();
234
+ }
235
+ if (/(node|data|http|https|file):/.test(id)) {
236
+ return id;
237
+ }
238
+ if (BUILTIN_MODULES.has(id)) {
239
+ return "node:" + id;
240
+ }
241
+ return "file://" + normalizeSlash(id);
242
+ }
243
+ function isNodeBuiltin(id = "") {
244
+ id = id.replace(/^node:/, "").split("/")[0];
245
+ return BUILTIN_MODULES.has(id);
246
+ }
247
+ const ProtocolRegex = /^(?<proto>.{2,}?):.+$/;
248
+ function getProtocol(id) {
249
+ const proto = id.match(ProtocolRegex);
250
+ return proto ? proto.groups.proto : null;
251
+ }
252
+
253
+ const reader = { read };
254
+ const packageJsonReader = reader;
255
+ function read(jsonPath) {
256
+ return find(path.dirname(jsonPath));
257
+ }
258
+ function find(dir) {
259
+ try {
260
+ const string = fs.readFileSync(path.toNamespacedPath(path.join(dir, "package.json")), "utf8");
261
+ return { string };
262
+ } catch (error) {
263
+ if (error.code === "ENOENT") {
264
+ const parent = path.dirname(dir);
265
+ if (dir !== parent) {
266
+ return find(parent);
267
+ }
268
+ return { string: void 0 };
269
+ }
270
+ throw error;
271
+ }
272
+ }
273
+
274
+ const isWindows$1 = process.platform === "win32";
275
+ const own$1 = {}.hasOwnProperty;
276
+ const codes = {};
277
+ const messages = /* @__PURE__ */ new Map();
278
+ const nodeInternalPrefix = "__node_internal_";
279
+ let userStackTraceLimit;
280
+ codes.ERR_INVALID_MODULE_SPECIFIER = createError("ERR_INVALID_MODULE_SPECIFIER", (request, reason, base = void 0) => {
281
+ return `Invalid module "${request}" ${reason}${base ? ` imported from ${base}` : ""}`;
282
+ }, TypeError);
283
+ codes.ERR_INVALID_PACKAGE_CONFIG = createError("ERR_INVALID_PACKAGE_CONFIG", (path, base, message) => {
284
+ return `Invalid package config ${path}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`;
285
+ }, Error);
286
+ codes.ERR_INVALID_PACKAGE_TARGET = createError("ERR_INVALID_PACKAGE_TARGET", (pkgPath, key, target, isImport = false, base = void 0) => {
287
+ const relError = typeof target === "string" && !isImport && target.length > 0 && !target.startsWith("./");
288
+ if (key === ".") {
289
+ assert(isImport === false);
290
+ return `Invalid "exports" main target ${JSON.stringify(target)} defined in the package config ${pkgPath}package.json${base ? ` imported from ${base}` : ""}${relError ? '; targets must start with "./"' : ""}`;
291
+ }
292
+ return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify(target)} defined for '${key}' in the package config ${pkgPath}package.json${base ? ` imported from ${base}` : ""}${relError ? '; targets must start with "./"' : ""}`;
293
+ }, Error);
294
+ codes.ERR_MODULE_NOT_FOUND = createError("ERR_MODULE_NOT_FOUND", (path, base, type = "package") => {
295
+ return `Cannot find ${type} '${path}' imported from ${base}`;
296
+ }, Error);
297
+ codes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError("ERR_PACKAGE_IMPORT_NOT_DEFINED", (specifier, packagePath, base) => {
298
+ return `Package import specifier "${specifier}" is not defined${packagePath ? ` in package ${packagePath}package.json` : ""} imported from ${base}`;
299
+ }, TypeError);
300
+ codes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError("ERR_PACKAGE_PATH_NOT_EXPORTED", (pkgPath, subpath, base = void 0) => {
301
+ if (subpath === ".") {
302
+ return `No "exports" main defined in ${pkgPath}package.json${base ? ` imported from ${base}` : ""}`;
303
+ }
304
+ return `Package subpath '${subpath}' is not defined by "exports" in ${pkgPath}package.json${base ? ` imported from ${base}` : ""}`;
305
+ }, Error);
306
+ codes.ERR_UNSUPPORTED_DIR_IMPORT = createError("ERR_UNSUPPORTED_DIR_IMPORT", "Directory import '%s' is not supported resolving ES modules imported from %s", Error);
307
+ codes.ERR_UNKNOWN_FILE_EXTENSION = createError("ERR_UNKNOWN_FILE_EXTENSION", 'Unknown file extension "%s" for %s', TypeError);
308
+ codes.ERR_INVALID_ARG_VALUE = createError("ERR_INVALID_ARG_VALUE", (name, value, reason = "is invalid") => {
309
+ let inspected = inspect(value);
310
+ if (inspected.length > 128) {
311
+ inspected = `${inspected.slice(0, 128)}...`;
312
+ }
313
+ const type = name.includes(".") ? "property" : "argument";
314
+ return `The ${type} '${name}' ${reason}. Received ${inspected}`;
315
+ }, TypeError);
316
+ codes.ERR_UNSUPPORTED_ESM_URL_SCHEME = createError("ERR_UNSUPPORTED_ESM_URL_SCHEME", (url) => {
317
+ let message = "Only file and data URLs are supported by the default ESM loader";
318
+ if (isWindows$1 && url.protocol.length === 2) {
319
+ message += ". On Windows, absolute paths must be valid file:// URLs";
320
+ }
321
+ message += `. Received protocol '${url.protocol}'`;
322
+ return message;
323
+ }, Error);
324
+ function createError(sym, value, def) {
325
+ messages.set(sym, value);
326
+ return makeNodeErrorWithCode(def, sym);
327
+ }
328
+ function makeNodeErrorWithCode(Base, key) {
329
+ return NodeError;
330
+ function NodeError(...args) {
331
+ const limit = Error.stackTraceLimit;
332
+ if (isErrorStackTraceLimitWritable()) {
333
+ Error.stackTraceLimit = 0;
334
+ }
335
+ const error = new Base();
336
+ if (isErrorStackTraceLimitWritable()) {
337
+ Error.stackTraceLimit = limit;
338
+ }
339
+ const message = getMessage(key, args, error);
340
+ Object.defineProperty(error, "message", {
341
+ value: message,
342
+ enumerable: false,
343
+ writable: true,
344
+ configurable: true
345
+ });
346
+ Object.defineProperty(error, "toString", {
347
+ value() {
348
+ return `${this.name} [${key}]: ${this.message}`;
349
+ },
350
+ enumerable: false,
351
+ writable: true,
352
+ configurable: true
353
+ });
354
+ addCodeToName(error, Base.name, key);
355
+ error.code = key;
356
+ return error;
357
+ }
358
+ }
359
+ const addCodeToName = hideStackFrames(function(error, name, code) {
360
+ error = captureLargerStackTrace(error);
361
+ error.name = `${name} [${code}]`;
362
+ error.stack;
363
+ if (name === "SystemError") {
364
+ Object.defineProperty(error, "name", {
365
+ value: name,
366
+ enumerable: false,
367
+ writable: true,
368
+ configurable: true
369
+ });
370
+ } else {
371
+ delete error.name;
372
+ }
373
+ });
374
+ function isErrorStackTraceLimitWritable() {
375
+ const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit");
376
+ if (desc === void 0) {
377
+ return Object.isExtensible(Error);
378
+ }
379
+ return own$1.call(desc, "writable") ? desc.writable : desc.set !== void 0;
380
+ }
381
+ function hideStackFrames(fn) {
382
+ const hidden = nodeInternalPrefix + fn.name;
383
+ Object.defineProperty(fn, "name", { value: hidden });
384
+ return fn;
385
+ }
386
+ const captureLargerStackTrace = hideStackFrames(function(error) {
387
+ const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
388
+ if (stackTraceLimitIsWritable) {
389
+ userStackTraceLimit = Error.stackTraceLimit;
390
+ Error.stackTraceLimit = Number.POSITIVE_INFINITY;
391
+ }
392
+ Error.captureStackTrace(error);
393
+ if (stackTraceLimitIsWritable) {
394
+ Error.stackTraceLimit = userStackTraceLimit;
395
+ }
396
+ return error;
397
+ });
398
+ function getMessage(key, args, self) {
399
+ const message = messages.get(key);
400
+ if (typeof message === "function") {
401
+ assert(message.length <= args.length, `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${message.length}).`);
402
+ return Reflect.apply(message, self, args);
403
+ }
404
+ const expectedLength = (message.match(/%[dfijoOs]/g) || []).length;
405
+ assert(expectedLength === args.length, `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).`);
406
+ if (args.length === 0) {
407
+ return message;
408
+ }
409
+ args.unshift(message);
410
+ return Reflect.apply(format, null, args);
411
+ }
412
+
413
+ const { ERR_UNKNOWN_FILE_EXTENSION } = codes;
414
+ const extensionFormatMap = {
415
+ __proto__: null,
416
+ ".cjs": "commonjs",
417
+ ".js": "module",
418
+ ".mjs": "module"
419
+ };
420
+ function defaultGetFormat(url) {
421
+ if (url.startsWith("node:")) {
422
+ return { format: "builtin" };
423
+ }
424
+ const parsed = new URL$1(url);
425
+ if (parsed.protocol === "data:") {
426
+ const { 1: mime } = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(parsed.pathname) || [null, null];
427
+ const format = mime === "text/javascript" ? "module" : null;
428
+ return { format };
429
+ }
430
+ if (parsed.protocol === "file:") {
431
+ const ext = path.extname(parsed.pathname);
432
+ let format;
433
+ if (ext === ".js") {
434
+ format = getPackageType(parsed.href) === "module" ? "module" : "commonjs";
435
+ } else {
436
+ format = extensionFormatMap[ext];
437
+ }
438
+ if (!format) {
439
+ throw new ERR_UNKNOWN_FILE_EXTENSION(ext, fileURLToPath$1(url));
440
+ }
441
+ return { format: format || null };
442
+ }
443
+ return { format: null };
444
+ }
445
+
446
+ const {
447
+ ERR_INVALID_MODULE_SPECIFIER,
448
+ ERR_INVALID_PACKAGE_CONFIG,
449
+ ERR_INVALID_PACKAGE_TARGET,
450
+ ERR_MODULE_NOT_FOUND,
451
+ ERR_PACKAGE_IMPORT_NOT_DEFINED,
452
+ ERR_PACKAGE_PATH_NOT_EXPORTED,
453
+ ERR_UNSUPPORTED_DIR_IMPORT,
454
+ ERR_UNSUPPORTED_ESM_URL_SCHEME,
455
+ ERR_INVALID_ARG_VALUE
456
+ } = codes;
457
+ const own = {}.hasOwnProperty;
458
+ Object.freeze(["node", "import"]);
459
+ const invalidSegmentRegEx = /(^|\\|\/)(\.\.?|node_modules)(\\|\/|$)/;
460
+ const patternRegEx = /\*/g;
461
+ const encodedSepRegEx = /%2f|%2c/i;
462
+ const emittedPackageWarnings = /* @__PURE__ */ new Set();
463
+ const packageJsonCache = /* @__PURE__ */ new Map();
464
+ function emitFolderMapDeprecation(match, pjsonUrl, isExports, base) {
465
+ const pjsonPath = fileURLToPath$1(pjsonUrl);
466
+ if (emittedPackageWarnings.has(pjsonPath + "|" + match)) {
467
+ return;
468
+ }
469
+ emittedPackageWarnings.add(pjsonPath + "|" + match);
470
+ process.emitWarning(`Use of deprecated folder mapping "${match}" in the ${isExports ? '"exports"' : '"imports"'} field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath$1(base)}` : ""}.
471
+ Update this package.json to use a subpath pattern like "${match}*".`, "DeprecationWarning", "DEP0148");
472
+ }
473
+ function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {
474
+ const { format } = defaultGetFormat(url.href);
475
+ if (format !== "module") {
476
+ return;
477
+ }
478
+ const path2 = fileURLToPath$1(url.href);
479
+ const pkgPath = fileURLToPath$1(new URL(".", packageJsonUrl));
480
+ const basePath = fileURLToPath$1(base);
481
+ if (main) {
482
+ process.emitWarning(`Package ${pkgPath} has a "main" field set to ${JSON.stringify(main)}, excluding the full filename and extension to the resolved file at "${path2.slice(pkgPath.length)}", imported from ${basePath}.
483
+ Automatic extension resolution of the "main" field isdeprecated for ES modules.`, "DeprecationWarning", "DEP0151");
484
+ } else {
485
+ process.emitWarning(`No "main" or "exports" field defined in the package.json for ${pkgPath} resolving the main entry point "${path2.slice(pkgPath.length)}", imported from ${basePath}.
486
+ Default "index" lookups for the main are deprecated for ES modules.`, "DeprecationWarning", "DEP0151");
487
+ }
488
+ }
489
+ function tryStatSync(path2) {
490
+ try {
491
+ return statSync(path2);
492
+ } catch {
493
+ return new Stats();
494
+ }
495
+ }
496
+ function getPackageConfig(path2, specifier, base) {
497
+ const existing = packageJsonCache.get(path2);
498
+ if (existing !== void 0) {
499
+ return existing;
500
+ }
501
+ const source = packageJsonReader.read(path2).string;
502
+ if (source === void 0) {
503
+ const packageConfig2 = {
504
+ pjsonPath: path2,
505
+ exists: false,
506
+ main: void 0,
507
+ name: void 0,
508
+ type: "none",
509
+ exports: void 0,
510
+ imports: void 0
511
+ };
512
+ packageJsonCache.set(path2, packageConfig2);
513
+ return packageConfig2;
514
+ }
515
+ let packageJson;
516
+ try {
517
+ packageJson = JSON.parse(source);
518
+ } catch (error) {
519
+ throw new ERR_INVALID_PACKAGE_CONFIG(path2, (base ? `"${specifier}" from ` : "") + fileURLToPath$1(base || specifier), error.message);
520
+ }
521
+ const { exports, imports, main, name, type } = packageJson;
522
+ const packageConfig = {
523
+ pjsonPath: path2,
524
+ exists: true,
525
+ main: typeof main === "string" ? main : void 0,
526
+ name: typeof name === "string" ? name : void 0,
527
+ type: type === "module" || type === "commonjs" ? type : "none",
528
+ exports,
529
+ imports: imports && typeof imports === "object" ? imports : void 0
530
+ };
531
+ packageJsonCache.set(path2, packageConfig);
532
+ return packageConfig;
533
+ }
534
+ function getPackageScopeConfig(resolved) {
535
+ let packageJsonUrl = new URL("./package.json", resolved);
536
+ while (true) {
537
+ const packageJsonPath2 = packageJsonUrl.pathname;
538
+ if (packageJsonPath2.endsWith("node_modules/package.json")) {
539
+ break;
540
+ }
541
+ const packageConfig2 = getPackageConfig(fileURLToPath$1(packageJsonUrl), resolved);
542
+ if (packageConfig2.exists) {
543
+ return packageConfig2;
544
+ }
545
+ const lastPackageJsonUrl = packageJsonUrl;
546
+ packageJsonUrl = new URL("../package.json", packageJsonUrl);
547
+ if (packageJsonUrl.pathname === lastPackageJsonUrl.pathname) {
548
+ break;
549
+ }
550
+ }
551
+ const packageJsonPath = fileURLToPath$1(packageJsonUrl);
552
+ const packageConfig = {
553
+ pjsonPath: packageJsonPath,
554
+ exists: false,
555
+ main: void 0,
556
+ name: void 0,
557
+ type: "none",
558
+ exports: void 0,
559
+ imports: void 0
560
+ };
561
+ packageJsonCache.set(packageJsonPath, packageConfig);
562
+ return packageConfig;
563
+ }
564
+ function fileExists(url) {
565
+ return tryStatSync(fileURLToPath$1(url)).isFile();
566
+ }
567
+ function legacyMainResolve(packageJsonUrl, packageConfig, base) {
568
+ let guess;
569
+ if (packageConfig.main !== void 0) {
570
+ guess = new URL(`./${packageConfig.main}`, packageJsonUrl);
571
+ if (fileExists(guess)) {
572
+ return guess;
573
+ }
574
+ const tries2 = [
575
+ `./${packageConfig.main}.js`,
576
+ `./${packageConfig.main}.json`,
577
+ `./${packageConfig.main}.node`,
578
+ `./${packageConfig.main}/index.js`,
579
+ `./${packageConfig.main}/index.json`,
580
+ `./${packageConfig.main}/index.node`
581
+ ];
582
+ let i2 = -1;
583
+ while (++i2 < tries2.length) {
584
+ guess = new URL(tries2[i2], packageJsonUrl);
585
+ if (fileExists(guess)) {
586
+ break;
587
+ }
588
+ guess = void 0;
589
+ }
590
+ if (guess) {
591
+ emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
592
+ return guess;
593
+ }
594
+ }
595
+ const tries = ["./index.js", "./index.json", "./index.node"];
596
+ let i = -1;
597
+ while (++i < tries.length) {
598
+ guess = new URL(tries[i], packageJsonUrl);
599
+ if (fileExists(guess)) {
600
+ break;
601
+ }
602
+ guess = void 0;
603
+ }
604
+ if (guess) {
605
+ emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
606
+ return guess;
607
+ }
608
+ throw new ERR_MODULE_NOT_FOUND(fileURLToPath$1(new URL(".", packageJsonUrl)), fileURLToPath$1(base));
609
+ }
610
+ function finalizeResolution(resolved, base) {
611
+ if (encodedSepRegEx.test(resolved.pathname)) {
612
+ throw new ERR_INVALID_MODULE_SPECIFIER(resolved.pathname, 'must not include encoded "/" or "\\" characters', fileURLToPath$1(base));
613
+ }
614
+ const path2 = fileURLToPath$1(resolved);
615
+ const stats = tryStatSync(path2.endsWith("/") ? path2.slice(-1) : path2);
616
+ if (stats.isDirectory()) {
617
+ const error = new ERR_UNSUPPORTED_DIR_IMPORT(path2, fileURLToPath$1(base));
618
+ error.url = String(resolved);
619
+ throw error;
620
+ }
621
+ if (!stats.isFile()) {
622
+ throw new ERR_MODULE_NOT_FOUND(path2 || resolved.pathname, base && fileURLToPath$1(base), "module");
623
+ }
624
+ return resolved;
625
+ }
626
+ function throwImportNotDefined(specifier, packageJsonUrl, base) {
627
+ throw new ERR_PACKAGE_IMPORT_NOT_DEFINED(specifier, packageJsonUrl && fileURLToPath$1(new URL(".", packageJsonUrl)), fileURLToPath$1(base));
628
+ }
629
+ function throwExportsNotFound(subpath, packageJsonUrl, base) {
630
+ throw new ERR_PACKAGE_PATH_NOT_EXPORTED(fileURLToPath$1(new URL(".", packageJsonUrl)), subpath, base && fileURLToPath$1(base));
631
+ }
632
+ function throwInvalidSubpath(subpath, packageJsonUrl, internal, base) {
633
+ const reason = `request is not a valid subpath for the "${internal ? "imports" : "exports"}" resolution of ${fileURLToPath$1(packageJsonUrl)}`;
634
+ throw new ERR_INVALID_MODULE_SPECIFIER(subpath, reason, base && fileURLToPath$1(base));
635
+ }
636
+ function throwInvalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {
637
+ target = typeof target === "object" && target !== null ? JSON.stringify(target, null, "") : `${target}`;
638
+ throw new ERR_INVALID_PACKAGE_TARGET(fileURLToPath$1(new URL(".", packageJsonUrl)), subpath, target, internal, base && fileURLToPath$1(base));
639
+ }
640
+ function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base, pattern, internal, conditions) {
641
+ if (subpath !== "" && !pattern && target[target.length - 1] !== "/") {
642
+ throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base);
643
+ }
644
+ if (!target.startsWith("./")) {
645
+ if (internal && !target.startsWith("../") && !target.startsWith("/")) {
646
+ let isURL = false;
647
+ try {
648
+ new URL(target);
649
+ isURL = true;
650
+ } catch {
651
+ }
652
+ if (!isURL) {
653
+ const exportTarget = pattern ? target.replace(patternRegEx, subpath) : target + subpath;
654
+ return packageResolve(exportTarget, packageJsonUrl, conditions);
655
+ }
656
+ }
657
+ throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base);
658
+ }
659
+ if (invalidSegmentRegEx.test(target.slice(2))) {
660
+ throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base);
661
+ }
662
+ const resolved = new URL(target, packageJsonUrl);
663
+ const resolvedPath = resolved.pathname;
664
+ const packagePath = new URL(".", packageJsonUrl).pathname;
665
+ if (!resolvedPath.startsWith(packagePath)) {
666
+ throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base);
667
+ }
668
+ if (subpath === "") {
669
+ return resolved;
670
+ }
671
+ if (invalidSegmentRegEx.test(subpath)) {
672
+ throwInvalidSubpath(match + subpath, packageJsonUrl, internal, base);
673
+ }
674
+ if (pattern) {
675
+ return new URL(resolved.href.replace(patternRegEx, subpath));
676
+ }
677
+ return new URL(subpath, resolved);
678
+ }
679
+ function isArrayIndex(key) {
680
+ const keyNumber = Number(key);
681
+ if (`${keyNumber}` !== key) {
682
+ return false;
683
+ }
684
+ return keyNumber >= 0 && keyNumber < 4294967295;
685
+ }
686
+ function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, base, pattern, internal, conditions) {
687
+ if (typeof target === "string") {
688
+ return resolvePackageTargetString(target, subpath, packageSubpath, packageJsonUrl, base, pattern, internal, conditions);
689
+ }
690
+ if (Array.isArray(target)) {
691
+ const targetList = target;
692
+ if (targetList.length === 0) {
693
+ return null;
694
+ }
695
+ let lastException;
696
+ let i = -1;
697
+ while (++i < targetList.length) {
698
+ const targetItem = targetList[i];
699
+ let resolved;
700
+ try {
701
+ resolved = resolvePackageTarget(packageJsonUrl, targetItem, subpath, packageSubpath, base, pattern, internal, conditions);
702
+ } catch (error) {
703
+ lastException = error;
704
+ if (error.code === "ERR_INVALID_PACKAGE_TARGET") {
705
+ continue;
706
+ }
707
+ throw error;
708
+ }
709
+ if (resolved === void 0) {
710
+ continue;
711
+ }
712
+ if (resolved === null) {
713
+ lastException = null;
714
+ continue;
715
+ }
716
+ return resolved;
717
+ }
718
+ if (lastException === void 0 || lastException === null) {
719
+ return lastException;
720
+ }
721
+ throw lastException;
722
+ }
723
+ if (typeof target === "object" && target !== null) {
724
+ const keys = Object.getOwnPropertyNames(target);
725
+ let i = -1;
726
+ while (++i < keys.length) {
727
+ const key = keys[i];
728
+ if (isArrayIndex(key)) {
729
+ throw new ERR_INVALID_PACKAGE_CONFIG(fileURLToPath$1(packageJsonUrl), base, '"exports" cannot contain numeric property keys.');
730
+ }
731
+ }
732
+ i = -1;
733
+ while (++i < keys.length) {
734
+ const key = keys[i];
735
+ if (key === "default" || conditions && conditions.has(key)) {
736
+ const conditionalTarget = target[key];
737
+ const resolved = resolvePackageTarget(packageJsonUrl, conditionalTarget, subpath, packageSubpath, base, pattern, internal, conditions);
738
+ if (resolved === void 0) {
739
+ continue;
740
+ }
741
+ return resolved;
742
+ }
743
+ }
744
+ return void 0;
745
+ }
746
+ if (target === null) {
747
+ return null;
748
+ }
749
+ throwInvalidPackageTarget(packageSubpath, target, packageJsonUrl, internal, base);
750
+ }
751
+ function isConditionalExportsMainSugar(exports, packageJsonUrl, base) {
752
+ if (typeof exports === "string" || Array.isArray(exports)) {
753
+ return true;
754
+ }
755
+ if (typeof exports !== "object" || exports === null) {
756
+ return false;
757
+ }
758
+ const keys = Object.getOwnPropertyNames(exports);
759
+ let isConditionalSugar = false;
760
+ let i = 0;
761
+ let j = -1;
762
+ while (++j < keys.length) {
763
+ const key = keys[j];
764
+ const curIsConditionalSugar = key === "" || key[0] !== ".";
765
+ if (i++ === 0) {
766
+ isConditionalSugar = curIsConditionalSugar;
767
+ } else if (isConditionalSugar !== curIsConditionalSugar) {
768
+ throw new ERR_INVALID_PACKAGE_CONFIG(fileURLToPath$1(packageJsonUrl), base, `"exports" cannot contain some keys starting with '.' and some not. The exports object must either be an object of package subpath keys or an object of main entry condition name keys only.`);
769
+ }
770
+ }
771
+ return isConditionalSugar;
772
+ }
773
+ function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) {
774
+ let exports = packageConfig.exports;
775
+ if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) {
776
+ exports = { ".": exports };
777
+ }
778
+ if (own.call(exports, packageSubpath)) {
779
+ const target = exports[packageSubpath];
780
+ const resolved = resolvePackageTarget(packageJsonUrl, target, "", packageSubpath, base, false, false, conditions);
781
+ if (resolved === null || resolved === void 0) {
782
+ throwExportsNotFound(packageSubpath, packageJsonUrl, base);
783
+ }
784
+ return { resolved, exact: true };
785
+ }
786
+ let bestMatch = "";
787
+ const keys = Object.getOwnPropertyNames(exports);
788
+ let i = -1;
789
+ while (++i < keys.length) {
790
+ const key = keys[i];
791
+ if (key[key.length - 1] === "*" && packageSubpath.startsWith(key.slice(0, -1)) && packageSubpath.length >= key.length && key.length > bestMatch.length) {
792
+ bestMatch = key;
793
+ } else if (key[key.length - 1] === "/" && packageSubpath.startsWith(key) && key.length > bestMatch.length) {
794
+ bestMatch = key;
795
+ }
796
+ }
797
+ if (bestMatch) {
798
+ const target = exports[bestMatch];
799
+ const pattern = bestMatch[bestMatch.length - 1] === "*";
800
+ const subpath = packageSubpath.slice(bestMatch.length - (pattern ? 1 : 0));
801
+ const resolved = resolvePackageTarget(packageJsonUrl, target, subpath, bestMatch, base, pattern, false, conditions);
802
+ if (resolved === null || resolved === void 0) {
803
+ throwExportsNotFound(packageSubpath, packageJsonUrl, base);
804
+ }
805
+ if (!pattern) {
806
+ emitFolderMapDeprecation(bestMatch, packageJsonUrl, true, base);
807
+ }
808
+ return { resolved, exact: pattern };
809
+ }
810
+ throwExportsNotFound(packageSubpath, packageJsonUrl, base);
811
+ }
812
+ function packageImportsResolve(name, base, conditions) {
813
+ if (name === "#" || name.startsWith("#/")) {
814
+ const reason = "is not a valid internal imports specifier name";
815
+ throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, fileURLToPath$1(base));
816
+ }
817
+ let packageJsonUrl;
818
+ const packageConfig = getPackageScopeConfig(base);
819
+ if (packageConfig.exists) {
820
+ packageJsonUrl = pathToFileURL(packageConfig.pjsonPath);
821
+ const imports = packageConfig.imports;
822
+ if (imports) {
823
+ if (own.call(imports, name)) {
824
+ const resolved = resolvePackageTarget(packageJsonUrl, imports[name], "", name, base, false, true, conditions);
825
+ if (resolved !== null) {
826
+ return { resolved, exact: true };
827
+ }
828
+ } else {
829
+ let bestMatch = "";
830
+ const keys = Object.getOwnPropertyNames(imports);
831
+ let i = -1;
832
+ while (++i < keys.length) {
833
+ const key = keys[i];
834
+ if (key[key.length - 1] === "*" && name.startsWith(key.slice(0, -1)) && name.length >= key.length && key.length > bestMatch.length) {
835
+ bestMatch = key;
836
+ } else if (key[key.length - 1] === "/" && name.startsWith(key) && key.length > bestMatch.length) {
837
+ bestMatch = key;
838
+ }
839
+ }
840
+ if (bestMatch) {
841
+ const target = imports[bestMatch];
842
+ const pattern = bestMatch[bestMatch.length - 1] === "*";
843
+ const subpath = name.slice(bestMatch.length - (pattern ? 1 : 0));
844
+ const resolved = resolvePackageTarget(packageJsonUrl, target, subpath, bestMatch, base, pattern, true, conditions);
845
+ if (resolved !== null) {
846
+ if (!pattern) {
847
+ emitFolderMapDeprecation(bestMatch, packageJsonUrl, false, base);
848
+ }
849
+ return { resolved, exact: pattern };
850
+ }
851
+ }
852
+ }
853
+ }
854
+ }
855
+ throwImportNotDefined(name, packageJsonUrl, base);
856
+ }
857
+ function getPackageType(url) {
858
+ const packageConfig = getPackageScopeConfig(url);
859
+ return packageConfig.type;
860
+ }
861
+ function parsePackageName(specifier, base) {
862
+ let separatorIndex = specifier.indexOf("/");
863
+ let validPackageName = true;
864
+ let isScoped = false;
865
+ if (specifier[0] === "@") {
866
+ isScoped = true;
867
+ if (separatorIndex === -1 || specifier.length === 0) {
868
+ validPackageName = false;
869
+ } else {
870
+ separatorIndex = specifier.indexOf("/", separatorIndex + 1);
871
+ }
872
+ }
873
+ const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
874
+ let i = -1;
875
+ while (++i < packageName.length) {
876
+ if (packageName[i] === "%" || packageName[i] === "\\") {
877
+ validPackageName = false;
878
+ break;
879
+ }
880
+ }
881
+ if (!validPackageName) {
882
+ throw new ERR_INVALID_MODULE_SPECIFIER(specifier, "is not a valid package name", fileURLToPath$1(base));
883
+ }
884
+ const packageSubpath = "." + (separatorIndex === -1 ? "" : specifier.slice(separatorIndex));
885
+ return { packageName, packageSubpath, isScoped };
886
+ }
887
+ function packageResolve(specifier, base, conditions) {
888
+ const { packageName, packageSubpath, isScoped } = parsePackageName(specifier, base);
889
+ const packageConfig = getPackageScopeConfig(base);
890
+ if (packageConfig.exists) {
891
+ const packageJsonUrl2 = pathToFileURL(packageConfig.pjsonPath);
892
+ if (packageConfig.name === packageName && packageConfig.exports !== void 0 && packageConfig.exports !== null) {
893
+ return packageExportsResolve(packageJsonUrl2, packageSubpath, packageConfig, base, conditions).resolved;
894
+ }
895
+ }
896
+ let packageJsonUrl = new URL("./node_modules/" + packageName + "/package.json", base);
897
+ let packageJsonPath = fileURLToPath$1(packageJsonUrl);
898
+ let lastPath;
899
+ do {
900
+ const stat = tryStatSync(packageJsonPath.slice(0, -13));
901
+ if (!stat.isDirectory()) {
902
+ lastPath = packageJsonPath;
903
+ packageJsonUrl = new URL((isScoped ? "../../../../node_modules/" : "../../../node_modules/") + packageName + "/package.json", packageJsonUrl);
904
+ packageJsonPath = fileURLToPath$1(packageJsonUrl);
905
+ continue;
906
+ }
907
+ const packageConfig2 = getPackageConfig(packageJsonPath, specifier, base);
908
+ if (packageConfig2.exports !== void 0 && packageConfig2.exports !== null) {
909
+ return packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig2, base, conditions).resolved;
910
+ }
911
+ if (packageSubpath === ".") {
912
+ return legacyMainResolve(packageJsonUrl, packageConfig2, base);
913
+ }
914
+ return new URL(packageSubpath, packageJsonUrl);
915
+ } while (packageJsonPath.length !== lastPath.length);
916
+ throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath$1(base));
917
+ }
918
+ function isRelativeSpecifier(specifier) {
919
+ if (specifier[0] === ".") {
920
+ if (specifier.length === 1 || specifier[1] === "/") {
921
+ return true;
922
+ }
923
+ if (specifier[1] === "." && (specifier.length === 2 || specifier[2] === "/")) {
924
+ return true;
925
+ }
926
+ }
927
+ return false;
928
+ }
929
+ function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
930
+ if (specifier === "") {
931
+ return false;
932
+ }
933
+ if (specifier[0] === "/") {
934
+ return true;
935
+ }
936
+ return isRelativeSpecifier(specifier);
937
+ }
938
+ function moduleResolve(specifier, base, conditions) {
939
+ let resolved;
940
+ if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
941
+ resolved = new URL(specifier, base);
942
+ } else if (specifier[0] === "#") {
943
+ ({ resolved } = packageImportsResolve(specifier, base, conditions));
944
+ } else {
945
+ try {
946
+ resolved = new URL(specifier);
947
+ } catch {
948
+ resolved = packageResolve(specifier, base, conditions);
949
+ }
950
+ }
951
+ return finalizeResolution(resolved, base);
952
+ }
953
+
954
+ const DEFAULT_CONDITIONS_SET = /* @__PURE__ */ new Set(["node", "import"]);
955
+ const DEFAULT_URL = pathToFileURL(process.cwd());
956
+ const DEFAULT_EXTENSIONS = [".mjs", ".cjs", ".js", ".json"];
957
+ const NOT_FOUND_ERRORS = /* @__PURE__ */ new Set(["ERR_MODULE_NOT_FOUND", "ERR_UNSUPPORTED_DIR_IMPORT", "MODULE_NOT_FOUND", "ERR_PACKAGE_PATH_NOT_EXPORTED"]);
958
+ function _tryModuleResolve(id, url, conditions) {
959
+ try {
960
+ return moduleResolve(id, url, conditions);
961
+ } catch (err) {
962
+ if (!NOT_FOUND_ERRORS.has(err.code)) {
963
+ throw err;
964
+ }
965
+ return null;
966
+ }
967
+ }
968
+ function _resolve(id, opts = {}) {
969
+ if (/(node|data|http|https):/.test(id)) {
970
+ return id;
971
+ }
972
+ if (BUILTIN_MODULES.has(id)) {
973
+ return "node:" + id;
974
+ }
975
+ if (isAbsolute(id) && existsSync(id)) {
976
+ const realPath2 = realpathSync(fileURLToPath(id));
977
+ return pathToFileURL(realPath2).toString();
978
+ }
979
+ const conditionsSet = opts.conditions ? new Set(opts.conditions) : DEFAULT_CONDITIONS_SET;
980
+ const _urls = (Array.isArray(opts.url) ? opts.url : [opts.url]).filter(Boolean).map((u) => new URL(normalizeid(u.toString())));
981
+ if (!_urls.length) {
982
+ _urls.push(DEFAULT_URL);
983
+ }
984
+ const urls = [..._urls];
985
+ for (const url of _urls) {
986
+ if (url.protocol === "file:" && !url.pathname.includes("node_modules")) {
987
+ const newURL = new URL(url);
988
+ newURL.pathname += "/node_modules";
989
+ urls.push(newURL);
990
+ }
991
+ }
992
+ let resolved;
993
+ for (const url of urls) {
994
+ resolved = _tryModuleResolve(id, url, conditionsSet);
995
+ if (resolved) {
996
+ break;
997
+ }
998
+ for (const prefix of ["", "/index"]) {
999
+ for (const ext of opts.extensions || DEFAULT_EXTENSIONS) {
1000
+ resolved = _tryModuleResolve(id + prefix + ext, url, conditionsSet);
1001
+ if (resolved) {
1002
+ break;
1003
+ }
1004
+ }
1005
+ if (resolved) {
1006
+ break;
1007
+ }
1008
+ }
1009
+ }
1010
+ if (!resolved) {
1011
+ const err = new Error(`Cannot find module ${id} imported from ${urls.join(", ")}`);
1012
+ err.code = "ERR_MODULE_NOT_FOUND";
1013
+ throw err;
1014
+ }
1015
+ const realPath = realpathSync(fileURLToPath(resolved));
1016
+ return pathToFileURL(realPath).toString();
1017
+ }
1018
+ function resolveSync(id, opts) {
1019
+ return _resolve(id, opts);
1020
+ }
1021
+ function resolvePathSync(id, opts) {
1022
+ return fileURLToPath(resolveSync(id, opts));
1023
+ }
1024
+ function resolvePath(id, opts) {
1025
+ return pcall(resolvePathSync, id, opts);
1026
+ }
1027
+
1028
+ const ESM_RE = /([\s;]|^)(import[\w,{}\s*]*from|import\s*['"*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m;
1029
+ const BUILTIN_EXTENSIONS = /* @__PURE__ */ new Set([".mjs", ".cjs", ".node", ".wasm"]);
1030
+ function hasESMSyntax(code) {
1031
+ return ESM_RE.test(code);
1032
+ }
1033
+ const CJS_RE = /([\s;]|^)(module.exports\b|exports\.\w|require\s*\(|global\.\w)/m;
1034
+ function hasCJSSyntax(code) {
1035
+ return CJS_RE.test(code);
1036
+ }
1037
+ const validNodeImportDefaults = {
1038
+ allowedProtocols: ["node", "file", "data"]
1039
+ };
1040
+ async function isValidNodeImport(id, _opts = {}) {
1041
+ if (isNodeBuiltin(id)) {
1042
+ return true;
1043
+ }
1044
+ const opts = { ...validNodeImportDefaults, ..._opts };
1045
+ const proto = getProtocol(id);
1046
+ if (proto && !opts.allowedProtocols.includes(proto)) {
1047
+ return false;
1048
+ }
1049
+ if (proto === "data") {
1050
+ return true;
1051
+ }
1052
+ const resolvedPath = await resolvePath(id, opts);
1053
+ const extension = extname(resolvedPath);
1054
+ if (BUILTIN_EXTENSIONS.has(extension)) {
1055
+ return true;
1056
+ }
1057
+ if (extension !== ".js") {
1058
+ return false;
1059
+ }
1060
+ if (resolvedPath.match(/\.(\w+-)?esm?(-\w+)?\.js$/)) {
1061
+ return false;
1062
+ }
1063
+ const pkg = await readPackageJSON(resolvedPath).catch(() => null);
1064
+ if (pkg?.type === "module") {
1065
+ return true;
1066
+ }
1067
+ const code = opts.code || await promises.readFile(resolvedPath, "utf-8").catch(() => null) || "";
1068
+ return hasCJSSyntax(code) || !hasESMSyntax(code);
1069
+ }
1070
+
1071
+ const isWindows = process.platform === "win32";
1072
+ function slash(str) {
1073
+ return str.replace(/\\/g, "/");
1074
+ }
1075
+ function mergeSlashes(str) {
1076
+ return str.replace(/\/\//g, "/");
1077
+ }
1078
+ function normalizeRequestId(id, base) {
1079
+ if (base && id.startsWith(base))
1080
+ id = `/${id.slice(base.length)}`;
1081
+ return id.replace(/^\/@id\/__x00__/, "\0").replace(/^\/@id\//, "").replace(/^__vite-browser-external:/, "").replace(/^(node|file):/, "").replace(/^\/+/, "/").replace(/\?v=\w+/, "?").replace(/&v=\w+/, "").replace(/\?t=\w+/, "?").replace(/&t=\w+/, "").replace(/\?import/, "?").replace(/&import/, "").replace(/\?&/, "?").replace(/\?+$/, "");
1082
+ }
1083
+ function normalizeModuleId(id) {
1084
+ return id.replace(/\\/g, "/").replace(/^\/@fs\//, "/").replace(/^file:\//, "/").replace(/^\/+/, "/");
1085
+ }
1086
+ function isPrimitive(v) {
1087
+ return v !== Object(v);
1088
+ }
1089
+ function toFilePath(id, root) {
1090
+ let absolute = id.startsWith("/@fs/") ? id.slice(4) : id.startsWith(root) ? id : id.startsWith("/") ? resolve$1(root, id.slice(1)) : id;
1091
+ if (absolute.startsWith("//"))
1092
+ absolute = absolute.slice(1);
1093
+ return isWindows && absolute.startsWith("/") ? slash(fileURLToPath$1(pathToFileURL(absolute.slice(1)).href)) : absolute;
1094
+ }
1095
+ let SOURCEMAPPING_URL = "sourceMa";
1096
+ SOURCEMAPPING_URL += "ppingURL";
1097
+ async function withInlineSourcemap(result) {
1098
+ const { code, map } = result;
1099
+ if (code.includes(`${SOURCEMAPPING_URL}=`))
1100
+ return result;
1101
+ if (map)
1102
+ result.code = `${code}
1103
+
1104
+ //# ${SOURCEMAPPING_URL}=data:application/json;charset=utf-8;base64,${Buffer.from(JSON.stringify(map), "utf-8").toString("base64")}
1105
+ `;
1106
+ return result;
1107
+ }
1108
+ function toArray(array) {
1109
+ if (array === null || array === void 0)
1110
+ array = [];
1111
+ if (Array.isArray(array))
1112
+ return array;
1113
+ return [array];
1114
+ }
1115
+
1116
+ const debugExecute = createDebug("vite-node:client:execute");
1117
+ const debugNative = createDebug("vite-node:client:native");
1118
+ const DEFAULT_REQUEST_STUBS = {
1119
+ "/@vite/client": {
1120
+ injectQuery: (id) => id,
1121
+ createHotContext() {
1122
+ return {
1123
+ accept: () => {
1124
+ },
1125
+ prune: () => {
1126
+ },
1127
+ dispose: () => {
1128
+ },
1129
+ decline: () => {
1130
+ },
1131
+ invalidate: () => {
1132
+ },
1133
+ on: () => {
1134
+ }
1135
+ };
1136
+ },
1137
+ updateStyle(id, css) {
1138
+ if (typeof document === "undefined")
1139
+ return;
1140
+ const element = document.getElementById(id);
1141
+ if (element)
1142
+ element.remove();
1143
+ const head = document.querySelector("head");
1144
+ const style = document.createElement("style");
1145
+ style.setAttribute("type", "text/css");
1146
+ style.id = id;
1147
+ style.innerHTML = css;
1148
+ head == null ? void 0 : head.appendChild(style);
1149
+ }
1150
+ }
1151
+ };
1152
+ class ModuleCacheMap extends Map {
1153
+ normalizePath(fsPath) {
1154
+ return normalizeModuleId(fsPath);
1155
+ }
1156
+ set(fsPath, mod) {
1157
+ fsPath = this.normalizePath(fsPath);
1158
+ if (!super.has(fsPath))
1159
+ super.set(fsPath, mod);
1160
+ else
1161
+ Object.assign(super.get(fsPath), mod);
1162
+ return this;
1163
+ }
1164
+ get(fsPath) {
1165
+ fsPath = this.normalizePath(fsPath);
1166
+ return super.get(fsPath);
1167
+ }
1168
+ delete(fsPath) {
1169
+ fsPath = this.normalizePath(fsPath);
1170
+ return super.delete(fsPath);
1171
+ }
1172
+ }
1173
+ class ViteNodeRunner {
1174
+ constructor(options) {
1175
+ this.options = options;
1176
+ this.root = options.root ?? process.cwd();
1177
+ this.moduleCache = options.moduleCache ?? new ModuleCacheMap();
1178
+ this.debug = options.debug ?? (typeof process !== "undefined" ? !!process.env.VITE_NODE_DEBUG : false);
1179
+ }
1180
+ async executeFile(file) {
1181
+ return await this.cachedRequest(`/@fs/${slash(resolve$1(file))}`, []);
1182
+ }
1183
+ async executeId(id) {
1184
+ return await this.cachedRequest(id, []);
1185
+ }
1186
+ async cachedRequest(rawId, callstack) {
1187
+ var _a, _b, _c, _d;
1188
+ const id = normalizeRequestId(rawId, this.options.base);
1189
+ const fsPath = toFilePath(id, this.root);
1190
+ if (callstack.includes(fsPath) && ((_a = this.moduleCache.get(fsPath)) == null ? void 0 : _a.exports))
1191
+ return (_b = this.moduleCache.get(fsPath)) == null ? void 0 : _b.exports;
1192
+ if ((_c = this.moduleCache.get(fsPath)) == null ? void 0 : _c.promise)
1193
+ return (_d = this.moduleCache.get(fsPath)) == null ? void 0 : _d.promise;
1194
+ const promise = this.directRequest(id, fsPath, callstack);
1195
+ this.moduleCache.set(fsPath, { promise });
1196
+ return await promise;
1197
+ }
1198
+ async directRequest(id, fsPath, _callstack) {
1199
+ const callstack = [..._callstack, fsPath];
1200
+ const request = async (dep) => {
1201
+ var _a;
1202
+ const fsPath2 = toFilePath(normalizeRequestId(dep, this.options.base), this.root);
1203
+ const getStack = () => {
1204
+ return `stack:
1205
+ ${[...callstack, fsPath2].reverse().map((p) => `- ${p}`).join("\n")}`;
1206
+ };
1207
+ let debugTimer;
1208
+ if (this.debug)
1209
+ debugTimer = setTimeout(() => this.debugLog(() => `module ${fsPath2} takes over 2s to load.
1210
+ ${getStack()}`), 2e3);
1211
+ try {
1212
+ if (callstack.includes(fsPath2)) {
1213
+ this.debugLog(() => `circular dependency, ${getStack()}`);
1214
+ const depExports = (_a = this.moduleCache.get(fsPath2)) == null ? void 0 : _a.exports;
1215
+ if (depExports)
1216
+ return depExports;
1217
+ throw new Error(`[vite-node] Failed to resolve circular dependency, ${getStack()}`);
1218
+ }
1219
+ const mod = await this.cachedRequest(dep, callstack);
1220
+ return mod;
1221
+ } finally {
1222
+ if (debugTimer)
1223
+ clearTimeout(debugTimer);
1224
+ }
1225
+ };
1226
+ Object.defineProperty(request, "callstack", { get: () => callstack });
1227
+ const resolveId = async (dep, callstackPosition = 1) => {
1228
+ if (this.options.resolveId && this.shouldResolveId(dep)) {
1229
+ let importer = callstack[callstack.length - callstackPosition];
1230
+ if (importer && importer.startsWith("mock:"))
1231
+ importer = importer.slice(5);
1232
+ const { id: id2 } = await this.options.resolveId(dep, importer) || {};
1233
+ dep = id2 && isAbsolute$1(id2) ? mergeSlashes(`/@fs/${id2}`) : id2 || dep;
1234
+ }
1235
+ return dep;
1236
+ };
1237
+ id = await resolveId(id, 2);
1238
+ const requestStubs = this.options.requestStubs || DEFAULT_REQUEST_STUBS;
1239
+ if (id in requestStubs)
1240
+ return requestStubs[id];
1241
+ let { code: transformed, externalize } = await this.options.fetchModule(id);
1242
+ if (externalize) {
1243
+ debugNative(externalize);
1244
+ const mod = await this.interopedImport(externalize);
1245
+ this.moduleCache.set(fsPath, { exports: mod });
1246
+ return mod;
1247
+ }
1248
+ if (transformed == null)
1249
+ throw new Error(`[vite-node] Failed to load ${id}`);
1250
+ const url = pathToFileURL(fsPath).href;
1251
+ const meta = { url };
1252
+ const exports = /* @__PURE__ */ Object.create(null);
1253
+ exports[Symbol.toStringTag] = "Module";
1254
+ this.moduleCache.set(fsPath, { code: transformed, exports });
1255
+ const __filename = fileURLToPath$1(url);
1256
+ const moduleProxy = {
1257
+ set exports(value) {
1258
+ exportAll(exports, value);
1259
+ exports.default = value;
1260
+ },
1261
+ get exports() {
1262
+ return exports;
1263
+ }
1264
+ };
1265
+ let hotContext;
1266
+ if (this.options.createHotContext) {
1267
+ Object.defineProperty(meta, "hot", {
1268
+ enumerable: true,
1269
+ get: () => {
1270
+ var _a, _b;
1271
+ hotContext || (hotContext = (_b = (_a = this.options).createHotContext) == null ? void 0 : _b.call(_a, this, `/@fs/${fsPath}`));
1272
+ return hotContext;
1273
+ }
1274
+ });
1275
+ }
1276
+ const context = this.prepareContext({
1277
+ __vite_ssr_import__: request,
1278
+ __vite_ssr_dynamic_import__: request,
1279
+ __vite_ssr_exports__: exports,
1280
+ __vite_ssr_exportAll__: (obj) => exportAll(exports, obj),
1281
+ __vite_ssr_import_meta__: meta,
1282
+ __vitest_resolve_id__: resolveId,
1283
+ require: createRequire(url),
1284
+ exports,
1285
+ module: moduleProxy,
1286
+ __filename,
1287
+ __dirname: dirname(__filename)
1288
+ });
1289
+ debugExecute(__filename);
1290
+ if (transformed[0] === "#")
1291
+ transformed = transformed.replace(/^\#\!.*/, (s) => " ".repeat(s.length));
1292
+ const fn = vm.runInThisContext(`'use strict';async (${Object.keys(context).join(",")})=>{{${transformed}
1293
+ }}`, {
1294
+ filename: fsPath,
1295
+ lineOffset: 0
1296
+ });
1297
+ await fn(...Object.values(context));
1298
+ return exports;
1299
+ }
1300
+ prepareContext(context) {
1301
+ return context;
1302
+ }
1303
+ shouldResolveId(dep) {
1304
+ if (isNodeBuiltin(dep) || dep in (this.options.requestStubs || DEFAULT_REQUEST_STUBS) || dep.startsWith("/@vite"))
1305
+ return false;
1306
+ return !isAbsolute$1(dep) || !extname$1(dep);
1307
+ }
1308
+ shouldInterop(path, mod) {
1309
+ if (this.options.interopDefault === false)
1310
+ return false;
1311
+ return !path.endsWith(".mjs") && "default" in mod;
1312
+ }
1313
+ async interopedImport(path) {
1314
+ const mod = await import(path);
1315
+ if (this.shouldInterop(path, mod)) {
1316
+ const tryDefault = this.hasNestedDefault(mod);
1317
+ return new Proxy(mod, {
1318
+ get: proxyMethod("get", tryDefault),
1319
+ set: proxyMethod("set", tryDefault),
1320
+ has: proxyMethod("has", tryDefault),
1321
+ deleteProperty: proxyMethod("deleteProperty", tryDefault)
1322
+ });
1323
+ }
1324
+ return mod;
1325
+ }
1326
+ hasNestedDefault(target) {
1327
+ return "__esModule" in target && target.__esModule && "default" in target.default;
1328
+ }
1329
+ debugLog(msg) {
1330
+ if (this.debug)
1331
+ console.log(`[vite-node] ${msg()}`);
1332
+ }
1333
+ }
1334
+ function proxyMethod(name, tryDefault) {
1335
+ return function(target, key, ...args) {
1336
+ const result = Reflect[name](target, key, ...args);
1337
+ if (isPrimitive(target.default))
1338
+ return result;
1339
+ if (tryDefault && key === "default" || typeof result === "undefined")
1340
+ return Reflect[name](target.default, key, ...args);
1341
+ return result;
1342
+ };
1343
+ }
1344
+ function exportAll(exports, sourceModule) {
1345
+ if (exports === sourceModule)
1346
+ return;
1347
+ for (const key in sourceModule) {
1348
+ if (key !== "default") {
1349
+ try {
1350
+ Object.defineProperty(exports, key, {
1351
+ enumerable: true,
1352
+ configurable: true,
1353
+ get() {
1354
+ return sourceModule[key];
1355
+ }
1356
+ });
1357
+ } catch (_err) {
1358
+ }
1359
+ }
1360
+ }
1361
+ }
1362
+
1363
+ const DEFAULT_TIMEOUT = 6e4;
1364
+ function createBirpc(functions, options) {
1365
+ const {
1366
+ post,
1367
+ on,
1368
+ eventNames = [],
1369
+ serialize = (i) => i,
1370
+ deserialize = (i) => i,
1371
+ timeout = DEFAULT_TIMEOUT
1372
+ } = options;
1373
+ const rpcPromiseMap = /* @__PURE__ */ new Map();
1374
+ const rpc = new Proxy({}, {
1375
+ get(_, method) {
1376
+ const sendEvent = (...args) => {
1377
+ post(serialize({ m: method, a: args, t: "q" }));
1378
+ };
1379
+ if (eventNames.includes(method)) {
1380
+ sendEvent.asEvent = sendEvent;
1381
+ return sendEvent;
1382
+ }
1383
+ const sendCall = (...args) => {
1384
+ return new Promise((resolve, reject) => {
1385
+ const id = nanoid();
1386
+ rpcPromiseMap.set(id, { resolve, reject });
1387
+ post(serialize({ m: method, a: args, i: id, t: "q" }));
1388
+ if (timeout >= 0) {
1389
+ setTimeout(() => {
1390
+ reject(new Error(`[birpc] timeout on calling "${method}"`));
1391
+ rpcPromiseMap.delete(id);
1392
+ }, timeout);
1393
+ }
1394
+ });
1395
+ };
1396
+ sendCall.asEvent = sendEvent;
1397
+ return sendCall;
1398
+ }
1399
+ });
1400
+ on(async (data, ...extra) => {
1401
+ const msg = deserialize(data);
1402
+ if (msg.t === "q") {
1403
+ const { m: method, a: args } = msg;
1404
+ let result, error;
1405
+ try {
1406
+ result = await functions[method].apply(rpc, args);
1407
+ } catch (e) {
1408
+ error = e;
1409
+ }
1410
+ if (msg.i)
1411
+ post(serialize({ t: "s", i: msg.i, r: result, e: error }), ...extra);
1412
+ } else {
1413
+ const { i: ack, r: result, e: error } = msg;
1414
+ const promise = rpcPromiseMap.get(ack);
1415
+ if (error)
1416
+ promise?.reject(error);
1417
+ else
1418
+ promise?.resolve(result);
1419
+ rpcPromiseMap.delete(ack);
1420
+ }
1421
+ });
1422
+ return rpc;
1423
+ }
1424
+ const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
1425
+ function nanoid(size = 21) {
1426
+ let id = "";
1427
+ let i = size;
1428
+ while (i--)
1429
+ id += urlAlphabet[Math.random() * 64 | 0];
1430
+ return id;
1431
+ }
1432
+
1433
+ export { ModuleCacheMap as M, ViteNodeRunner as V, isValidNodeImport as a, toFilePath as b, createBirpc as c, isNodeBuiltin as i, normalizeRequestId as n, slash as s, toArray as t, withInlineSourcemap as w };