pack.js 14 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
// A readable tar stream creator
// Technically, this is a transform stream that you write paths into,
// and tar format comes out of.
// The `add()` method is like `write()` but returns this,
// and end() return `this` as well, so you can
// do `new Pack(opt).add('files').add('dir').end().pipe(output)
// You could also do something like:
// streamOfPaths().pipe(new Pack()).pipe(new fs.WriteStream('out.tar'))
import fs from 'fs';
import { WriteEntry, WriteEntrySync, WriteEntryTar, } from './write-entry.js';
export class PackJob {
    path;
    absolute;
    entry;
    stat;
    readdir;
    pending = false;
    ignore = false;
    piped = false;
    constructor(path, absolute) {
        this.path = path || './';
        this.absolute = absolute;
    }
}
import { Minipass } from 'minipass';
import * as zlib from 'minizlib';
import { Yallist } from 'yallist';
import { ReadEntry } from './read-entry.js';
import { warnMethod } from './warn-method.js';
const EOF = Buffer.alloc(1024);
const ONSTAT = Symbol('onStat');
const ENDED = Symbol('ended');
const QUEUE = Symbol('queue');
const CURRENT = Symbol('current');
const PROCESS = Symbol('process');
const PROCESSING = Symbol('processing');
const PROCESSJOB = Symbol('processJob');
const JOBS = Symbol('jobs');
const JOBDONE = Symbol('jobDone');
const ADDFSENTRY = Symbol('addFSEntry');
const ADDTARENTRY = Symbol('addTarEntry');
const STAT = Symbol('stat');
const READDIR = Symbol('readdir');
const ONREADDIR = Symbol('onreaddir');
const PIPE = Symbol('pipe');
const ENTRY = Symbol('entry');
const ENTRYOPT = Symbol('entryOpt');
const WRITEENTRYCLASS = Symbol('writeEntryClass');
const WRITE = Symbol('write');
const ONDRAIN = Symbol('ondrain');
import path from 'path';
import { normalizeWindowsPath } from './normalize-windows-path.js';
export class Pack extends Minipass {
    sync = false;
    opt;
    cwd;
    maxReadSize;
    preservePaths;
    strict;
    noPax;
    prefix;
    linkCache;
    statCache;
    file;
    portable;
    zip;
    readdirCache;
    noDirRecurse;
    follow;
    noMtime;
    mtime;
    filter;
    jobs;
    [WRITEENTRYCLASS];
    onWriteEntry;
    // Note: we actually DO need a linked list here, because we
    // shift() to update the head of the list where we start, but still
    // while that happens, need to know what the next item in the queue
    // will be. Since we do multiple jobs in parallel, it's not as simple
    // as just an Array.shift(), since that would lose the information about
    // the next job in the list. We could add a .next field on the PackJob
    // class, but then we'd have to be tracking the tail of the queue the
    // whole time, and Yallist just does that for us anyway.
    [QUEUE];
    [JOBS] = 0;
    [PROCESSING] = false;
    [ENDED] = false;
    constructor(opt = {}) {
        super();
        this.opt = opt;
        this.file = opt.file || '';
        this.cwd = opt.cwd || process.cwd();
        this.maxReadSize = opt.maxReadSize;
        this.preservePaths = !!opt.preservePaths;
        this.strict = !!opt.strict;
        this.noPax = !!opt.noPax;
        this.prefix = normalizeWindowsPath(opt.prefix || '');
        this.linkCache = opt.linkCache || new Map();
        this.statCache = opt.statCache || new Map();
        this.readdirCache = opt.readdirCache || new Map();
        this.onWriteEntry = opt.onWriteEntry;
        this[WRITEENTRYCLASS] = WriteEntry;
        if (typeof opt.onwarn === 'function') {
            this.on('warn', opt.onwarn);
        }
        this.portable = !!opt.portable;
        if (opt.gzip || opt.brotli || opt.zstd) {
            if ((opt.gzip ? 1 : 0) + (opt.brotli ? 1 : 0) + (opt.zstd ? 1 : 0) >
                1) {
                throw new TypeError('gzip, brotli, zstd are mutually exclusive');
            }
            if (opt.gzip) {
                if (typeof opt.gzip !== 'object') {
                    opt.gzip = {};
                }
                if (this.portable) {
                    opt.gzip.portable = true;
                }
                this.zip = new zlib.Gzip(opt.gzip);
            }
            if (opt.brotli) {
                if (typeof opt.brotli !== 'object') {
                    opt.brotli = {};
                }
                this.zip = new zlib.BrotliCompress(opt.brotli);
            }
            if (opt.zstd) {
                if (typeof opt.zstd !== 'object') {
                    opt.zstd = {};
                }
                this.zip = new zlib.ZstdCompress(opt.zstd);
            }
            /* c8 ignore next */
            if (!this.zip)
                throw new Error('impossible');
            const zip = this.zip;
            zip.on('data', chunk => super.write(chunk));
            zip.on('end', () => super.end());
            zip.on('drain', () => this[ONDRAIN]());
            this.on('resume', () => zip.resume());
        }
        else {
            this.on('drain', this[ONDRAIN]);
        }
        this.noDirRecurse = !!opt.noDirRecurse;
        this.follow = !!opt.follow;
        this.noMtime = !!opt.noMtime;
        if (opt.mtime)
            this.mtime = opt.mtime;
        this.filter =
            typeof opt.filter === 'function' ? opt.filter : () => true;
        this[QUEUE] = new Yallist();
        this[JOBS] = 0;
        this.jobs = Number(opt.jobs) || 4;
        this[PROCESSING] = false;
        this[ENDED] = false;
    }
    [WRITE](chunk) {
        return super.write(chunk);
    }
    add(path) {
        this.write(path);
        return this;
    }
    end(path, encoding, cb) {
        /* c8 ignore start */
        if (typeof path === 'function') {
            cb = path;
            path = undefined;
        }
        if (typeof encoding === 'function') {
            cb = encoding;
            encoding = undefined;
        }
        /* c8 ignore stop */
        if (path) {
            this.add(path);
        }
        this[ENDED] = true;
        this[PROCESS]();
        /* c8 ignore next */
        if (cb)
            cb();
        return this;
    }
    write(path) {
        if (this[ENDED]) {
            throw new Error('write after end');
        }
        if (path instanceof ReadEntry) {
            this[ADDTARENTRY](path);
        }
        else {
            this[ADDFSENTRY](path);
        }
        return this.flowing;
    }
    [ADDTARENTRY](p) {
        const absolute = normalizeWindowsPath(path.resolve(this.cwd, p.path));
        // in this case, we don't have to wait for the stat
        if (!this.filter(p.path, p)) {
            p.resume();
        }
        else {
            const job = new PackJob(p.path, absolute);
            job.entry = new WriteEntryTar(p, this[ENTRYOPT](job));
            job.entry.on('end', () => this[JOBDONE](job));
            this[JOBS] += 1;
            this[QUEUE].push(job);
        }
        this[PROCESS]();
    }
    [ADDFSENTRY](p) {
        const absolute = normalizeWindowsPath(path.resolve(this.cwd, p));
        this[QUEUE].push(new PackJob(p, absolute));
        this[PROCESS]();
    }
    [STAT](job) {
        job.pending = true;
        this[JOBS] += 1;
        const stat = this.follow ? 'stat' : 'lstat';
        fs[stat](job.absolute, (er, stat) => {
            job.pending = false;
            this[JOBS] -= 1;
            if (er) {
                this.emit('error', er);
            }
            else {
                this[ONSTAT](job, stat);
            }
        });
    }
    [ONSTAT](job, stat) {
        this.statCache.set(job.absolute, stat);
        job.stat = stat;
        // now we have the stat, we can filter it.
        if (!this.filter(job.path, stat)) {
            job.ignore = true;
        }
        else if (stat.isFile() &&
            stat.nlink > 1 &&
            job === this[CURRENT] &&
            !this.linkCache.get(`${stat.dev}:${stat.ino}`) &&
            !this.sync) {
            // if it's not filtered, and it's a new File entry,
            // jump the queue in case any pending Link entries are about
            // to try to link to it. This prevents a hardlink from coming ahead
            // of its target in the archive.
            this[PROCESSJOB](job);
        }
        this[PROCESS]();
    }
    [READDIR](job) {
        job.pending = true;
        this[JOBS] += 1;
        fs.readdir(job.absolute, (er, entries) => {
            job.pending = false;
            this[JOBS] -= 1;
            if (er) {
                return this.emit('error', er);
            }
            this[ONREADDIR](job, entries);
        });
    }
    [ONREADDIR](job, entries) {
        this.readdirCache.set(job.absolute, entries);
        job.readdir = entries;
        this[PROCESS]();
    }
    [PROCESS]() {
        if (this[PROCESSING]) {
            return;
        }
        this[PROCESSING] = true;
        for (let w = this[QUEUE].head; !!w && this[JOBS] < this.jobs; w = w.next) {
            this[PROCESSJOB](w.value);
            if (w.value.ignore) {
                const p = w.next;
                this[QUEUE].removeNode(w);
                w.next = p;
            }
        }
        this[PROCESSING] = false;
        if (this[ENDED] && this[QUEUE].length === 0 && this[JOBS] === 0) {
            if (this.zip) {
                this.zip.end(EOF);
            }
            else {
                super.write(EOF);
                super.end();
            }
        }
    }
    get [CURRENT]() {
        return this[QUEUE] && this[QUEUE].head && this[QUEUE].head.value;
    }
    [JOBDONE](_job) {
        this[QUEUE].shift();
        this[JOBS] -= 1;
        this[PROCESS]();
    }
    [PROCESSJOB](job) {
        if (job.pending) {
            return;
        }
        if (job.entry) {
            if (job === this[CURRENT] && !job.piped) {
                this[PIPE](job);
            }
            return;
        }
        if (!job.stat) {
            const sc = this.statCache.get(job.absolute);
            if (sc) {
                this[ONSTAT](job, sc);
            }
            else {
                this[STAT](job);
            }
        }
        if (!job.stat) {
            return;
        }
        // filtered out!
        if (job.ignore) {
            return;
        }
        if (!this.noDirRecurse && job.stat.isDirectory() && !job.readdir) {
            const rc = this.readdirCache.get(job.absolute);
            if (rc) {
                this[ONREADDIR](job, rc);
            }
            else {
                this[READDIR](job);
            }
            if (!job.readdir) {
                return;
            }
        }
        // we know it doesn't have an entry, because that got checked above
        job.entry = this[ENTRY](job);
        if (!job.entry) {
            job.ignore = true;
            return;
        }
        if (job === this[CURRENT] && !job.piped) {
            this[PIPE](job);
        }
    }
    [ENTRYOPT](job) {
        return {
            onwarn: (code, msg, data) => this.warn(code, msg, data),
            noPax: this.noPax,
            cwd: this.cwd,
            absolute: job.absolute,
            preservePaths: this.preservePaths,
            maxReadSize: this.maxReadSize,
            strict: this.strict,
            portable: this.portable,
            linkCache: this.linkCache,
            statCache: this.statCache,
            noMtime: this.noMtime,
            mtime: this.mtime,
            prefix: this.prefix,
            onWriteEntry: this.onWriteEntry,
        };
    }
    [ENTRY](job) {
        this[JOBS] += 1;
        try {
            const e = new this[WRITEENTRYCLASS](job.path, this[ENTRYOPT](job));
            return e
                .on('end', () => this[JOBDONE](job))
                .on('error', er => this.emit('error', er));
        }
        catch (er) {
            this.emit('error', er);
        }
    }
    [ONDRAIN]() {
        if (this[CURRENT] && this[CURRENT].entry) {
            this[CURRENT].entry.resume();
        }
    }
    // like .pipe() but using super, because our write() is special
    [PIPE](job) {
        job.piped = true;
        if (job.readdir) {
            job.readdir.forEach(entry => {
                const p = job.path;
                const base = p === './' ? '' : p.replace(/\/*$/, '/');
                this[ADDFSENTRY](base + entry);
            });
        }
        const source = job.entry;
        const zip = this.zip;
        /* c8 ignore start */
        if (!source)
            throw new Error('cannot pipe without source');
        /* c8 ignore stop */
        if (zip) {
            source.on('data', chunk => {
                if (!zip.write(chunk)) {
                    source.pause();
                }
            });
        }
        else {
            source.on('data', chunk => {
                if (!super.write(chunk)) {
                    source.pause();
                }
            });
        }
    }
    pause() {
        if (this.zip) {
            this.zip.pause();
        }
        return super.pause();
    }
    warn(code, message, data = {}) {
        warnMethod(this, code, message, data);
    }
}
export class PackSync extends Pack {
    sync = true;
    constructor(opt) {
        super(opt);
        this[WRITEENTRYCLASS] = WriteEntrySync;
    }
    // pause/resume are no-ops in sync streams.
    pause() { }
    resume() { }
    [STAT](job) {
        const stat = this.follow ? 'statSync' : 'lstatSync';
        this[ONSTAT](job, fs[stat](job.absolute));
    }
    [READDIR](job) {
        this[ONREADDIR](job, fs.readdirSync(job.absolute));
    }
    // gotta get it all in this tick
    [PIPE](job) {
        const source = job.entry;
        const zip = this.zip;
        if (job.readdir) {
            job.readdir.forEach(entry => {
                const p = job.path;
                const base = p === './' ? '' : p.replace(/\/*$/, '/');
                this[ADDFSENTRY](base + entry);
            });
        }
        /* c8 ignore start */
        if (!source)
            throw new Error('Cannot pipe without source');
        /* c8 ignore stop */
        if (zip) {
            source.on('data', chunk => {
                zip.write(chunk);
            });
        }
        else {
            source.on('data', chunk => {
                super[WRITE](chunk);
            });
        }
    }
}
//# sourceMappingURL=pack.js.map