Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes15kdownloads
unpack.js957 linesDownload Raw Back to commonjs
1"use strict";
2// the PEND/UNPEND stuff tracks whether we're ready to emit end/close yet.
3// but the path reservations are required to avoid race conditions where
4// parallelized unpack ops may mess with one another, due to dependencies
5// (like a Link depending on its target) or destructive operations (like
6// clobbering an fs object to create one of a different type.)
7var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8    if (k2 === undefined) k2 = k;
9    var desc = Object.getOwnPropertyDescriptor(m, k);
10    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11      desc = { enumerable: true, get: function() { return m[k]; } };
12    }
13    Object.defineProperty(o, k2, desc);
14}) : (function(o, m, k, k2) {
15    if (k2 === undefined) k2 = k;
16    o[k2] = m[k];
17}));
18var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
19    Object.defineProperty(o, "default", { enumerable: true, value: v });
20}) : function(o, v) {
21    o["default"] = v;
22});
23var __importStar = (this && this.__importStar) || (function () {
24    var ownKeys = function(o) {
25        ownKeys = Object.getOwnPropertyNames || function (o) {
26            var ar = [];
27            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
28            return ar;
29        };
30        return ownKeys(o);
31    };
32    return function (mod) {
33        if (mod && mod.__esModule) return mod;
34        var result = {};
35        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
36        __setModuleDefault(result, mod);
37        return result;
38    };
39})();
40var __importDefault = (this && this.__importDefault) || function (mod) {
41    return (mod && mod.__esModule) ? mod : { "default": mod };
42};
43Object.defineProperty(exports, "__esModule", { value: true });
44exports.UnpackSync = exports.Unpack = void 0;
45const fsm = __importStar(require("@isaacs/fs-minipass"));
46const node_assert_1 = __importDefault(require("node:assert"));
47const node_crypto_1 = require("node:crypto");
48const node_fs_1 = __importDefault(require("node:fs"));
49const node_path_1 = __importDefault(require("node:path"));
50const get_write_flag_js_1 = require("./get-write-flag.js");
51const mkdir_js_1 = require("./mkdir.js");
52const normalize_windows_path_js_1 = require("./normalize-windows-path.js");
53const parse_js_1 = require("./parse.js");
54const strip_absolute_path_js_1 = require("./strip-absolute-path.js");
55const wc = __importStar(require("./winchars.js"));
56const path_reservations_js_1 = require("./path-reservations.js");
57const symlink_error_js_1 = require("./symlink-error.js");
58const process_umask_js_1 = require("./process-umask.js");
59const ONENTRY = Symbol('onEntry');
60const CHECKFS = Symbol('checkFs');
61const CHECKFS2 = Symbol('checkFs2');
62const ISREUSABLE = Symbol('isReusable');
63const MAKEFS = Symbol('makeFs');
64const FILE = Symbol('file');
65const DIRECTORY = Symbol('directory');
66const LINK = Symbol('link');
67const SYMLINK = Symbol('symlink');
68const HARDLINK = Symbol('hardlink');
69const ENSURE_NO_SYMLINK = Symbol('ensureNoSymlink');
70const UNSUPPORTED = Symbol('unsupported');
71const CHECKPATH = Symbol('checkPath');
72const STRIPABSOLUTEPATH = Symbol('stripAbsolutePath');
73const MKDIR = Symbol('mkdir');
74const ONERROR = Symbol('onError');
75const PENDING = Symbol('pending');
76const PEND = Symbol('pend');
77const UNPEND = Symbol('unpend');
78const ENDED = Symbol('ended');
79const MAYBECLOSE = Symbol('maybeClose');
80const SKIP = Symbol('skip');
81const DOCHOWN = Symbol('doChown');
82const UID = Symbol('uid');
83const GID = Symbol('gid');
84const CHECKED_CWD = Symbol('checkedCwd');
85const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform;
86const isWindows = platform === 'win32';
87const DEFAULT_MAX_DEPTH = 1024;
88// Unlinks on Windows are not atomic.
89//
90// This means that if you have a file entry, followed by another
91// file entry with an identical name, and you cannot re-use the file
92// (because it's a hardlink, or because unlink:true is set, or it's
93// Windows, which does not have useful nlink values), then the unlink
94// will be committed to the disk AFTER the new file has been written
95// over the old one, deleting the new file.
96//
97// To work around this, on Windows systems, we rename the file and then
98// delete the renamed file.  It's a sloppy kludge, but frankly, I do not
99// know of a better way to do this, given windows' non-atomic unlink
100// semantics.
101//
102// See: https://github.com/npm/node-tar/issues/183
103/* c8 ignore start */
104const unlinkFile = (path, cb) => {
105    if (!isWindows) {
106        return node_fs_1.default.unlink(path, cb);
107    }
108    const name = path + '.DELETE.' + (0, node_crypto_1.randomBytes)(16).toString('hex');
109    node_fs_1.default.rename(path, name, er => {
110        if (er) {
111            return cb(er);
112        }
113        node_fs_1.default.unlink(name, cb);
114    });
115};
116/* c8 ignore stop */
117/* c8 ignore start */
118const unlinkFileSync = (path) => {
119    if (!isWindows) {
120        return node_fs_1.default.unlinkSync(path);
121    }
122    const name = path + '.DELETE.' + (0, node_crypto_1.randomBytes)(16).toString('hex');
123    node_fs_1.default.renameSync(path, name);
124    node_fs_1.default.unlinkSync(name);
125};
126/* c8 ignore stop */
127// this.gid, entry.gid, this.processUid
128const uint32 = (a, b, c) => a !== undefined && a === a >>> 0 ? a
129    : b !== undefined && b === b >>> 0 ? b
130        : c;
131class Unpack extends parse_js_1.Parser {
132    [ENDED] = false;
133    [CHECKED_CWD] = false;
134    [PENDING] = 0;
135    reservations = new path_reservations_js_1.PathReservations();
136    transform;
137    writable = true;
138    readable = false;
139    uid;
140    gid;
141    setOwner;
142    preserveOwner;
143    processGid;
144    processUid;
145    maxDepth;
146    forceChown;
147    win32;
148    newer;
149    keep;
150    noMtime;
151    preservePaths;
152    unlink;
153    cwd;
154    strip;
155    processUmask;
156    umask;
157    dmode;
158    fmode;
159    chmod;
160    constructor(opt = {}) {
161        opt.ondone = () => {
162            this[ENDED] = true;
163            this[MAYBECLOSE]();
164        };
165        super(opt);
166        this.transform = opt.transform;
167        this.chmod = !!opt.chmod;
168        if (typeof opt.uid === 'number' || typeof opt.gid === 'number') {
169            // need both or neither
170            if (typeof opt.uid !== 'number' ||
171                typeof opt.gid !== 'number') {
172                throw new TypeError('cannot set owner without number uid and gid');
173            }
174            if (opt.preserveOwner) {
175                throw new TypeError('cannot preserve owner in archive and also set owner explicitly');
176            }
177            this.uid = opt.uid;
178            this.gid = opt.gid;
179            this.setOwner = true;
180        }
181        else {
182            this.uid = undefined;
183            this.gid = undefined;
184            this.setOwner = false;
185        }
186        // default true for root
187        if (opt.preserveOwner === undefined &&
188            typeof opt.uid !== 'number') {
189            this.preserveOwner = !!(process.getuid && process.getuid() === 0);
190        }
191        else {
192            this.preserveOwner = !!opt.preserveOwner;
193        }
194        this.processUid =
195            (this.preserveOwner || this.setOwner) && process.getuid ?
196                process.getuid()
197                : undefined;
198        this.processGid =
199            (this.preserveOwner || this.setOwner) && process.getgid ?
200                process.getgid()
201                : undefined;
202        // prevent excessively deep nesting of subfolders
203        // set to `Infinity` to remove this restriction
204        this.maxDepth =
205            typeof opt.maxDepth === 'number' ?
206                opt.maxDepth
207                : DEFAULT_MAX_DEPTH;
208        // mostly just for testing, but useful in some cases.
209        // Forcibly trigger a chown on every entry, no matter what
210        this.forceChown = opt.forceChown === true;
211        // turn ><?| in filenames into 0xf000-higher encoded forms
212        this.win32 = !!opt.win32 || isWindows;
213        // do not unpack over files that are newer than what's in the archive
214        this.newer = !!opt.newer;
215        // do not unpack over ANY files
216        this.keep = !!opt.keep;
217        // do not set mtime/atime of extracted entries
218        this.noMtime = !!opt.noMtime;
219        // allow .., absolute path entries, and unpacking through symlinks
220        // without this, warn and skip .., relativize absolutes, and error
221        // on symlinks in extraction path
222        this.preservePaths = !!opt.preservePaths;
223        // unlink files and links before writing. This breaks existing hard
224        // links, and removes symlink directories rather than erroring
225        this.unlink = !!opt.unlink;
226        this.cwd = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.resolve(opt.cwd || process.cwd()));
227        this.strip = Number(opt.strip) || 0;
228        // if we're not chmodding, then we don't need the process umask
229        this.processUmask =
230            !this.chmod ? 0
231                : typeof opt.processUmask === 'number' ? opt.processUmask
232                    : (0, process_umask_js_1.umask)();
233        this.umask =
234            typeof opt.umask === 'number' ? opt.umask : this.processUmask;
235        // default mode for dirs created as parents
236        this.dmode = opt.dmode || 0o0777 & ~this.umask;
237        this.fmode = opt.fmode || 0o0666 & ~this.umask;
238        this.on('entry', entry => this[ONENTRY](entry));
239    }
240    // a bad or damaged archive is a warning for Parser, but an error
241    // when extracting.  Mark those errors as unrecoverable, because
242    // the Unpack contract cannot be met.
243    warn(code, msg, data = {}) {
244        if (code === 'TAR_BAD_ARCHIVE' || code === 'TAR_ABORT') {
245            data.recoverable = false;
246        }
247        return super.warn(code, msg, data);
248    }
249    [MAYBECLOSE]() {
250        if (this[ENDED] && this[PENDING] === 0) {
251            this.emit('prefinish');
252            this.emit('finish');
253            this.emit('end');
254        }
255    }
256    // return false if we need to skip this file
257    // return true if the field was successfully sanitized
258    [STRIPABSOLUTEPATH](entry, field) {
259        const p = entry[field];
260        const { type } = entry;
261        if (!p || this.preservePaths)
262            return true;
263        // strip off the root
264        const [root, stripped] = (0, strip_absolute_path_js_1.stripAbsolutePath)(p);
265        const parts = stripped.replace(/\\/g, '/').split('/');
266        if (parts.includes('..') ||
267            /* c8 ignore next */
268            (isWindows && /^[a-z]:\.\.$/i.test(parts[0] ?? ''))) {
269            // For linkpath, check if the resolved path escapes cwd rather than
270            // just rejecting any path with '..' - relative symlinks like
271            // '../sibling/file' are valid if they resolve within the cwd.
272            // For paths, they just simply may not ever use .. at all.
273            if (field === 'path' || type === 'Link') {
274                this.warn('TAR_ENTRY_ERROR', `${field} contains '..'`, {
275                    entry,
276                    [field]: p,
277                });
278                // not ok!
279                return false;
280            }
281            else {
282                // Resolve linkpath relative to the entry's directory.
283                // `path.posix` is safe to use because we're operating on
284                // tar paths, not a filesystem.
285                const entryDir = node_path_1.default.posix.dirname(entry.path);
286                const resolved = node_path_1.default.posix.normalize(node_path_1.default.posix.join(entryDir, parts.join('/')));
287                // If the resolved path escapes (starts with ..), reject it
288                if (resolved.startsWith('../') || resolved === '..') {
289                    this.warn('TAR_ENTRY_ERROR', `${field} escapes extraction directory`, {
290                        entry,
291                        [field]: p,
292                    });
293                    return false;
294                }
295            }
296        }
297        if (root) {
298            // ok, but triggers warning about stripping root
299            entry[field] = String(stripped);
300            this.warn('TAR_ENTRY_INFO', `stripping ${root} from absolute ${field}`, {
301                entry,
302                [field]: p,
303            });
304        }
305        return true;
306    }
307    // no IO, just string checking for absolute indicators
308    [CHECKPATH](entry) {
309        const p = (0, normalize_windows_path_js_1.normalizeWindowsPath)(entry.path);
310        const parts = p.split('/');
311        if (this.strip) {
312            if (parts.length < this.strip) {
313                return false;
314            }
315            if (entry.type === 'Link') {
316                const linkparts = (0, normalize_windows_path_js_1.normalizeWindowsPath)(String(entry.linkpath)).split('/');
317                if (linkparts.length >= this.strip) {
318                    entry.linkpath = linkparts.slice(this.strip).join('/');
319                }
320                else {
321                    return false;
322                }
323            }
324            parts.splice(0, this.strip);
325            entry.path = parts.join('/');
326        }
327        if (isFinite(this.maxDepth) && parts.length > this.maxDepth) {
328            this.warn('TAR_ENTRY_ERROR', 'path excessively deep', {
329                entry,
330                path: p,
331                depth: parts.length,
332                maxDepth: this.maxDepth,
333            });
334            return false;
335        }
336        if (!this[STRIPABSOLUTEPATH](entry, 'path') ||
337            !this[STRIPABSOLUTEPATH](entry, 'linkpath')) {
338            return false;
339        }
340        if (node_path_1.default.isAbsolute(entry.path)) {
341            entry.absolute = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.resolve(entry.path));
342        }
343        else {
344            entry.absolute = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.resolve(this.cwd, entry.path));
345        }
346        // if we somehow ended up with a path that escapes the cwd, and we are
347        // not in preservePaths mode, then something is fishy!  This should have
348        // been prevented above, so ignore this for coverage.
349        /* c8 ignore start - defense in depth */
350        if (!this.preservePaths &&
351            typeof entry.absolute === 'string' &&
352            entry.absolute.indexOf(this.cwd + '/') !== 0 &&
353            entry.absolute !== this.cwd) {
354            this.warn('TAR_ENTRY_ERROR', 'path escaped extraction target', {
355                entry,
356                path: (0, normalize_windows_path_js_1.normalizeWindowsPath)(entry.path),
357                resolvedPath: entry.absolute,
358                cwd: this.cwd,
359            });
360            return false;
361        }
362        /* c8 ignore stop */
363        // an archive can set properties on the extraction directory, but it
364        // may not replace the cwd with a different kind of thing entirely.
365        if (entry.absolute === this.cwd &&
366            entry.type !== 'Directory' &&
367            entry.type !== 'GNUDumpDir') {
368            return false;
369        }
370        // only encode : chars that aren't drive letter indicators
371        if (this.win32) {
372            const { root: aRoot } = node_path_1.default.win32.parse(String(entry.absolute));
373            entry.absolute =
374                aRoot + wc.encode(String(entry.absolute).slice(aRoot.length));
375            const { root: pRoot } = node_path_1.default.win32.parse(entry.path);
376            entry.path = pRoot + wc.encode(entry.path.slice(pRoot.length));
377        }
378        return true;
379    }
380    [ONENTRY](entry) {
381        if (!this[CHECKPATH](entry)) {
382            return entry.resume();
383        }
384        node_assert_1.default.equal(typeof entry.absolute, 'string');
385        switch (entry.type) {
386            case 'Directory':
387            case 'GNUDumpDir':
388                if (entry.mode) {
389                    entry.mode = entry.mode | 0o700;
390                }
391            // eslint-disable-next-line no-fallthrough
392            case 'File':
393            case 'OldFile':
394            case 'ContiguousFile':
395            case 'Link':
396            case 'SymbolicLink':
397                return this[CHECKFS](entry);
398            case 'CharacterDevice':
399            case 'BlockDevice':
400            case 'FIFO':
401            default:
402                return this[UNSUPPORTED](entry);
403        }
404    }
405    [ONERROR](er, entry) {
406        // Cwd has to exist, or else nothing works. That's serious.
407        // Other errors are warnings, which raise the error in strict
408        // mode, but otherwise continue on.
409        if (er.name === 'CwdError') {
410            this.emit('error', er);
411        }
412        else {
413            this.warn('TAR_ENTRY_ERROR', er, { entry });
414            this[UNPEND]();
415            entry.resume();
416        }
417    }
418    [MKDIR](dir, mode, cb) {
419        (0, mkdir_js_1.mkdir)((0, normalize_windows_path_js_1.normalizeWindowsPath)(dir), {
420            uid: this.uid,
421            gid: this.gid,
422            processUid: this.processUid,
423            processGid: this.processGid,
424            umask: this.processUmask,
425            preserve: this.preservePaths,
426            unlink: this.unlink,
427            cwd: this.cwd,
428            mode: mode,
429        }, cb);
430    }
431    [DOCHOWN](entry) {
432        // in preserve owner mode, chown if the entry doesn't match process
433        // in set owner mode, chown if setting doesn't match process
434        return (this.forceChown ||
435            (this.preserveOwner &&
436                ((typeof entry.uid === 'number' &&
437                    entry.uid !== this.processUid) ||
438                    (typeof entry.gid === 'number' &&
439                        entry.gid !== this.processGid))) ||
440            (typeof this.uid === 'number' &&
441                this.uid !== this.processUid) ||
442            (typeof this.gid === 'number' && this.gid !== this.processGid));
443    }
444    [UID](entry) {
445        return uint32(this.uid, entry.uid, this.processUid);
446    }
447    [GID](entry) {
448        return uint32(this.gid, entry.gid, this.processGid);
449    }
450    [FILE](entry, fullyDone) {
451        const mode = typeof entry.mode === 'number' ?
452            entry.mode & 0o7777
453            : this.fmode;
454        const stream = new fsm.WriteStream(String(entry.absolute), {
455            // slight lie, but it can be numeric flags
456            flags: (0, get_write_flag_js_1.getWriteFlag)(entry.size),
457            mode: mode,
458            autoClose: false,
459        });
460        stream.on('error', (er) => {
461            if (stream.fd) {
462                node_fs_1.default.close(stream.fd, () => { });
463            }
464            // flush all the data out so that we aren't left hanging
465            // if the error wasn't actually fatal.  otherwise the parse
466            // is blocked, and we never proceed.
467            stream.write = () => true;
468            this[ONERROR](er, entry);
469            fullyDone();
470        });
471        let actions = 1;
472        const done = (er) => {
473            if (er) {
474                /* c8 ignore start - we should always have a fd by now */
475                if (stream.fd) {
476                    node_fs_1.default.close(stream.fd, () => { });
477                }
478                /* c8 ignore stop */
479                this[ONERROR](er, entry);
480                fullyDone();
481                return;
482            }
483            if (--actions === 0) {
484                if (stream.fd !== undefined) {
485                    node_fs_1.default.close(stream.fd, er => {
486                        if (er) {
487                            this[ONERROR](er, entry);
488                        }
489                        else {
490                            this[UNPEND]();
491                        }
492                        fullyDone();
493                    });
494                }
495            }
496        };
497        stream.on('finish', () => {
498            // if futimes fails, try utimes
499            // if utimes fails, fail with the original error
500            // same for fchown/chown
501            const abs = String(entry.absolute);
502            const fd = stream.fd;
503            if (typeof fd === 'number' && entry.mtime && !this.noMtime) {
504                actions++;
505                const atime = entry.atime || new Date();
506                const mtime = entry.mtime;
507                node_fs_1.default.futimes(fd, atime, mtime, er => er ?
508                    node_fs_1.default.utimes(abs, atime, mtime, er2 => done(er2 && er))
509                    : done());
510            }
511            if (typeof fd === 'number' && this[DOCHOWN](entry)) {
512                actions++;
513                const uid = this[UID](entry);
514                const gid = this[GID](entry);
515                if (typeof uid === 'number' && typeof gid === 'number') {
516                    node_fs_1.default.fchown(fd, uid, gid, er => er ?
517                        node_fs_1.default.chown(abs, uid, gid, er2 => done(er2 && er))
518                        : done());
519                }
520            }
521            done();
522        });
523        const tx = this.transform ? this.transform(entry) || entry : entry;
524        if (tx !== entry) {
525            tx.on('error', (er) => {
526                this[ONERROR](er, entry);
527                fullyDone();
528            });
529            entry.pipe(tx);
530        }
531        tx.pipe(stream);
532    }
533    [DIRECTORY](entry, fullyDone) {
534        const mode = typeof entry.mode === 'number' ?
535            entry.mode & 0o7777
536            : this.dmode;
537        this[MKDIR](String(entry.absolute), mode, er => {
538            if (er) {
539                this[ONERROR](er, entry);
540                fullyDone();
541                return;
542            }
543            let actions = 1;
544            const done = () => {
545                if (--actions === 0) {
546                    fullyDone();
547                    this[UNPEND]();
548                    entry.resume();
549                }
550            };
551            if (entry.mtime && !this.noMtime) {
552                actions++;
553                node_fs_1.default.utimes(String(entry.absolute), entry.atime || new Date(), entry.mtime, done);
554            }
555            if (this[DOCHOWN](entry)) {
556                actions++;
557                node_fs_1.default.chown(String(entry.absolute), Number(this[UID](entry)), Number(this[GID](entry)), done);
558            }
559            done();
560        });
561    }
562    [UNSUPPORTED](entry) {
563        entry.unsupported = true;
564        this.warn('TAR_ENTRY_UNSUPPORTED', `unsupported entry type: ${entry.type}`, { entry });
565        entry.resume();
566    }
567    [SYMLINK](entry, done) {
568        const parts = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.relative(this.cwd, node_path_1.default.resolve(node_path_1.default.dirname(String(entry.absolute)), String(entry.linkpath)))).split('/');
569        this[ENSURE_NO_SYMLINK](entry, this.cwd, parts, () => this[LINK](entry, String(entry.linkpath), 'symlink', done), er => {
570            this[ONERROR](er, entry);
571            done();
572        });
573    }
574    [HARDLINK](entry, done) {
575        const linkpath = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.resolve(this.cwd, String(entry.linkpath)));
576        const parts = (0, normalize_windows_path_js_1.normalizeWindowsPath)(String(entry.linkpath)).split('/');
577        this[ENSURE_NO_SYMLINK](entry, this.cwd, parts, () => this[LINK](entry, linkpath, 'link', done), er => {
578            this[ONERROR](er, entry);
579            done();
580        });
581    }
582    [ENSURE_NO_SYMLINK](entry, cwd, parts, done, onError) {
583        const p = parts.shift();
584        if (this.preservePaths || p === undefined)
585            return done();
586        const t = node_path_1.default.resolve(cwd, p);
587        node_fs_1.default.lstat(t, (er, st) => {
588            if (er)
589                return done();
590            if (st?.isSymbolicLink()) {
591                return onError(new symlink_error_js_1.SymlinkError(t, node_path_1.default.resolve(t, parts.join('/'))));
592            }
593            this[ENSURE_NO_SYMLINK](entry, t, parts, done, onError);
594        });
595    }
596    [PEND]() {
597        this[PENDING]++;
598    }
599    [UNPEND]() {
600        this[PENDING]--;
601        this[MAYBECLOSE]();
602    }
603    [SKIP](entry) {
604        this[UNPEND]();
605        entry.resume();
606    }
607    // Check if we can reuse an existing filesystem entry safely and
608    // overwrite it, rather than unlinking and recreating
609    // Windows doesn't report a useful nlink, so we just never reuse entries
610    [ISREUSABLE](entry, st) {
611        return (entry.type === 'File' &&
612            !this.unlink &&
613            st.isFile() &&
614            st.nlink <= 1 &&
615            !isWindows);
616    }
617    // check if a thing is there, and if so, try to clobber it
618    [CHECKFS](entry) {
619        this[PEND]();
620        const paths = [entry.path];
621        if (entry.linkpath) {
622            paths.push(entry.linkpath);
623        }
624        this.reservations.reserve(paths, done => this[CHECKFS2](entry, done));
625    }
626    [CHECKFS2](entry, fullyDone) {
627        const done = (er) => {
628            fullyDone(er);
629        };
630        const checkCwd = () => {
631            this[MKDIR](this.cwd, this.dmode, er => {
632                if (er) {
633                    this[ONERROR](er, entry);
634                    done();
635                    return;
636                }
637                this[CHECKED_CWD] = true;
638                start();
639            });
640        };
641        const start = () => {
642            if (entry.absolute !== this.cwd) {
643                const parent = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.dirname(String(entry.absolute)));
644                if (parent !== this.cwd) {
645                    return this[MKDIR](parent, this.dmode, er => {
646                        if (er) {
647                            this[ONERROR](er, entry);
648                            done();
649                            return;
650                        }
651                        afterMakeParent();
652                    });
653                }
654            }
655            afterMakeParent();
656        };
657        const afterMakeParent = () => {
658            node_fs_1.default.lstat(String(entry.absolute), (lstatEr, st) => {
659                if (st &&
660                    (this.keep ||
661                        /* c8 ignore next */
662                        (this.newer && st.mtime > (entry.mtime ?? st.mtime)))) {
663                    this[SKIP](entry);
664                    done();
665                    return;
666                }
667                if (lstatEr || this[ISREUSABLE](entry, st)) {
668                    return this[MAKEFS](null, entry, done);
669                }
670                if (st.isDirectory()) {
671                    if (entry.type === 'Directory') {
672                        const needChmod = this.chmod &&
673                            entry.mode &&
674                            (st.mode & 0o7777) !== entry.mode;
675                        const afterChmod = (er) => this[MAKEFS](er ?? null, entry, done);
676                        if (!needChmod) {
677                            return afterChmod();
678                        }
679                        return node_fs_1.default.chmod(String(entry.absolute), Number(entry.mode), afterChmod);
680                    }
681                    // Not a dir entry, have to remove it.
682                    // NB: the only way to end up with an entry that is the cwd
683                    // itself, in such a way that == does not detect, is a
684                    // tricky windows absolute path with UNC or 8.3 parts (and
685                    // preservePaths:true, or else it will have been stripped).
686                    // In that case, the user has opted out of path protections
687                    // explicitly, so if they blow away the cwd, c'est la vie.
688                    if (entry.absolute !== this.cwd) {
689                        return node_fs_1.default.rmdir(String(entry.absolute), (er) => this[MAKEFS](er ?? null, entry, done));
690                    }
691                }
692                // not a dir, and not reusable
693                // don't remove if the cwd, we want that error
694                if (entry.absolute === this.cwd) {
695                    return this[MAKEFS](null, entry, done);
696                }
697                unlinkFile(String(entry.absolute), er => this[MAKEFS](er ?? null, entry, done));
698            });
699        };
700        if (this[CHECKED_CWD]) {
701            start();
702        }
703        else {
704            checkCwd();
705        }
706    }
707    [MAKEFS](er, entry, done) {
708        if (er) {
709            this[ONERROR](er, entry);
710            done();
711            return;
712        }
713        switch (entry.type) {
714            case 'File':
715            case 'OldFile':
716            case 'ContiguousFile':
717                return this[FILE](entry, done);
718            case 'Link':
719                return this[HARDLINK](entry, done);
720            case 'SymbolicLink':
721                return this[SYMLINK](entry, done);
722            case 'Directory':
723            case 'GNUDumpDir':
724                return this[DIRECTORY](entry, done);
725        }
726    }
727    [LINK](entry, linkpath, link, done) {
728        node_fs_1.default[link](linkpath, String(entry.absolute), er => {
729            if (er) {
730                this[ONERROR](er, entry);
731            }
732            else {
733                this[UNPEND]();
734                entry.resume();
735            }
736            done();
737        });
738    }
739}
740exports.Unpack = Unpack;
741const callSync = (fn) => {
742    try {
743        return [null, fn()];
744    }
745    catch (er) {
746        return [er, null];
747    }
748};
749class UnpackSync extends Unpack {
750    sync = true;
751    [MAKEFS](er, entry) {
752        return super[MAKEFS](er, entry, () => { });
753    }
754    [CHECKFS](entry) {
755        if (!this[CHECKED_CWD]) {
756            const er = this[MKDIR](this.cwd, this.dmode);
757            if (er) {
758                return this[ONERROR](er, entry);
759            }
760            this[CHECKED_CWD] = true;
761        }
762        // don't bother to make the parent if the current entry is the cwd,
763        // we've already checked it.
764        if (entry.absolute !== this.cwd) {
765            const parent = (0, normalize_windows_path_js_1.normalizeWindowsPath)(node_path_1.default.dirname(String(entry.absolute)));
766            if (parent !== this.cwd) {
767                const mkParent = this[MKDIR](parent, this.dmode);
768                if (mkParent) {
769                    return this[ONERROR](mkParent, entry);
770                }
771            }
772        }
773        const [lstatEr, st] = callSync(() => node_fs_1.default.lstatSync(String(entry.absolute)));
774        if (st &&
775            (this.keep ||
776                /* c8 ignore next */
777                (this.newer && st.mtime > (entry.mtime ?? st.mtime)))) {
778            return this[SKIP](entry);
779        }
780        if (lstatEr || this[ISREUSABLE](entry, st)) {
781            return this[MAKEFS](null, entry);
782        }
783        if (st.isDirectory()) {
784            if (entry.type === 'Directory') {
785                const needChmod = this.chmod &&
786                    entry.mode &&
787                    (st.mode & 0o7777) !== entry.mode;
788                const [er] = needChmod ?
789                    callSync(() => {
790                        node_fs_1.default.chmodSync(String(entry.absolute), Number(entry.mode));
791                    })
792                    : [];
793                return this[MAKEFS](er, entry);
794            }
795            // not a dir entry, have to remove it
796            const [er] = callSync(() => node_fs_1.default.rmdirSync(String(entry.absolute)));
797            this[MAKEFS](er, entry);
798        }
799        // not a dir, and not reusable.
800        // don't remove if it's the cwd, since we want that error.
801        const [er] = entry.absolute === this.cwd ?
802            []
803            : callSync(() => unlinkFileSync(String(entry.absolute)));
804        this[MAKEFS](er, entry);
805    }
806    [FILE](entry, done) {
807        const mode = typeof entry.mode === 'number' ?
808            entry.mode & 0o7777
809            : this.fmode;
810        const oner = (er) => {
811            let closeError;
812            try {
813                node_fs_1.default.closeSync(fd);
814            }
815            catch (e) {
816                closeError = e;
817            }
818            if (er || closeError) {
819                this[ONERROR](er || closeError, entry);
820            }
821            done();
822        };
823        let fd;
824        try {
825            fd = node_fs_1.default.openSync(String(entry.absolute), (0, get_write_flag_js_1.getWriteFlag)(entry.size), mode);
826            /* c8 ignore start - This is only a problem if the file was successfully
827             * statted, BUT failed to open. Testing this is annoying, and we
828             * already have ample testint for other uses of oner() methods.
829             */
830        }
831        catch (er) {
832            return oner(er);
833        }
834        /* c8 ignore stop */
835        const tx = this.transform ? this.transform(entry) || entry : entry;
836        if (tx !== entry) {
837            tx.on('error', (er) => this[ONERROR](er, entry));
838            entry.pipe(tx);
839        }
840        tx.on('data', (chunk) => {
841            try {
842                node_fs_1.default.writeSync(fd, chunk, 0, chunk.length);
843            }
844            catch (er) {
845                oner(er);
846            }
847        });
848        tx.on('end', () => {
849            let er = null;
850            // try both, falling futimes back to utimes
851            // if either fails, handle the first error
852            if (entry.mtime && !this.noMtime) {
853                const atime = entry.atime || new Date();
854                const mtime = entry.mtime;
855                try {
856                    node_fs_1.default.futimesSync(fd, atime, mtime);
857                }
858                catch (futimeser) {
859                    try {
860                        node_fs_1.default.utimesSync(String(entry.absolute), atime, mtime);
861                    }
862                    catch (utimeser) {
863                        er = futimeser;
864                    }
865                }
866            }
867            if (this[DOCHOWN](entry)) {
868                const uid = this[UID](entry);
869                const gid = this[GID](entry);
870                try {
871                    node_fs_1.default.fchownSync(fd, Number(uid), Number(gid));
872                }
873                catch (fchowner) {
874                    try {
875                        node_fs_1.default.chownSync(String(entry.absolute), Number(uid), Number(gid));
876                    }
877                    catch (chowner) {
878                        er = er || fchowner;
879                    }
880                }
881            }
882            oner(er);
883        });
884    }
885    [DIRECTORY](entry, done) {
886        const mode = typeof entry.mode === 'number' ?
887            entry.mode & 0o7777
888            : this.dmode;
889        const er = this[MKDIR](String(entry.absolute), mode);
890        if (er) {
891            this[ONERROR](er, entry);
892            done();
893            return;
894        }
895        if (entry.mtime && !this.noMtime) {
896            try {
897                node_fs_1.default.utimesSync(String(entry.absolute), entry.atime || new Date(), entry.mtime);
898                /* c8 ignore next */
899            }
900            catch (er) { }
901        }
902        if (this[DOCHOWN](entry)) {
903            try {
904                node_fs_1.default.chownSync(String(entry.absolute), Number(this[UID](entry)), Number(this[GID](entry)));
905            }
906            catch (er) { }
907        }
908        done();
909        entry.resume();
910    }
911    [MKDIR](dir, mode) {
912        try {
913            return (0, mkdir_js_1.mkdirSync)((0, normalize_windows_path_js_1.normalizeWindowsPath)(dir), {
914                uid: this.uid,
915                gid: this.gid,
916                processUid: this.processUid,
917                processGid: this.processGid,
918                umask: this.processUmask,
919                preserve: this.preservePaths,
920                unlink: this.unlink,
921                cwd: this.cwd,
922                mode: mode,
923            });
924        }
925        catch (er) {
926            return er;
927        }
928    }
929    [ENSURE_NO_SYMLINK](_entry, cwd, parts, done, onError) {
930        if (this.preservePaths || !parts.length)
931            return done();
932        let t = cwd;
933        for (const p of parts) {
934            t = node_path_1.default.resolve(t, p);
935            const [er, st] = callSync(() => node_fs_1.default.lstatSync(t));
936            if (er)
937                return done();
938            if (st.isSymbolicLink()) {
939                return onError(new symlink_error_js_1.SymlinkError(t, node_path_1.default.resolve(cwd, parts.join('/'))));
940            }
941        }
942        done();
943    }
944    [LINK](entry, linkpath, link, done) {
945        const linkSync = `${link}Sync`;
946        try {
947            node_fs_1.default[linkSync](linkpath, String(entry.absolute));
948            done();
949            entry.resume();
950        }
951        catch (er) {
952            return this[ONERROR](er, entry);
953        }
954    }
955}
956exports.UnpackSync = UnpackSync;
957//# sourceMappingURL=unpack.js.map
codekingpro/portable-devtools · Team Ai