UNPKG

tar

Version:
398 lines • 13.8 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.entriesSync = exports.entries = exports.TarReaderSync = exports.TarReader = exports.EntryCursor = exports.findCodec = exports.headLength = void 0; const bytes_js_1 = require("./bytes.js"); const header_js_1 = require("./header.js"); const codec_js_1 = require("./codec.js"); const concat_js_1 = require("./concat.js"); const options_js_1 = require("./options.js"); const parser_js_1 = require("./parser.js"); const read_entry_js_1 = require("./read-entry.js"); const read_file_js_1 = require("./read-file.js"); const warn_js_1 = require("./warn.js"); const noop = () => { }; // The number of bytes to read before the choice of a codec. const headLength = (codecs) => Math.max(512, ...codecs.map(c => c.headLength)); exports.headLength = headLength; const isTar = (head) => { try { const header = new header_js_1.Header(head); return header.cksumValid || header.nullBlock; } catch { return false; } }; const findCodec = (codecs, head, file = '') => codecs.find(c => c.detect(head)) ?? (isTar(head) ? undefined : (codecs.find(c => c.extensions?.some(x => file.endsWith(x))))); exports.findCodec = findCodec; const maxRatio = (opt) => typeof opt.maxDecompressionRatio === 'number' ? opt.maxDecompressionRatio : 1000; const abort = (opt, er) => (0, warn_js_1.tarError)(opt, 'TAR_ABORT', er, { recoverable: false }); const ratioError = (opt, ratio, max) => abort(opt, new Error(`max decompression ratio exceeded: ${ratio.toFixed(2)} > ${max}`)); const notCurrent = () => new TypeError('The body of an entry cannot be read after a later entry'); /** * Gets entries and the parts of their bodies from a `Parser`. The * readers use it. It does not read input. */ class EntryCursor { parser; /** The entry that has a body to read now. */ current; /** True after the end of the archive. */ ended = false; constructor(parser) { this.parser = parser; } /** * The next entry that is not ignored. `null` at the end of the * archive. `undefined` if the parser needs more input. The rest of * the body of the entry before it is skipped. */ entry() { this.current = undefined; if (this.ended) return null; for (let ev; (ev = this.parser.next());) { if (ev.type === 'end') { this.ended = true; return null; } if (ev.type === 'entry' && !ev.entry.ignore) { return (this.current = ev.entry); } } } /** * The next part of the body of `entry`. `null` at the end of the * body. `undefined` if the parser needs more input. */ body(entry) { if (entry !== this.current) throw notCurrent(); const ev = this.parser.next(); if (!ev) return undefined; if (ev.type === 'body') return ev.data; this.current = undefined; return null; } } exports.EntryCursor = EntryCursor; // Skip the rest of a body that no consumer reads, if it is after the // input that the parser has, and the source can skip it. The source // must be the input of the reader: decompressed data has no place in // the input. const skipBody = (cursor, source) => { if (cursor.current) return; const n = cursor.parser.bodyRemain; if (n && source[read_file_js_1.SKIP]?.(n)) cursor.parser.skipBody(); }; const toSource = (input) => { if ((0, bytes_js_1.isUint8Array)(input)) return [input].values(); if ((0, bytes_js_1.isArrayBuffer)(input)) return [new Uint8Array(input)].values(); if ((0, bytes_js_1.isBlob)(input)) input = input.stream(); if ((0, bytes_js_1.isReadableStream)(input)) { const reader = input.getReader(); return { next: () => reader.read(), return: () => reader.cancel() }; } return Symbol.asyncIterator in input ? input[Symbol.asyncIterator]() : input[Symbol.iterator](); }; /** * Reads the entries of an archive from async input. It is the * iterator that `entries()` returns. * * Input is read only when the consumer asks for the next entry or * for more of a body. `poll()` and `fill()` do the same work as * `next()`, with no promise for an entry that is in memory. */ class TarReader { parser; #cursor; #opt; #input; #source; // the first bytes of input that is not compressed #head; #filling; #done = false; constructor(input, opt = {}) { opt = (0, options_js_1.ownOptions)(opt); const win32 = opt.platform === 'win32'; this.parser = new parser_js_1.Parser(opt, (header, ex, gex) => new read_entry_js_1.ReadEntry(header, ex, gex, win32, this)); this.#cursor = new EntryCursor(this.parser); this.#opt = opt; this.#input = toSource(input); } /** * The next entry, if it is in memory. `null` at the end of the * archive. `undefined` if more input is needed: then await `fill()` * and call this again. */ poll() { return this.#done ? null : this.#cursor.entry(); } readBody(entry) { return this.#cursor.body(entry); } /** Read one chunk of input, and give it to the parser. */ fill() { return (this.#filling ??= this.#fill()); } async #fill() { try { const source = (this.#source ??= await this.#open(this.#input)); const head = this.#head; this.#head = undefined; if (source === this.#input) skipBody(this.#cursor, source); const res = head ? { value: head, done: false } : await source.next(); if (res.done) this.parser.end(); else this.parser.push(res.value); } finally { this.#filling = undefined; } } // Read the first bytes, and add the decompression if they need it. async #open(input) { const opt = this.#opt; const codecs = [...(opt.codecs ?? []), codec_js_1.gzip]; const need = (0, exports.headLength)(codecs); let head; while (!head || head.length < need) { const res = await input.next(); if (res.done) break; head = head ? (0, concat_js_1.concat)([head, res.value]) : res.value; } const codec = head && (0, exports.findCodec)(codecs, head, opt.file); if (!codec) { this.#head = head; return input; } let compressed = 0; let decompressed = 0; const { readable, writable } = codec.decompress(); const writer = writable.getWriter(); const reader = readable.getReader(); let stopped = false; // Give the input to the codec, as fast as the codec takes it. This // loop holds each promise of the writer, so that a write that // fails after the consumer stops is not an unhandled rejection. const feed = async () => { try { for (;;) { await writer.ready; if (stopped) return; const res = head ? { value: head, done: false } : await input.next(); head = undefined; if (stopped) return; if (res.done) return await writer.close(); compressed += res.value.length; await writer.write(res.value); } } catch (er) { // An error of the input goes to the reader of the output. An // error of the codec is there already. if (!stopped) await writer.abort(er).catch(noop); } }; void feed(); const max = maxRatio(opt); return { next: async () => { const res = await reader.read().catch(er => { throw abort(opt, er); }); if (!res.done) { decompressed += res.value.length; const ratio = decompressed / compressed; if (ratio > max) throw ratioError(opt, ratio, max); } return res; }, return: async () => { stopped = true; await reader.cancel().catch(noop); await writer.abort().catch(noop); await input.return?.(); return { value: undefined, done: true }; }, }; } async next() { try { for (;;) { const entry = this.poll(); if (entry) return { value: entry, done: false }; if (entry === null) break; await this.fill(); } } catch (er) { await this.return(); throw er; } return this.return(); } /** Stop reading, and release the input. */ async return() { if (!this.#done) { this.#done = true; this.#cursor.current = undefined; await (this.#source ?? this.#input).return?.(); } return { value: undefined, done: true }; } [Symbol.asyncIterator]() { return this; } } exports.TarReader = TarReader; /** * Reads the entries of an archive from sync input. It is the * iterator that `entriesSync()` returns. */ class TarReaderSync { parser; #cursor; #opt; #input; #source; // the first bytes of input that is not compressed #head; #done = false; constructor(input, opt = {}) { opt = (0, options_js_1.ownOptions)(opt); const win32 = opt.platform === 'win32'; this.parser = new parser_js_1.Parser(opt, (header, ex, gex) => new read_entry_js_1.ReadEntrySync(header, ex, gex, win32, this)); this.#cursor = new EntryCursor(this.parser); this.#opt = opt; this.#input = (0, bytes_js_1.isUint8Array)(input) ? [input].values() : (0, bytes_js_1.isArrayBuffer)(input) ? [new Uint8Array(input)].values() : input[Symbol.iterator](); } readBody(entry) { for (;;) { const part = this.#cursor.body(entry); if (part !== undefined) return part; this.#fill(); } } #fill() { const source = (this.#source ??= this.#open(this.#input)); const head = this.#head; this.#head = undefined; if (source === this.#input) skipBody(this.#cursor, source); const res = head ? { value: head, done: false } : source.next(); if (res.done) this.parser.end(); else this.parser.push(res.value); } // Read the first bytes. If they are compressed, read and decompress // all the input. #open(input) { const opt = this.#opt; const codecs = [...(opt.codecs ?? []), codec_js_1.gzip]; const need = (0, exports.headLength)(codecs); let head; let res; while ((!head || head.length < need) && !(res = input.next()).done) { head = head ? (0, concat_js_1.concat)([head, res.value]) : res.value; } const codec = head && (0, exports.findCodec)(codecs, head, opt.file); if (!head || !codec) { this.#head = head; return input; } const { decompressSync } = codec; if (!decompressSync) { throw abort(opt, new Error(`the ${codec.name} codec has no decompressSync function`)); } const parts = [head]; while (!(res = input.next()).done) parts.push(res.value); const data = (0, concat_js_1.concat)(parts); const max = maxRatio(opt); let out; try { out = decompressSync(data, { maxOutputLength: data.length * max }); } catch (er) { throw abort(opt, er); } const ratio = out.length / data.length; if (ratio > max) throw ratioError(opt, ratio, max); return [out].values(); } next() { try { for (;;) { const entry = this.#done ? null : this.#cursor.entry(); if (entry) return { value: entry, done: false }; if (entry === null) break; this.#fill(); } } catch (er) { this.return(); throw er; } return this.return(); } /** Stop reading, and release the input. */ return() { if (!this.#done) { this.#done = true; this.#cursor.current = undefined; (this.#source ?? this.#input).return?.(); } return { value: undefined, done: true }; } [Symbol.iterator]() { return this; } } exports.TarReaderSync = TarReaderSync; /** * Read the entries of an archive. Gzip input is decompressed. * * Read the body of an entry before the next entry: when the iterator * moves on, the rest of the body is skipped. */ const entries = (input, opt) => new TarReader(input, opt); exports.entries = entries; /** * Read the entries of an archive with no promises. Compressed input * needs a codec with a `decompressSync` function in `opt.codecs`. */ const entriesSync = (input, opt) => new TarReaderSync(input, opt); exports.entriesSync = entriesSync; //# sourceMappingURL=entries.js.map