vitest 1.0.0-beta.4 → 1.0.0-beta.5

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 (65) hide show
  1. package/LICENSE.md +1 -513
  2. package/dist/browser.d.ts +1 -1
  3. package/dist/browser.js +4 -4
  4. package/dist/child.js +13 -17
  5. package/dist/{chunk-api-setup.6d19ab38.js → chunks/api-setup.jHV5vgr2.js} +97 -39
  6. package/dist/chunks/install-pkg.ORGzQeqb.js +457 -0
  7. package/dist/chunks/integrations-globals.-pds_Gug.js +29 -0
  8. package/dist/{chunk-node-git.6c12e560.js → chunks/node-git.Hw101KjS.js} +1 -18
  9. package/dist/{chunk-runtime-console.f3263f87.js → chunks/runtime-console.iCAG0Yz3.js} +1 -1
  10. package/dist/cli-wrapper.js +2 -18
  11. package/dist/cli.js +18 -23
  12. package/dist/config.cjs +1 -1
  13. package/dist/config.d.ts +4 -6
  14. package/dist/config.js +1 -1
  15. package/dist/coverage.d.ts +25 -15
  16. package/dist/coverage.js +118 -49
  17. package/dist/entry-vm.js +13 -13
  18. package/dist/entry.js +14 -14
  19. package/dist/environments.d.ts +1 -1
  20. package/dist/environments.js +1 -1
  21. package/dist/execute.d.ts +1 -1
  22. package/dist/execute.js +3 -3
  23. package/dist/index.d.ts +166 -38
  24. package/dist/index.js +10 -10
  25. package/dist/node.d.ts +5 -5
  26. package/dist/node.js +17 -22
  27. package/dist/{vendor-paths.84fc7a99.js → paths.js} +1 -1
  28. package/dist/{reporters-50c2bd49.d.ts → reporters-ANEBTnOh.d.ts} +324 -361
  29. package/dist/reporters.d.ts +1 -1
  30. package/dist/reporters.js +7 -8
  31. package/dist/runners.d.ts +1 -1
  32. package/dist/runners.js +8 -8
  33. package/dist/{suite-ad69b7cd.d.ts → suite-C1OmA61l.d.ts} +1 -1
  34. package/dist/suite.d.ts +2 -2
  35. package/dist/suite.js +3 -3
  36. package/dist/{vendor-benchmark.b6befc50.js → vendor/benchmark.WVm6DARl.js} +1 -1
  37. package/dist/{vendor-execute.157302d6.js → vendor/execute.aMjV5C9u.js} +2 -4
  38. package/dist/{vendor-index.72df742e.js → vendor/index.Npc-eff0.js} +4 -4
  39. package/dist/{vendor-index.2b92937b.js → vendor/index.XU72Rmy8.js} +1 -1
  40. package/dist/{vendor-index.57925a34.js → vendor/index.h0j9y5vy.js} +5 -5
  41. package/dist/vendor/index.xL8XjTLv.js +3962 -0
  42. package/dist/vendor/loader.CU0NY2Is.js +39 -0
  43. package/dist/{vendor-node.65461b16.js → vendor/node.c-kzGvOB.js} +1874 -5960
  44. package/dist/{vendor-reporters.d24d80a4.js → vendor/reporters.1xKxm8im.js} +424 -374
  45. package/dist/{vendor-rpc.171f65fb.js → vendor/rpc.Bl-ysZIr.js} +1 -1
  46. package/dist/{vendor-run-once.fb836747.js → vendor/run-once.X3E7xx3F.js} +1 -1
  47. package/dist/{vendor-vi.3baa7c4a.js → vendor/vi.voNYQWB_.js} +4 -4
  48. package/dist/vm.js +13 -18
  49. package/dist/worker.js +13 -18
  50. package/index.cjs +5 -0
  51. package/package.json +49 -53
  52. package/dist/chunk-install-pkg.e1d6323e.js +0 -1740
  53. package/dist/chunk-integrations-globals.2b099e04.js +0 -29
  54. package/dist/vendor-index.8efe7746.js +0 -2236
  55. package/dist/vendor-loader.9c966f23.js +0 -2089
  56. /package/dist/{vendor-_commonjsHelpers.7d1333e8.js → vendor/_commonjsHelpers.jjO7Zipk.js} +0 -0
  57. /package/dist/{vendor-base.9c08bbd0.js → vendor/base._79unx2z.js} +0 -0
  58. /package/dist/{vendor-constants.538d9b49.js → vendor/constants.WSvnD_fn.js} +0 -0
  59. /package/dist/{vendor-coverage.78040316.js → vendor/coverage.v6aD8iAh.js} +0 -0
  60. /package/dist/{vendor-date.6e993429.js → vendor/date.W90-E5kF.js} +0 -0
  61. /package/dist/{vendor-environments.dcc4a34e.js → vendor/environments.hpEVJZPC.js} +0 -0
  62. /package/dist/{vendor-global.c3664e75.js → vendor/global.L7JRz1qU.js} +0 -0
  63. /package/dist/{vendor-index.1ca68bd5.js → vendor/index.cAUulNDf.js} +0 -0
  64. /package/dist/{vendor-inspector.209edf5a.js → vendor/inspector.lFAeuaAt.js} +0 -0
  65. /package/dist/{vendor-tasks.f9d75aed.js → vendor/tasks.IknbGB2n.js} +0 -0
@@ -1,2089 +0,0 @@
1
- import { isAbsolute, resolve, normalize } from 'pathe';
2
- import 'acorn';
3
- import { builtinModules } from 'node:module';
4
- import fs, { existsSync, realpathSync, statSync, Stats } from 'node:fs';
5
- import { pathToFileURL, fileURLToPath as fileURLToPath$1, URL as URL$1 } from 'node:url';
6
- import assert from 'node:assert';
7
- import process$1 from 'node:process';
8
- import path from 'node:path';
9
- import v8 from 'node:v8';
10
- import { format, inspect } from 'node:util';
11
- import { ViteNodeRunner } from 'vite-node/client';
12
- import { e as environments } from './vendor-environments.dcc4a34e.js';
13
-
14
- const TRAILING_SLASH_RE = /\/$|\/\?/;
15
- function hasTrailingSlash(input = "", queryParameters = false) {
16
- if (!queryParameters) {
17
- return input.endsWith("/");
18
- }
19
- return TRAILING_SLASH_RE.test(input);
20
- }
21
- function withTrailingSlash(input = "", queryParameters = false) {
22
- if (!queryParameters) {
23
- return input.endsWith("/") ? input : input + "/";
24
- }
25
- if (hasTrailingSlash(input, true)) {
26
- return input || "/";
27
- }
28
- const [s0, ...s] = input.split("?");
29
- return s0 + "/" + (s.length > 0 ? `?${s.join("?")}` : "");
30
- }
31
- function hasLeadingSlash(input = "") {
32
- return input.startsWith("/");
33
- }
34
- function withoutLeadingSlash(input = "") {
35
- return (hasLeadingSlash(input) ? input.slice(1) : input) || "/";
36
- }
37
- function isNonEmptyURL(url) {
38
- return url && url !== "/";
39
- }
40
- function joinURL(base, ...input) {
41
- let url = base || "";
42
- for (const index of input.filter((url2) => isNonEmptyURL(url2))) {
43
- url = url ? withTrailingSlash(url) + withoutLeadingSlash(index) : index;
44
- }
45
- return url;
46
- }
47
-
48
- const BUILTIN_MODULES = new Set(builtinModules);
49
- function normalizeSlash(string_) {
50
- return string_.replace(/\\/g, "/");
51
- }
52
- function pcall(function_, ...arguments_) {
53
- try {
54
- return Promise.resolve(function_(...arguments_)).catch(
55
- (error) => perr(error)
56
- );
57
- } catch (error) {
58
- return perr(error);
59
- }
60
- }
61
- function perr(_error) {
62
- const error = new Error(_error);
63
- error.code = _error.code;
64
- Error.captureStackTrace(error, pcall);
65
- return Promise.reject(error);
66
- }
67
-
68
- /**
69
- * @typedef ErrnoExceptionFields
70
- * @property {number | undefined} [errnode]
71
- * @property {string | undefined} [code]
72
- * @property {string | undefined} [path]
73
- * @property {string | undefined} [syscall]
74
- * @property {string | undefined} [url]
75
- *
76
- * @typedef {Error & ErrnoExceptionFields} ErrnoException
77
- */
78
-
79
-
80
- const isWindows = process$1.platform === 'win32';
81
-
82
- const own$1 = {}.hasOwnProperty;
83
-
84
- const classRegExp = /^([A-Z][a-z\d]*)+$/;
85
- // Sorted by a rough estimate on most frequently used entries.
86
- const kTypes = new Set([
87
- 'string',
88
- 'function',
89
- 'number',
90
- 'object',
91
- // Accept 'Function' and 'Object' as alternative to the lower cased version.
92
- 'Function',
93
- 'Object',
94
- 'boolean',
95
- 'bigint',
96
- 'symbol'
97
- ]);
98
-
99
- const codes = {};
100
-
101
- /**
102
- * Create a list string in the form like 'A and B' or 'A, B, ..., and Z'.
103
- * We cannot use Intl.ListFormat because it's not available in
104
- * --without-intl builds.
105
- *
106
- * @param {Array<string>} array
107
- * An array of strings.
108
- * @param {string} [type]
109
- * The list type to be inserted before the last element.
110
- * @returns {string}
111
- */
112
- function formatList(array, type = 'and') {
113
- return array.length < 3
114
- ? array.join(` ${type} `)
115
- : `${array.slice(0, -1).join(', ')}, ${type} ${array[array.length - 1]}`
116
- }
117
-
118
- /** @type {Map<string, MessageFunction | string>} */
119
- const messages = new Map();
120
- const nodeInternalPrefix = '__node_internal_';
121
- /** @type {number} */
122
- let userStackTraceLimit;
123
-
124
- codes.ERR_INVALID_ARG_TYPE = createError(
125
- 'ERR_INVALID_ARG_TYPE',
126
- /**
127
- * @param {string} name
128
- * @param {Array<string> | string} expected
129
- * @param {unknown} actual
130
- */
131
- (name, expected, actual) => {
132
- assert(typeof name === 'string', "'name' must be a string");
133
- if (!Array.isArray(expected)) {
134
- expected = [expected];
135
- }
136
-
137
- let message = 'The ';
138
- if (name.endsWith(' argument')) {
139
- // For cases like 'first argument'
140
- message += `${name} `;
141
- } else {
142
- const type = name.includes('.') ? 'property' : 'argument';
143
- message += `"${name}" ${type} `;
144
- }
145
-
146
- message += 'must be ';
147
-
148
- /** @type {Array<string>} */
149
- const types = [];
150
- /** @type {Array<string>} */
151
- const instances = [];
152
- /** @type {Array<string>} */
153
- const other = [];
154
-
155
- for (const value of expected) {
156
- assert(
157
- typeof value === 'string',
158
- 'All expected entries have to be of type string'
159
- );
160
-
161
- if (kTypes.has(value)) {
162
- types.push(value.toLowerCase());
163
- } else if (classRegExp.exec(value) === null) {
164
- assert(
165
- value !== 'object',
166
- 'The value "object" should be written as "Object"'
167
- );
168
- other.push(value);
169
- } else {
170
- instances.push(value);
171
- }
172
- }
173
-
174
- // Special handle `object` in case other instances are allowed to outline
175
- // the differences between each other.
176
- if (instances.length > 0) {
177
- const pos = types.indexOf('object');
178
- if (pos !== -1) {
179
- types.slice(pos, 1);
180
- instances.push('Object');
181
- }
182
- }
183
-
184
- if (types.length > 0) {
185
- message += `${types.length > 1 ? 'one of type' : 'of type'} ${formatList(
186
- types,
187
- 'or'
188
- )}`;
189
- if (instances.length > 0 || other.length > 0) message += ' or ';
190
- }
191
-
192
- if (instances.length > 0) {
193
- message += `an instance of ${formatList(instances, 'or')}`;
194
- if (other.length > 0) message += ' or ';
195
- }
196
-
197
- if (other.length > 0) {
198
- if (other.length > 1) {
199
- message += `one of ${formatList(other, 'or')}`;
200
- } else {
201
- if (other[0].toLowerCase() !== other[0]) message += 'an ';
202
- message += `${other[0]}`;
203
- }
204
- }
205
-
206
- message += `. Received ${determineSpecificType(actual)}`;
207
-
208
- return message
209
- },
210
- TypeError
211
- );
212
-
213
- codes.ERR_INVALID_MODULE_SPECIFIER = createError(
214
- 'ERR_INVALID_MODULE_SPECIFIER',
215
- /**
216
- * @param {string} request
217
- * @param {string} reason
218
- * @param {string} [base]
219
- */
220
- (request, reason, base = undefined) => {
221
- return `Invalid module "${request}" ${reason}${
222
- base ? ` imported from ${base}` : ''
223
- }`
224
- },
225
- TypeError
226
- );
227
-
228
- codes.ERR_INVALID_PACKAGE_CONFIG = createError(
229
- 'ERR_INVALID_PACKAGE_CONFIG',
230
- /**
231
- * @param {string} path
232
- * @param {string} [base]
233
- * @param {string} [message]
234
- */
235
- (path, base, message) => {
236
- return `Invalid package config ${path}${
237
- base ? ` while importing ${base}` : ''
238
- }${message ? `. ${message}` : ''}`
239
- },
240
- Error
241
- );
242
-
243
- codes.ERR_INVALID_PACKAGE_TARGET = createError(
244
- 'ERR_INVALID_PACKAGE_TARGET',
245
- /**
246
- * @param {string} pkgPath
247
- * @param {string} key
248
- * @param {unknown} target
249
- * @param {boolean} [isImport=false]
250
- * @param {string} [base]
251
- */
252
- (pkgPath, key, target, isImport = false, base = undefined) => {
253
- const relError =
254
- typeof target === 'string' &&
255
- !isImport &&
256
- target.length > 0 &&
257
- !target.startsWith('./');
258
- if (key === '.') {
259
- assert(isImport === false);
260
- return (
261
- `Invalid "exports" main target ${JSON.stringify(target)} defined ` +
262
- `in the package config ${pkgPath}package.json${
263
- base ? ` imported from ${base}` : ''
264
- }${relError ? '; targets must start with "./"' : ''}`
265
- )
266
- }
267
-
268
- return `Invalid "${
269
- isImport ? 'imports' : 'exports'
270
- }" target ${JSON.stringify(
271
- target
272
- )} defined for '${key}' in the package config ${pkgPath}package.json${
273
- base ? ` imported from ${base}` : ''
274
- }${relError ? '; targets must start with "./"' : ''}`
275
- },
276
- Error
277
- );
278
-
279
- codes.ERR_MODULE_NOT_FOUND = createError(
280
- 'ERR_MODULE_NOT_FOUND',
281
- /**
282
- * @param {string} path
283
- * @param {string} base
284
- * @param {string} [type]
285
- */
286
- (path, base, type = 'package') => {
287
- return `Cannot find ${type} '${path}' imported from ${base}`
288
- },
289
- Error
290
- );
291
-
292
- codes.ERR_NETWORK_IMPORT_DISALLOWED = createError(
293
- 'ERR_NETWORK_IMPORT_DISALLOWED',
294
- "import of '%s' by %s is not supported: %s",
295
- Error
296
- );
297
-
298
- codes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError(
299
- 'ERR_PACKAGE_IMPORT_NOT_DEFINED',
300
- /**
301
- * @param {string} specifier
302
- * @param {string} packagePath
303
- * @param {string} base
304
- */
305
- (specifier, packagePath, base) => {
306
- return `Package import specifier "${specifier}" is not defined${
307
- packagePath ? ` in package ${packagePath}package.json` : ''
308
- } imported from ${base}`
309
- },
310
- TypeError
311
- );
312
-
313
- codes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError(
314
- 'ERR_PACKAGE_PATH_NOT_EXPORTED',
315
- /**
316
- * @param {string} pkgPath
317
- * @param {string} subpath
318
- * @param {string} [base]
319
- */
320
- (pkgPath, subpath, base = undefined) => {
321
- if (subpath === '.')
322
- return `No "exports" main defined in ${pkgPath}package.json${
323
- base ? ` imported from ${base}` : ''
324
- }`
325
- return `Package subpath '${subpath}' is not defined by "exports" in ${pkgPath}package.json${
326
- base ? ` imported from ${base}` : ''
327
- }`
328
- },
329
- Error
330
- );
331
-
332
- codes.ERR_UNSUPPORTED_DIR_IMPORT = createError(
333
- 'ERR_UNSUPPORTED_DIR_IMPORT',
334
- "Directory import '%s' is not supported " +
335
- 'resolving ES modules imported from %s',
336
- Error
337
- );
338
-
339
- codes.ERR_UNKNOWN_FILE_EXTENSION = createError(
340
- 'ERR_UNKNOWN_FILE_EXTENSION',
341
- /**
342
- * @param {string} ext
343
- * @param {string} path
344
- */
345
- (ext, path) => {
346
- return `Unknown file extension "${ext}" for ${path}`
347
- },
348
- TypeError
349
- );
350
-
351
- codes.ERR_INVALID_ARG_VALUE = createError(
352
- 'ERR_INVALID_ARG_VALUE',
353
- /**
354
- * @param {string} name
355
- * @param {unknown} value
356
- * @param {string} [reason='is invalid']
357
- */
358
- (name, value, reason = 'is invalid') => {
359
- let inspected = inspect(value);
360
-
361
- if (inspected.length > 128) {
362
- inspected = `${inspected.slice(0, 128)}...`;
363
- }
364
-
365
- const type = name.includes('.') ? 'property' : 'argument';
366
-
367
- return `The ${type} '${name}' ${reason}. Received ${inspected}`
368
- },
369
- TypeError
370
- // Note: extra classes have been shaken out.
371
- // , RangeError
372
- );
373
-
374
- codes.ERR_UNSUPPORTED_ESM_URL_SCHEME = createError(
375
- 'ERR_UNSUPPORTED_ESM_URL_SCHEME',
376
- /**
377
- * @param {URL} url
378
- * @param {Array<string>} supported
379
- */
380
- (url, supported) => {
381
- let message = `Only URLs with a scheme in: ${formatList(
382
- supported
383
- )} are supported by the default ESM loader`;
384
-
385
- if (isWindows && url.protocol.length === 2) {
386
- message += '. On Windows, absolute paths must be valid file:// URLs';
387
- }
388
-
389
- message += `. Received protocol '${url.protocol}'`;
390
- return message
391
- },
392
- Error
393
- );
394
-
395
- /**
396
- * Utility function for registering the error codes. Only used here. Exported
397
- * *only* to allow for testing.
398
- * @param {string} sym
399
- * @param {MessageFunction | string} value
400
- * @param {ErrorConstructor} def
401
- * @returns {new (...args: Array<any>) => Error}
402
- */
403
- function createError(sym, value, def) {
404
- // Special case for SystemError that formats the error message differently
405
- // The SystemErrors only have SystemError as their base classes.
406
- messages.set(sym, value);
407
-
408
- return makeNodeErrorWithCode(def, sym)
409
- }
410
-
411
- /**
412
- * @param {ErrorConstructor} Base
413
- * @param {string} key
414
- * @returns {ErrorConstructor}
415
- */
416
- function makeNodeErrorWithCode(Base, key) {
417
- // @ts-expect-error It’s a Node error.
418
- return NodeError
419
- /**
420
- * @param {Array<unknown>} args
421
- */
422
- function NodeError(...args) {
423
- const limit = Error.stackTraceLimit;
424
- if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
425
- const error = new Base();
426
- // Reset the limit and setting the name property.
427
- if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit;
428
- const message = getMessage(key, args, error);
429
- Object.defineProperties(error, {
430
- // Note: no need to implement `kIsNodeError` symbol, would be hard,
431
- // probably.
432
- message: {
433
- value: message,
434
- enumerable: false,
435
- writable: true,
436
- configurable: true
437
- },
438
- toString: {
439
- /** @this {Error} */
440
- value() {
441
- return `${this.name} [${key}]: ${this.message}`
442
- },
443
- enumerable: false,
444
- writable: true,
445
- configurable: true
446
- }
447
- });
448
-
449
- captureLargerStackTrace(error);
450
- // @ts-expect-error It’s a Node error.
451
- error.code = key;
452
- return error
453
- }
454
- }
455
-
456
- /**
457
- * @returns {boolean}
458
- */
459
- function isErrorStackTraceLimitWritable() {
460
- // Do no touch Error.stackTraceLimit as V8 would attempt to install
461
- // it again during deserialization.
462
- try {
463
- // @ts-expect-error: not in types?
464
- if (v8.startupSnapshot.isBuildingSnapshot()) {
465
- return false
466
- }
467
- } catch {}
468
-
469
- const desc = Object.getOwnPropertyDescriptor(Error, 'stackTraceLimit');
470
- if (desc === undefined) {
471
- return Object.isExtensible(Error)
472
- }
473
-
474
- return own$1.call(desc, 'writable') && desc.writable !== undefined
475
- ? desc.writable
476
- : desc.set !== undefined
477
- }
478
-
479
- /**
480
- * This function removes unnecessary frames from Node.js core errors.
481
- * @template {(...args: unknown[]) => unknown} T
482
- * @param {T} fn
483
- * @returns {T}
484
- */
485
- function hideStackFrames(fn) {
486
- // We rename the functions that will be hidden to cut off the stacktrace
487
- // at the outermost one
488
- const hidden = nodeInternalPrefix + fn.name;
489
- Object.defineProperty(fn, 'name', {value: hidden});
490
- return fn
491
- }
492
-
493
- const captureLargerStackTrace = hideStackFrames(
494
- /**
495
- * @param {Error} error
496
- * @returns {Error}
497
- */
498
- // @ts-expect-error: fine
499
- function (error) {
500
- const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
501
- if (stackTraceLimitIsWritable) {
502
- userStackTraceLimit = Error.stackTraceLimit;
503
- Error.stackTraceLimit = Number.POSITIVE_INFINITY;
504
- }
505
-
506
- Error.captureStackTrace(error);
507
-
508
- // Reset the limit
509
- if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;
510
-
511
- return error
512
- }
513
- );
514
-
515
- /**
516
- * @param {string} key
517
- * @param {Array<unknown>} args
518
- * @param {Error} self
519
- * @returns {string}
520
- */
521
- function getMessage(key, args, self) {
522
- const message = messages.get(key);
523
- assert(message !== undefined, 'expected `message` to be found');
524
-
525
- if (typeof message === 'function') {
526
- assert(
527
- message.length <= args.length, // Default options do not count.
528
- `Code: ${key}; The provided arguments length (${args.length}) does not ` +
529
- `match the required ones (${message.length}).`
530
- );
531
- return Reflect.apply(message, self, args)
532
- }
533
-
534
- const regex = /%[dfijoOs]/g;
535
- let expectedLength = 0;
536
- while (regex.exec(message) !== null) expectedLength++;
537
- assert(
538
- expectedLength === args.length,
539
- `Code: ${key}; The provided arguments length (${args.length}) does not ` +
540
- `match the required ones (${expectedLength}).`
541
- );
542
- if (args.length === 0) return message
543
-
544
- args.unshift(message);
545
- return Reflect.apply(format, null, args)
546
- }
547
-
548
- /**
549
- * Determine the specific type of a value for type-mismatch errors.
550
- * @param {unknown} value
551
- * @returns {string}
552
- */
553
- function determineSpecificType(value) {
554
- if (value === null || value === undefined) {
555
- return String(value)
556
- }
557
-
558
- if (typeof value === 'function' && value.name) {
559
- return `function ${value.name}`
560
- }
561
-
562
- if (typeof value === 'object') {
563
- if (value.constructor && value.constructor.name) {
564
- return `an instance of ${value.constructor.name}`
565
- }
566
-
567
- return `${inspect(value, {depth: -1})}`
568
- }
569
-
570
- let inspected = inspect(value, {colors: false});
571
-
572
- if (inspected.length > 28) {
573
- inspected = `${inspected.slice(0, 25)}...`;
574
- }
575
-
576
- return `type ${typeof value} (${inspected})`
577
- }
578
-
579
- // Manually “tree shaken” from:
580
- // <https://github.com/nodejs/node/blob/3e74590/lib/internal/modules/package_json_reader.js>
581
- // Last checked on: Apr 24, 2023.
582
- // Removed the native dependency.
583
- // Also: no need to cache, we do that in resolve already.
584
-
585
-
586
- const reader = {read};
587
- const packageJsonReader = reader;
588
-
589
- /**
590
- * @param {string} jsonPath
591
- * @returns {{string: string | undefined}}
592
- */
593
- function read(jsonPath) {
594
- try {
595
- const string = fs.readFileSync(
596
- path.toNamespacedPath(path.join(path.dirname(jsonPath), 'package.json')),
597
- 'utf8'
598
- );
599
- return {string}
600
- } catch (error) {
601
- const exception = /** @type {ErrnoException} */ (error);
602
-
603
- if (exception.code === 'ENOENT') {
604
- return {string: undefined}
605
- // Throw all other errors.
606
- /* c8 ignore next 4 */
607
- }
608
-
609
- throw exception
610
- }
611
- }
612
-
613
- // Manually “tree shaken” from:
614
- // <https://github.com/nodejs/node/blob/3e74590/lib/internal/modules/esm/package_config.js>
615
- // Last checked on: Apr 24, 2023.
616
-
617
-
618
- const {ERR_INVALID_PACKAGE_CONFIG: ERR_INVALID_PACKAGE_CONFIG$1} = codes;
619
-
620
- /** @type {Map<string, PackageConfig>} */
621
- const packageJsonCache = new Map();
622
-
623
- /**
624
- * @param {string} path
625
- * @param {URL | string} specifier Note: `specifier` is actually optional, not base.
626
- * @param {URL} [base]
627
- * @returns {PackageConfig}
628
- */
629
- function getPackageConfig(path, specifier, base) {
630
- const existing = packageJsonCache.get(path);
631
- if (existing !== undefined) {
632
- return existing
633
- }
634
-
635
- const source = packageJsonReader.read(path).string;
636
-
637
- if (source === undefined) {
638
- /** @type {PackageConfig} */
639
- const packageConfig = {
640
- pjsonPath: path,
641
- exists: false,
642
- main: undefined,
643
- name: undefined,
644
- type: 'none',
645
- exports: undefined,
646
- imports: undefined
647
- };
648
- packageJsonCache.set(path, packageConfig);
649
- return packageConfig
650
- }
651
-
652
- /** @type {Record<string, unknown>} */
653
- let packageJson;
654
- try {
655
- packageJson = JSON.parse(source);
656
- } catch (error) {
657
- const exception = /** @type {ErrnoException} */ (error);
658
-
659
- throw new ERR_INVALID_PACKAGE_CONFIG$1(
660
- path,
661
- (base ? `"${specifier}" from ` : '') + fileURLToPath$1(base || specifier),
662
- exception.message
663
- )
664
- }
665
-
666
- const {exports, imports, main, name, type} = packageJson;
667
-
668
- /** @type {PackageConfig} */
669
- const packageConfig = {
670
- pjsonPath: path,
671
- exists: true,
672
- main: typeof main === 'string' ? main : undefined,
673
- name: typeof name === 'string' ? name : undefined,
674
- type: type === 'module' || type === 'commonjs' ? type : 'none',
675
- // @ts-expect-error Assume `Record<string, unknown>`.
676
- exports,
677
- // @ts-expect-error Assume `Record<string, unknown>`.
678
- imports: imports && typeof imports === 'object' ? imports : undefined
679
- };
680
- packageJsonCache.set(path, packageConfig);
681
- return packageConfig
682
- }
683
-
684
- /**
685
- * @param {URL} resolved
686
- * @returns {PackageConfig}
687
- */
688
- function getPackageScopeConfig(resolved) {
689
- let packageJsonUrl = new URL$1('package.json', resolved);
690
-
691
- while (true) {
692
- const packageJsonPath = packageJsonUrl.pathname;
693
-
694
- if (packageJsonPath.endsWith('node_modules/package.json')) break
695
-
696
- const packageConfig = getPackageConfig(
697
- fileURLToPath$1(packageJsonUrl),
698
- resolved
699
- );
700
- if (packageConfig.exists) return packageConfig
701
-
702
- const lastPackageJsonUrl = packageJsonUrl;
703
- packageJsonUrl = new URL$1('../package.json', packageJsonUrl);
704
-
705
- // Terminates at root where ../package.json equals ../../package.json
706
- // (can't just check "/package.json" for Windows support).
707
- if (packageJsonUrl.pathname === lastPackageJsonUrl.pathname) break
708
- }
709
-
710
- const packageJsonPath = fileURLToPath$1(packageJsonUrl);
711
- /** @type {PackageConfig} */
712
- const packageConfig = {
713
- pjsonPath: packageJsonPath,
714
- exists: false,
715
- main: undefined,
716
- name: undefined,
717
- type: 'none',
718
- exports: undefined,
719
- imports: undefined
720
- };
721
- packageJsonCache.set(packageJsonPath, packageConfig);
722
- return packageConfig
723
- }
724
-
725
- // Manually “tree shaken” from:
726
- // <https://github.com/nodejs/node/blob/3e74590/lib/internal/modules/esm/resolve.js>
727
- // Last checked on: Apr 24, 2023.
728
- //
729
- // This file solves a circular dependency.
730
- // In Node.js, `getPackageType` is in `resolve.js`.
731
- // `resolve.js` imports `get-format.js`, which needs `getPackageType`.
732
- // We split that up so that bundlers don’t fail.
733
-
734
-
735
- /**
736
- * @param {URL} url
737
- * @returns {PackageType}
738
- */
739
- function getPackageType(url) {
740
- const packageConfig = getPackageScopeConfig(url);
741
- return packageConfig.type
742
- }
743
-
744
- // Manually “tree shaken” from:
745
- // <https://github.com/nodejs/node/blob/3e74590/lib/internal/modules/esm/get_format.js>
746
- // Last checked on: Apr 24, 2023.
747
-
748
-
749
- const {ERR_UNKNOWN_FILE_EXTENSION} = codes;
750
-
751
- const hasOwnProperty = {}.hasOwnProperty;
752
-
753
- /** @type {Record<string, string>} */
754
- const extensionFormatMap = {
755
- // @ts-expect-error: hush.
756
- __proto__: null,
757
- '.cjs': 'commonjs',
758
- '.js': 'module',
759
- '.json': 'json',
760
- '.mjs': 'module'
761
- };
762
-
763
- /**
764
- * @param {string | null} mime
765
- * @returns {string | null}
766
- */
767
- function mimeToFormat(mime) {
768
- if (
769
- mime &&
770
- /\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(mime)
771
- )
772
- return 'module'
773
- if (mime === 'application/json') return 'json'
774
- return null
775
- }
776
-
777
- /**
778
- * @callback ProtocolHandler
779
- * @param {URL} parsed
780
- * @param {{parentURL: string}} context
781
- * @param {boolean} ignoreErrors
782
- * @returns {string | null | void}
783
- */
784
-
785
- /**
786
- * @type {Record<string, ProtocolHandler>}
787
- */
788
- const protocolHandlers = {
789
- // @ts-expect-error: hush.
790
- __proto__: null,
791
- 'data:': getDataProtocolModuleFormat,
792
- 'file:': getFileProtocolModuleFormat,
793
- 'http:': getHttpProtocolModuleFormat,
794
- 'https:': getHttpProtocolModuleFormat,
795
- 'node:'() {
796
- return 'builtin'
797
- }
798
- };
799
-
800
- /**
801
- * @param {URL} parsed
802
- */
803
- function getDataProtocolModuleFormat(parsed) {
804
- const {1: mime} = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(
805
- parsed.pathname
806
- ) || [null, null, null];
807
- return mimeToFormat(mime)
808
- }
809
-
810
- /**
811
- * Returns the file extension from a URL.
812
- *
813
- * Should give similar result to
814
- * `require('node:path').extname(require('node:url').fileURLToPath(url))`
815
- * when used with a `file:` URL.
816
- *
817
- * @param {URL} url
818
- * @returns {string}
819
- */
820
- function extname(url) {
821
- const pathname = url.pathname;
822
- let index = pathname.length;
823
-
824
- while (index--) {
825
- const code = pathname.codePointAt(index);
826
-
827
- if (code === 47 /* `/` */) {
828
- return ''
829
- }
830
-
831
- if (code === 46 /* `.` */) {
832
- return pathname.codePointAt(index - 1) === 47 /* `/` */
833
- ? ''
834
- : pathname.slice(index)
835
- }
836
- }
837
-
838
- return ''
839
- }
840
-
841
- /**
842
- * @type {ProtocolHandler}
843
- */
844
- function getFileProtocolModuleFormat(url, _context, ignoreErrors) {
845
- const ext = extname(url);
846
-
847
- if (ext === '.js') {
848
- return getPackageType(url) === 'module' ? 'module' : 'commonjs'
849
- }
850
-
851
- const format = extensionFormatMap[ext];
852
- if (format) return format
853
-
854
- // Explicit undefined return indicates load hook should rerun format check
855
- if (ignoreErrors) {
856
- return undefined
857
- }
858
-
859
- const filepath = fileURLToPath$1(url);
860
- throw new ERR_UNKNOWN_FILE_EXTENSION(ext, filepath)
861
- }
862
-
863
- function getHttpProtocolModuleFormat() {
864
- // To do: HTTPS imports.
865
- }
866
-
867
- /**
868
- * @param {URL} url
869
- * @param {{parentURL: string}} context
870
- * @returns {string | null}
871
- */
872
- function defaultGetFormatWithoutErrors(url, context) {
873
- if (!hasOwnProperty.call(protocolHandlers, url.protocol)) {
874
- return null
875
- }
876
-
877
- return protocolHandlers[url.protocol](url, context, true) || null
878
- }
879
-
880
- // Manually “tree shaken” from:
881
- // <https://github.com/nodejs/node/blob/3e74590/lib/internal/modules/esm/resolve.js>
882
- // Last checked on: Apr 24, 2023.
883
-
884
-
885
- const RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace];
886
-
887
- const {
888
- ERR_NETWORK_IMPORT_DISALLOWED,
889
- ERR_INVALID_MODULE_SPECIFIER,
890
- ERR_INVALID_PACKAGE_CONFIG,
891
- ERR_INVALID_PACKAGE_TARGET,
892
- ERR_MODULE_NOT_FOUND,
893
- ERR_PACKAGE_IMPORT_NOT_DEFINED,
894
- ERR_PACKAGE_PATH_NOT_EXPORTED,
895
- ERR_UNSUPPORTED_DIR_IMPORT,
896
- ERR_UNSUPPORTED_ESM_URL_SCHEME
897
- } = codes;
898
-
899
- const own = {}.hasOwnProperty;
900
-
901
- const invalidSegmentRegEx =
902
- /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i;
903
- const deprecatedInvalidSegmentRegEx =
904
- /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i;
905
- const invalidPackageNameRegEx = /^\.|%|\\/;
906
- const patternRegEx = /\*/g;
907
- const encodedSepRegEx = /%2f|%5c/i;
908
- /** @type {Set<string>} */
909
- const emittedPackageWarnings = new Set();
910
-
911
- const doubleSlashRegEx = /[/\\]{2}/;
912
-
913
- /**
914
- *
915
- * @param {string} target
916
- * @param {string} request
917
- * @param {string} match
918
- * @param {URL} packageJsonUrl
919
- * @param {boolean} internal
920
- * @param {URL} base
921
- * @param {boolean} isTarget
922
- */
923
- function emitInvalidSegmentDeprecation(
924
- target,
925
- request,
926
- match,
927
- packageJsonUrl,
928
- internal,
929
- base,
930
- isTarget
931
- ) {
932
- const pjsonPath = fileURLToPath$1(packageJsonUrl);
933
- const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null;
934
- process$1.emitWarning(
935
- `Use of deprecated ${
936
- double ? 'double slash' : 'leading or trailing slash matching'
937
- } resolving "${target}" for module ` +
938
- `request "${request}" ${
939
- request === match ? '' : `matched to "${match}" `
940
- }in the "${
941
- internal ? 'imports' : 'exports'
942
- }" field module resolution of the package at ${pjsonPath}${
943
- base ? ` imported from ${fileURLToPath$1(base)}` : ''
944
- }.`,
945
- 'DeprecationWarning',
946
- 'DEP0166'
947
- );
948
- }
949
-
950
- /**
951
- * @param {URL} url
952
- * @param {URL} packageJsonUrl
953
- * @param {URL} base
954
- * @param {unknown} [main]
955
- * @returns {void}
956
- */
957
- function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {
958
- const format = defaultGetFormatWithoutErrors(url, {parentURL: base.href});
959
- if (format !== 'module') return
960
- const path = fileURLToPath$1(url.href);
961
- const pkgPath = fileURLToPath$1(new URL$1('.', packageJsonUrl));
962
- const basePath = fileURLToPath$1(base);
963
- if (main)
964
- process$1.emitWarning(
965
- `Package ${pkgPath} has a "main" field set to ${JSON.stringify(main)}, ` +
966
- `excluding the full filename and extension to the resolved file at "${path.slice(
967
- pkgPath.length
968
- )}", imported from ${basePath}.\n Automatic extension resolution of the "main" field is` +
969
- 'deprecated for ES modules.',
970
- 'DeprecationWarning',
971
- 'DEP0151'
972
- );
973
- else
974
- process$1.emitWarning(
975
- `No "main" or "exports" field defined in the package.json for ${pkgPath} resolving the main entry point "${path.slice(
976
- pkgPath.length
977
- )}", imported from ${basePath}.\nDefault "index" lookups for the main are deprecated for ES modules.`,
978
- 'DeprecationWarning',
979
- 'DEP0151'
980
- );
981
- }
982
-
983
- /**
984
- * @param {string} path
985
- * @returns {Stats}
986
- */
987
- function tryStatSync(path) {
988
- // Note: from Node 15 onwards we can use `throwIfNoEntry: false` instead.
989
- try {
990
- return statSync(path)
991
- } catch {
992
- return new Stats()
993
- }
994
- }
995
-
996
- /**
997
- * Legacy CommonJS main resolution:
998
- * 1. let M = pkg_url + (json main field)
999
- * 2. TRY(M, M.js, M.json, M.node)
1000
- * 3. TRY(M/index.js, M/index.json, M/index.node)
1001
- * 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node)
1002
- * 5. NOT_FOUND
1003
- *
1004
- * @param {URL} url
1005
- * @returns {boolean}
1006
- */
1007
- function fileExists(url) {
1008
- const stats = statSync(url, {throwIfNoEntry: false});
1009
- const isFile = stats ? stats.isFile() : undefined;
1010
- return isFile === null || isFile === undefined ? false : isFile
1011
- }
1012
-
1013
- /**
1014
- * @param {URL} packageJsonUrl
1015
- * @param {PackageConfig} packageConfig
1016
- * @param {URL} base
1017
- * @returns {URL}
1018
- */
1019
- function legacyMainResolve(packageJsonUrl, packageConfig, base) {
1020
- /** @type {URL | undefined} */
1021
- let guess;
1022
- if (packageConfig.main !== undefined) {
1023
- guess = new URL$1(packageConfig.main, packageJsonUrl);
1024
- // Note: fs check redundances will be handled by Descriptor cache here.
1025
- if (fileExists(guess)) return guess
1026
-
1027
- const tries = [
1028
- `./${packageConfig.main}.js`,
1029
- `./${packageConfig.main}.json`,
1030
- `./${packageConfig.main}.node`,
1031
- `./${packageConfig.main}/index.js`,
1032
- `./${packageConfig.main}/index.json`,
1033
- `./${packageConfig.main}/index.node`
1034
- ];
1035
- let i = -1;
1036
-
1037
- while (++i < tries.length) {
1038
- guess = new URL$1(tries[i], packageJsonUrl);
1039
- if (fileExists(guess)) break
1040
- guess = undefined;
1041
- }
1042
-
1043
- if (guess) {
1044
- emitLegacyIndexDeprecation(
1045
- guess,
1046
- packageJsonUrl,
1047
- base,
1048
- packageConfig.main
1049
- );
1050
- return guess
1051
- }
1052
- // Fallthrough.
1053
- }
1054
-
1055
- const tries = ['./index.js', './index.json', './index.node'];
1056
- let i = -1;
1057
-
1058
- while (++i < tries.length) {
1059
- guess = new URL$1(tries[i], packageJsonUrl);
1060
- if (fileExists(guess)) break
1061
- guess = undefined;
1062
- }
1063
-
1064
- if (guess) {
1065
- emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
1066
- return guess
1067
- }
1068
-
1069
- // Not found.
1070
- throw new ERR_MODULE_NOT_FOUND(
1071
- fileURLToPath$1(new URL$1('.', packageJsonUrl)),
1072
- fileURLToPath$1(base)
1073
- )
1074
- }
1075
-
1076
- /**
1077
- * @param {URL} resolved
1078
- * @param {URL} base
1079
- * @param {boolean} [preserveSymlinks]
1080
- * @returns {URL}
1081
- */
1082
- function finalizeResolution(resolved, base, preserveSymlinks) {
1083
- if (encodedSepRegEx.exec(resolved.pathname) !== null)
1084
- throw new ERR_INVALID_MODULE_SPECIFIER(
1085
- resolved.pathname,
1086
- 'must not include encoded "/" or "\\" characters',
1087
- fileURLToPath$1(base)
1088
- )
1089
-
1090
- const filePath = fileURLToPath$1(resolved);
1091
-
1092
- const stats = tryStatSync(
1093
- filePath.endsWith('/') ? filePath.slice(-1) : filePath
1094
- );
1095
-
1096
- if (stats.isDirectory()) {
1097
- const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, fileURLToPath$1(base));
1098
- // @ts-expect-error Add this for `import.meta.resolve`.
1099
- error.url = String(resolved);
1100
- throw error
1101
- }
1102
-
1103
- if (!stats.isFile()) {
1104
- throw new ERR_MODULE_NOT_FOUND(
1105
- filePath || resolved.pathname,
1106
- base && fileURLToPath$1(base),
1107
- 'module'
1108
- )
1109
- }
1110
-
1111
- if (!preserveSymlinks) {
1112
- const real = realpathSync(filePath);
1113
- const {search, hash} = resolved;
1114
- resolved = pathToFileURL(real + (filePath.endsWith(path.sep) ? '/' : ''));
1115
- resolved.search = search;
1116
- resolved.hash = hash;
1117
- }
1118
-
1119
- return resolved
1120
- }
1121
-
1122
- /**
1123
- * @param {string} specifier
1124
- * @param {URL | undefined} packageJsonUrl
1125
- * @param {URL} base
1126
- * @returns {Error}
1127
- */
1128
- function importNotDefined(specifier, packageJsonUrl, base) {
1129
- return new ERR_PACKAGE_IMPORT_NOT_DEFINED(
1130
- specifier,
1131
- packageJsonUrl && fileURLToPath$1(new URL$1('.', packageJsonUrl)),
1132
- fileURLToPath$1(base)
1133
- )
1134
- }
1135
-
1136
- /**
1137
- * @param {string} subpath
1138
- * @param {URL} packageJsonUrl
1139
- * @param {URL} base
1140
- * @returns {Error}
1141
- */
1142
- function exportsNotFound(subpath, packageJsonUrl, base) {
1143
- return new ERR_PACKAGE_PATH_NOT_EXPORTED(
1144
- fileURLToPath$1(new URL$1('.', packageJsonUrl)),
1145
- subpath,
1146
- base && fileURLToPath$1(base)
1147
- )
1148
- }
1149
-
1150
- /**
1151
- * @param {string} request
1152
- * @param {string} match
1153
- * @param {URL} packageJsonUrl
1154
- * @param {boolean} internal
1155
- * @param {URL} [base]
1156
- * @returns {never}
1157
- */
1158
- function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
1159
- const reason = `request is not a valid match in pattern "${match}" for the "${
1160
- internal ? 'imports' : 'exports'
1161
- }" resolution of ${fileURLToPath$1(packageJsonUrl)}`;
1162
- throw new ERR_INVALID_MODULE_SPECIFIER(
1163
- request,
1164
- reason,
1165
- base && fileURLToPath$1(base)
1166
- )
1167
- }
1168
-
1169
- /**
1170
- * @param {string} subpath
1171
- * @param {unknown} target
1172
- * @param {URL} packageJsonUrl
1173
- * @param {boolean} internal
1174
- * @param {URL} [base]
1175
- * @returns {Error}
1176
- */
1177
- function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {
1178
- target =
1179
- typeof target === 'object' && target !== null
1180
- ? JSON.stringify(target, null, '')
1181
- : `${target}`;
1182
-
1183
- return new ERR_INVALID_PACKAGE_TARGET(
1184
- fileURLToPath$1(new URL$1('.', packageJsonUrl)),
1185
- subpath,
1186
- target,
1187
- internal,
1188
- base && fileURLToPath$1(base)
1189
- )
1190
- }
1191
-
1192
- /**
1193
- * @param {string} target
1194
- * @param {string} subpath
1195
- * @param {string} match
1196
- * @param {URL} packageJsonUrl
1197
- * @param {URL} base
1198
- * @param {boolean} pattern
1199
- * @param {boolean} internal
1200
- * @param {boolean} isPathMap
1201
- * @param {Set<string> | undefined} conditions
1202
- * @returns {URL}
1203
- */
1204
- function resolvePackageTargetString(
1205
- target,
1206
- subpath,
1207
- match,
1208
- packageJsonUrl,
1209
- base,
1210
- pattern,
1211
- internal,
1212
- isPathMap,
1213
- conditions
1214
- ) {
1215
- if (subpath !== '' && !pattern && target[target.length - 1] !== '/')
1216
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
1217
-
1218
- if (!target.startsWith('./')) {
1219
- if (internal && !target.startsWith('../') && !target.startsWith('/')) {
1220
- let isURL = false;
1221
-
1222
- try {
1223
- new URL$1(target);
1224
- isURL = true;
1225
- } catch {
1226
- // Continue regardless of error.
1227
- }
1228
-
1229
- if (!isURL) {
1230
- const exportTarget = pattern
1231
- ? RegExpPrototypeSymbolReplace.call(
1232
- patternRegEx,
1233
- target,
1234
- () => subpath
1235
- )
1236
- : target + subpath;
1237
-
1238
- return packageResolve(exportTarget, packageJsonUrl, conditions)
1239
- }
1240
- }
1241
-
1242
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
1243
- }
1244
-
1245
- if (invalidSegmentRegEx.exec(target.slice(2)) !== null) {
1246
- if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) {
1247
- if (!isPathMap) {
1248
- const request = pattern
1249
- ? match.replace('*', () => subpath)
1250
- : match + subpath;
1251
- const resolvedTarget = pattern
1252
- ? RegExpPrototypeSymbolReplace.call(
1253
- patternRegEx,
1254
- target,
1255
- () => subpath
1256
- )
1257
- : target;
1258
- emitInvalidSegmentDeprecation(
1259
- resolvedTarget,
1260
- request,
1261
- match,
1262
- packageJsonUrl,
1263
- internal,
1264
- base,
1265
- true
1266
- );
1267
- }
1268
- } else {
1269
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
1270
- }
1271
- }
1272
-
1273
- const resolved = new URL$1(target, packageJsonUrl);
1274
- const resolvedPath = resolved.pathname;
1275
- const packagePath = new URL$1('.', packageJsonUrl).pathname;
1276
-
1277
- if (!resolvedPath.startsWith(packagePath))
1278
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
1279
-
1280
- if (subpath === '') return resolved
1281
-
1282
- if (invalidSegmentRegEx.exec(subpath) !== null) {
1283
- const request = pattern
1284
- ? match.replace('*', () => subpath)
1285
- : match + subpath;
1286
- if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) {
1287
- if (!isPathMap) {
1288
- const resolvedTarget = pattern
1289
- ? RegExpPrototypeSymbolReplace.call(
1290
- patternRegEx,
1291
- target,
1292
- () => subpath
1293
- )
1294
- : target;
1295
- emitInvalidSegmentDeprecation(
1296
- resolvedTarget,
1297
- request,
1298
- match,
1299
- packageJsonUrl,
1300
- internal,
1301
- base,
1302
- false
1303
- );
1304
- }
1305
- } else {
1306
- throwInvalidSubpath(request, match, packageJsonUrl, internal, base);
1307
- }
1308
- }
1309
-
1310
- if (pattern) {
1311
- return new URL$1(
1312
- RegExpPrototypeSymbolReplace.call(
1313
- patternRegEx,
1314
- resolved.href,
1315
- () => subpath
1316
- )
1317
- )
1318
- }
1319
-
1320
- return new URL$1(subpath, resolved)
1321
- }
1322
-
1323
- /**
1324
- * @param {string} key
1325
- * @returns {boolean}
1326
- */
1327
- function isArrayIndex(key) {
1328
- const keyNumber = Number(key);
1329
- if (`${keyNumber}` !== key) return false
1330
- return keyNumber >= 0 && keyNumber < 0xff_ff_ff_ff
1331
- }
1332
-
1333
- /**
1334
- * @param {URL} packageJsonUrl
1335
- * @param {unknown} target
1336
- * @param {string} subpath
1337
- * @param {string} packageSubpath
1338
- * @param {URL} base
1339
- * @param {boolean} pattern
1340
- * @param {boolean} internal
1341
- * @param {boolean} isPathMap
1342
- * @param {Set<string> | undefined} conditions
1343
- * @returns {URL | null}
1344
- */
1345
- function resolvePackageTarget(
1346
- packageJsonUrl,
1347
- target,
1348
- subpath,
1349
- packageSubpath,
1350
- base,
1351
- pattern,
1352
- internal,
1353
- isPathMap,
1354
- conditions
1355
- ) {
1356
- if (typeof target === 'string') {
1357
- return resolvePackageTargetString(
1358
- target,
1359
- subpath,
1360
- packageSubpath,
1361
- packageJsonUrl,
1362
- base,
1363
- pattern,
1364
- internal,
1365
- isPathMap,
1366
- conditions
1367
- )
1368
- }
1369
-
1370
- if (Array.isArray(target)) {
1371
- /** @type {Array<unknown>} */
1372
- const targetList = target;
1373
- if (targetList.length === 0) return null
1374
-
1375
- /** @type {ErrnoException | null | undefined} */
1376
- let lastException;
1377
- let i = -1;
1378
-
1379
- while (++i < targetList.length) {
1380
- const targetItem = targetList[i];
1381
- /** @type {URL | null} */
1382
- let resolveResult;
1383
- try {
1384
- resolveResult = resolvePackageTarget(
1385
- packageJsonUrl,
1386
- targetItem,
1387
- subpath,
1388
- packageSubpath,
1389
- base,
1390
- pattern,
1391
- internal,
1392
- isPathMap,
1393
- conditions
1394
- );
1395
- } catch (error) {
1396
- const exception = /** @type {ErrnoException} */ (error);
1397
- lastException = exception;
1398
- if (exception.code === 'ERR_INVALID_PACKAGE_TARGET') continue
1399
- throw error
1400
- }
1401
-
1402
- if (resolveResult === undefined) continue
1403
-
1404
- if (resolveResult === null) {
1405
- lastException = null;
1406
- continue
1407
- }
1408
-
1409
- return resolveResult
1410
- }
1411
-
1412
- if (lastException === undefined || lastException === null) {
1413
- return null
1414
- }
1415
-
1416
- throw lastException
1417
- }
1418
-
1419
- if (typeof target === 'object' && target !== null) {
1420
- const keys = Object.getOwnPropertyNames(target);
1421
- let i = -1;
1422
-
1423
- while (++i < keys.length) {
1424
- const key = keys[i];
1425
- if (isArrayIndex(key)) {
1426
- throw new ERR_INVALID_PACKAGE_CONFIG(
1427
- fileURLToPath$1(packageJsonUrl),
1428
- base,
1429
- '"exports" cannot contain numeric property keys.'
1430
- )
1431
- }
1432
- }
1433
-
1434
- i = -1;
1435
-
1436
- while (++i < keys.length) {
1437
- const key = keys[i];
1438
- if (key === 'default' || (conditions && conditions.has(key))) {
1439
- // @ts-expect-error: indexable.
1440
- const conditionalTarget = /** @type {unknown} */ (target[key]);
1441
- const resolveResult = resolvePackageTarget(
1442
- packageJsonUrl,
1443
- conditionalTarget,
1444
- subpath,
1445
- packageSubpath,
1446
- base,
1447
- pattern,
1448
- internal,
1449
- isPathMap,
1450
- conditions
1451
- );
1452
- if (resolveResult === undefined) continue
1453
- return resolveResult
1454
- }
1455
- }
1456
-
1457
- return null
1458
- }
1459
-
1460
- if (target === null) {
1461
- return null
1462
- }
1463
-
1464
- throw invalidPackageTarget(
1465
- packageSubpath,
1466
- target,
1467
- packageJsonUrl,
1468
- internal,
1469
- base
1470
- )
1471
- }
1472
-
1473
- /**
1474
- * @param {unknown} exports
1475
- * @param {URL} packageJsonUrl
1476
- * @param {URL} base
1477
- * @returns {boolean}
1478
- */
1479
- function isConditionalExportsMainSugar(exports, packageJsonUrl, base) {
1480
- if (typeof exports === 'string' || Array.isArray(exports)) return true
1481
- if (typeof exports !== 'object' || exports === null) return false
1482
-
1483
- const keys = Object.getOwnPropertyNames(exports);
1484
- let isConditionalSugar = false;
1485
- let i = 0;
1486
- let j = -1;
1487
- while (++j < keys.length) {
1488
- const key = keys[j];
1489
- const curIsConditionalSugar = key === '' || key[0] !== '.';
1490
- if (i++ === 0) {
1491
- isConditionalSugar = curIsConditionalSugar;
1492
- } else if (isConditionalSugar !== curIsConditionalSugar) {
1493
- throw new ERR_INVALID_PACKAGE_CONFIG(
1494
- fileURLToPath$1(packageJsonUrl),
1495
- base,
1496
- '"exports" cannot contain some keys starting with \'.\' and some not.' +
1497
- ' The exports object must either be an object of package subpath keys' +
1498
- ' or an object of main entry condition name keys only.'
1499
- )
1500
- }
1501
- }
1502
-
1503
- return isConditionalSugar
1504
- }
1505
-
1506
- /**
1507
- * @param {string} match
1508
- * @param {URL} pjsonUrl
1509
- * @param {URL} base
1510
- */
1511
- function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
1512
- const pjsonPath = fileURLToPath$1(pjsonUrl);
1513
- if (emittedPackageWarnings.has(pjsonPath + '|' + match)) return
1514
- emittedPackageWarnings.add(pjsonPath + '|' + match);
1515
- process$1.emitWarning(
1516
- `Use of deprecated trailing slash pattern mapping "${match}" in the ` +
1517
- `"exports" field module resolution of the package at ${pjsonPath}${
1518
- base ? ` imported from ${fileURLToPath$1(base)}` : ''
1519
- }. Mapping specifiers ending in "/" is no longer supported.`,
1520
- 'DeprecationWarning',
1521
- 'DEP0155'
1522
- );
1523
- }
1524
-
1525
- /**
1526
- * @param {URL} packageJsonUrl
1527
- * @param {string} packageSubpath
1528
- * @param {Record<string, unknown>} packageConfig
1529
- * @param {URL} base
1530
- * @param {Set<string> | undefined} conditions
1531
- * @returns {URL}
1532
- */
1533
- function packageExportsResolve(
1534
- packageJsonUrl,
1535
- packageSubpath,
1536
- packageConfig,
1537
- base,
1538
- conditions
1539
- ) {
1540
- let exports = packageConfig.exports;
1541
-
1542
- if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) {
1543
- exports = {'.': exports};
1544
- }
1545
-
1546
- if (
1547
- own.call(exports, packageSubpath) &&
1548
- !packageSubpath.includes('*') &&
1549
- !packageSubpath.endsWith('/')
1550
- ) {
1551
- // @ts-expect-error: indexable.
1552
- const target = exports[packageSubpath];
1553
- const resolveResult = resolvePackageTarget(
1554
- packageJsonUrl,
1555
- target,
1556
- '',
1557
- packageSubpath,
1558
- base,
1559
- false,
1560
- false,
1561
- false,
1562
- conditions
1563
- );
1564
- if (resolveResult === null || resolveResult === undefined) {
1565
- throw exportsNotFound(packageSubpath, packageJsonUrl, base)
1566
- }
1567
-
1568
- return resolveResult
1569
- }
1570
-
1571
- let bestMatch = '';
1572
- let bestMatchSubpath = '';
1573
- const keys = Object.getOwnPropertyNames(exports);
1574
- let i = -1;
1575
-
1576
- while (++i < keys.length) {
1577
- const key = keys[i];
1578
- const patternIndex = key.indexOf('*');
1579
-
1580
- if (
1581
- patternIndex !== -1 &&
1582
- packageSubpath.startsWith(key.slice(0, patternIndex))
1583
- ) {
1584
- // When this reaches EOL, this can throw at the top of the whole function:
1585
- //
1586
- // if (StringPrototypeEndsWith(packageSubpath, '/'))
1587
- // throwInvalidSubpath(packageSubpath)
1588
- //
1589
- // To match "imports" and the spec.
1590
- if (packageSubpath.endsWith('/')) {
1591
- emitTrailingSlashPatternDeprecation(
1592
- packageSubpath,
1593
- packageJsonUrl,
1594
- base
1595
- );
1596
- }
1597
-
1598
- const patternTrailer = key.slice(patternIndex + 1);
1599
-
1600
- if (
1601
- packageSubpath.length >= key.length &&
1602
- packageSubpath.endsWith(patternTrailer) &&
1603
- patternKeyCompare(bestMatch, key) === 1 &&
1604
- key.lastIndexOf('*') === patternIndex
1605
- ) {
1606
- bestMatch = key;
1607
- bestMatchSubpath = packageSubpath.slice(
1608
- patternIndex,
1609
- packageSubpath.length - patternTrailer.length
1610
- );
1611
- }
1612
- }
1613
- }
1614
-
1615
- if (bestMatch) {
1616
- // @ts-expect-error: indexable.
1617
- const target = /** @type {unknown} */ (exports[bestMatch]);
1618
- const resolveResult = resolvePackageTarget(
1619
- packageJsonUrl,
1620
- target,
1621
- bestMatchSubpath,
1622
- bestMatch,
1623
- base,
1624
- true,
1625
- false,
1626
- packageSubpath.endsWith('/'),
1627
- conditions
1628
- );
1629
-
1630
- if (resolveResult === null || resolveResult === undefined) {
1631
- throw exportsNotFound(packageSubpath, packageJsonUrl, base)
1632
- }
1633
-
1634
- return resolveResult
1635
- }
1636
-
1637
- throw exportsNotFound(packageSubpath, packageJsonUrl, base)
1638
- }
1639
-
1640
- /**
1641
- * @param {string} a
1642
- * @param {string} b
1643
- */
1644
- function patternKeyCompare(a, b) {
1645
- const aPatternIndex = a.indexOf('*');
1646
- const bPatternIndex = b.indexOf('*');
1647
- const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
1648
- const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
1649
- if (baseLengthA > baseLengthB) return -1
1650
- if (baseLengthB > baseLengthA) return 1
1651
- if (aPatternIndex === -1) return 1
1652
- if (bPatternIndex === -1) return -1
1653
- if (a.length > b.length) return -1
1654
- if (b.length > a.length) return 1
1655
- return 0
1656
- }
1657
-
1658
- /**
1659
- * @param {string} name
1660
- * @param {URL} base
1661
- * @param {Set<string>} [conditions]
1662
- * @returns {URL}
1663
- */
1664
- function packageImportsResolve(name, base, conditions) {
1665
- if (name === '#' || name.startsWith('#/') || name.endsWith('/')) {
1666
- const reason = 'is not a valid internal imports specifier name';
1667
- throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, fileURLToPath$1(base))
1668
- }
1669
-
1670
- /** @type {URL | undefined} */
1671
- let packageJsonUrl;
1672
-
1673
- const packageConfig = getPackageScopeConfig(base);
1674
-
1675
- if (packageConfig.exists) {
1676
- packageJsonUrl = pathToFileURL(packageConfig.pjsonPath);
1677
- const imports = packageConfig.imports;
1678
- if (imports) {
1679
- if (own.call(imports, name) && !name.includes('*')) {
1680
- const resolveResult = resolvePackageTarget(
1681
- packageJsonUrl,
1682
- imports[name],
1683
- '',
1684
- name,
1685
- base,
1686
- false,
1687
- true,
1688
- false,
1689
- conditions
1690
- );
1691
- if (resolveResult !== null && resolveResult !== undefined) {
1692
- return resolveResult
1693
- }
1694
- } else {
1695
- let bestMatch = '';
1696
- let bestMatchSubpath = '';
1697
- const keys = Object.getOwnPropertyNames(imports);
1698
- let i = -1;
1699
-
1700
- while (++i < keys.length) {
1701
- const key = keys[i];
1702
- const patternIndex = key.indexOf('*');
1703
-
1704
- if (patternIndex !== -1 && name.startsWith(key.slice(0, -1))) {
1705
- const patternTrailer = key.slice(patternIndex + 1);
1706
- if (
1707
- name.length >= key.length &&
1708
- name.endsWith(patternTrailer) &&
1709
- patternKeyCompare(bestMatch, key) === 1 &&
1710
- key.lastIndexOf('*') === patternIndex
1711
- ) {
1712
- bestMatch = key;
1713
- bestMatchSubpath = name.slice(
1714
- patternIndex,
1715
- name.length - patternTrailer.length
1716
- );
1717
- }
1718
- }
1719
- }
1720
-
1721
- if (bestMatch) {
1722
- const target = imports[bestMatch];
1723
- const resolveResult = resolvePackageTarget(
1724
- packageJsonUrl,
1725
- target,
1726
- bestMatchSubpath,
1727
- bestMatch,
1728
- base,
1729
- true,
1730
- true,
1731
- false,
1732
- conditions
1733
- );
1734
-
1735
- if (resolveResult !== null && resolveResult !== undefined) {
1736
- return resolveResult
1737
- }
1738
- }
1739
- }
1740
- }
1741
- }
1742
-
1743
- throw importNotDefined(name, packageJsonUrl, base)
1744
- }
1745
-
1746
- // Note: In Node.js, `getPackageType` is here.
1747
- // To prevent a circular dependency, we move it to
1748
- // `resolve-get-package-type.js`.
1749
-
1750
- /**
1751
- * @param {string} specifier
1752
- * @param {URL} base
1753
- */
1754
- function parsePackageName(specifier, base) {
1755
- let separatorIndex = specifier.indexOf('/');
1756
- let validPackageName = true;
1757
- let isScoped = false;
1758
- if (specifier[0] === '@') {
1759
- isScoped = true;
1760
- if (separatorIndex === -1 || specifier.length === 0) {
1761
- validPackageName = false;
1762
- } else {
1763
- separatorIndex = specifier.indexOf('/', separatorIndex + 1);
1764
- }
1765
- }
1766
-
1767
- const packageName =
1768
- separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
1769
-
1770
- // Package name cannot have leading . and cannot have percent-encoding or
1771
- // \\ separators.
1772
- if (invalidPackageNameRegEx.exec(packageName) !== null) {
1773
- validPackageName = false;
1774
- }
1775
-
1776
- if (!validPackageName) {
1777
- throw new ERR_INVALID_MODULE_SPECIFIER(
1778
- specifier,
1779
- 'is not a valid package name',
1780
- fileURLToPath$1(base)
1781
- )
1782
- }
1783
-
1784
- const packageSubpath =
1785
- '.' + (separatorIndex === -1 ? '' : specifier.slice(separatorIndex));
1786
-
1787
- return {packageName, packageSubpath, isScoped}
1788
- }
1789
-
1790
- /**
1791
- * @param {string} specifier
1792
- * @param {URL} base
1793
- * @param {Set<string> | undefined} conditions
1794
- * @returns {URL}
1795
- */
1796
- function packageResolve(specifier, base, conditions) {
1797
- if (builtinModules.includes(specifier)) {
1798
- return new URL$1('node:' + specifier)
1799
- }
1800
-
1801
- const {packageName, packageSubpath, isScoped} = parsePackageName(
1802
- specifier,
1803
- base
1804
- );
1805
-
1806
- // ResolveSelf
1807
- const packageConfig = getPackageScopeConfig(base);
1808
-
1809
- // Can’t test.
1810
- /* c8 ignore next 16 */
1811
- if (packageConfig.exists) {
1812
- const packageJsonUrl = pathToFileURL(packageConfig.pjsonPath);
1813
- if (
1814
- packageConfig.name === packageName &&
1815
- packageConfig.exports !== undefined &&
1816
- packageConfig.exports !== null
1817
- ) {
1818
- return packageExportsResolve(
1819
- packageJsonUrl,
1820
- packageSubpath,
1821
- packageConfig,
1822
- base,
1823
- conditions
1824
- )
1825
- }
1826
- }
1827
-
1828
- let packageJsonUrl = new URL$1(
1829
- './node_modules/' + packageName + '/package.json',
1830
- base
1831
- );
1832
- let packageJsonPath = fileURLToPath$1(packageJsonUrl);
1833
- /** @type {string} */
1834
- let lastPath;
1835
- do {
1836
- const stat = tryStatSync(packageJsonPath.slice(0, -13));
1837
- if (!stat.isDirectory()) {
1838
- lastPath = packageJsonPath;
1839
- packageJsonUrl = new URL$1(
1840
- (isScoped ? '../../../../node_modules/' : '../../../node_modules/') +
1841
- packageName +
1842
- '/package.json',
1843
- packageJsonUrl
1844
- );
1845
- packageJsonPath = fileURLToPath$1(packageJsonUrl);
1846
- continue
1847
- }
1848
-
1849
- // Package match.
1850
- const packageConfig = getPackageConfig(packageJsonPath, specifier, base);
1851
- if (packageConfig.exports !== undefined && packageConfig.exports !== null) {
1852
- return packageExportsResolve(
1853
- packageJsonUrl,
1854
- packageSubpath,
1855
- packageConfig,
1856
- base,
1857
- conditions
1858
- )
1859
- }
1860
-
1861
- if (packageSubpath === '.') {
1862
- return legacyMainResolve(packageJsonUrl, packageConfig, base)
1863
- }
1864
-
1865
- return new URL$1(packageSubpath, packageJsonUrl)
1866
- // Cross-platform root check.
1867
- } while (packageJsonPath.length !== lastPath.length)
1868
-
1869
- throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath$1(base))
1870
- }
1871
-
1872
- /**
1873
- * @param {string} specifier
1874
- * @returns {boolean}
1875
- */
1876
- function isRelativeSpecifier(specifier) {
1877
- if (specifier[0] === '.') {
1878
- if (specifier.length === 1 || specifier[1] === '/') return true
1879
- if (
1880
- specifier[1] === '.' &&
1881
- (specifier.length === 2 || specifier[2] === '/')
1882
- ) {
1883
- return true
1884
- }
1885
- }
1886
-
1887
- return false
1888
- }
1889
-
1890
- /**
1891
- * @param {string} specifier
1892
- * @returns {boolean}
1893
- */
1894
- function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
1895
- if (specifier === '') return false
1896
- if (specifier[0] === '/') return true
1897
- return isRelativeSpecifier(specifier)
1898
- }
1899
-
1900
- /**
1901
- * The “Resolver Algorithm Specification” as detailed in the Node docs (which is
1902
- * sync and slightly lower-level than `resolve`).
1903
- *
1904
- * @param {string} specifier
1905
- * `/example.js`, `./example.js`, `../example.js`, `some-package`, `fs`, etc.
1906
- * @param {URL} base
1907
- * Full URL (to a file) that `specifier` is resolved relative from.
1908
- * @param {Set<string>} [conditions]
1909
- * Conditions.
1910
- * @param {boolean} [preserveSymlinks]
1911
- * Keep symlinks instead of resolving them.
1912
- * @returns {URL}
1913
- * A URL object to the found thing.
1914
- */
1915
- function moduleResolve(specifier, base, conditions, preserveSymlinks) {
1916
- const protocol = base.protocol;
1917
- const isRemote = protocol === 'http:' || protocol === 'https:';
1918
- // Order swapped from spec for minor perf gain.
1919
- // Ok since relative URLs cannot parse as URLs.
1920
- /** @type {URL | undefined} */
1921
- let resolved;
1922
-
1923
- if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
1924
- resolved = new URL$1(specifier, base);
1925
- } else if (!isRemote && specifier[0] === '#') {
1926
- resolved = packageImportsResolve(specifier, base, conditions);
1927
- } else {
1928
- try {
1929
- resolved = new URL$1(specifier);
1930
- } catch {
1931
- if (!isRemote) {
1932
- resolved = packageResolve(specifier, base, conditions);
1933
- }
1934
- }
1935
- }
1936
-
1937
- assert(resolved !== undefined, 'expected to be defined');
1938
-
1939
- if (resolved.protocol !== 'file:') {
1940
- return resolved
1941
- }
1942
-
1943
- return finalizeResolution(resolved, base, preserveSymlinks)
1944
- }
1945
-
1946
- function fileURLToPath(id) {
1947
- if (typeof id === "string" && !id.startsWith("file://")) {
1948
- return normalizeSlash(id);
1949
- }
1950
- return normalizeSlash(fileURLToPath$1(id));
1951
- }
1952
- function normalizeid(id) {
1953
- if (typeof id !== "string") {
1954
- id = id.toString();
1955
- }
1956
- if (/(node|data|http|https|file):/.test(id)) {
1957
- return id;
1958
- }
1959
- if (BUILTIN_MODULES.has(id)) {
1960
- return "node:" + id;
1961
- }
1962
- return "file://" + encodeURI(normalizeSlash(id));
1963
- }
1964
-
1965
- const DEFAULT_CONDITIONS_SET = /* @__PURE__ */ new Set(["node", "import"]);
1966
- const DEFAULT_URL = pathToFileURL(process.cwd());
1967
- const DEFAULT_EXTENSIONS = [".mjs", ".cjs", ".js", ".json"];
1968
- const NOT_FOUND_ERRORS = /* @__PURE__ */ new Set([
1969
- "ERR_MODULE_NOT_FOUND",
1970
- "ERR_UNSUPPORTED_DIR_IMPORT",
1971
- "MODULE_NOT_FOUND",
1972
- "ERR_PACKAGE_PATH_NOT_EXPORTED"
1973
- ]);
1974
- function _tryModuleResolve(id, url, conditions) {
1975
- try {
1976
- return moduleResolve(id, url, conditions);
1977
- } catch (error) {
1978
- if (!NOT_FOUND_ERRORS.has(error.code)) {
1979
- throw error;
1980
- }
1981
- }
1982
- }
1983
- function _resolve(id, options = {}) {
1984
- if (/(node|data|http|https):/.test(id)) {
1985
- return id;
1986
- }
1987
- if (BUILTIN_MODULES.has(id)) {
1988
- return "node:" + id;
1989
- }
1990
- if (isAbsolute(id) && existsSync(id)) {
1991
- const realPath2 = realpathSync(fileURLToPath(id));
1992
- return pathToFileURL(realPath2).toString();
1993
- }
1994
- const conditionsSet = options.conditions ? new Set(options.conditions) : DEFAULT_CONDITIONS_SET;
1995
- const _urls = (Array.isArray(options.url) ? options.url : [options.url]).filter(Boolean).map((u) => new URL(normalizeid(u.toString())));
1996
- if (_urls.length === 0) {
1997
- _urls.push(DEFAULT_URL);
1998
- }
1999
- const urls = [..._urls];
2000
- for (const url of _urls) {
2001
- if (url.protocol === "file:") {
2002
- urls.push(
2003
- new URL("./", url),
2004
- // If url is directory
2005
- new URL(joinURL(url.pathname, "_index.js"), url),
2006
- // TODO: Remove in next major version?
2007
- new URL("node_modules", url)
2008
- );
2009
- }
2010
- }
2011
- let resolved;
2012
- for (const url of urls) {
2013
- resolved = _tryModuleResolve(id, url, conditionsSet);
2014
- if (resolved) {
2015
- break;
2016
- }
2017
- for (const prefix of ["", "/index"]) {
2018
- for (const extension of options.extensions || DEFAULT_EXTENSIONS) {
2019
- resolved = _tryModuleResolve(
2020
- id + prefix + extension,
2021
- url,
2022
- conditionsSet
2023
- );
2024
- if (resolved) {
2025
- break;
2026
- }
2027
- }
2028
- if (resolved) {
2029
- break;
2030
- }
2031
- }
2032
- if (resolved) {
2033
- break;
2034
- }
2035
- }
2036
- if (!resolved) {
2037
- const error = new Error(
2038
- `Cannot find module ${id} imported from ${urls.join(", ")}`
2039
- );
2040
- error.code = "ERR_MODULE_NOT_FOUND";
2041
- throw error;
2042
- }
2043
- const realPath = realpathSync(fileURLToPath(resolved));
2044
- return pathToFileURL(realPath).toString();
2045
- }
2046
- function resolveSync(id, options) {
2047
- return _resolve(id, options);
2048
- }
2049
- function resolvePathSync(id, options) {
2050
- return fileURLToPath(resolveSync(id, options));
2051
- }
2052
- function resolvePath(id, options) {
2053
- return pcall(resolvePathSync, id, options);
2054
- }
2055
-
2056
- function isBuiltinEnvironment(env) {
2057
- return env in environments;
2058
- }
2059
- const _loaders = /* @__PURE__ */ new Map();
2060
- async function createEnvironmentLoader(options) {
2061
- if (!_loaders.has(options.root)) {
2062
- const loader = new ViteNodeRunner(options);
2063
- await loader.executeId("/@vite/env");
2064
- _loaders.set(options.root, loader);
2065
- }
2066
- return _loaders.get(options.root);
2067
- }
2068
- async function loadEnvironment(name, options) {
2069
- if (isBuiltinEnvironment(name))
2070
- return environments[name];
2071
- const loader = await createEnvironmentLoader(options);
2072
- const root = loader.root;
2073
- const packageId = name[0] === "." || name[0] === "/" ? resolve(root, name) : await resolvePath(`vitest-environment-${name}`, { url: [root] }) ?? resolve(root, name);
2074
- const pkg = await loader.executeId(normalize(packageId));
2075
- if (!pkg || !pkg.default || typeof pkg.default !== "object") {
2076
- throw new TypeError(
2077
- `Environment "${name}" is not a valid environment. Path "${packageId}" should export default object with a "setup" or/and "setupVM" method.`
2078
- );
2079
- }
2080
- const environment = pkg.default;
2081
- if (environment.transformMode !== "web" && environment.transformMode !== "ssr") {
2082
- throw new TypeError(
2083
- `Environment "${name}" is not a valid environment. Path "${packageId}" should export default object with a "transformMode" method equal to "ssr" or "web".`
2084
- );
2085
- }
2086
- return environment;
2087
- }
2088
-
2089
- export { loadEnvironment as l };