vitest 0.34.0 → 0.34.2

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