mollenhauer

Форк
0
/
.pnp.loader.mjs 
2090 строк · 69.2 Кб
1
import fs from 'fs';
2
import { URL as URL$1, fileURLToPath, pathToFileURL } from 'url';
3
import path from 'path';
4
import { createHash } from 'crypto';
5
import { EOL } from 'os';
6
import moduleExports, { isBuiltin } from 'module';
7
import assert from 'assert';
8

9
const SAFE_TIME = 456789e3;
10

11
const PortablePath = {
12
  root: `/`,
13
  dot: `.`,
14
  parent: `..`
15
};
16
const npath = Object.create(path);
17
const ppath = Object.create(path.posix);
18
npath.cwd = () => process.cwd();
19
ppath.cwd = process.platform === `win32` ? () => toPortablePath(process.cwd()) : process.cwd;
20
if (process.platform === `win32`) {
21
  ppath.resolve = (...segments) => {
22
    if (segments.length > 0 && ppath.isAbsolute(segments[0])) {
23
      return path.posix.resolve(...segments);
24
    } else {
25
      return path.posix.resolve(ppath.cwd(), ...segments);
26
    }
27
  };
28
}
29
const contains = function(pathUtils, from, to) {
30
  from = pathUtils.normalize(from);
31
  to = pathUtils.normalize(to);
32
  if (from === to)
33
    return `.`;
34
  if (!from.endsWith(pathUtils.sep))
35
    from = from + pathUtils.sep;
36
  if (to.startsWith(from)) {
37
    return to.slice(from.length);
38
  } else {
39
    return null;
40
  }
41
};
42
npath.contains = (from, to) => contains(npath, from, to);
43
ppath.contains = (from, to) => contains(ppath, from, to);
44
const WINDOWS_PATH_REGEXP = /^([a-zA-Z]:.*)$/;
45
const UNC_WINDOWS_PATH_REGEXP = /^\/\/(\.\/)?(.*)$/;
46
const PORTABLE_PATH_REGEXP = /^\/([a-zA-Z]:.*)$/;
47
const UNC_PORTABLE_PATH_REGEXP = /^\/unc\/(\.dot\/)?(.*)$/;
48
function fromPortablePathWin32(p) {
49
  let portablePathMatch, uncPortablePathMatch;
50
  if (portablePathMatch = p.match(PORTABLE_PATH_REGEXP))
51
    p = portablePathMatch[1];
52
  else if (uncPortablePathMatch = p.match(UNC_PORTABLE_PATH_REGEXP))
53
    p = `\\\\${uncPortablePathMatch[1] ? `.\\` : ``}${uncPortablePathMatch[2]}`;
54
  else
55
    return p;
56
  return p.replace(/\//g, `\\`);
57
}
58
function toPortablePathWin32(p) {
59
  p = p.replace(/\\/g, `/`);
60
  let windowsPathMatch, uncWindowsPathMatch;
61
  if (windowsPathMatch = p.match(WINDOWS_PATH_REGEXP))
62
    p = `/${windowsPathMatch[1]}`;
63
  else if (uncWindowsPathMatch = p.match(UNC_WINDOWS_PATH_REGEXP))
64
    p = `/unc/${uncWindowsPathMatch[1] ? `.dot/` : ``}${uncWindowsPathMatch[2]}`;
65
  return p;
66
}
67
const toPortablePath = process.platform === `win32` ? toPortablePathWin32 : (p) => p;
68
const fromPortablePath = process.platform === `win32` ? fromPortablePathWin32 : (p) => p;
69
npath.fromPortablePath = fromPortablePath;
70
npath.toPortablePath = toPortablePath;
71
function convertPath(targetPathUtils, sourcePath) {
72
  return targetPathUtils === npath ? fromPortablePath(sourcePath) : toPortablePath(sourcePath);
73
}
74

75
const defaultTime = new Date(SAFE_TIME * 1e3);
76
const defaultTimeMs = defaultTime.getTime();
77
async function copyPromise(destinationFs, destination, sourceFs, source, opts) {
78
  const normalizedDestination = destinationFs.pathUtils.normalize(destination);
79
  const normalizedSource = sourceFs.pathUtils.normalize(source);
80
  const prelayout = [];
81
  const postlayout = [];
82
  const { atime, mtime } = opts.stableTime ? { atime: defaultTime, mtime: defaultTime } : await sourceFs.lstatPromise(normalizedSource);
83
  await destinationFs.mkdirpPromise(destinationFs.pathUtils.dirname(destination), { utimes: [atime, mtime] });
84
  await copyImpl(prelayout, postlayout, destinationFs, normalizedDestination, sourceFs, normalizedSource, { ...opts, didParentExist: true });
85
  for (const operation of prelayout)
86
    await operation();
87
  await Promise.all(postlayout.map((operation) => {
88
    return operation();
89
  }));
90
}
91
async function copyImpl(prelayout, postlayout, destinationFs, destination, sourceFs, source, opts) {
92
  const destinationStat = opts.didParentExist ? await maybeLStat(destinationFs, destination) : null;
93
  const sourceStat = await sourceFs.lstatPromise(source);
94
  const { atime, mtime } = opts.stableTime ? { atime: defaultTime, mtime: defaultTime } : sourceStat;
95
  let updated;
96
  switch (true) {
97
    case sourceStat.isDirectory():
98
      {
99
        updated = await copyFolder(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts);
100
      }
101
      break;
102
    case sourceStat.isFile():
103
      {
104
        updated = await copyFile(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts);
105
      }
106
      break;
107
    case sourceStat.isSymbolicLink():
108
      {
109
        updated = await copySymlink(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts);
110
      }
111
      break;
112
    default:
113
      {
114
        throw new Error(`Unsupported file type (${sourceStat.mode})`);
115
      }
116
  }
117
  if (opts.linkStrategy?.type !== `HardlinkFromIndex` || !sourceStat.isFile()) {
118
    if (updated || destinationStat?.mtime?.getTime() !== mtime.getTime() || destinationStat?.atime?.getTime() !== atime.getTime()) {
119
      postlayout.push(() => destinationFs.lutimesPromise(destination, atime, mtime));
120
      updated = true;
121
    }
122
    if (destinationStat === null || (destinationStat.mode & 511) !== (sourceStat.mode & 511)) {
123
      postlayout.push(() => destinationFs.chmodPromise(destination, sourceStat.mode & 511));
124
      updated = true;
125
    }
126
  }
127
  return updated;
128
}
129
async function maybeLStat(baseFs, p) {
130
  try {
131
    return await baseFs.lstatPromise(p);
132
  } catch (e) {
133
    return null;
134
  }
135
}
136
async function copyFolder(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts) {
137
  if (destinationStat !== null && !destinationStat.isDirectory()) {
138
    if (opts.overwrite) {
139
      prelayout.push(async () => destinationFs.removePromise(destination));
140
      destinationStat = null;
141
    } else {
142
      return false;
143
    }
144
  }
145
  let updated = false;
146
  if (destinationStat === null) {
147
    prelayout.push(async () => {
148
      try {
149
        await destinationFs.mkdirPromise(destination, { mode: sourceStat.mode });
150
      } catch (err) {
151
        if (err.code !== `EEXIST`) {
152
          throw err;
153
        }
154
      }
155
    });
156
    updated = true;
157
  }
158
  const entries = await sourceFs.readdirPromise(source);
159
  const nextOpts = opts.didParentExist && !destinationStat ? { ...opts, didParentExist: false } : opts;
160
  if (opts.stableSort) {
161
    for (const entry of entries.sort()) {
162
      if (await copyImpl(prelayout, postlayout, destinationFs, destinationFs.pathUtils.join(destination, entry), sourceFs, sourceFs.pathUtils.join(source, entry), nextOpts)) {
163
        updated = true;
164
      }
165
    }
166
  } else {
167
    const entriesUpdateStatus = await Promise.all(entries.map(async (entry) => {
168
      await copyImpl(prelayout, postlayout, destinationFs, destinationFs.pathUtils.join(destination, entry), sourceFs, sourceFs.pathUtils.join(source, entry), nextOpts);
169
    }));
170
    if (entriesUpdateStatus.some((status) => status)) {
171
      updated = true;
172
    }
173
  }
174
  return updated;
175
}
176
async function copyFileViaIndex(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts, linkStrategy) {
177
  const sourceHash = await sourceFs.checksumFilePromise(source, { algorithm: `sha1` });
178
  const indexPath = destinationFs.pathUtils.join(linkStrategy.indexPath, sourceHash.slice(0, 2), `${sourceHash}.dat`);
179
  let AtomicBehavior;
180
  ((AtomicBehavior2) => {
181
    AtomicBehavior2[AtomicBehavior2["Lock"] = 0] = "Lock";
182
    AtomicBehavior2[AtomicBehavior2["Rename"] = 1] = "Rename";
183
  })(AtomicBehavior || (AtomicBehavior = {}));
184
  let atomicBehavior = 1 /* Rename */;
185
  let indexStat = await maybeLStat(destinationFs, indexPath);
186
  if (destinationStat) {
187
    const isDestinationHardlinkedFromIndex = indexStat && destinationStat.dev === indexStat.dev && destinationStat.ino === indexStat.ino;
188
    const isIndexModified = indexStat?.mtimeMs !== defaultTimeMs;
189
    if (isDestinationHardlinkedFromIndex) {
190
      if (isIndexModified && linkStrategy.autoRepair) {
191
        atomicBehavior = 0 /* Lock */;
192
        indexStat = null;
193
      }
194
    }
195
    if (!isDestinationHardlinkedFromIndex) {
196
      if (opts.overwrite) {
197
        prelayout.push(async () => destinationFs.removePromise(destination));
198
        destinationStat = null;
199
      } else {
200
        return false;
201
      }
202
    }
203
  }
204
  const tempPath = !indexStat && atomicBehavior === 1 /* Rename */ ? `${indexPath}.${Math.floor(Math.random() * 4294967296).toString(16).padStart(8, `0`)}` : null;
205
  let tempPathCleaned = false;
206
  prelayout.push(async () => {
207
    if (!indexStat) {
208
      if (atomicBehavior === 0 /* Lock */) {
209
        await destinationFs.lockPromise(indexPath, async () => {
210
          const content = await sourceFs.readFilePromise(source);
211
          await destinationFs.writeFilePromise(indexPath, content);
212
        });
213
      }
214
      if (atomicBehavior === 1 /* Rename */ && tempPath) {
215
        const content = await sourceFs.readFilePromise(source);
216
        await destinationFs.writeFilePromise(tempPath, content);
217
        try {
218
          await destinationFs.linkPromise(tempPath, indexPath);
219
        } catch (err) {
220
          if (err.code === `EEXIST`) {
221
            tempPathCleaned = true;
222
            await destinationFs.unlinkPromise(tempPath);
223
          } else {
224
            throw err;
225
          }
226
        }
227
      }
228
    }
229
    if (!destinationStat) {
230
      await destinationFs.linkPromise(indexPath, destination);
231
    }
232
  });
233
  postlayout.push(async () => {
234
    if (!indexStat)
235
      await destinationFs.lutimesPromise(indexPath, defaultTime, defaultTime);
236
    if (tempPath && !tempPathCleaned) {
237
      await destinationFs.unlinkPromise(tempPath);
238
    }
239
  });
240
  return false;
241
}
242
async function copyFileDirect(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts) {
243
  if (destinationStat !== null) {
244
    if (opts.overwrite) {
245
      prelayout.push(async () => destinationFs.removePromise(destination));
246
      destinationStat = null;
247
    } else {
248
      return false;
249
    }
250
  }
251
  prelayout.push(async () => {
252
    const content = await sourceFs.readFilePromise(source);
253
    await destinationFs.writeFilePromise(destination, content);
254
  });
255
  return true;
256
}
257
async function copyFile(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts) {
258
  if (opts.linkStrategy?.type === `HardlinkFromIndex`) {
259
    return copyFileViaIndex(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts, opts.linkStrategy);
260
  } else {
261
    return copyFileDirect(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts);
262
  }
263
}
264
async function copySymlink(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts) {
265
  if (destinationStat !== null) {
266
    if (opts.overwrite) {
267
      prelayout.push(async () => destinationFs.removePromise(destination));
268
      destinationStat = null;
269
    } else {
270
      return false;
271
    }
272
  }
273
  prelayout.push(async () => {
274
    await destinationFs.symlinkPromise(convertPath(destinationFs.pathUtils, await sourceFs.readlinkPromise(source)), destination);
275
  });
276
  return true;
277
}
278

279
class FakeFS {
280
  constructor(pathUtils) {
281
    this.pathUtils = pathUtils;
282
  }
283
  async *genTraversePromise(init, { stableSort = false } = {}) {
284
    const stack = [init];
285
    while (stack.length > 0) {
286
      const p = stack.shift();
287
      const entry = await this.lstatPromise(p);
288
      if (entry.isDirectory()) {
289
        const entries = await this.readdirPromise(p);
290
        if (stableSort) {
291
          for (const entry2 of entries.sort()) {
292
            stack.push(this.pathUtils.join(p, entry2));
293
          }
294
        } else {
295
          throw new Error(`Not supported`);
296
        }
297
      } else {
298
        yield p;
299
      }
300
    }
301
  }
302
  async checksumFilePromise(path, { algorithm = `sha512` } = {}) {
303
    const fd = await this.openPromise(path, `r`);
304
    try {
305
      const CHUNK_SIZE = 65536;
306
      const chunk = Buffer.allocUnsafeSlow(CHUNK_SIZE);
307
      const hash = createHash(algorithm);
308
      let bytesRead = 0;
309
      while ((bytesRead = await this.readPromise(fd, chunk, 0, CHUNK_SIZE)) !== 0)
310
        hash.update(bytesRead === CHUNK_SIZE ? chunk : chunk.slice(0, bytesRead));
311
      return hash.digest(`hex`);
312
    } finally {
313
      await this.closePromise(fd);
314
    }
315
  }
316
  async removePromise(p, { recursive = true, maxRetries = 5 } = {}) {
317
    let stat;
318
    try {
319
      stat = await this.lstatPromise(p);
320
    } catch (error) {
321
      if (error.code === `ENOENT`) {
322
        return;
323
      } else {
324
        throw error;
325
      }
326
    }
327
    if (stat.isDirectory()) {
328
      if (recursive) {
329
        const entries = await this.readdirPromise(p);
330
        await Promise.all(entries.map((entry) => {
331
          return this.removePromise(this.pathUtils.resolve(p, entry));
332
        }));
333
      }
334
      for (let t = 0; t <= maxRetries; t++) {
335
        try {
336
          await this.rmdirPromise(p);
337
          break;
338
        } catch (error) {
339
          if (error.code !== `EBUSY` && error.code !== `ENOTEMPTY`) {
340
            throw error;
341
          } else if (t < maxRetries) {
342
            await new Promise((resolve) => setTimeout(resolve, t * 100));
343
          }
344
        }
345
      }
346
    } else {
347
      await this.unlinkPromise(p);
348
    }
349
  }
350
  removeSync(p, { recursive = true } = {}) {
351
    let stat;
352
    try {
353
      stat = this.lstatSync(p);
354
    } catch (error) {
355
      if (error.code === `ENOENT`) {
356
        return;
357
      } else {
358
        throw error;
359
      }
360
    }
361
    if (stat.isDirectory()) {
362
      if (recursive)
363
        for (const entry of this.readdirSync(p))
364
          this.removeSync(this.pathUtils.resolve(p, entry));
365
      this.rmdirSync(p);
366
    } else {
367
      this.unlinkSync(p);
368
    }
369
  }
370
  async mkdirpPromise(p, { chmod, utimes } = {}) {
371
    p = this.resolve(p);
372
    if (p === this.pathUtils.dirname(p))
373
      return void 0;
374
    const parts = p.split(this.pathUtils.sep);
375
    let createdDirectory;
376
    for (let u = 2; u <= parts.length; ++u) {
377
      const subPath = parts.slice(0, u).join(this.pathUtils.sep);
378
      if (!this.existsSync(subPath)) {
379
        try {
380
          await this.mkdirPromise(subPath);
381
        } catch (error) {
382
          if (error.code === `EEXIST`) {
383
            continue;
384
          } else {
385
            throw error;
386
          }
387
        }
388
        createdDirectory ??= subPath;
389
        if (chmod != null)
390
          await this.chmodPromise(subPath, chmod);
391
        if (utimes != null) {
392
          await this.utimesPromise(subPath, utimes[0], utimes[1]);
393
        } else {
394
          const parentStat = await this.statPromise(this.pathUtils.dirname(subPath));
395
          await this.utimesPromise(subPath, parentStat.atime, parentStat.mtime);
396
        }
397
      }
398
    }
399
    return createdDirectory;
400
  }
401
  mkdirpSync(p, { chmod, utimes } = {}) {
402
    p = this.resolve(p);
403
    if (p === this.pathUtils.dirname(p))
404
      return void 0;
405
    const parts = p.split(this.pathUtils.sep);
406
    let createdDirectory;
407
    for (let u = 2; u <= parts.length; ++u) {
408
      const subPath = parts.slice(0, u).join(this.pathUtils.sep);
409
      if (!this.existsSync(subPath)) {
410
        try {
411
          this.mkdirSync(subPath);
412
        } catch (error) {
413
          if (error.code === `EEXIST`) {
414
            continue;
415
          } else {
416
            throw error;
417
          }
418
        }
419
        createdDirectory ??= subPath;
420
        if (chmod != null)
421
          this.chmodSync(subPath, chmod);
422
        if (utimes != null) {
423
          this.utimesSync(subPath, utimes[0], utimes[1]);
424
        } else {
425
          const parentStat = this.statSync(this.pathUtils.dirname(subPath));
426
          this.utimesSync(subPath, parentStat.atime, parentStat.mtime);
427
        }
428
      }
429
    }
430
    return createdDirectory;
431
  }
432
  async copyPromise(destination, source, { baseFs = this, overwrite = true, stableSort = false, stableTime = false, linkStrategy = null } = {}) {
433
    return await copyPromise(this, destination, baseFs, source, { overwrite, stableSort, stableTime, linkStrategy });
434
  }
435
  copySync(destination, source, { baseFs = this, overwrite = true } = {}) {
436
    const stat = baseFs.lstatSync(source);
437
    const exists = this.existsSync(destination);
438
    if (stat.isDirectory()) {
439
      this.mkdirpSync(destination);
440
      const directoryListing = baseFs.readdirSync(source);
441
      for (const entry of directoryListing) {
442
        this.copySync(this.pathUtils.join(destination, entry), baseFs.pathUtils.join(source, entry), { baseFs, overwrite });
443
      }
444
    } else if (stat.isFile()) {
445
      if (!exists || overwrite) {
446
        if (exists)
447
          this.removeSync(destination);
448
        const content = baseFs.readFileSync(source);
449
        this.writeFileSync(destination, content);
450
      }
451
    } else if (stat.isSymbolicLink()) {
452
      if (!exists || overwrite) {
453
        if (exists)
454
          this.removeSync(destination);
455
        const target = baseFs.readlinkSync(source);
456
        this.symlinkSync(convertPath(this.pathUtils, target), destination);
457
      }
458
    } else {
459
      throw new Error(`Unsupported file type (file: ${source}, mode: 0o${stat.mode.toString(8).padStart(6, `0`)})`);
460
    }
461
    const mode = stat.mode & 511;
462
    this.chmodSync(destination, mode);
463
  }
464
  async changeFilePromise(p, content, opts = {}) {
465
    if (Buffer.isBuffer(content)) {
466
      return this.changeFileBufferPromise(p, content, opts);
467
    } else {
468
      return this.changeFileTextPromise(p, content, opts);
469
    }
470
  }
471
  async changeFileBufferPromise(p, content, { mode } = {}) {
472
    let current = Buffer.alloc(0);
473
    try {
474
      current = await this.readFilePromise(p);
475
    } catch (error) {
476
    }
477
    if (Buffer.compare(current, content) === 0)
478
      return;
479
    await this.writeFilePromise(p, content, { mode });
480
  }
481
  async changeFileTextPromise(p, content, { automaticNewlines, mode } = {}) {
482
    let current = ``;
483
    try {
484
      current = await this.readFilePromise(p, `utf8`);
485
    } catch (error) {
486
    }
487
    const normalizedContent = automaticNewlines ? normalizeLineEndings(current, content) : content;
488
    if (current === normalizedContent)
489
      return;
490
    await this.writeFilePromise(p, normalizedContent, { mode });
491
  }
492
  changeFileSync(p, content, opts = {}) {
493
    if (Buffer.isBuffer(content)) {
494
      return this.changeFileBufferSync(p, content, opts);
495
    } else {
496
      return this.changeFileTextSync(p, content, opts);
497
    }
498
  }
499
  changeFileBufferSync(p, content, { mode } = {}) {
500
    let current = Buffer.alloc(0);
501
    try {
502
      current = this.readFileSync(p);
503
    } catch (error) {
504
    }
505
    if (Buffer.compare(current, content) === 0)
506
      return;
507
    this.writeFileSync(p, content, { mode });
508
  }
509
  changeFileTextSync(p, content, { automaticNewlines = false, mode } = {}) {
510
    let current = ``;
511
    try {
512
      current = this.readFileSync(p, `utf8`);
513
    } catch (error) {
514
    }
515
    const normalizedContent = automaticNewlines ? normalizeLineEndings(current, content) : content;
516
    if (current === normalizedContent)
517
      return;
518
    this.writeFileSync(p, normalizedContent, { mode });
519
  }
520
  async movePromise(fromP, toP) {
521
    try {
522
      await this.renamePromise(fromP, toP);
523
    } catch (error) {
524
      if (error.code === `EXDEV`) {
525
        await this.copyPromise(toP, fromP);
526
        await this.removePromise(fromP);
527
      } else {
528
        throw error;
529
      }
530
    }
531
  }
532
  moveSync(fromP, toP) {
533
    try {
534
      this.renameSync(fromP, toP);
535
    } catch (error) {
536
      if (error.code === `EXDEV`) {
537
        this.copySync(toP, fromP);
538
        this.removeSync(fromP);
539
      } else {
540
        throw error;
541
      }
542
    }
543
  }
544
  async lockPromise(affectedPath, callback) {
545
    const lockPath = `${affectedPath}.flock`;
546
    const interval = 1e3 / 60;
547
    const startTime = Date.now();
548
    let fd = null;
549
    const isAlive = async () => {
550
      let pid;
551
      try {
552
        [pid] = await this.readJsonPromise(lockPath);
553
      } catch (error) {
554
        return Date.now() - startTime < 500;
555
      }
556
      try {
557
        process.kill(pid, 0);
558
        return true;
559
      } catch (error) {
560
        return false;
561
      }
562
    };
563
    while (fd === null) {
564
      try {
565
        fd = await this.openPromise(lockPath, `wx`);
566
      } catch (error) {
567
        if (error.code === `EEXIST`) {
568
          if (!await isAlive()) {
569
            try {
570
              await this.unlinkPromise(lockPath);
571
              continue;
572
            } catch (error2) {
573
            }
574
          }
575
          if (Date.now() - startTime < 60 * 1e3) {
576
            await new Promise((resolve) => setTimeout(resolve, interval));
577
          } else {
578
            throw new Error(`Couldn't acquire a lock in a reasonable time (via ${lockPath})`);
579
          }
580
        } else {
581
          throw error;
582
        }
583
      }
584
    }
585
    await this.writePromise(fd, JSON.stringify([process.pid]));
586
    try {
587
      return await callback();
588
    } finally {
589
      try {
590
        await this.closePromise(fd);
591
        await this.unlinkPromise(lockPath);
592
      } catch (error) {
593
      }
594
    }
595
  }
596
  async readJsonPromise(p) {
597
    const content = await this.readFilePromise(p, `utf8`);
598
    try {
599
      return JSON.parse(content);
600
    } catch (error) {
601
      error.message += ` (in ${p})`;
602
      throw error;
603
    }
604
  }
605
  readJsonSync(p) {
606
    const content = this.readFileSync(p, `utf8`);
607
    try {
608
      return JSON.parse(content);
609
    } catch (error) {
610
      error.message += ` (in ${p})`;
611
      throw error;
612
    }
613
  }
614
  async writeJsonPromise(p, data, { compact = false } = {}) {
615
    const space = compact ? 0 : 2;
616
    return await this.writeFilePromise(p, `${JSON.stringify(data, null, space)}
617
`);
618
  }
619
  writeJsonSync(p, data, { compact = false } = {}) {
620
    const space = compact ? 0 : 2;
621
    return this.writeFileSync(p, `${JSON.stringify(data, null, space)}
622
`);
623
  }
624
  async preserveTimePromise(p, cb) {
625
    const stat = await this.lstatPromise(p);
626
    const result = await cb();
627
    if (typeof result !== `undefined`)
628
      p = result;
629
    await this.lutimesPromise(p, stat.atime, stat.mtime);
630
  }
631
  async preserveTimeSync(p, cb) {
632
    const stat = this.lstatSync(p);
633
    const result = cb();
634
    if (typeof result !== `undefined`)
635
      p = result;
636
    this.lutimesSync(p, stat.atime, stat.mtime);
637
  }
638
}
639
class BasePortableFakeFS extends FakeFS {
640
  constructor() {
641
    super(ppath);
642
  }
643
}
644
function getEndOfLine(content) {
645
  const matches = content.match(/\r?\n/g);
646
  if (matches === null)
647
    return EOL;
648
  const crlf = matches.filter((nl) => nl === `\r
649
`).length;
650
  const lf = matches.length - crlf;
651
  return crlf > lf ? `\r
652
` : `
653
`;
654
}
655
function normalizeLineEndings(originalContent, newContent) {
656
  return newContent.replace(/\r?\n/g, getEndOfLine(originalContent));
657
}
658

659
class ProxiedFS extends FakeFS {
660
  getExtractHint(hints) {
661
    return this.baseFs.getExtractHint(hints);
662
  }
663
  resolve(path) {
664
    return this.mapFromBase(this.baseFs.resolve(this.mapToBase(path)));
665
  }
666
  getRealPath() {
667
    return this.mapFromBase(this.baseFs.getRealPath());
668
  }
669
  async openPromise(p, flags, mode) {
670
    return this.baseFs.openPromise(this.mapToBase(p), flags, mode);
671
  }
672
  openSync(p, flags, mode) {
673
    return this.baseFs.openSync(this.mapToBase(p), flags, mode);
674
  }
675
  async opendirPromise(p, opts) {
676
    return Object.assign(await this.baseFs.opendirPromise(this.mapToBase(p), opts), { path: p });
677
  }
678
  opendirSync(p, opts) {
679
    return Object.assign(this.baseFs.opendirSync(this.mapToBase(p), opts), { path: p });
680
  }
681
  async readPromise(fd, buffer, offset, length, position) {
682
    return await this.baseFs.readPromise(fd, buffer, offset, length, position);
683
  }
684
  readSync(fd, buffer, offset, length, position) {
685
    return this.baseFs.readSync(fd, buffer, offset, length, position);
686
  }
687
  async writePromise(fd, buffer, offset, length, position) {
688
    if (typeof buffer === `string`) {
689
      return await this.baseFs.writePromise(fd, buffer, offset);
690
    } else {
691
      return await this.baseFs.writePromise(fd, buffer, offset, length, position);
692
    }
693
  }
694
  writeSync(fd, buffer, offset, length, position) {
695
    if (typeof buffer === `string`) {
696
      return this.baseFs.writeSync(fd, buffer, offset);
697
    } else {
698
      return this.baseFs.writeSync(fd, buffer, offset, length, position);
699
    }
700
  }
701
  async closePromise(fd) {
702
    return this.baseFs.closePromise(fd);
703
  }
704
  closeSync(fd) {
705
    this.baseFs.closeSync(fd);
706
  }
707
  createReadStream(p, opts) {
708
    return this.baseFs.createReadStream(p !== null ? this.mapToBase(p) : p, opts);
709
  }
710
  createWriteStream(p, opts) {
711
    return this.baseFs.createWriteStream(p !== null ? this.mapToBase(p) : p, opts);
712
  }
713
  async realpathPromise(p) {
714
    return this.mapFromBase(await this.baseFs.realpathPromise(this.mapToBase(p)));
715
  }
716
  realpathSync(p) {
717
    return this.mapFromBase(this.baseFs.realpathSync(this.mapToBase(p)));
718
  }
719
  async existsPromise(p) {
720
    return this.baseFs.existsPromise(this.mapToBase(p));
721
  }
722
  existsSync(p) {
723
    return this.baseFs.existsSync(this.mapToBase(p));
724
  }
725
  accessSync(p, mode) {
726
    return this.baseFs.accessSync(this.mapToBase(p), mode);
727
  }
728
  async accessPromise(p, mode) {
729
    return this.baseFs.accessPromise(this.mapToBase(p), mode);
730
  }
731
  async statPromise(p, opts) {
732
    return this.baseFs.statPromise(this.mapToBase(p), opts);
733
  }
734
  statSync(p, opts) {
735
    return this.baseFs.statSync(this.mapToBase(p), opts);
736
  }
737
  async fstatPromise(fd, opts) {
738
    return this.baseFs.fstatPromise(fd, opts);
739
  }
740
  fstatSync(fd, opts) {
741
    return this.baseFs.fstatSync(fd, opts);
742
  }
743
  lstatPromise(p, opts) {
744
    return this.baseFs.lstatPromise(this.mapToBase(p), opts);
745
  }
746
  lstatSync(p, opts) {
747
    return this.baseFs.lstatSync(this.mapToBase(p), opts);
748
  }
749
  async fchmodPromise(fd, mask) {
750
    return this.baseFs.fchmodPromise(fd, mask);
751
  }
752
  fchmodSync(fd, mask) {
753
    return this.baseFs.fchmodSync(fd, mask);
754
  }
755
  async chmodPromise(p, mask) {
756
    return this.baseFs.chmodPromise(this.mapToBase(p), mask);
757
  }
758
  chmodSync(p, mask) {
759
    return this.baseFs.chmodSync(this.mapToBase(p), mask);
760
  }
761
  async fchownPromise(fd, uid, gid) {
762
    return this.baseFs.fchownPromise(fd, uid, gid);
763
  }
764
  fchownSync(fd, uid, gid) {
765
    return this.baseFs.fchownSync(fd, uid, gid);
766
  }
767
  async chownPromise(p, uid, gid) {
768
    return this.baseFs.chownPromise(this.mapToBase(p), uid, gid);
769
  }
770
  chownSync(p, uid, gid) {
771
    return this.baseFs.chownSync(this.mapToBase(p), uid, gid);
772
  }
773
  async renamePromise(oldP, newP) {
774
    return this.baseFs.renamePromise(this.mapToBase(oldP), this.mapToBase(newP));
775
  }
776
  renameSync(oldP, newP) {
777
    return this.baseFs.renameSync(this.mapToBase(oldP), this.mapToBase(newP));
778
  }
779
  async copyFilePromise(sourceP, destP, flags = 0) {
780
    return this.baseFs.copyFilePromise(this.mapToBase(sourceP), this.mapToBase(destP), flags);
781
  }
782
  copyFileSync(sourceP, destP, flags = 0) {
783
    return this.baseFs.copyFileSync(this.mapToBase(sourceP), this.mapToBase(destP), flags);
784
  }
785
  async appendFilePromise(p, content, opts) {
786
    return this.baseFs.appendFilePromise(this.fsMapToBase(p), content, opts);
787
  }
788
  appendFileSync(p, content, opts) {
789
    return this.baseFs.appendFileSync(this.fsMapToBase(p), content, opts);
790
  }
791
  async writeFilePromise(p, content, opts) {
792
    return this.baseFs.writeFilePromise(this.fsMapToBase(p), content, opts);
793
  }
794
  writeFileSync(p, content, opts) {
795
    return this.baseFs.writeFileSync(this.fsMapToBase(p), content, opts);
796
  }
797
  async unlinkPromise(p) {
798
    return this.baseFs.unlinkPromise(this.mapToBase(p));
799
  }
800
  unlinkSync(p) {
801
    return this.baseFs.unlinkSync(this.mapToBase(p));
802
  }
803
  async utimesPromise(p, atime, mtime) {
804
    return this.baseFs.utimesPromise(this.mapToBase(p), atime, mtime);
805
  }
806
  utimesSync(p, atime, mtime) {
807
    return this.baseFs.utimesSync(this.mapToBase(p), atime, mtime);
808
  }
809
  async lutimesPromise(p, atime, mtime) {
810
    return this.baseFs.lutimesPromise(this.mapToBase(p), atime, mtime);
811
  }
812
  lutimesSync(p, atime, mtime) {
813
    return this.baseFs.lutimesSync(this.mapToBase(p), atime, mtime);
814
  }
815
  async mkdirPromise(p, opts) {
816
    return this.baseFs.mkdirPromise(this.mapToBase(p), opts);
817
  }
818
  mkdirSync(p, opts) {
819
    return this.baseFs.mkdirSync(this.mapToBase(p), opts);
820
  }
821
  async rmdirPromise(p, opts) {
822
    return this.baseFs.rmdirPromise(this.mapToBase(p), opts);
823
  }
824
  rmdirSync(p, opts) {
825
    return this.baseFs.rmdirSync(this.mapToBase(p), opts);
826
  }
827
  async linkPromise(existingP, newP) {
828
    return this.baseFs.linkPromise(this.mapToBase(existingP), this.mapToBase(newP));
829
  }
830
  linkSync(existingP, newP) {
831
    return this.baseFs.linkSync(this.mapToBase(existingP), this.mapToBase(newP));
832
  }
833
  async symlinkPromise(target, p, type) {
834
    const mappedP = this.mapToBase(p);
835
    if (this.pathUtils.isAbsolute(target))
836
      return this.baseFs.symlinkPromise(this.mapToBase(target), mappedP, type);
837
    const mappedAbsoluteTarget = this.mapToBase(this.pathUtils.join(this.pathUtils.dirname(p), target));
838
    const mappedTarget = this.baseFs.pathUtils.relative(this.baseFs.pathUtils.dirname(mappedP), mappedAbsoluteTarget);
839
    return this.baseFs.symlinkPromise(mappedTarget, mappedP, type);
840
  }
841
  symlinkSync(target, p, type) {
842
    const mappedP = this.mapToBase(p);
843
    if (this.pathUtils.isAbsolute(target))
844
      return this.baseFs.symlinkSync(this.mapToBase(target), mappedP, type);
845
    const mappedAbsoluteTarget = this.mapToBase(this.pathUtils.join(this.pathUtils.dirname(p), target));
846
    const mappedTarget = this.baseFs.pathUtils.relative(this.baseFs.pathUtils.dirname(mappedP), mappedAbsoluteTarget);
847
    return this.baseFs.symlinkSync(mappedTarget, mappedP, type);
848
  }
849
  async readFilePromise(p, encoding) {
850
    return this.baseFs.readFilePromise(this.fsMapToBase(p), encoding);
851
  }
852
  readFileSync(p, encoding) {
853
    return this.baseFs.readFileSync(this.fsMapToBase(p), encoding);
854
  }
855
  readdirPromise(p, opts) {
856
    return this.baseFs.readdirPromise(this.mapToBase(p), opts);
857
  }
858
  readdirSync(p, opts) {
859
    return this.baseFs.readdirSync(this.mapToBase(p), opts);
860
  }
861
  async readlinkPromise(p) {
862
    return this.mapFromBase(await this.baseFs.readlinkPromise(this.mapToBase(p)));
863
  }
864
  readlinkSync(p) {
865
    return this.mapFromBase(this.baseFs.readlinkSync(this.mapToBase(p)));
866
  }
867
  async truncatePromise(p, len) {
868
    return this.baseFs.truncatePromise(this.mapToBase(p), len);
869
  }
870
  truncateSync(p, len) {
871
    return this.baseFs.truncateSync(this.mapToBase(p), len);
872
  }
873
  async ftruncatePromise(fd, len) {
874
    return this.baseFs.ftruncatePromise(fd, len);
875
  }
876
  ftruncateSync(fd, len) {
877
    return this.baseFs.ftruncateSync(fd, len);
878
  }
879
  watch(p, a, b) {
880
    return this.baseFs.watch(
881
      this.mapToBase(p),
882
      a,
883
      b
884
    );
885
  }
886
  watchFile(p, a, b) {
887
    return this.baseFs.watchFile(
888
      this.mapToBase(p),
889
      a,
890
      b
891
    );
892
  }
893
  unwatchFile(p, cb) {
894
    return this.baseFs.unwatchFile(this.mapToBase(p), cb);
895
  }
896
  fsMapToBase(p) {
897
    if (typeof p === `number`) {
898
      return p;
899
    } else {
900
      return this.mapToBase(p);
901
    }
902
  }
903
}
904

905
function direntToPortable(dirent) {
906
  const portableDirent = dirent;
907
  if (typeof dirent.path === `string`)
908
    portableDirent.path = npath.toPortablePath(dirent.path);
909
  return portableDirent;
910
}
911
class NodeFS extends BasePortableFakeFS {
912
  constructor(realFs = fs) {
913
    super();
914
    this.realFs = realFs;
915
  }
916
  getExtractHint() {
917
    return false;
918
  }
919
  getRealPath() {
920
    return PortablePath.root;
921
  }
922
  resolve(p) {
923
    return ppath.resolve(p);
924
  }
925
  async openPromise(p, flags, mode) {
926
    return await new Promise((resolve, reject) => {
927
      this.realFs.open(npath.fromPortablePath(p), flags, mode, this.makeCallback(resolve, reject));
928
    });
929
  }
930
  openSync(p, flags, mode) {
931
    return this.realFs.openSync(npath.fromPortablePath(p), flags, mode);
932
  }
933
  async opendirPromise(p, opts) {
934
    return await new Promise((resolve, reject) => {
935
      if (typeof opts !== `undefined`) {
936
        this.realFs.opendir(npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject));
937
      } else {
938
        this.realFs.opendir(npath.fromPortablePath(p), this.makeCallback(resolve, reject));
939
      }
940
    }).then((dir) => {
941
      const dirWithFixedPath = dir;
942
      Object.defineProperty(dirWithFixedPath, `path`, {
943
        value: p,
944
        configurable: true,
945
        writable: true
946
      });
947
      return dirWithFixedPath;
948
    });
949
  }
950
  opendirSync(p, opts) {
951
    const dir = typeof opts !== `undefined` ? this.realFs.opendirSync(npath.fromPortablePath(p), opts) : this.realFs.opendirSync(npath.fromPortablePath(p));
952
    const dirWithFixedPath = dir;
953
    Object.defineProperty(dirWithFixedPath, `path`, {
954
      value: p,
955
      configurable: true,
956
      writable: true
957
    });
958
    return dirWithFixedPath;
959
  }
960
  async readPromise(fd, buffer, offset = 0, length = 0, position = -1) {
961
    return await new Promise((resolve, reject) => {
962
      this.realFs.read(fd, buffer, offset, length, position, (error, bytesRead) => {
963
        if (error) {
964
          reject(error);
965
        } else {
966
          resolve(bytesRead);
967
        }
968
      });
969
    });
970
  }
971
  readSync(fd, buffer, offset, length, position) {
972
    return this.realFs.readSync(fd, buffer, offset, length, position);
973
  }
974
  async writePromise(fd, buffer, offset, length, position) {
975
    return await new Promise((resolve, reject) => {
976
      if (typeof buffer === `string`) {
977
        return this.realFs.write(fd, buffer, offset, this.makeCallback(resolve, reject));
978
      } else {
979
        return this.realFs.write(fd, buffer, offset, length, position, this.makeCallback(resolve, reject));
980
      }
981
    });
982
  }
983
  writeSync(fd, buffer, offset, length, position) {
984
    if (typeof buffer === `string`) {
985
      return this.realFs.writeSync(fd, buffer, offset);
986
    } else {
987
      return this.realFs.writeSync(fd, buffer, offset, length, position);
988
    }
989
  }
990
  async closePromise(fd) {
991
    await new Promise((resolve, reject) => {
992
      this.realFs.close(fd, this.makeCallback(resolve, reject));
993
    });
994
  }
995
  closeSync(fd) {
996
    this.realFs.closeSync(fd);
997
  }
998
  createReadStream(p, opts) {
999
    const realPath = p !== null ? npath.fromPortablePath(p) : p;
1000
    return this.realFs.createReadStream(realPath, opts);
1001
  }
1002
  createWriteStream(p, opts) {
1003
    const realPath = p !== null ? npath.fromPortablePath(p) : p;
1004
    return this.realFs.createWriteStream(realPath, opts);
1005
  }
1006
  async realpathPromise(p) {
1007
    return await new Promise((resolve, reject) => {
1008
      this.realFs.realpath(npath.fromPortablePath(p), {}, this.makeCallback(resolve, reject));
1009
    }).then((path) => {
1010
      return npath.toPortablePath(path);
1011
    });
1012
  }
1013
  realpathSync(p) {
1014
    return npath.toPortablePath(this.realFs.realpathSync(npath.fromPortablePath(p), {}));
1015
  }
1016
  async existsPromise(p) {
1017
    return await new Promise((resolve) => {
1018
      this.realFs.exists(npath.fromPortablePath(p), resolve);
1019
    });
1020
  }
1021
  accessSync(p, mode) {
1022
    return this.realFs.accessSync(npath.fromPortablePath(p), mode);
1023
  }
1024
  async accessPromise(p, mode) {
1025
    return await new Promise((resolve, reject) => {
1026
      this.realFs.access(npath.fromPortablePath(p), mode, this.makeCallback(resolve, reject));
1027
    });
1028
  }
1029
  existsSync(p) {
1030
    return this.realFs.existsSync(npath.fromPortablePath(p));
1031
  }
1032
  async statPromise(p, opts) {
1033
    return await new Promise((resolve, reject) => {
1034
      if (opts) {
1035
        this.realFs.stat(npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject));
1036
      } else {
1037
        this.realFs.stat(npath.fromPortablePath(p), this.makeCallback(resolve, reject));
1038
      }
1039
    });
1040
  }
1041
  statSync(p, opts) {
1042
    if (opts) {
1043
      return this.realFs.statSync(npath.fromPortablePath(p), opts);
1044
    } else {
1045
      return this.realFs.statSync(npath.fromPortablePath(p));
1046
    }
1047
  }
1048
  async fstatPromise(fd, opts) {
1049
    return await new Promise((resolve, reject) => {
1050
      if (opts) {
1051
        this.realFs.fstat(fd, opts, this.makeCallback(resolve, reject));
1052
      } else {
1053
        this.realFs.fstat(fd, this.makeCallback(resolve, reject));
1054
      }
1055
    });
1056
  }
1057
  fstatSync(fd, opts) {
1058
    if (opts) {
1059
      return this.realFs.fstatSync(fd, opts);
1060
    } else {
1061
      return this.realFs.fstatSync(fd);
1062
    }
1063
  }
1064
  async lstatPromise(p, opts) {
1065
    return await new Promise((resolve, reject) => {
1066
      if (opts) {
1067
        this.realFs.lstat(npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject));
1068
      } else {
1069
        this.realFs.lstat(npath.fromPortablePath(p), this.makeCallback(resolve, reject));
1070
      }
1071
    });
1072
  }
1073
  lstatSync(p, opts) {
1074
    if (opts) {
1075
      return this.realFs.lstatSync(npath.fromPortablePath(p), opts);
1076
    } else {
1077
      return this.realFs.lstatSync(npath.fromPortablePath(p));
1078
    }
1079
  }
1080
  async fchmodPromise(fd, mask) {
1081
    return await new Promise((resolve, reject) => {
1082
      this.realFs.fchmod(fd, mask, this.makeCallback(resolve, reject));
1083
    });
1084
  }
1085
  fchmodSync(fd, mask) {
1086
    return this.realFs.fchmodSync(fd, mask);
1087
  }
1088
  async chmodPromise(p, mask) {
1089
    return await new Promise((resolve, reject) => {
1090
      this.realFs.chmod(npath.fromPortablePath(p), mask, this.makeCallback(resolve, reject));
1091
    });
1092
  }
1093
  chmodSync(p, mask) {
1094
    return this.realFs.chmodSync(npath.fromPortablePath(p), mask);
1095
  }
1096
  async fchownPromise(fd, uid, gid) {
1097
    return await new Promise((resolve, reject) => {
1098
      this.realFs.fchown(fd, uid, gid, this.makeCallback(resolve, reject));
1099
    });
1100
  }
1101
  fchownSync(fd, uid, gid) {
1102
    return this.realFs.fchownSync(fd, uid, gid);
1103
  }
1104
  async chownPromise(p, uid, gid) {
1105
    return await new Promise((resolve, reject) => {
1106
      this.realFs.chown(npath.fromPortablePath(p), uid, gid, this.makeCallback(resolve, reject));
1107
    });
1108
  }
1109
  chownSync(p, uid, gid) {
1110
    return this.realFs.chownSync(npath.fromPortablePath(p), uid, gid);
1111
  }
1112
  async renamePromise(oldP, newP) {
1113
    return await new Promise((resolve, reject) => {
1114
      this.realFs.rename(npath.fromPortablePath(oldP), npath.fromPortablePath(newP), this.makeCallback(resolve, reject));
1115
    });
1116
  }
1117
  renameSync(oldP, newP) {
1118
    return this.realFs.renameSync(npath.fromPortablePath(oldP), npath.fromPortablePath(newP));
1119
  }
1120
  async copyFilePromise(sourceP, destP, flags = 0) {
1121
    return await new Promise((resolve, reject) => {
1122
      this.realFs.copyFile(npath.fromPortablePath(sourceP), npath.fromPortablePath(destP), flags, this.makeCallback(resolve, reject));
1123
    });
1124
  }
1125
  copyFileSync(sourceP, destP, flags = 0) {
1126
    return this.realFs.copyFileSync(npath.fromPortablePath(sourceP), npath.fromPortablePath(destP), flags);
1127
  }
1128
  async appendFilePromise(p, content, opts) {
1129
    return await new Promise((resolve, reject) => {
1130
      const fsNativePath = typeof p === `string` ? npath.fromPortablePath(p) : p;
1131
      if (opts) {
1132
        this.realFs.appendFile(fsNativePath, content, opts, this.makeCallback(resolve, reject));
1133
      } else {
1134
        this.realFs.appendFile(fsNativePath, content, this.makeCallback(resolve, reject));
1135
      }
1136
    });
1137
  }
1138
  appendFileSync(p, content, opts) {
1139
    const fsNativePath = typeof p === `string` ? npath.fromPortablePath(p) : p;
1140
    if (opts) {
1141
      this.realFs.appendFileSync(fsNativePath, content, opts);
1142
    } else {
1143
      this.realFs.appendFileSync(fsNativePath, content);
1144
    }
1145
  }
1146
  async writeFilePromise(p, content, opts) {
1147
    return await new Promise((resolve, reject) => {
1148
      const fsNativePath = typeof p === `string` ? npath.fromPortablePath(p) : p;
1149
      if (opts) {
1150
        this.realFs.writeFile(fsNativePath, content, opts, this.makeCallback(resolve, reject));
1151
      } else {
1152
        this.realFs.writeFile(fsNativePath, content, this.makeCallback(resolve, reject));
1153
      }
1154
    });
1155
  }
1156
  writeFileSync(p, content, opts) {
1157
    const fsNativePath = typeof p === `string` ? npath.fromPortablePath(p) : p;
1158
    if (opts) {
1159
      this.realFs.writeFileSync(fsNativePath, content, opts);
1160
    } else {
1161
      this.realFs.writeFileSync(fsNativePath, content);
1162
    }
1163
  }
1164
  async unlinkPromise(p) {
1165
    return await new Promise((resolve, reject) => {
1166
      this.realFs.unlink(npath.fromPortablePath(p), this.makeCallback(resolve, reject));
1167
    });
1168
  }
1169
  unlinkSync(p) {
1170
    return this.realFs.unlinkSync(npath.fromPortablePath(p));
1171
  }
1172
  async utimesPromise(p, atime, mtime) {
1173
    return await new Promise((resolve, reject) => {
1174
      this.realFs.utimes(npath.fromPortablePath(p), atime, mtime, this.makeCallback(resolve, reject));
1175
    });
1176
  }
1177
  utimesSync(p, atime, mtime) {
1178
    this.realFs.utimesSync(npath.fromPortablePath(p), atime, mtime);
1179
  }
1180
  async lutimesPromise(p, atime, mtime) {
1181
    return await new Promise((resolve, reject) => {
1182
      this.realFs.lutimes(npath.fromPortablePath(p), atime, mtime, this.makeCallback(resolve, reject));
1183
    });
1184
  }
1185
  lutimesSync(p, atime, mtime) {
1186
    this.realFs.lutimesSync(npath.fromPortablePath(p), atime, mtime);
1187
  }
1188
  async mkdirPromise(p, opts) {
1189
    return await new Promise((resolve, reject) => {
1190
      this.realFs.mkdir(npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject));
1191
    });
1192
  }
1193
  mkdirSync(p, opts) {
1194
    return this.realFs.mkdirSync(npath.fromPortablePath(p), opts);
1195
  }
1196
  async rmdirPromise(p, opts) {
1197
    return await new Promise((resolve, reject) => {
1198
      if (opts) {
1199
        this.realFs.rmdir(npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject));
1200
      } else {
1201
        this.realFs.rmdir(npath.fromPortablePath(p), this.makeCallback(resolve, reject));
1202
      }
1203
    });
1204
  }
1205
  rmdirSync(p, opts) {
1206
    return this.realFs.rmdirSync(npath.fromPortablePath(p), opts);
1207
  }
1208
  async linkPromise(existingP, newP) {
1209
    return await new Promise((resolve, reject) => {
1210
      this.realFs.link(npath.fromPortablePath(existingP), npath.fromPortablePath(newP), this.makeCallback(resolve, reject));
1211
    });
1212
  }
1213
  linkSync(existingP, newP) {
1214
    return this.realFs.linkSync(npath.fromPortablePath(existingP), npath.fromPortablePath(newP));
1215
  }
1216
  async symlinkPromise(target, p, type) {
1217
    return await new Promise((resolve, reject) => {
1218
      this.realFs.symlink(npath.fromPortablePath(target.replace(/\/+$/, ``)), npath.fromPortablePath(p), type, this.makeCallback(resolve, reject));
1219
    });
1220
  }
1221
  symlinkSync(target, p, type) {
1222
    return this.realFs.symlinkSync(npath.fromPortablePath(target.replace(/\/+$/, ``)), npath.fromPortablePath(p), type);
1223
  }
1224
  async readFilePromise(p, encoding) {
1225
    return await new Promise((resolve, reject) => {
1226
      const fsNativePath = typeof p === `string` ? npath.fromPortablePath(p) : p;
1227
      this.realFs.readFile(fsNativePath, encoding, this.makeCallback(resolve, reject));
1228
    });
1229
  }
1230
  readFileSync(p, encoding) {
1231
    const fsNativePath = typeof p === `string` ? npath.fromPortablePath(p) : p;
1232
    return this.realFs.readFileSync(fsNativePath, encoding);
1233
  }
1234
  async readdirPromise(p, opts) {
1235
    return await new Promise((resolve, reject) => {
1236
      if (opts) {
1237
        if (opts.recursive && process.platform === `win32`) {
1238
          if (opts.withFileTypes) {
1239
            this.realFs.readdir(npath.fromPortablePath(p), opts, this.makeCallback((results) => resolve(results.map(direntToPortable)), reject));
1240
          } else {
1241
            this.realFs.readdir(npath.fromPortablePath(p), opts, this.makeCallback((results) => resolve(results.map(npath.toPortablePath)), reject));
1242
          }
1243
        } else {
1244
          this.realFs.readdir(npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject));
1245
        }
1246
      } else {
1247
        this.realFs.readdir(npath.fromPortablePath(p), this.makeCallback(resolve, reject));
1248
      }
1249
    });
1250
  }
1251
  readdirSync(p, opts) {
1252
    if (opts) {
1253
      if (opts.recursive && process.platform === `win32`) {
1254
        if (opts.withFileTypes) {
1255
          return this.realFs.readdirSync(npath.fromPortablePath(p), opts).map(direntToPortable);
1256
        } else {
1257
          return this.realFs.readdirSync(npath.fromPortablePath(p), opts).map(npath.toPortablePath);
1258
        }
1259
      } else {
1260
        return this.realFs.readdirSync(npath.fromPortablePath(p), opts);
1261
      }
1262
    } else {
1263
      return this.realFs.readdirSync(npath.fromPortablePath(p));
1264
    }
1265
  }
1266
  async readlinkPromise(p) {
1267
    return await new Promise((resolve, reject) => {
1268
      this.realFs.readlink(npath.fromPortablePath(p), this.makeCallback(resolve, reject));
1269
    }).then((path) => {
1270
      return npath.toPortablePath(path);
1271
    });
1272
  }
1273
  readlinkSync(p) {
1274
    return npath.toPortablePath(this.realFs.readlinkSync(npath.fromPortablePath(p)));
1275
  }
1276
  async truncatePromise(p, len) {
1277
    return await new Promise((resolve, reject) => {
1278
      this.realFs.truncate(npath.fromPortablePath(p), len, this.makeCallback(resolve, reject));
1279
    });
1280
  }
1281
  truncateSync(p, len) {
1282
    return this.realFs.truncateSync(npath.fromPortablePath(p), len);
1283
  }
1284
  async ftruncatePromise(fd, len) {
1285
    return await new Promise((resolve, reject) => {
1286
      this.realFs.ftruncate(fd, len, this.makeCallback(resolve, reject));
1287
    });
1288
  }
1289
  ftruncateSync(fd, len) {
1290
    return this.realFs.ftruncateSync(fd, len);
1291
  }
1292
  watch(p, a, b) {
1293
    return this.realFs.watch(
1294
      npath.fromPortablePath(p),
1295
      a,
1296
      b
1297
    );
1298
  }
1299
  watchFile(p, a, b) {
1300
    return this.realFs.watchFile(
1301
      npath.fromPortablePath(p),
1302
      a,
1303
      b
1304
    );
1305
  }
1306
  unwatchFile(p, cb) {
1307
    return this.realFs.unwatchFile(npath.fromPortablePath(p), cb);
1308
  }
1309
  makeCallback(resolve, reject) {
1310
    return (err, result) => {
1311
      if (err) {
1312
        reject(err);
1313
      } else {
1314
        resolve(result);
1315
      }
1316
    };
1317
  }
1318
}
1319

1320
const NUMBER_REGEXP = /^[0-9]+$/;
1321
const VIRTUAL_REGEXP = /^(\/(?:[^/]+\/)*?(?:\$\$virtual|__virtual__))((?:\/((?:[^/]+-)?[a-f0-9]+)(?:\/([^/]+))?)?((?:\/.*)?))$/;
1322
const VALID_COMPONENT = /^([^/]+-)?[a-f0-9]+$/;
1323
class VirtualFS extends ProxiedFS {
1324
  constructor({ baseFs = new NodeFS() } = {}) {
1325
    super(ppath);
1326
    this.baseFs = baseFs;
1327
  }
1328
  static makeVirtualPath(base, component, to) {
1329
    if (ppath.basename(base) !== `__virtual__`)
1330
      throw new Error(`Assertion failed: Virtual folders must be named "__virtual__"`);
1331
    if (!ppath.basename(component).match(VALID_COMPONENT))
1332
      throw new Error(`Assertion failed: Virtual components must be ended by an hexadecimal hash`);
1333
    const target = ppath.relative(ppath.dirname(base), to);
1334
    const segments = target.split(`/`);
1335
    let depth = 0;
1336
    while (depth < segments.length && segments[depth] === `..`)
1337
      depth += 1;
1338
    const finalSegments = segments.slice(depth);
1339
    const fullVirtualPath = ppath.join(base, component, String(depth), ...finalSegments);
1340
    return fullVirtualPath;
1341
  }
1342
  static resolveVirtual(p) {
1343
    const match = p.match(VIRTUAL_REGEXP);
1344
    if (!match || !match[3] && match[5])
1345
      return p;
1346
    const target = ppath.dirname(match[1]);
1347
    if (!match[3] || !match[4])
1348
      return target;
1349
    const isnum = NUMBER_REGEXP.test(match[4]);
1350
    if (!isnum)
1351
      return p;
1352
    const depth = Number(match[4]);
1353
    const backstep = `../`.repeat(depth);
1354
    const subpath = match[5] || `.`;
1355
    return VirtualFS.resolveVirtual(ppath.join(target, backstep, subpath));
1356
  }
1357
  getExtractHint(hints) {
1358
    return this.baseFs.getExtractHint(hints);
1359
  }
1360
  getRealPath() {
1361
    return this.baseFs.getRealPath();
1362
  }
1363
  realpathSync(p) {
1364
    const match = p.match(VIRTUAL_REGEXP);
1365
    if (!match)
1366
      return this.baseFs.realpathSync(p);
1367
    if (!match[5])
1368
      return p;
1369
    const realpath = this.baseFs.realpathSync(this.mapToBase(p));
1370
    return VirtualFS.makeVirtualPath(match[1], match[3], realpath);
1371
  }
1372
  async realpathPromise(p) {
1373
    const match = p.match(VIRTUAL_REGEXP);
1374
    if (!match)
1375
      return await this.baseFs.realpathPromise(p);
1376
    if (!match[5])
1377
      return p;
1378
    const realpath = await this.baseFs.realpathPromise(this.mapToBase(p));
1379
    return VirtualFS.makeVirtualPath(match[1], match[3], realpath);
1380
  }
1381
  mapToBase(p) {
1382
    if (p === ``)
1383
      return p;
1384
    if (this.pathUtils.isAbsolute(p))
1385
      return VirtualFS.resolveVirtual(p);
1386
    const resolvedRoot = VirtualFS.resolveVirtual(this.baseFs.resolve(PortablePath.dot));
1387
    const resolvedP = VirtualFS.resolveVirtual(this.baseFs.resolve(p));
1388
    return ppath.relative(resolvedRoot, resolvedP) || PortablePath.dot;
1389
  }
1390
  mapFromBase(p) {
1391
    return p;
1392
  }
1393
}
1394

1395
const [major, minor] = process.versions.node.split(`.`).map((value) => parseInt(value, 10));
1396
const WATCH_MODE_MESSAGE_USES_ARRAYS = major > 19 || major === 19 && minor >= 2 || major === 18 && minor >= 13;
1397
const HAS_LAZY_LOADED_TRANSLATORS = major === 20 && minor < 6 || major === 19 && minor >= 3;
1398

1399
function readPackageScope(checkPath) {
1400
  const rootSeparatorIndex = checkPath.indexOf(npath.sep);
1401
  let separatorIndex;
1402
  do {
1403
    separatorIndex = checkPath.lastIndexOf(npath.sep);
1404
    checkPath = checkPath.slice(0, separatorIndex);
1405
    if (checkPath.endsWith(`${npath.sep}node_modules`))
1406
      return false;
1407
    const pjson = readPackage(checkPath + npath.sep);
1408
    if (pjson) {
1409
      return {
1410
        data: pjson,
1411
        path: checkPath
1412
      };
1413
    }
1414
  } while (separatorIndex > rootSeparatorIndex);
1415
  return false;
1416
}
1417
function readPackage(requestPath) {
1418
  const jsonPath = npath.resolve(requestPath, `package.json`);
1419
  if (!fs.existsSync(jsonPath))
1420
    return null;
1421
  return JSON.parse(fs.readFileSync(jsonPath, `utf8`));
1422
}
1423

1424
async function tryReadFile$1(path2) {
1425
  try {
1426
    return await fs.promises.readFile(path2, `utf8`);
1427
  } catch (error) {
1428
    if (error.code === `ENOENT`)
1429
      return null;
1430
    throw error;
1431
  }
1432
}
1433
function tryParseURL(str, base) {
1434
  try {
1435
    return new URL$1(str, base);
1436
  } catch {
1437
    return null;
1438
  }
1439
}
1440
let entrypointPath = null;
1441
function setEntrypointPath(file) {
1442
  entrypointPath = file;
1443
}
1444
function getFileFormat(filepath) {
1445
  const ext = path.extname(filepath);
1446
  switch (ext) {
1447
    case `.mjs`: {
1448
      return `module`;
1449
    }
1450
    case `.cjs`: {
1451
      return `commonjs`;
1452
    }
1453
    case `.wasm`: {
1454
      throw new Error(
1455
        `Unknown file extension ".wasm" for ${filepath}`
1456
      );
1457
    }
1458
    case `.json`: {
1459
      return `json`;
1460
    }
1461
    case `.js`: {
1462
      const pkg = readPackageScope(filepath);
1463
      if (!pkg)
1464
        return `commonjs`;
1465
      return pkg.data.type ?? `commonjs`;
1466
    }
1467
    default: {
1468
      if (entrypointPath !== filepath)
1469
        return null;
1470
      const pkg = readPackageScope(filepath);
1471
      if (!pkg)
1472
        return `commonjs`;
1473
      if (pkg.data.type === `module`)
1474
        return null;
1475
      return pkg.data.type ?? `commonjs`;
1476
    }
1477
  }
1478
}
1479

1480
async function load$1(urlString, context, nextLoad) {
1481
  const url = tryParseURL(urlString);
1482
  if (url?.protocol !== `file:`)
1483
    return nextLoad(urlString, context, nextLoad);
1484
  const filePath = fileURLToPath(url);
1485
  const format = getFileFormat(filePath);
1486
  if (!format)
1487
    return nextLoad(urlString, context, nextLoad);
1488
  if (format === `json` && context.importAssertions?.type !== `json`) {
1489
    const err = new TypeError(`[ERR_IMPORT_ASSERTION_TYPE_MISSING]: Module "${urlString}" needs an import assertion of type "json"`);
1490
    err.code = `ERR_IMPORT_ASSERTION_TYPE_MISSING`;
1491
    throw err;
1492
  }
1493
  if (process.env.WATCH_REPORT_DEPENDENCIES && process.send) {
1494
    const pathToSend = pathToFileURL(
1495
      npath.fromPortablePath(
1496
        VirtualFS.resolveVirtual(npath.toPortablePath(filePath))
1497
      )
1498
    ).href;
1499
    process.send({
1500
      "watch:import": WATCH_MODE_MESSAGE_USES_ARRAYS ? [pathToSend] : pathToSend
1501
    });
1502
  }
1503
  return {
1504
    format,
1505
    source: format === `commonjs` ? void 0 : await fs.promises.readFile(filePath, `utf8`),
1506
    shortCircuit: true
1507
  };
1508
}
1509

1510
const ArrayIsArray = Array.isArray;
1511
const JSONStringify = JSON.stringify;
1512
const ObjectGetOwnPropertyNames = Object.getOwnPropertyNames;
1513
const ObjectPrototypeHasOwnProperty = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);
1514
const RegExpPrototypeExec = (obj, string) => RegExp.prototype.exec.call(obj, string);
1515
const RegExpPrototypeSymbolReplace = (obj, ...rest) => RegExp.prototype[Symbol.replace].apply(obj, rest);
1516
const StringPrototypeEndsWith = (str, ...rest) => String.prototype.endsWith.apply(str, rest);
1517
const StringPrototypeIncludes = (str, ...rest) => String.prototype.includes.apply(str, rest);
1518
const StringPrototypeLastIndexOf = (str, ...rest) => String.prototype.lastIndexOf.apply(str, rest);
1519
const StringPrototypeIndexOf = (str, ...rest) => String.prototype.indexOf.apply(str, rest);
1520
const StringPrototypeReplace = (str, ...rest) => String.prototype.replace.apply(str, rest);
1521
const StringPrototypeSlice = (str, ...rest) => String.prototype.slice.apply(str, rest);
1522
const StringPrototypeStartsWith = (str, ...rest) => String.prototype.startsWith.apply(str, rest);
1523
const SafeMap = Map;
1524
const JSONParse = JSON.parse;
1525

1526
function createErrorType(code, messageCreator, errorType) {
1527
  return class extends errorType {
1528
    constructor(...args) {
1529
      super(messageCreator(...args));
1530
      this.code = code;
1531
      this.name = `${errorType.name} [${code}]`;
1532
    }
1533
  };
1534
}
1535
const ERR_PACKAGE_IMPORT_NOT_DEFINED = createErrorType(
1536
  `ERR_PACKAGE_IMPORT_NOT_DEFINED`,
1537
  (specifier, packagePath, base) => {
1538
    return `Package import specifier "${specifier}" is not defined${packagePath ? ` in package ${packagePath}package.json` : ``} imported from ${base}`;
1539
  },
1540
  TypeError
1541
);
1542
const ERR_INVALID_MODULE_SPECIFIER = createErrorType(
1543
  `ERR_INVALID_MODULE_SPECIFIER`,
1544
  (request, reason, base = void 0) => {
1545
    return `Invalid module "${request}" ${reason}${base ? ` imported from ${base}` : ``}`;
1546
  },
1547
  TypeError
1548
);
1549
const ERR_INVALID_PACKAGE_TARGET = createErrorType(
1550
  `ERR_INVALID_PACKAGE_TARGET`,
1551
  (pkgPath, key, target, isImport = false, base = void 0) => {
1552
    const relError = typeof target === `string` && !isImport && target.length && !StringPrototypeStartsWith(target, `./`);
1553
    if (key === `.`) {
1554
      assert(isImport === false);
1555
      return `Invalid "exports" main target ${JSONStringify(target)} defined in the package config ${pkgPath}package.json${base ? ` imported from ${base}` : ``}${relError ? `; targets must start with "./"` : ``}`;
1556
    }
1557
    return `Invalid "${isImport ? `imports` : `exports`}" target ${JSONStringify(
1558
      target
1559
    )} defined for '${key}' in the package config ${pkgPath}package.json${base ? ` imported from ${base}` : ``}${relError ? `; targets must start with "./"` : ``}`;
1560
  },
1561
  Error
1562
);
1563
const ERR_INVALID_PACKAGE_CONFIG = createErrorType(
1564
  `ERR_INVALID_PACKAGE_CONFIG`,
1565
  (path, base, message) => {
1566
    return `Invalid package config ${path}${base ? ` while importing ${base}` : ``}${message ? `. ${message}` : ``}`;
1567
  },
1568
  Error
1569
);
1570

1571
function filterOwnProperties(source, keys) {
1572
  const filtered = /* @__PURE__ */ Object.create(null);
1573
  for (let i = 0; i < keys.length; i++) {
1574
    const key = keys[i];
1575
    if (ObjectPrototypeHasOwnProperty(source, key)) {
1576
      filtered[key] = source[key];
1577
    }
1578
  }
1579
  return filtered;
1580
}
1581

1582
const packageJSONCache = new SafeMap();
1583
function getPackageConfig(path, specifier, base, readFileSyncFn) {
1584
  const existing = packageJSONCache.get(path);
1585
  if (existing !== void 0) {
1586
    return existing;
1587
  }
1588
  const source = readFileSyncFn(path);
1589
  if (source === void 0) {
1590
    const packageConfig2 = {
1591
      pjsonPath: path,
1592
      exists: false,
1593
      main: void 0,
1594
      name: void 0,
1595
      type: "none",
1596
      exports: void 0,
1597
      imports: void 0
1598
    };
1599
    packageJSONCache.set(path, packageConfig2);
1600
    return packageConfig2;
1601
  }
1602
  let packageJSON;
1603
  try {
1604
    packageJSON = JSONParse(source);
1605
  } catch (error) {
1606
    throw new ERR_INVALID_PACKAGE_CONFIG(
1607
      path,
1608
      (base ? `"${specifier}" from ` : "") + fileURLToPath(base || specifier),
1609
      error.message
1610
    );
1611
  }
1612
  let { imports, main, name, type } = filterOwnProperties(packageJSON, [
1613
    "imports",
1614
    "main",
1615
    "name",
1616
    "type"
1617
  ]);
1618
  const exports = ObjectPrototypeHasOwnProperty(packageJSON, "exports") ? packageJSON.exports : void 0;
1619
  if (typeof imports !== "object" || imports === null) {
1620
    imports = void 0;
1621
  }
1622
  if (typeof main !== "string") {
1623
    main = void 0;
1624
  }
1625
  if (typeof name !== "string") {
1626
    name = void 0;
1627
  }
1628
  if (type !== "module" && type !== "commonjs") {
1629
    type = "none";
1630
  }
1631
  const packageConfig = {
1632
    pjsonPath: path,
1633
    exists: true,
1634
    main,
1635
    name,
1636
    type,
1637
    exports,
1638
    imports
1639
  };
1640
  packageJSONCache.set(path, packageConfig);
1641
  return packageConfig;
1642
}
1643
function getPackageScopeConfig(resolved, readFileSyncFn) {
1644
  let packageJSONUrl = new URL("./package.json", resolved);
1645
  while (true) {
1646
    const packageJSONPath2 = packageJSONUrl.pathname;
1647
    if (StringPrototypeEndsWith(packageJSONPath2, "node_modules/package.json")) {
1648
      break;
1649
    }
1650
    const packageConfig2 = getPackageConfig(
1651
      fileURLToPath(packageJSONUrl),
1652
      resolved,
1653
      void 0,
1654
      readFileSyncFn
1655
    );
1656
    if (packageConfig2.exists) {
1657
      return packageConfig2;
1658
    }
1659
    const lastPackageJSONUrl = packageJSONUrl;
1660
    packageJSONUrl = new URL("../package.json", packageJSONUrl);
1661
    if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) {
1662
      break;
1663
    }
1664
  }
1665
  const packageJSONPath = fileURLToPath(packageJSONUrl);
1666
  const packageConfig = {
1667
    pjsonPath: packageJSONPath,
1668
    exists: false,
1669
    main: void 0,
1670
    name: void 0,
1671
    type: "none",
1672
    exports: void 0,
1673
    imports: void 0
1674
  };
1675
  packageJSONCache.set(packageJSONPath, packageConfig);
1676
  return packageConfig;
1677
}
1678

1679
/**
1680
  @license
1681
  Copyright Node.js contributors. All rights reserved.
1682

1683
  Permission is hereby granted, free of charge, to any person obtaining a copy
1684
  of this software and associated documentation files (the "Software"), to
1685
  deal in the Software without restriction, including without limitation the
1686
  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
1687
  sell copies of the Software, and to permit persons to whom the Software is
1688
  furnished to do so, subject to the following conditions:
1689

1690
  The above copyright notice and this permission notice shall be included in
1691
  all copies or substantial portions of the Software.
1692

1693
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1694
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1695
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1696
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1697
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
1698
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
1699
  IN THE SOFTWARE.
1700
*/
1701
function throwImportNotDefined(specifier, packageJSONUrl, base) {
1702
  throw new ERR_PACKAGE_IMPORT_NOT_DEFINED(
1703
    specifier,
1704
    packageJSONUrl && fileURLToPath(new URL(".", packageJSONUrl)),
1705
    fileURLToPath(base)
1706
  );
1707
}
1708
function throwInvalidSubpath(subpath, packageJSONUrl, internal, base) {
1709
  const reason = `request is not a valid subpath for the "${internal ? "imports" : "exports"}" resolution of ${fileURLToPath(packageJSONUrl)}`;
1710
  throw new ERR_INVALID_MODULE_SPECIFIER(
1711
    subpath,
1712
    reason,
1713
    base && fileURLToPath(base)
1714
  );
1715
}
1716
function throwInvalidPackageTarget(subpath, target, packageJSONUrl, internal, base) {
1717
  if (typeof target === "object" && target !== null) {
1718
    target = JSONStringify(target, null, "");
1719
  } else {
1720
    target = `${target}`;
1721
  }
1722
  throw new ERR_INVALID_PACKAGE_TARGET(
1723
    fileURLToPath(new URL(".", packageJSONUrl)),
1724
    subpath,
1725
    target,
1726
    internal,
1727
    base && fileURLToPath(base)
1728
  );
1729
}
1730
const invalidSegmentRegEx = /(^|\\|\/)((\.|%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;
1731
const patternRegEx = /\*/g;
1732
function resolvePackageTargetString(target, subpath, match, packageJSONUrl, base, pattern, internal, conditions) {
1733
  if (subpath !== "" && !pattern && target[target.length - 1] !== "/")
1734
    throwInvalidPackageTarget(match, target, packageJSONUrl, internal, base);
1735
  if (!StringPrototypeStartsWith(target, "./")) {
1736
    if (internal && !StringPrototypeStartsWith(target, "../") && !StringPrototypeStartsWith(target, "/")) {
1737
      let isURL = false;
1738
      try {
1739
        new URL(target);
1740
        isURL = true;
1741
      } catch {
1742
      }
1743
      if (!isURL) {
1744
        const exportTarget = pattern ? RegExpPrototypeSymbolReplace(patternRegEx, target, () => subpath) : target + subpath;
1745
        return exportTarget;
1746
      }
1747
    }
1748
    throwInvalidPackageTarget(match, target, packageJSONUrl, internal, base);
1749
  }
1750
  if (RegExpPrototypeExec(
1751
    invalidSegmentRegEx,
1752
    StringPrototypeSlice(target, 2)
1753
  ) !== null)
1754
    throwInvalidPackageTarget(match, target, packageJSONUrl, internal, base);
1755
  const resolved = new URL(target, packageJSONUrl);
1756
  const resolvedPath = resolved.pathname;
1757
  const packagePath = new URL(".", packageJSONUrl).pathname;
1758
  if (!StringPrototypeStartsWith(resolvedPath, packagePath))
1759
    throwInvalidPackageTarget(match, target, packageJSONUrl, internal, base);
1760
  if (subpath === "")
1761
    return resolved;
1762
  if (RegExpPrototypeExec(invalidSegmentRegEx, subpath) !== null) {
1763
    const request = pattern ? StringPrototypeReplace(match, "*", () => subpath) : match + subpath;
1764
    throwInvalidSubpath(request, packageJSONUrl, internal, base);
1765
  }
1766
  if (pattern) {
1767
    return new URL(
1768
      RegExpPrototypeSymbolReplace(patternRegEx, resolved.href, () => subpath)
1769
    );
1770
  }
1771
  return new URL(subpath, resolved);
1772
}
1773
function isArrayIndex(key) {
1774
  const keyNum = +key;
1775
  if (`${keyNum}` !== key)
1776
    return false;
1777
  return keyNum >= 0 && keyNum < 4294967295;
1778
}
1779
function resolvePackageTarget(packageJSONUrl, target, subpath, packageSubpath, base, pattern, internal, conditions) {
1780
  if (typeof target === "string") {
1781
    return resolvePackageTargetString(
1782
      target,
1783
      subpath,
1784
      packageSubpath,
1785
      packageJSONUrl,
1786
      base,
1787
      pattern,
1788
      internal);
1789
  } else if (ArrayIsArray(target)) {
1790
    if (target.length === 0) {
1791
      return null;
1792
    }
1793
    let lastException;
1794
    for (let i = 0; i < target.length; i++) {
1795
      const targetItem = target[i];
1796
      let resolveResult;
1797
      try {
1798
        resolveResult = resolvePackageTarget(
1799
          packageJSONUrl,
1800
          targetItem,
1801
          subpath,
1802
          packageSubpath,
1803
          base,
1804
          pattern,
1805
          internal,
1806
          conditions
1807
        );
1808
      } catch (e) {
1809
        lastException = e;
1810
        if (e.code === "ERR_INVALID_PACKAGE_TARGET") {
1811
          continue;
1812
        }
1813
        throw e;
1814
      }
1815
      if (resolveResult === void 0) {
1816
        continue;
1817
      }
1818
      if (resolveResult === null) {
1819
        lastException = null;
1820
        continue;
1821
      }
1822
      return resolveResult;
1823
    }
1824
    if (lastException === void 0 || lastException === null)
1825
      return lastException;
1826
    throw lastException;
1827
  } else if (typeof target === "object" && target !== null) {
1828
    const keys = ObjectGetOwnPropertyNames(target);
1829
    for (let i = 0; i < keys.length; i++) {
1830
      const key = keys[i];
1831
      if (isArrayIndex(key)) {
1832
        throw new ERR_INVALID_PACKAGE_CONFIG(
1833
          fileURLToPath(packageJSONUrl),
1834
          base,
1835
          '"exports" cannot contain numeric property keys.'
1836
        );
1837
      }
1838
    }
1839
    for (let i = 0; i < keys.length; i++) {
1840
      const key = keys[i];
1841
      if (key === "default" || conditions.has(key)) {
1842
        const conditionalTarget = target[key];
1843
        const resolveResult = resolvePackageTarget(
1844
          packageJSONUrl,
1845
          conditionalTarget,
1846
          subpath,
1847
          packageSubpath,
1848
          base,
1849
          pattern,
1850
          internal,
1851
          conditions
1852
        );
1853
        if (resolveResult === void 0)
1854
          continue;
1855
        return resolveResult;
1856
      }
1857
    }
1858
    return void 0;
1859
  } else if (target === null) {
1860
    return null;
1861
  }
1862
  throwInvalidPackageTarget(
1863
    packageSubpath,
1864
    target,
1865
    packageJSONUrl,
1866
    internal,
1867
    base
1868
  );
1869
}
1870
function patternKeyCompare(a, b) {
1871
  const aPatternIndex = StringPrototypeIndexOf(a, "*");
1872
  const bPatternIndex = StringPrototypeIndexOf(b, "*");
1873
  const baseLenA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
1874
  const baseLenB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
1875
  if (baseLenA > baseLenB)
1876
    return -1;
1877
  if (baseLenB > baseLenA)
1878
    return 1;
1879
  if (aPatternIndex === -1)
1880
    return 1;
1881
  if (bPatternIndex === -1)
1882
    return -1;
1883
  if (a.length > b.length)
1884
    return -1;
1885
  if (b.length > a.length)
1886
    return 1;
1887
  return 0;
1888
}
1889
function packageImportsResolve({ name, base, conditions, readFileSyncFn }) {
1890
  if (name === "#" || StringPrototypeStartsWith(name, "#/") || StringPrototypeEndsWith(name, "/")) {
1891
    const reason = "is not a valid internal imports specifier name";
1892
    throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, fileURLToPath(base));
1893
  }
1894
  let packageJSONUrl;
1895
  const packageConfig = getPackageScopeConfig(base, readFileSyncFn);
1896
  if (packageConfig.exists) {
1897
    packageJSONUrl = pathToFileURL(packageConfig.pjsonPath);
1898
    const imports = packageConfig.imports;
1899
    if (imports) {
1900
      if (ObjectPrototypeHasOwnProperty(imports, name) && !StringPrototypeIncludes(name, "*")) {
1901
        const resolveResult = resolvePackageTarget(
1902
          packageJSONUrl,
1903
          imports[name],
1904
          "",
1905
          name,
1906
          base,
1907
          false,
1908
          true,
1909
          conditions
1910
        );
1911
        if (resolveResult != null) {
1912
          return resolveResult;
1913
        }
1914
      } else {
1915
        let bestMatch = "";
1916
        let bestMatchSubpath;
1917
        const keys = ObjectGetOwnPropertyNames(imports);
1918
        for (let i = 0; i < keys.length; i++) {
1919
          const key = keys[i];
1920
          const patternIndex = StringPrototypeIndexOf(key, "*");
1921
          if (patternIndex !== -1 && StringPrototypeStartsWith(
1922
            name,
1923
            StringPrototypeSlice(key, 0, patternIndex)
1924
          )) {
1925
            const patternTrailer = StringPrototypeSlice(key, patternIndex + 1);
1926
            if (name.length >= key.length && StringPrototypeEndsWith(name, patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && StringPrototypeLastIndexOf(key, "*") === patternIndex) {
1927
              bestMatch = key;
1928
              bestMatchSubpath = StringPrototypeSlice(
1929
                name,
1930
                patternIndex,
1931
                name.length - patternTrailer.length
1932
              );
1933
            }
1934
          }
1935
        }
1936
        if (bestMatch) {
1937
          const target = imports[bestMatch];
1938
          const resolveResult = resolvePackageTarget(
1939
            packageJSONUrl,
1940
            target,
1941
            bestMatchSubpath,
1942
            bestMatch,
1943
            base,
1944
            true,
1945
            true,
1946
            conditions
1947
          );
1948
          if (resolveResult != null) {
1949
            return resolveResult;
1950
          }
1951
        }
1952
      }
1953
    }
1954
  }
1955
  throwImportNotDefined(name, packageJSONUrl, base);
1956
}
1957

1958
const pathRegExp = /^(?![a-zA-Z]:[\\/]|\\\\|\.{0,2}(?:\/|$))((?:node:)?(?:@[^/]+\/)?[^/]+)\/*(.*|)$/;
1959
const isRelativeRegexp = /^\.{0,2}\//;
1960
function tryReadFile(filePath) {
1961
  try {
1962
    return fs.readFileSync(filePath, `utf8`);
1963
  } catch (err) {
1964
    if (err.code === `ENOENT`)
1965
      return void 0;
1966
    throw err;
1967
  }
1968
}
1969
async function resolvePrivateRequest(specifier, issuer, context, nextResolve) {
1970
  const resolved = packageImportsResolve({
1971
    name: specifier,
1972
    base: pathToFileURL(issuer),
1973
    conditions: new Set(context.conditions),
1974
    readFileSyncFn: tryReadFile
1975
  });
1976
  if (resolved instanceof URL) {
1977
    return { url: resolved.href, shortCircuit: true };
1978
  } else {
1979
    if (resolved.startsWith(`#`))
1980
      throw new Error(`Mapping from one private import to another isn't allowed`);
1981
    return resolve$1(resolved, context, nextResolve);
1982
  }
1983
}
1984
async function resolve$1(originalSpecifier, context, nextResolve) {
1985
  const { findPnpApi } = moduleExports;
1986
  if (!findPnpApi || isBuiltin(originalSpecifier))
1987
    return nextResolve(originalSpecifier, context, nextResolve);
1988
  let specifier = originalSpecifier;
1989
  const url = tryParseURL(specifier, isRelativeRegexp.test(specifier) ? context.parentURL : void 0);
1990
  if (url) {
1991
    if (url.protocol !== `file:`)
1992
      return nextResolve(originalSpecifier, context, nextResolve);
1993
    specifier = fileURLToPath(url);
1994
  }
1995
  const { parentURL, conditions = [] } = context;
1996
  const issuer = parentURL && tryParseURL(parentURL)?.protocol === `file:` ? fileURLToPath(parentURL) : process.cwd();
1997
  const pnpapi = findPnpApi(issuer) ?? (url ? findPnpApi(specifier) : null);
1998
  if (!pnpapi)
1999
    return nextResolve(originalSpecifier, context, nextResolve);
2000
  if (specifier.startsWith(`#`))
2001
    return resolvePrivateRequest(specifier, issuer, context, nextResolve);
2002
  const dependencyNameMatch = specifier.match(pathRegExp);
2003
  let allowLegacyResolve = false;
2004
  if (dependencyNameMatch) {
2005
    const [, dependencyName, subPath] = dependencyNameMatch;
2006
    if (subPath === `` && dependencyName !== `pnpapi`) {
2007
      const resolved = pnpapi.resolveToUnqualified(`${dependencyName}/package.json`, issuer);
2008
      if (resolved) {
2009
        const content = await tryReadFile$1(resolved);
2010
        if (content) {
2011
          const pkg = JSON.parse(content);
2012
          allowLegacyResolve = pkg.exports == null;
2013
        }
2014
      }
2015
    }
2016
  }
2017
  let result;
2018
  try {
2019
    result = pnpapi.resolveRequest(specifier, issuer, {
2020
      conditions: new Set(conditions),
2021
      extensions: allowLegacyResolve ? void 0 : []
2022
    });
2023
  } catch (err) {
2024
    if (err instanceof Error && `code` in err && err.code === `MODULE_NOT_FOUND`)
2025
      err.code = `ERR_MODULE_NOT_FOUND`;
2026
    throw err;
2027
  }
2028
  if (!result)
2029
    throw new Error(`Resolving '${specifier}' from '${issuer}' failed`);
2030
  const resultURL = pathToFileURL(result);
2031
  if (url) {
2032
    resultURL.search = url.search;
2033
    resultURL.hash = url.hash;
2034
  }
2035
  if (!parentURL)
2036
    setEntrypointPath(fileURLToPath(resultURL));
2037
  return {
2038
    url: resultURL.href,
2039
    shortCircuit: true
2040
  };
2041
}
2042

2043
if (!HAS_LAZY_LOADED_TRANSLATORS) {
2044
  const binding = process.binding(`fs`);
2045
  const originalReadFile = binding.readFileUtf8 || binding.readFileSync;
2046
  if (originalReadFile) {
2047
    binding[originalReadFile.name] = function(...args) {
2048
      try {
2049
        return fs.readFileSync(args[0], {
2050
          encoding: `utf8`,
2051
          flag: args[1]
2052
        });
2053
      } catch {
2054
      }
2055
      return originalReadFile.apply(this, args);
2056
    };
2057
  } else {
2058
    const binding2 = process.binding(`fs`);
2059
    const originalfstat = binding2.fstat;
2060
    const ZIP_MASK = 4278190080;
2061
    const ZIP_MAGIC = 704643072;
2062
    binding2.fstat = function(...args) {
2063
      const [fd, useBigint, req] = args;
2064
      if ((fd & ZIP_MASK) === ZIP_MAGIC && useBigint === false && req === void 0) {
2065
        try {
2066
          const stats = fs.fstatSync(fd);
2067
          return new Float64Array([
2068
            stats.dev,
2069
            stats.mode,
2070
            stats.nlink,
2071
            stats.uid,
2072
            stats.gid,
2073
            stats.rdev,
2074
            stats.blksize,
2075
            stats.ino,
2076
            stats.size,
2077
            stats.blocks
2078
          ]);
2079
        } catch {
2080
        }
2081
      }
2082
      return originalfstat.apply(this, args);
2083
    };
2084
  }
2085
}
2086

2087
const resolve = resolve$1;
2088
const load = load$1;
2089

2090
export { load, resolve };
2091

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.