From 11498552299186d79ae42ee5152ac1e5a4946a0d Mon Sep 17 00:00:00 2001 From: Ziggy Jonsson Date: Sat, 11 May 2024 20:11:29 +0000 Subject: [PATCH] eslint (#314) * eslint * only run on 18 --- .github/workflows/test.yml | 12 +++ eslint.config.mjs | 29 ++++++ lib/BufferStream.js | 19 ++-- lib/Decrypt.js | 37 ++++---- lib/NoopStream.js | 10 +-- lib/Open/directory.js | 150 +++++++++++++++---------------- lib/Open/index.js | 57 ++++++------ lib/Open/unzip.js | 107 +++++++++++----------- lib/PullStream.js | 98 ++++++++++---------- lib/extract.js | 29 +++--- lib/parse.js | 108 +++++++++++----------- lib/parseBuffer.js | 14 +-- lib/parseExtraField.js | 8 +- lib/parseOne.js | 46 +++++----- package.json | 3 + test/autodrain-passthrough.js | 20 ++--- test/broken.js | 22 +++-- test/chunkBoundary.js | 24 +++-- test/compressed-crx.js | 61 ++++++------- test/compressed.js | 30 +++---- test/extract-finish.js | 28 +++--- test/extractFromUrl.js | 20 ++--- test/extractNormalize.js | 42 +++++---- test/fileSizeUnknownFlag.js | 26 +++--- test/forceStream.js | 24 ++--- test/notArchive.js | 18 ++-- test/office-files.js | 18 ++-- test/open-extract.js | 15 ++-- test/openBuffer.js | 18 ++-- test/openComment.js | 14 ++- test/openCustom.js | 21 ++--- test/openFile.js | 39 ++++---- test/openFileEncrypted.js | 60 ++++++------- test/openS3.js | 28 +++--- test/openUrl.js | 18 ++-- test/parseBuffer.js | 24 ++--- test/parseCompressedDirectory.js | 18 ++-- test/parseContent.js | 16 ++-- test/parseDateTime.js | 18 ++-- test/parseOneEntry.js | 36 ++++---- test/parsePromise.js | 29 +++--- test/pipeSingleEntry.js | 21 ++--- test/streamSingleEntry.js | 35 +++----- test/uncompressed.js | 64 ++++++------- test/zip64.js | 91 +++++++++---------- 45 files changed, 785 insertions(+), 840 deletions(-) create mode 100644 eslint.config.mjs diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 62bf35e..eefdaf4 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -8,6 +8,18 @@ on: workflow_dispatch: jobs: + lint: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Linting with ESLint + uses: actions/setup-node@v3 + with: + node-version: 18.x + - run: npm install + - run: npx eslint . + test: runs-on: ubuntu-latest diff --git a/eslint.config.mjs b/eslint.config.mjs new file mode 100644 index 0000000..e48c5f5 --- /dev/null +++ b/eslint.config.mjs @@ -0,0 +1,29 @@ +import globals from "globals"; +import pluginJs from "@eslint/js"; + + +export default [ + { + rules:{ + "semi": 2, + "no-multiple-empty-lines": 2, + "no-multi-spaces": 2, + "comma-spacing": 2, + "prefer-const": 2, + "no-trailing-spaces": 2, + "no-var": 2, + "indent": [ + "error", + 2, + { + "MemberExpression": 1, + "SwitchCase": 1, + "ignoredNodes": ["TemplateLiteral > *"] + } + ], + } + }, + {files: ["**/*.js"], languageOptions: {sourceType: "script"}}, + {languageOptions: { globals: globals.node }}, + pluginJs.configs.recommended, +]; diff --git a/lib/BufferStream.js b/lib/BufferStream.js index ab2e7f6..0ee7e5e 100644 --- a/lib/BufferStream.js +++ b/lib/BufferStream.js @@ -1,20 +1,19 @@ -var Promise = require('bluebird'); -var Stream = require('stream'); +const Stream = require('stream'); module.exports = function(entry) { - return new Promise(function(resolve,reject) { - var chunks = []; - var bufferStream = Stream.Transform() - .on('finish',function() { + return new Promise(function(resolve, reject) { + const chunks = []; + const bufferStream = Stream.Transform() + .on('finish', function() { resolve(Buffer.concat(chunks)); }) - .on('error',reject); - - bufferStream._transform = function(d,e,cb) { + .on('error', reject); + + bufferStream._transform = function(d, e, cb) { chunks.push(d); cb(); }; - entry.on('error',reject) + entry.on('error', reject) .pipe(bufferStream); }); }; diff --git a/lib/Decrypt.js b/lib/Decrypt.js index d775072..447d8af 100644 --- a/lib/Decrypt.js +++ b/lib/Decrypt.js @@ -1,25 +1,26 @@ -var bigInt = require('big-integer'); -var Stream = require('stream'); +const bigInt = require('big-integer'); +const Stream = require('stream'); -var table; +let table; function generateTable() { - var poly = 0xEDB88320,c,n,k; + const poly = 0xEDB88320; + let c, n, k; table = []; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) - c = (c & 1) ? poly ^ (c >>> 1) : c = c >>> 1; + c = (c & 1) ? poly ^ (c >>> 1) : c = c >>> 1; table[n] = c >>> 0; } } -function crc(ch,crc) { +function crc(ch, crc) { if (!table) generateTable(); if (ch.charCodeAt) - ch = ch.charCodeAt(0); + ch = ch.charCodeAt(0); return (bigInt(crc).shiftRight(8).and(0xffffff)).xor(table[bigInt(crc).xor(ch).and(0xff)]).value; } @@ -33,27 +34,27 @@ function Decrypt() { this.key2 = 878082192; } -Decrypt.prototype.update = function(h) { - this.key0 = crc(h,this.key0); - this.key1 = bigInt(this.key0).and(255).and(4294967295).add(this.key1) +Decrypt.prototype.update = function(h) { + this.key0 = crc(h, this.key0); + this.key1 = bigInt(this.key0).and(255).and(4294967295).add(this.key1); this.key1 = bigInt(this.key1).multiply(134775813).add(1).and(4294967295).value; this.key2 = crc(bigInt(this.key1).shiftRight(24).and(255), this.key2); -} +}; Decrypt.prototype.decryptByte = function(c) { - var k = bigInt(this.key2).or(2); + const k = bigInt(this.key2).or(2); c = c ^ bigInt(k).multiply(bigInt(k^1)).shiftRight(8).and(255); this.update(c); return c; }; - Decrypt.prototype.stream = function() { - var stream = Stream.Transform(), - self = this; +Decrypt.prototype.stream = function() { + const stream = Stream.Transform(), + self = this; - stream._transform = function(d,e,cb) { - for (var i = 0; i 1 ? opts.concurrency : 1 }); }); }; - vars.files = Promise.mapSeries(Array(vars.numberOfRecords),function() { - return records.pull(46).then(function(data) { - var vars = vars = parseBuffer.parse(data, [ + vars.files = Bluebird.mapSeries(Array(vars.numberOfRecords), function() { + return records.pull(46).then(function(data) { + const vars = parseBuffer.parse(data, [ ['signature', 4], ['versionMadeBy', 2], ['versionsNeededToExtract', 2], @@ -198,40 +198,40 @@ module.exports = function centralDirectory(source, options) { ['offsetToLocalFileHeader', 4], ]); - vars.offsetToLocalFileHeader += startOffset; - vars.lastModifiedDateTime = parseDateTime(vars.lastModifiedDate, vars.lastModifiedTime); - - return records.pull(vars.fileNameLength).then(function(fileNameBuffer) { - vars.pathBuffer = fileNameBuffer; - vars.path = fileNameBuffer.toString('utf8'); - vars.isUnicode = (vars.flags & 0x800) != 0; - return records.pull(vars.extraFieldLength); - }) - .then(function(extraField) { - vars.extra = parseExtraField(extraField, vars); - return records.pull(vars.fileCommentLength); - }) - .then(function(comment) { - vars.comment = comment; - vars.type = (vars.uncompressedSize === 0 && /[\/\\]$/.test(vars.path)) ? 'Directory' : 'File'; - var padding = options && options.padding || 1000; - vars.stream = function(_password) { - var totalSize = 30 + vars.offsetToLocalFileHeader += startOffset; + vars.lastModifiedDateTime = parseDateTime(vars.lastModifiedDate, vars.lastModifiedTime); + + return records.pull(vars.fileNameLength).then(function(fileNameBuffer) { + vars.pathBuffer = fileNameBuffer; + vars.path = fileNameBuffer.toString('utf8'); + vars.isUnicode = (vars.flags & 0x800) != 0; + return records.pull(vars.extraFieldLength); + }) + .then(function(extraField) { + vars.extra = parseExtraField(extraField, vars); + return records.pull(vars.fileCommentLength); + }) + .then(function(comment) { + vars.comment = comment; + vars.type = (vars.uncompressedSize === 0 && /[/\\]$/.test(vars.path)) ? 'Directory' : 'File'; + const padding = options && options.padding || 1000; + vars.stream = function(_password) { + const totalSize = 30 + padding // add an extra buffer - + (vars.extraFieldLength || 0) + + (vars.extraFieldLength || 0) + (vars.fileNameLength || 0) + vars.compressedSize; - return unzip(source, vars.offsetToLocalFileHeader,_password, vars, totalSize); - }; - vars.buffer = function(_password) { - return BufferStream(vars.stream(_password)); - }; - return vars; + return unzip(source, vars.offsetToLocalFileHeader, _password, vars, totalSize); + }; + vars.buffer = function(_password) { + return BufferStream(vars.stream(_password)); + }; + return vars; + }); }); }); - }); - return Promise.props(vars); - }); + return Bluebird.props(vars); + }); }; diff --git a/lib/Open/index.js b/lib/Open/index.js index 4196086..83c349b 100644 --- a/lib/Open/index.js +++ b/lib/Open/index.js @@ -1,14 +1,13 @@ -var fs = require('graceful-fs'); -var Promise = require('bluebird'); -var directory = require('./directory'); -var Stream = require('stream'); +const fs = require('graceful-fs'); +const directory = require('./directory'); +const Stream = require('stream'); module.exports = { buffer: function(buffer, options) { - var source = { + const source = { stream: function(offset, length) { - var stream = Stream.PassThrough(); - var end = length ? offset + length : undefined; + const stream = Stream.PassThrough(); + const end = length ? offset + length : undefined; stream.end(buffer.slice(offset, end)); return stream; }, @@ -19,14 +18,14 @@ module.exports = { return directory(source, options); }, file: function(filename, options) { - var source = { - stream: function(start,length) { - var end = length ? start + length : undefined; - return fs.createReadStream(filename,{start, end}); + const source = { + stream: function(start, length) { + const end = length ? start + length : undefined; + return fs.createReadStream(filename, {start, end}); }, size: function() { - return new Promise(function(resolve,reject) { - fs.stat(filename,function(err,d) { + return new Promise(function(resolve, reject) { + fs.stat(filename, function(err, d) { if (err) reject(err); else @@ -45,24 +44,24 @@ module.exports = { throw 'URL missing'; params.headers = params.headers || {}; - var source = { - stream : function(offset,length) { - var options = Object.create(params); - var end = length ? offset + length : ''; + const source = { + stream : function(offset, length) { + const options = Object.create(params); + const end = length ? offset + length : ''; options.headers = Object.create(params.headers); options.headers.range = 'bytes='+offset+'-' + end; return request(options); }, size: function() { - return new Promise(function(resolve,reject) { - var req = request(params); - req.on('response',function(d) { + return new Promise(function(resolve, reject) { + const req = request(params); + req.on('response', function(d) { req.abort(); if (!d.headers['content-length']) reject(new Error('Missing content length header')); else resolve(d.headers['content-length']); - }).on('error',reject); + }).on('error', reject); }); } }; @@ -70,11 +69,11 @@ module.exports = { return directory(source, options); }, - s3 : function(client,params, options) { - var source = { + s3 : function(client, params, options) { + const source = { size: function() { - return new Promise(function(resolve,reject) { - client.headObject(params, function(err,d) { + return new Promise(function(resolve, reject) { + client.headObject(params, function(err, d) { if (err) reject(err); else @@ -82,11 +81,11 @@ module.exports = { }); }); }, - stream: function(offset,length) { - var d = {}; - for (var key in params) + stream: function(offset, length) { + const d = {}; + for (const key in params) d[key] = params[key]; - var end = length ? offset + length : ''; + const end = length ? offset + length : ''; d.Range = 'bytes='+offset+'-' + end; return client.getObject(d).createReadStream(); } diff --git a/lib/Open/unzip.js b/lib/Open/unzip.js index 6205ab4..b8d55bf 100644 --- a/lib/Open/unzip.js +++ b/lib/Open/unzip.js @@ -1,24 +1,23 @@ -var Promise = require('bluebird'); -var Decrypt = require('../Decrypt'); -var PullStream = require('../PullStream'); -var Stream = require('stream'); -var zlib = require('zlib'); -var parseExtraField = require('../parseExtraField'); -var parseDateTime = require('../parseDateTime'); -var parseBuffer = require('../parseBuffer'); +const Decrypt = require('../Decrypt'); +const PullStream = require('../PullStream'); +const Stream = require('stream'); +const zlib = require('zlib'); +const parseExtraField = require('../parseExtraField'); +const parseDateTime = require('../parseDateTime'); +const parseBuffer = require('../parseBuffer'); module.exports = function unzip(source, offset, _password, directoryVars, length) { - var file = PullStream(), - entry = Stream.PassThrough(); + const file = PullStream(), + entry = Stream.PassThrough(); - var req = source.stream(offset, length); + const req = source.stream(offset, length); req.pipe(file).on('error', function(e) { entry.emit('error', e); }); entry.vars = file.pull(30) .then(function(data) { - var vars = parseBuffer.parse(data, [ + let vars = parseBuffer.parse(data, [ ['signature', 4], ['versionsNeededToExtract', 2], ['flags', 2], @@ -40,7 +39,7 @@ module.exports = function unzip(source, offset, _password, directoryVars, length return file.pull(vars.extraFieldLength); }) .then(function(extraField) { - var checkEncryption; + let checkEncryption; vars.extra = parseExtraField(extraField, vars); // Ignore logal file header vars if the directory vars are available if (directoryVars && directoryVars.compressedSize) vars = directoryVars; @@ -50,19 +49,19 @@ module.exports = function unzip(source, offset, _password, directoryVars, length if (!_password) throw new Error('MISSING_PASSWORD'); - var decrypt = Decrypt(); + const decrypt = Decrypt(); String(_password).split('').forEach(function(d) { decrypt.update(d); }); - for (var i=0; i < header.length; i++) + for (let i=0; i < header.length; i++) header[i] = decrypt.decryptByte(header[i]); vars.decrypt = decrypt; vars.compressedSize -= 12; - var check = (vars.flags & 0x8) ? (vars.lastModifiedTime >> 8) & 0xff : (vars.crc32 >> 24) & 0xff; + const check = (vars.flags & 0x8) ? (vars.lastModifiedTime >> 8) & 0xff : (vars.crc32 >> 24) & 0xff; if (header[11] !== check) throw new Error('BAD_PASSWORD'); @@ -71,50 +70,50 @@ module.exports = function unzip(source, offset, _password, directoryVars, length return Promise.resolve(checkEncryption) .then(function() { - entry.emit('vars',vars); + entry.emit('vars', vars); return vars; }); }); }); - entry.vars.then(function(vars) { - var fileSizeKnown = !(vars.flags & 0x08) || vars.compressedSize > 0, - eof; - - var inflater = vars.compressionMethod ? zlib.createInflateRaw() : Stream.PassThrough(); - - if (fileSizeKnown) { - entry.size = vars.uncompressedSize; - eof = vars.compressedSize; - } else { - eof = Buffer.alloc(4); - eof.writeUInt32LE(0x08074b50, 0); - } - - var stream = file.stream(eof); - - if (vars.decrypt) - stream = stream.pipe(vars.decrypt.stream()); - - stream - .pipe(inflater) - .on('error',function(err) { entry.emit('error',err);}) - .pipe(entry) - .on('finish', function() { - if(req.destroy) - req.destroy() - else if (req.abort) - req.abort(); - else if (req.close) - req.close(); - else if (req.push) - req.push(); - else - console.log('warning - unable to close stream'); - }); - }) + entry.vars.then(function(vars) { + const fileSizeKnown = !(vars.flags & 0x08) || vars.compressedSize > 0; + let eof; + + const inflater = vars.compressionMethod ? zlib.createInflateRaw() : Stream.PassThrough(); + + if (fileSizeKnown) { + entry.size = vars.uncompressedSize; + eof = vars.compressedSize; + } else { + eof = Buffer.alloc(4); + eof.writeUInt32LE(0x08074b50, 0); + } + + let stream = file.stream(eof); + + if (vars.decrypt) + stream = stream.pipe(vars.decrypt.stream()); + + stream + .pipe(inflater) + .on('error', function(err) { entry.emit('error', err);}) + .pipe(entry) + .on('finish', function() { + if(req.destroy) + req.destroy(); + else if (req.abort) + req.abort(); + else if (req.close) + req.close(); + else if (req.push) + req.push(); + else + console.log('warning - unable to close stream'); + }); + }) .catch(function(e) { - entry.emit('error',e); + entry.emit('error', e); }); return entry; diff --git a/lib/PullStream.js b/lib/PullStream.js index 0195d01..93f18e4 100644 --- a/lib/PullStream.js +++ b/lib/PullStream.js @@ -1,25 +1,24 @@ -var Stream = require('stream'); -var Promise = require('bluebird'); -var util = require('util'); -var strFunction = 'function'; +const Stream = require('stream'); +const util = require('util'); +const strFunction = 'function'; function PullStream() { if (!(this instanceof PullStream)) return new PullStream(); - Stream.Duplex.call(this,{decodeStrings:false, objectMode:true}); + Stream.Duplex.call(this, {decodeStrings:false, objectMode:true}); this.buffer = Buffer.from(''); - var self = this; - self.on('finish',function() { + const self = this; + self.on('finish', function() { self.finished = true; - self.emit('chunk',false); + self.emit('chunk', false); }); } -util.inherits(PullStream,Stream.Duplex); +util.inherits(PullStream, Stream.Duplex); -PullStream.prototype._write = function(chunk,e,cb) { - this.buffer = Buffer.concat([this.buffer,chunk]); +PullStream.prototype._write = function(chunk, e, cb) { + this.buffer = Buffer.concat([this.buffer, chunk]); this.cb = cb; this.emit('chunk'); }; @@ -27,111 +26,112 @@ PullStream.prototype._write = function(chunk,e,cb) { // The `eof` parameter is interpreted as `file_length` if the type is number // otherwise (i.e. buffer) it is interpreted as a pattern signaling end of stream -PullStream.prototype.stream = function(eof,includeEof) { - var p = Stream.PassThrough(); - var done,self= this; +PullStream.prototype.stream = function(eof, includeEof) { + const p = Stream.PassThrough(); + let done; + const self= this; function cb() { if (typeof self.cb === strFunction) { - var callback = self.cb; + const callback = self.cb; self.cb = undefined; return callback(); } } function pull() { - var packet; + let packet; if (self.buffer && self.buffer.length) { if (typeof eof === 'number') { - packet = self.buffer.slice(0,eof); + packet = self.buffer.slice(0, eof); self.buffer = self.buffer.slice(eof); eof -= packet.length; done = done || !eof; } else { - var match = self.buffer.indexOf(eof); + let match = self.buffer.indexOf(eof); if (match !== -1) { // store signature match byte offset to allow us to reference // this for zip64 offset - self.match = match + self.match = match; if (includeEof) match = match + eof.length; - packet = self.buffer.slice(0,match); + packet = self.buffer.slice(0, match); self.buffer = self.buffer.slice(match); done = true; } else { - var len = self.buffer.length - eof.length; + const len = self.buffer.length - eof.length; if (len <= 0) { cb(); } else { - packet = self.buffer.slice(0,len); + packet = self.buffer.slice(0, len); self.buffer = self.buffer.slice(len); } } } - if (packet) p.write(packet,function() { + if (packet) p.write(packet, function() { if (self.buffer.length === 0 || (eof.length && self.buffer.length <= eof.length)) cb(); }); } - + if (!done) { if (self.finished) { - self.removeListener('chunk',pull); + self.removeListener('chunk', pull); self.emit('error', new Error('FILE_ENDED')); return; } - + } else { - self.removeListener('chunk',pull); + self.removeListener('chunk', pull); p.end(); } } - self.on('chunk',pull); + self.on('chunk', pull); pull(); return p; }; -PullStream.prototype.pull = function(eof,includeEof) { +PullStream.prototype.pull = function(eof, includeEof) { if (eof === 0) return Promise.resolve(''); // If we already have the required data in buffer // we can resolve the request immediately if (!isNaN(eof) && this.buffer.length > eof) { - var data = this.buffer.slice(0,eof); + const data = this.buffer.slice(0, eof); this.buffer = this.buffer.slice(eof); return Promise.resolve(data); } // Otherwise we stream until we have it - var buffer = Buffer.from(''), - self = this; + let buffer = Buffer.from(''); + const self = this; - var concatStream = Stream.Transform(); - concatStream._transform = function(d,e,cb) { - buffer = Buffer.concat([buffer,d]); + const concatStream = new Stream.Transform(); + concatStream._transform = function(d, e, cb) { + buffer = Buffer.concat([buffer, d]); cb(); }; - - var rejectHandler; - var pullStreamRejectHandler; - return new Promise(function(resolve,reject) { + + let rejectHandler; + let pullStreamRejectHandler; + return new Promise(function(resolve, reject) { rejectHandler = reject; pullStreamRejectHandler = function(e) { self.__emittedError = e; reject(e); - } + }; if (self.finished) return reject(new Error('FILE_ENDED')); - self.once('error',pullStreamRejectHandler); // reject any errors from pullstream itself - self.stream(eof,includeEof) - .on('error',reject) + self.once('error', pullStreamRejectHandler); // reject any errors from pullstream itself + self.stream(eof, includeEof) + .on('error', reject) .pipe(concatStream) - .on('finish',function() {resolve(buffer);}) - .on('error',reject); + .on('finish', function() {resolve(buffer);}) + .on('error', reject); }) - .finally(function() { - self.removeListener('error',rejectHandler); - self.removeListener('error',pullStreamRejectHandler); - }); + .finally(function() { + self.removeListener('error', rejectHandler); + self.removeListener('error', pullStreamRejectHandler); + }); }; PullStream.prototype._read = function(){}; diff --git a/lib/extract.js b/lib/extract.js index e6e0555..31d725a 100644 --- a/lib/extract.js +++ b/lib/extract.js @@ -1,19 +1,18 @@ module.exports = Extract; -var Parse = require('./parse'); -var Writer = require('fstream').Writer; -var path = require('path'); -var stream = require('stream'); -var duplexer2 = require('duplexer2'); -var Promise = require('bluebird'); +const Parse = require('./parse'); +const Writer = require('fstream').Writer; +const path = require('path'); +const stream = require('stream'); +const duplexer2 = require('duplexer2'); function Extract (opts) { // make sure path is normalized before using it opts.path = path.resolve(path.normalize(opts.path)); - var parser = new Parse(opts); + const parser = new Parse(opts); - var outStream = new stream.Writable({objectMode: true}); + const outStream = new stream.Writable({objectMode: true}); outStream._write = function(entry, encoding, cb) { if (entry.type == 'Directory') return cb(); @@ -21,35 +20,35 @@ function Extract (opts) { // to avoid zip slip (writing outside of the destination), we resolve // the target path, and make sure it's nested in the intended // destination, or not extract it otherwise. - // NOTE: Need to normalize to forward slashes for UNIX OS's to properly + // NOTE: Need to normalize to forward slashes for UNIX OS's to properly // ignore the zip slipped file entirely - var extractPath = path.join(opts.path, entry.path.replace(/\\/g, '/')); + const extractPath = path.join(opts.path, entry.path.replace(/\\/g, '/')); if (extractPath.indexOf(opts.path) != 0) { return cb(); } - const writer = opts.getWriter ? opts.getWriter({path: extractPath}) : Writer({ path: extractPath }); + const writer = opts.getWriter ? opts.getWriter({path: extractPath}) : Writer({ path: extractPath }); entry.pipe(writer) .on('error', cb) .on('close', cb); }; - var extract = duplexer2(parser,outStream); + const extract = duplexer2(parser, outStream); parser.once('crx-header', function(crxHeader) { extract.crxHeader = crxHeader; }); parser .pipe(outStream) - .on('finish',function() { + .on('finish', function() { extract.emit('close'); }); - + extract.promise = function() { return new Promise(function(resolve, reject) { extract.on('close', resolve); - extract.on('error',reject); + extract.on('error', reject); }); }; diff --git a/lib/parse.js b/lib/parse.js index 20c23bf..0921f4a 100644 --- a/lib/parse.js +++ b/lib/parse.js @@ -1,46 +1,45 @@ -var util = require('util'); -var zlib = require('zlib'); -var Stream = require('stream'); -var Promise = require('bluebird'); -var PullStream = require('./PullStream'); -var NoopStream = require('./NoopStream'); -var BufferStream = require('./BufferStream'); -var parseExtraField = require('./parseExtraField'); -var parseDateTime = require('./parseDateTime'); -var pipeline = Stream.pipeline; -var parseBuffer = require('./parseBuffer'); - -var endDirectorySignature = Buffer.alloc(4); +const util = require('util'); +const zlib = require('zlib'); +const Stream = require('stream'); +const PullStream = require('./PullStream'); +const NoopStream = require('./NoopStream'); +const BufferStream = require('./BufferStream'); +const parseExtraField = require('./parseExtraField'); +const parseDateTime = require('./parseDateTime'); +const pipeline = Stream.pipeline; +const parseBuffer = require('./parseBuffer'); + +const endDirectorySignature = Buffer.alloc(4); endDirectorySignature.writeUInt32LE(0x06054b50, 0); function Parse(opts) { if (!(this instanceof Parse)) { return new Parse(opts); } - var self = this; + const self = this; self._opts = opts || { verbose: false }; PullStream.call(self, self._opts); - self.on('finish',function() { + self.on('finish', function() { self.emit('end'); self.emit('close'); }); self._readRecord().catch(function(e) { if (!self.__emittedError || self.__emittedError !== e) - self.emit('error',e); + self.emit('error', e); }); } util.inherits(Parse, PullStream); Parse.prototype._readRecord = function () { - var self = this; + const self = this; return self.pull(4).then(function(data) { if (data.length === 0) return; - var signature = data.readUInt32LE(0); + const signature = data.readUInt32LE(0); if (signature === 0x34327243) { return self._readCrxHeader(); @@ -58,7 +57,7 @@ Parse.prototype._readRecord = function () { else if (self.reachedCD) { // _readEndOfCentralDirectoryRecord expects the EOCD // signature to be consumed so set includeEof=true - var includeEof = true; + const includeEof = true; return self.pull(endDirectorySignature, includeEof).then(function() { return self._readEndOfCentralDirectoryRecord(); }); @@ -73,7 +72,7 @@ Parse.prototype._readRecord = function () { }; Parse.prototype._readCrxHeader = function() { - var self = this; + const self = this; return self.pull(12).then(function(data) { self.crxHeader = parseBuffer.parse(data, [ ['version', 4], @@ -82,17 +81,17 @@ Parse.prototype._readCrxHeader = function() { ]); return self.pull(self.crxHeader.pubKeyLength + self.crxHeader.signatureLength); }).then(function(data) { - self.crxHeader.publicKey = data.slice(0,self.crxHeader.pubKeyLength); + self.crxHeader.publicKey = data.slice(0, self.crxHeader.pubKeyLength); self.crxHeader.signature = data.slice(self.crxHeader.pubKeyLength); - self.emit('crx-header',self.crxHeader); + self.emit('crx-header', self.crxHeader); return true; }); }; Parse.prototype._readFile = function () { - var self = this; + const self = this; return self.pull(26).then(function(data) { - var vars = parseBuffer.parse(data, [ + const vars = parseBuffer.parse(data, [ ['versionsNeededToExtract', 2], ['flags', 2], ['compressionMethod', 2], @@ -110,17 +109,17 @@ Parse.prototype._readFile = function () { if (self.crxHeader) vars.crxHeader = self.crxHeader; return self.pull(vars.fileNameLength).then(function(fileNameBuffer) { - var fileName = fileNameBuffer.toString('utf8'); - var entry = Stream.PassThrough(); - var __autodraining = false; + const fileName = fileNameBuffer.toString('utf8'); + const entry = Stream.PassThrough(); + let __autodraining = false; entry.autodrain = function() { __autodraining = true; - var draining = entry.pipe(NoopStream()); + const draining = entry.pipe(NoopStream()); draining.promise = function() { return new Promise(function(resolve, reject) { - draining.on('finish',resolve); - draining.on('error',reject); + draining.on('finish', resolve); + draining.on('error', reject); }); }; return draining; @@ -137,7 +136,7 @@ Parse.prototype._readFile = function () { entry.props.flags = { "isUnicode": (vars.flags & 0x800) != 0 }; - entry.type = (vars.uncompressedSize === 0 && /[\/\\]$/.test(fileName)) ? 'Directory' : 'File'; + entry.type = (vars.uncompressedSize === 0 && /[/\\]$/.test(fileName)) ? 'Directory' : 'File'; if (self._opts.verbose) { if (entry.type === 'Directory') { @@ -152,7 +151,7 @@ Parse.prototype._readFile = function () { } return self.pull(vars.extraFieldLength).then(function(extraField) { - var extra = parseExtraField(extraField, vars); + const extra = parseExtraField(extraField, vars); entry.vars = vars; entry.extra = extra; @@ -173,11 +172,11 @@ Parse.prototype._readFile = function () { extra: extra }); - var fileSizeKnown = !(vars.flags & 0x08) || vars.compressedSize > 0, - eof; + const fileSizeKnown = !(vars.flags & 0x08) || vars.compressedSize > 0; + let eof; - entry.__autodraining = __autodraining; // expose __autodraining for test purposes - var inflater = (vars.compressionMethod && !__autodraining) ? zlib.createInflateRaw() : Stream.PassThrough(); + entry.__autodraining = __autodraining; // expose __autodraining for test purposes + const inflater = (vars.compressionMethod && !__autodraining) ? zlib.createInflateRaw() : Stream.PassThrough(); if (fileSizeKnown) { entry.size = vars.uncompressedSize; @@ -199,7 +198,7 @@ Parse.prototype._readFile = function () { return fileSizeKnown ? resolve(fileSizeKnown) : self._processDataDescriptor(entry).then(resolve).catch(reject); } - ) + ); }); }); }); @@ -207,9 +206,9 @@ Parse.prototype._readFile = function () { }; Parse.prototype._processDataDescriptor = function (entry) { - var self = this; + const self = this; return self.pull(16).then(function(data) { - var vars = parseBuffer.parse(data, [ + const vars = parseBuffer.parse(data, [ ['dataDescriptorSignature', 4], ['crc32', 4], ['compressedSize', 4], @@ -222,9 +221,9 @@ Parse.prototype._processDataDescriptor = function (entry) { }; Parse.prototype._readCentralDirectoryFileHeader = function () { - var self = this; + const self = this; return self.pull(42).then(function(data) { - var vars = parseBuffer.parse(data, [ + const vars = parseBuffer.parse(data, [ ['versionMadeBy', 2], ['versionsNeededToExtract', 2], ['flags', 2], @@ -247,20 +246,20 @@ Parse.prototype._readCentralDirectoryFileHeader = function () { vars.fileName = fileName.toString('utf8'); return self.pull(vars.extraFieldLength); }) - .then(function(extraField) { - return self.pull(vars.fileCommentLength); - }) - .then(function(fileComment) { - return true; - }); + .then(function() { + return self.pull(vars.fileCommentLength); + }) + .then(function() { + return true; + }); }); }; Parse.prototype._readEndOfCentralDirectoryRecord = function() { - var self = this; + const self = this; return self.pull(18).then(function(data) { - var vars = parseBuffer.parse(data, [ + const vars = parseBuffer.parse(data, [ ['diskNumber', 2], ['diskStart', 2], ['numberOfRecordsOnDisk', 2], @@ -270,8 +269,7 @@ Parse.prototype._readEndOfCentralDirectoryRecord = function() { ['commentLength', 2], ]); - return self.pull(vars.commentLength).then(function(comment) { - comment = comment.toString('utf8'); + return self.pull(vars.commentLength).then(function() { self.end(); self.push(null); }); @@ -280,10 +278,10 @@ Parse.prototype._readEndOfCentralDirectoryRecord = function() { }; Parse.prototype.promise = function() { - var self = this; - return new Promise(function(resolve,reject) { - self.on('finish',resolve); - self.on('error',reject); + const self = this; + return new Promise(function(resolve, reject) { + self.on('finish', resolve); + self.on('error', reject); }); }; diff --git a/lib/parseBuffer.js b/lib/parseBuffer.js index 30ca539..78b078b 100644 --- a/lib/parseBuffer.js +++ b/lib/parseBuffer.js @@ -1,5 +1,5 @@ const parseUIntLE = function(buffer, offset, size) { - var result; + let result; switch(size) { case 1: result = buffer.readUInt8(offset); @@ -14,10 +14,10 @@ const parseUIntLE = function(buffer, offset, size) { result = Number(buffer.readBigUInt64LE(offset)); break; default: - throw new Error('Unsupported UInt LE size!'); + throw new Error('Unsupported UInt LE size!'); } return result; -} +}; /** * Parses sequential unsigned little endian numbers from the head of the passed buffer according to @@ -36,8 +36,8 @@ const parseUIntLE = function(buffer, offset, size) { * @returns An object with keys set to their associated extracted values. */ const parse = function(buffer, format) { - var result = {} - var offset = 0; + const result = {}; + let offset = 0; for(const [key, size] of format) { if(buffer.length >= offset + size) { result[key] = parseUIntLE(buffer, offset, size); @@ -48,8 +48,8 @@ const parse = function(buffer, format) { offset += size; } return result; -} +}; module.exports = { parse -} \ No newline at end of file +}; \ No newline at end of file diff --git a/lib/parseExtraField.js b/lib/parseExtraField.js index 0edcd03..42d178f 100644 --- a/lib/parseExtraField.js +++ b/lib/parseExtraField.js @@ -1,10 +1,10 @@ -var parseBuffer = require('./parseBuffer'); +const parseBuffer = require('./parseBuffer'); module.exports = function(extraField, vars) { - var extra; + let extra; // Find the ZIP64 header, if present. while(!extra && extraField && extraField.length) { - var candidateExtra = parseBuffer.parse(extraField, [ + const candidateExtra = parseBuffer.parse(extraField, [ ['signature', 2], ['partsize', 2], ['uncompressedSize', 8], @@ -27,7 +27,7 @@ module.exports = function(extraField, vars) { if (vars.compressedSize === 0xffffffff) vars.compressedSize = extra.compressedSize; - if (vars.uncompressedSize === 0xffffffff) + if (vars.uncompressedSize === 0xffffffff) vars.uncompressedSize= extra.uncompressedSize; if (vars.offsetToLocalFileHeader === 0xffffffff) diff --git a/lib/parseOne.js b/lib/parseOne.js index 8954c5b..275dde0 100644 --- a/lib/parseOne.js +++ b/lib/parseOne.js @@ -1,49 +1,49 @@ -var Stream = require('stream'); -var Parse = require('./parse'); -var duplexer2 = require('duplexer2'); -var BufferStream = require('./BufferStream'); +const Stream = require('stream'); +const Parse = require('./parse'); +const duplexer2 = require('duplexer2'); +const BufferStream = require('./BufferStream'); -function parseOne(match,opts) { - var inStream = Stream.PassThrough({objectMode:true}); - var outStream = Stream.PassThrough(); - var transform = Stream.Transform({objectMode:true}); - var re = match instanceof RegExp ? match : (match && new RegExp(match)); - var found; +function parseOne(match, opts) { + const inStream = Stream.PassThrough({objectMode:true}); + const outStream = Stream.PassThrough(); + const transform = Stream.Transform({objectMode:true}); + const re = match instanceof RegExp ? match : (match && new RegExp(match)); + let found; - transform._transform = function(entry,e,cb) { + transform._transform = function(entry, e, cb) { if (found || (re && !re.exec(entry.path))) { entry.autodrain(); return cb(); } else { found = true; - out.emit('entry',entry); - entry.on('error',function(e) { - outStream.emit('error',e); + out.emit('entry', entry); + entry.on('error', function(e) { + outStream.emit('error', e); }); entry.pipe(outStream) - .on('error',function(err) { + .on('error', function(err) { cb(err); }) - .on('finish',function(d) { - cb(null,d); + .on('finish', function(d) { + cb(null, d); }); } }; inStream.pipe(Parse(opts)) - .on('error',function(err) { - outStream.emit('error',err); + .on('error', function(err) { + outStream.emit('error', err); }) .pipe(transform) - .on('error',Object) // Silence error as its already addressed in transform - .on('finish',function() { + .on('error', Object) // Silence error as its already addressed in transform + .on('finish', function() { if (!found) - outStream.emit('error',new Error('PATTERN_NOT_FOUND')); + outStream.emit('error', new Error('PATTERN_NOT_FOUND')); else outStream.end(); }); - var out = duplexer2(inStream,outStream); + const out = duplexer2(inStream, outStream); out.buffer = function() { return BufferStream(outStream); }; diff --git a/package.json b/package.json index 22b688a..071a492 100644 --- a/package.json +++ b/package.json @@ -30,8 +30,11 @@ "graceful-fs": "^4.2.2" }, "devDependencies": { + "@eslint/js": "^9.2.0", "aws-sdk": "^2.77.0", "dirdiff": ">= 0.0.1 < 1", + "eslint": "^9.2.0", + "globals": "^15.2.0", "iconv-lite": "^0.4.24", "request": "^2.88.0", "stream-buffers": ">= 0.2.5 < 1", diff --git a/test/autodrain-passthrough.js b/test/autodrain-passthrough.js index 66d2bd0..968efdc 100644 --- a/test/autodrain-passthrough.js +++ b/test/autodrain-passthrough.js @@ -1,12 +1,10 @@ -'use strict'; - -var test = require('tap').test; -var fs = require('fs'); -var path = require('path'); -var unzip = require('../'); +const test = require('tap').test; +const fs = require('fs'); +const path = require('path'); +const unzip = require('../'); test("verify that immediate autodrain does not unzip", function (t) { - var archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); + const archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); fs.createReadStream(archive) .pipe(unzip.Parse()) @@ -22,7 +20,7 @@ test("verify that immediate autodrain does not unzip", function (t) { }); test("verify that autodrain promise works", function (t) { - var archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); + const archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); fs.createReadStream(archive) .pipe(unzip.Parse()) @@ -34,16 +32,16 @@ test("verify that autodrain promise works", function (t) { }); }) .on('finish', function() { - console.log('end') + console.log('end'); t.end(); }); }); test("verify that autodrain resolves after it has finished", function (t) { - var archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); + const archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); fs.createReadStream(archive) .pipe(unzip.Parse()) .on('entry', entry => entry.autodrain()) - .on('end', () => t.end()) + .on('end', () => t.end()); }); diff --git a/test/broken.js b/test/broken.js index 725e01b..78beb63 100644 --- a/test/broken.js +++ b/test/broken.js @@ -1,19 +1,17 @@ -'use strict'; - -var test = require('tap').test; -var fs = require('fs'); -var path = require('path'); -var temp = require('temp'); -var unzip = require('../'); +const test = require('tap').test; +const fs = require('fs'); +const path = require('path'); +const temp = require('temp'); +const unzip = require('../'); test("Parse a broken zipfile", function (t) { - var archive = path.join(__dirname, '../testData/compressed-standard/broken.zip'); + const archive = path.join(__dirname, '../testData/compressed-standard/broken.zip'); fs.createReadStream(archive) .pipe(unzip.Parse()) .on('entry', function(entry) { - return entry.autodrain(); + return entry.autodrain(); }) .promise() .catch(function(e) { @@ -24,19 +22,19 @@ test("Parse a broken zipfile", function (t) { test("extract a broken", function (t) { - var archive = path.join(__dirname, '../testData/compressed-standard/broken.zip'); + const archive = path.join(__dirname, '../testData/compressed-standard/broken.zip'); temp.mkdir('node-unzip-', function (err, dirPath) { if (err) { throw err; } - var unzipExtractor = unzip.Extract({ path: dirPath }); + const unzipExtractor = unzip.Extract({ path: dirPath }); fs.createReadStream(archive) .pipe(unzipExtractor) .promise() .catch(function(e) { - t.same(e.message,'FILE_ENDED'); + t.same(e.message, 'FILE_ENDED'); t.end(); }); }); diff --git a/test/chunkBoundary.js b/test/chunkBoundary.js index e97bcaa..445e9db 100644 --- a/test/chunkBoundary.js +++ b/test/chunkBoundary.js @@ -1,24 +1,22 @@ -'use strict'; - -var test = require('tap').test; -var fs = require('fs'); -var path = require('path'); -var unzip = require('../'); +const test = require('tap').test; +const fs = require('fs'); +const path = require('path'); +const unzip = require('../'); test("parse an archive that has a file that falls on a chunk boundary", { - timeout: 2000, + timeout: 2000, }, function (t) { - - var archive = path.join(__dirname, '../testData/chunk-boundary/chunk-boundary-archive.zip'); + + const archive = path.join(__dirname, '../testData/chunk-boundary/chunk-boundary-archive.zip'); // Use an artificially low highWaterMark to make the edge case more likely to happen. - fs.createReadStream(archive,{ highWaterMark: 3 }) + fs.createReadStream(archive, { highWaterMark: 3 }) .pipe(unzip.Parse()) .on('entry', function(entry) { - return entry.autodrain(); + return entry.autodrain(); }).on("finish", function() { - t.ok(true,'file complete'); - t.end(); + t.ok(true, 'file complete'); + t.end(); }); }); \ No newline at end of file diff --git a/test/compressed-crx.js b/test/compressed-crx.js index 5f8393f..865567e 100644 --- a/test/compressed-crx.js +++ b/test/compressed-crx.js @@ -1,20 +1,18 @@ -'use strict'; - -var test = require('tap').test; -var fs = require('fs'); -var path = require('path'); -var temp = require('temp'); -var dirdiff = require('dirdiff'); -var unzip = require('../'); +const test = require('tap').test; +const fs = require('fs'); +const path = require('path'); +const temp = require('temp'); +const dirdiff = require('dirdiff'); +const unzip = require('../'); test('parse/extract crx archive', function (t) { - var archive = path.join(__dirname, '../testData/compressed-standard-crx/archive.crx'); + const archive = path.join(__dirname, '../testData/compressed-standard-crx/archive.crx'); temp.mkdir('node-unzip-', function (err, dirPath) { if (err) { throw err; } - var unzipExtractor = unzip.Extract({ path: dirPath }); + const unzipExtractor = unzip.Extract({ path: dirPath }); unzipExtractor.on('error', function(err) { throw err; }); @@ -23,7 +21,7 @@ test('parse/extract crx archive', function (t) { fs.createReadStream(archive).pipe(unzipExtractor); function testExtractionResults() { - t.same(unzipExtractor.crxHeader.version,2); + t.same(unzipExtractor.crxHeader.version, 2); dirdiff(path.join(__dirname, '../testData/compressed-standard/inflated'), dirPath, { fileContents: true }, function (err, diffs) { @@ -38,40 +36,39 @@ test('parse/extract crx archive', function (t) { }); test('open methods', async function(t) { - var archive = path.join(__dirname, '../testData/compressed-standard-crx/archive.crx'); - var buffer = fs.readFileSync(archive); - var request = require('request'); - var AWS = require('aws-sdk'); - var s3 = new AWS.S3({region: 'us-east-1'}); + const archive = path.join(__dirname, '../testData/compressed-standard-crx/archive.crx'); + const buffer = fs.readFileSync(archive); + const AWS = require('aws-sdk'); + const s3 = new AWS.S3({region: 'us-east-1'}); // We have to modify the `getObject` and `headObject` to use makeUnauthenticated - s3.getObject = function(params,cb) { - return s3.makeUnauthenticatedRequest('getObject',params,cb); + s3.getObject = function(params, cb) { + return s3.makeUnauthenticatedRequest('getObject', params, cb); }; - s3.headObject = function(params,cb) { - return s3.makeUnauthenticatedRequest('headObject',params,cb); + s3.headObject = function(params, cb) { + return s3.makeUnauthenticatedRequest('headObject', params, cb); }; - - var tests = [ - {name: 'buffer',args: [buffer]}, + + const tests = [ + {name: 'buffer', args: [buffer]}, {name: 'file', args: [archive]}, // {name: 'url', args: [request, 'https://s3.amazonaws.com/unzipper/archive.crx']}, // {name: 's3', args: [s3, { Bucket: 'unzipper', Key: 'archive.crx'}]} ]; - for (let test of tests) { + for (const test of tests) { t.test(test.name, async function(t) { t.test('opening with crx option', function(t) { - var method = unzip.Open[test.name]; + const method = unzip.Open[test.name]; method.apply(method, test.args.concat({crx:true})) - .then(function(d) { - return d.files[1].buffer(); - }) - .then(function(d) { - t.same(String(d), '42\n', test.name + ' content matches'); - t.end(); - }); + .then(function(d) { + return d.files[1].buffer(); + }) + .then(function(d) { + t.same(String(d), '42\n', test.name + ' content matches'); + t.end(); + }); }); }); }; diff --git a/test/compressed.js b/test/compressed.js index aefb283..e154cab 100644 --- a/test/compressed.js +++ b/test/compressed.js @@ -1,17 +1,15 @@ -'use strict'; - -var test = require('tap').test; -var fs = require('fs'); -var path = require('path'); -var temp = require('temp'); -var dirdiff = require('dirdiff'); -var unzip = require('../'); -var il = require('iconv-lite'); +const test = require('tap').test; +const fs = require('fs'); +const path = require('path'); +const temp = require('temp'); +const dirdiff = require('dirdiff'); +const unzip = require('../'); +const il = require('iconv-lite'); test("parse compressed archive (created by POSIX zip)", function (t) { - var archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); + const archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); - var unzipParser = unzip.Parse(); + const unzipParser = unzip.Parse(); fs.createReadStream(archive).pipe(unzipParser); unzipParser.on('error', function(err) { throw err; @@ -21,12 +19,12 @@ test("parse compressed archive (created by POSIX zip)", function (t) { }); test("parse compressed archive (created by DOS zip)", function (t) { - var archive = path.join(__dirname, '../testData/compressed-cp866/archive.zip'); + const archive = path.join(__dirname, '../testData/compressed-cp866/archive.zip'); - var unzipParser = unzip.Parse(); + const unzipParser = unzip.Parse(); fs.createReadStream(archive).pipe(unzipParser); unzipParser.on('entry', function(entry) { - var fileName = entry.props.flags.isUnicode ? entry.path : il.decode(entry.props.pathBuffer, 'cp866'); + const fileName = entry.props.flags.isUnicode ? entry.path : il.decode(entry.props.pathBuffer, 'cp866'); t.equal(fileName, 'Тест.txt'); }); unzipParser.on('error', function(err) { @@ -37,13 +35,13 @@ test("parse compressed archive (created by DOS zip)", function (t) { }); test("extract compressed archive w/ file sizes known prior to zlib inflation (created by POSIX zip)", function (t) { - var archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); + const archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); temp.mkdir('node-unzip-', function (err, dirPath) { if (err) { throw err; } - var unzipExtractor = unzip.Extract({ path: dirPath }); + const unzipExtractor = unzip.Extract({ path: dirPath }); unzipExtractor.on('error', function(err) { throw err; }); diff --git a/test/extract-finish.js b/test/extract-finish.js index 1fd50b1..0a133de 100644 --- a/test/extract-finish.js +++ b/test/extract-finish.js @@ -1,26 +1,24 @@ -'use strict'; - -var test = require('tap').test; -var fs = require('fs'); -var os = require('os'); -var path = require('path'); -var temp = require('temp'); -var unzip = require('../'); -var Stream = require('stream'); +const test = require('tap').test; +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const temp = require('temp'); +const unzip = require('../'); +const Stream = require('stream'); test("Only emit finish/close when extraction has completed", function (t) { - var archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); + const archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); - temp.mkdir('node-unzip-finish-', function (err, dirPath) { + temp.mkdir('node-unzip-finish-', function (err) { if (err) { throw err; } - var filesDone = 0; + let filesDone = 0; function getWriter() { - var delayStream = new Stream.Transform(); + const delayStream = new Stream.Transform(); delayStream._transform = function(d, e, cb) { setTimeout(cb, 500); @@ -36,12 +34,12 @@ test("Only emit finish/close when extraction has completed", function (t) { } - var unzipExtractor = unzip.Extract({ getWriter: getWriter, path: os.tmpdir() }); + const unzipExtractor = unzip.Extract({ getWriter: getWriter, path: os.tmpdir() }); unzipExtractor.on('error', function(err) { throw err; }); unzipExtractor.promise().then(function() { - t.same(filesDone,2); + t.same(filesDone, 2); t.end(); }); diff --git a/test/extractFromUrl.js b/test/extractFromUrl.js index 0bafb09..e8b4461 100644 --- a/test/extractFromUrl.js +++ b/test/extractFromUrl.js @@ -1,21 +1,19 @@ -"use strict"; - -var test = require("tap").test; -var fs = require("fs"); -var unzip = require("../"); -var os = require("os"); -var request = require("request"); +const test = require("tap").test; +const fs = require("fs"); +const unzip = require("../"); +const os = require("os"); +const request = require("request"); test("extract zip from url", function (t) { - var extractPath = os.tmpdir() + "/node-unzip-extract-fromURL"; // Not using path resolve, cause it should be resolved in extract() function + const extractPath = os.tmpdir() + "/node-unzip-extract-fromURL"; // Not using path resolve, cause it should be resolved in extract() function unzip.Open.url( request, "https://github.com/h5bp/html5-boilerplate/releases/download/v7.3.0/html5-boilerplate_v7.3.0.zip" ) .then(function(d) { return d.extract({ path: extractPath }); }) - .then(function(d) { - var dirFiles = fs.readdirSync(extractPath); - var isPassing = + .then(function() { + const dirFiles = fs.readdirSync(extractPath); + const isPassing = dirFiles.length > 10 && dirFiles.indexOf("css") > -1 && dirFiles.indexOf("index.html") > -1 && diff --git a/test/extractNormalize.js b/test/extractNormalize.js index 1a89867..334ac13 100644 --- a/test/extractNormalize.js +++ b/test/extractNormalize.js @@ -1,26 +1,24 @@ -'use strict'; - -var test = require('tap').test; -var fs = require('fs'); -var os = require('os'); -var path = require('path'); -var temp = require('temp'); -var unzip = require('../'); -var Stream = require('stream'); +const test = require('tap').test; +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const temp = require('temp'); +const unzip = require('../'); +const Stream = require('stream'); test("Extract should normalize the path option", function (t) { - var archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); + const archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); - temp.mkdir('node-unzip-normalize-', function (err, dirPath) { + temp.mkdir('node-unzip-normalize-', function (err) { if (err) { throw err; } - var filesDone = 0; + let filesDone = 0; function getWriter() { - var delayStream = new Stream.Transform(); + const delayStream = new Stream.Transform(); delayStream._transform = function(d, e, cb) { setTimeout(cb, 500); @@ -37,14 +35,14 @@ test("Extract should normalize the path option", function (t) { // don't use path.join, it will normalize the path which defeats // the purpose of this test - var extractPath = os.tmpdir() + "/unzipper\\normalize/././extract\\test"; + const extractPath = os.tmpdir() + "/unzipper\\normalize/././extract\\test"; - var unzipExtractor = unzip.Extract({ getWriter: getWriter, path: extractPath }); + const unzipExtractor = unzip.Extract({ getWriter: getWriter, path: extractPath }); unzipExtractor.on('error', function(err) { throw err; }); unzipExtractor.on('close', function() { - t.same(filesDone,2); + t.same(filesDone, 2); t.end(); }); @@ -53,17 +51,17 @@ test("Extract should normalize the path option", function (t) { }); test("Extract should resolve after normalize the path option", function (t) { - var archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); + const archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); - temp.mkdir('node-unzip-normalize-2-', function (err, dirPath) { + temp.mkdir('node-unzip-normalize-2-', function (err) { if (err) { throw err; } - var filesDone = 0; + let filesDone = 0; function getWriter() { - var delayStream = new Stream.Transform(); + const delayStream = new Stream.Transform(); delayStream._transform = function(d, e, cb) { setTimeout(cb, 500); @@ -78,12 +76,12 @@ test("Extract should resolve after normalize the path option", function (t) { return delayStream; } - var unzipExtractor = unzip.Extract({ getWriter: getWriter, path: '.' }); + const unzipExtractor = unzip.Extract({ getWriter: getWriter, path: '.' }); unzipExtractor.on('error', function(err) { throw err; }); unzipExtractor.on('close', function() { - t.same(filesDone,2); + t.same(filesDone, 2); t.end(); }); diff --git a/test/fileSizeUnknownFlag.js b/test/fileSizeUnknownFlag.js index a0f3af4..b86e78e 100644 --- a/test/fileSizeUnknownFlag.js +++ b/test/fileSizeUnknownFlag.js @@ -1,16 +1,14 @@ -'use strict'; - -var test = require('tap').test; -var fs = require('fs'); -var path = require('path'); -var temp = require('temp'); -var dirdiff = require('dirdiff'); -var unzip = require('../'); +const test = require('tap').test; +const fs = require('fs'); +const path = require('path'); +const temp = require('temp'); +const dirdiff = require('dirdiff'); +const unzip = require('../'); test("parse archive w/ file size unknown flag set (created by OS X Finder)", function (t) { - var archive = path.join(__dirname, '../testData/compressed-OSX-Finder/archive.zip'); + const archive = path.join(__dirname, '../testData/compressed-OSX-Finder/archive.zip'); - var unzipParser = unzip.Parse(); + const unzipParser = unzip.Parse(); fs.createReadStream(archive).pipe(unzipParser); unzipParser.on('error', function(err) { throw err; @@ -20,13 +18,13 @@ test("parse archive w/ file size unknown flag set (created by OS X Finder)", fun }); test("extract archive w/ file size unknown flag set (created by OS X Finder)", function (t) { - var archive = path.join(__dirname, '../testData/compressed-OSX-Finder/archive.zip'); + const archive = path.join(__dirname, '../testData/compressed-OSX-Finder/archive.zip'); temp.mkdir('node-unzip-', function (err, dirPath) { if (err) { throw err; } - var unzipExtractor = unzip.Extract({ path: dirPath }); + const unzipExtractor = unzip.Extract({ path: dirPath }); unzipExtractor.on('error', function(err) { throw err; }); @@ -49,13 +47,13 @@ test("extract archive w/ file size unknown flag set (created by OS X Finder)", f }); test("archive w/ language encoding flag set", function (t) { - var archive = path.join(__dirname, '../testData/compressed-flags-set/archive.zip'); + const archive = path.join(__dirname, '../testData/compressed-flags-set/archive.zip'); temp.mkdir('node-unzip-', function (err, dirPath) { if (err) { throw err; } - var unzipExtractor = unzip.Extract({ path: dirPath }); + const unzipExtractor = unzip.Extract({ path: dirPath }); unzipExtractor.on('error', function(err) { throw err; }); diff --git a/test/forceStream.js b/test/forceStream.js index 510870b..de69c13 100644 --- a/test/forceStream.js +++ b/test/forceStream.js @@ -1,20 +1,14 @@ -'use strict'; - -var test = require('tap').test; -var fs = require('fs'); -var path = require('path'); -var Stream = require('stream'); -var unzip = require('../'); - -// Backwards compatibility for node versions < 8 -if (!Stream.Writable || !Stream.Writable.prototype.destroy) - Stream = require('readable-stream'); +const test = require('tap').test; +const fs = require('fs'); +const path = require('path'); +const Stream = require('stream'); +const unzip = require('../'); test("verify that setting the forceStream option emits a data event instead of entry", function (t) { - var archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); + const archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); - var dataEventEmitted = false; - var entryEventEmitted = false; + let dataEventEmitted = false; + let entryEventEmitted = false; fs.createReadStream(archive) .pipe(unzip.Parse({ forceStream: true })) .on('data', function(entry) { @@ -24,7 +18,7 @@ test("verify that setting the forceStream option emits a data event instead of e .on('entry', function() { entryEventEmitted = true; }) - .on('finish', function() { + .on('finish', function() { t.equal(dataEventEmitted, true); t.equal(entryEventEmitted, false); t.end(); diff --git a/test/notArchive.js b/test/notArchive.js index fa941f3..d371a65 100644 --- a/test/notArchive.js +++ b/test/notArchive.js @@ -1,16 +1,14 @@ -'use strict'; +const test = require('tap').test; +const fs = require('fs'); +const path = require('path'); +const temp = require('temp'); +const unzip = require('../'); -var test = require('tap').test; -var fs = require('fs'); -var path = require('path'); -var temp = require('temp'); -var unzip = require('../'); - -var archive = path.join(__dirname, '../package.json'); +const archive = path.join(__dirname, '../package.json'); test('parse a file that is not an archive', function (t) { - var unzipParser = unzip.Parse(); + const unzipParser = unzip.Parse(); fs.createReadStream(archive).pipe(unzipParser); unzipParser.on('error', function(err) { t.ok(err.message.indexOf('invalid signature: 0x') !== -1); @@ -28,7 +26,7 @@ test('extract a file that is not an archive', function (t) { if (err) { throw err; } - var unzipExtractor = unzip.Extract({ path: dirPath }); + const unzipExtractor = unzip.Extract({ path: dirPath }); unzipExtractor.on('error', function(err) { t.ok(err.message.indexOf('invalid signature: 0x') !== -1); t.end(); diff --git a/test/office-files.js b/test/office-files.js index c0f51c4..b7baabe 100644 --- a/test/office-files.js +++ b/test/office-files.js @@ -1,20 +1,16 @@ +const test = require('tap').test; +const path = require('path'); +const unzip = require('../'); -var test = require('tap').test; -var fs = require('fs'); -var path = require('path'); -var unzip = require('../'); -var il = require('iconv-lite'); -var Promise = require('bluebird'); - -test("get content a docx file without errors", async function (t) { - var archive = path.join(__dirname, '../testData/office/testfile.docx'); +test("get content a docx file without errors", async function () { + const archive = path.join(__dirname, '../testData/office/testfile.docx'); const directory = await unzip.Open.file(archive); await Promise.all(directory.files.map(file => file.buffer())); }); -test("get content a xlsx file without errors", async function (t) { - var archive = path.join(__dirname, '../testData/office/testfile.xlsx'); +test("get content a xlsx file without errors", async function () { + const archive = path.join(__dirname, '../testData/office/testfile.xlsx'); const directory = await unzip.Open.file(archive); await Promise.all(directory.files.map(file => file.buffer())); diff --git a/test/open-extract.js b/test/open-extract.js index 7c97198..f14347e 100644 --- a/test/open-extract.js +++ b/test/open-extract.js @@ -1,14 +1,12 @@ -'use strict'; - -var test = require('tap').test; -var path = require('path'); -var temp = require('temp'); -var dirdiff = require('dirdiff'); -var unzip = require('../'); +const test = require('tap').test; +const path = require('path'); +const temp = require('temp'); +const dirdiff = require('dirdiff'); +const unzip = require('../'); test("extract compressed archive with open.file.extract", function (t) { - var archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); + const archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); temp.mkdir('node-unzip-2', function (err, dirPath) { if (err) { @@ -29,6 +27,5 @@ test("extract compressed archive with open.file.extract", function (t) { t.end(); }); }); - }); }); \ No newline at end of file diff --git a/test/openBuffer.js b/test/openBuffer.js index 8ca4f46..511a323 100644 --- a/test/openBuffer.js +++ b/test/openBuffer.js @@ -1,23 +1,21 @@ -'use strict'; - -var test = require('tap').test; -var fs = require('fs'); -var path = require('path'); -var unzip = require('../'); +const test = require('tap').test; +const fs = require('fs'); +const path = require('path'); +const unzip = require('../'); test("get content of a single file entry out of a buffer", function (t) { - var archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); - var buffer = fs.readFileSync(archive); + const archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); + const buffer = fs.readFileSync(archive); return unzip.Open.buffer(buffer) .then(function(d) { - var file = d.files.filter(function(file) { + const file = d.files.filter(function(file) { return file.path == 'file.txt'; })[0]; return file.buffer() .then(function(str) { - var fileStr = fs.readFileSync(path.join(__dirname, '../testData/compressed-standard/inflated/file.txt'), 'utf8'); + const fileStr = fs.readFileSync(path.join(__dirname, '../testData/compressed-standard/inflated/file.txt'), 'utf8'); t.equal(str.toString(), fileStr); t.end(); }); diff --git a/test/openComment.js b/test/openComment.js index e23fd65..2c5024a 100644 --- a/test/openComment.js +++ b/test/openComment.js @@ -1,16 +1,14 @@ -'use strict'; - -var test = require('tap').test; -var path = require('path'); -var unzip = require('../'); +const test = require('tap').test; +const path = require('path'); +const unzip = require('../'); test("get comment out of a zip", function (t) { - var archive = path.join(__dirname, '../testData/compressed-comment/archive.zip'); + const archive = path.join(__dirname, '../testData/compressed-comment/archive.zip'); unzip.Open.file(archive) .then(function(d) { - t.equal('Zipfile has a comment', d.comment); - t.end(); + t.equal('Zipfile has a comment', d.comment); + t.end(); }); }); \ No newline at end of file diff --git a/test/openCustom.js b/test/openCustom.js index 5cd0f78..de60836 100644 --- a/test/openCustom.js +++ b/test/openCustom.js @@ -1,16 +1,13 @@ -'use strict'; - -var test = require('tap').test; -var fs = require('fs'); -var path = require('path'); -var unzip = require('../unzip'); -var Promise = require('bluebird'); +const test = require('tap').test; +const fs = require('fs'); +const path = require('path'); +const unzip = require('../unzip'); test("get content of a single file entry out of a zip", function (t) { - var archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); + const archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); - var customSource = { - stream: function(offset,length) { + const customSource = { + stream: function(offset, length) { return fs.createReadStream(archive, {start: offset, end: length && offset+length}); }, size: function() { @@ -27,13 +24,13 @@ test("get content of a single file entry out of a zip", function (t) { return unzip.Open.custom(customSource) .then(function(d) { - var file = d.files.filter(function(file) { + const file = d.files.filter(function(file) { return file.path == 'file.txt'; })[0]; return file.buffer() .then(function(str) { - var fileStr = fs.readFileSync(path.join(__dirname, '../testData/compressed-standard/inflated/file.txt'), 'utf8'); + const fileStr = fs.readFileSync(path.join(__dirname, '../testData/compressed-standard/inflated/file.txt'), 'utf8'); t.equal(str.toString(), fileStr); t.end(); }); diff --git a/test/openFile.js b/test/openFile.js index 750fd51..245c6d1 100644 --- a/test/openFile.js +++ b/test/openFile.js @@ -1,24 +1,23 @@ 'use strict'; -var test = require('tap').test; -var fs = require('fs'); -var path = require('path'); -var unzip = require('../'); -var il = require('iconv-lite'); -var Promise = require('bluebird'); +const test = require('tap').test; +const fs = require('fs'); +const path = require('path'); +const unzip = require('../'); +const il = require('iconv-lite'); test("get content of a single file entry out of a zip", function (t) { - var archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); + const archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); return unzip.Open.file(archive) .then(function(d) { - var file = d.files.filter(function(file) { + const file = d.files.filter(function(file) { return file.path == 'file.txt'; })[0]; return file.buffer() .then(function(str) { - var fileStr = fs.readFileSync(path.join(__dirname, '../testData/compressed-standard/inflated/file.txt'), 'utf8'); + const fileStr = fs.readFileSync(path.join(__dirname, '../testData/compressed-standard/inflated/file.txt'), 'utf8'); t.equal(str.toString(), fileStr); t.end(); }); @@ -26,19 +25,19 @@ test("get content of a single file entry out of a zip", function (t) { }); test("get content of a single file entry out of a DOS zip", function (t) { - var archive = path.join(__dirname, '../testData/compressed-cp866/archive.zip'); + const archive = path.join(__dirname, '../testData/compressed-cp866/archive.zip'); return unzip.Open.file(archive, { fileNameEncoding: 'cp866' }) .then(function(d) { - var file = d.files.filter(function(file) { - var fileName = file.isUnicode ? file.path : il.decode(file.pathBuffer, 'cp866'); + const file = d.files.filter(function(file) { + const fileName = file.isUnicode ? file.path : il.decode(file.pathBuffer, 'cp866'); return fileName == 'Тест.txt'; })[0]; return file.buffer() .then(function(str) { - var fileStr = il.decode(fs.readFileSync(path.join(__dirname, '../testData/compressed-cp866/inflated/Тест.txt')), 'cp1251'); - var zipStr = il.decode(str, 'cp1251'); + const fileStr = il.decode(fs.readFileSync(path.join(__dirname, '../testData/compressed-cp866/inflated/Тест.txt')), 'cp1251'); + const zipStr = il.decode(str, 'cp1251'); t.equal(zipStr, fileStr); t.equal(zipStr, 'Тестовый файл'); t.end(); @@ -48,17 +47,17 @@ test("get content of a single file entry out of a DOS zip", function (t) { test("get multiple buffers concurrently", function (t) { - var archive = path.join(__dirname, '../testData/compressed-directory-entry/archive.zip'); + const archive = path.join(__dirname, '../testData/compressed-directory-entry/archive.zip'); return unzip.Open.file(archive) .then(function(directory) { return Promise.all(directory.files.map(function(file) { return file.buffer(); })) - .then(function(b) { - directory.files.forEach(function(file,i) { - t.equal(file.uncompressedSize,b[i].length); + .then(function(b) { + directory.files.forEach(function(file, i) { + t.equal(file.uncompressedSize, b[i].length); + }); + t.end(); }); - t.end(); - }); }); }); \ No newline at end of file diff --git a/test/openFileEncrypted.js b/test/openFileEncrypted.js index aa7da3c..b263cf7 100644 --- a/test/openFileEncrypted.js +++ b/test/openFileEncrypted.js @@ -1,22 +1,20 @@ -'use strict'; +const test = require('tap').test; +const fs = require('fs'); +const path = require('path'); +const unzip = require('../'); -var test = require('tap').test; -var fs = require('fs'); -var path = require('path'); -var unzip = require('../'); - -var archive = path.join(__dirname, '../testData/compressed-encrypted/archive.zip'); +const archive = path.join(__dirname, '../testData/compressed-encrypted/archive.zip'); test("get content of a single file entry out of a zip", function (t) { return unzip.Open.file(archive) .then(function(d) { - var file = d.files.filter(function(file) { + const file = d.files.filter(function(file) { return file.path == 'file.txt'; })[0]; - return file.buffer('abc123') + return file.buffer('abc123') .then(function(str) { - var fileStr = fs.readFileSync(path.join(__dirname, '../testData/compressed-standard/inflated/file.txt'), 'utf8'); + const fileStr = fs.readFileSync(path.join(__dirname, '../testData/compressed-standard/inflated/file.txt'), 'utf8'); t.equal(str.toString(), fileStr); t.end(); }); @@ -26,39 +24,37 @@ test("get content of a single file entry out of a zip", function (t) { test("error if password is missing", function (t) { return unzip.Open.file(archive) .then(function(d) { - var file = d.files.filter(function(file) { + const file = d.files.filter(function(file) { return file.path == 'file.txt'; })[0]; - return file.buffer() - .then(function() { - t.error('should error'); - },function(e) { - t.equal(e.message,'MISSING_PASSWORD'); - }) - .then(function() { - t.end(); - }); - + return file.buffer() + .then(function() { + t.error('should error'); + }, function(e) { + t.equal(e.message, 'MISSING_PASSWORD'); + }) + .then(function() { + t.end(); + }); }); }); test("error if password is wrong", function (t) { return unzip.Open.file(archive) .then(function(d) { - var file = d.files.filter(function(file) { + const file = d.files.filter(function(file) { return file.path == 'file.txt'; })[0]; - return file.buffer('abc1') - .then(function() { - t.error('should error'); - },function(e) { - t.equal(e.message,'BAD_PASSWORD'); - }) - .then(function() { - t.end(); - }); - + return file.buffer('abc1') + .then(function() { + t.error('should error'); + }, function(e) { + t.equal(e.message, 'BAD_PASSWORD'); + }) + .then(function() { + t.end(); + }); }); }); \ No newline at end of file diff --git a/test/openS3.js b/test/openS3.js index e2afb78..a5efdac 100644 --- a/test/openS3.js +++ b/test/openS3.js @@ -1,32 +1,30 @@ -'use strict'; - -var test = require('tap').test; -var fs = require('fs'); -var path = require('path'); -var unzip = require('../'); -var AWS = require('aws-sdk'); -var s3 = new AWS.S3({region: 'us-east-1'}); +const test = require('tap').test; +const fs = require('fs'); +const path = require('path'); +const unzip = require('../'); +const AWS = require('aws-sdk'); +const s3 = new AWS.S3({region: 'us-east-1'}); // We have to modify the `getObject` and `headObject` to use makeUnauthenticated -s3.getObject = function(params,cb) { - return s3.makeUnauthenticatedRequest('getObject',params,cb); +s3.getObject = function(params, cb) { + return s3.makeUnauthenticatedRequest('getObject', params, cb); }; -s3.headObject = function(params,cb) { - return s3.makeUnauthenticatedRequest('headObject',params,cb); +s3.headObject = function(params, cb) { + return s3.makeUnauthenticatedRequest('headObject', params, cb); }; test("get content of a single file entry out of a zip", { skip: true }, function(t) { - return unzip.Open.s3(s3,{ Bucket: 'unzipper', Key: 'archive.zip' }) + return unzip.Open.s3(s3, { Bucket: 'unzipper', Key: 'archive.zip' }) .then(function(d) { - var file = d.files.filter(function(file) { + const file = d.files.filter(function(file) { return file.path == 'file.txt'; })[0]; return file.buffer() .then(function(str) { - var fileStr = fs.readFileSync(path.join(__dirname, '../testData/compressed-standard/inflated/file.txt'), 'utf8'); + const fileStr = fs.readFileSync(path.join(__dirname, '../testData/compressed-standard/inflated/file.txt'), 'utf8'); t.equal(str.toString(), fileStr); t.end(); }); diff --git a/test/openUrl.js b/test/openUrl.js index 4e241cd..ba4df72 100644 --- a/test/openUrl.js +++ b/test/openUrl.js @@ -1,21 +1,19 @@ -'use strict'; - -var test = require('tap').test; -var fs = require('fs'); -var path = require('path'); -var unzip = require('../'); -var request = require('request'); +const test = require('tap').test; +const fs = require('fs'); +const path = require('path'); +const unzip = require('../'); +const request = require('request'); test("get content of a single file entry out of a 502 MB zip from web", function (t) { - return unzip.Open.url(request,'https://github.com/twbs/bootstrap/releases/download/v4.0.0/bootstrap-4.0.0-dist.zip') + return unzip.Open.url(request, 'https://github.com/twbs/bootstrap/releases/download/v4.0.0/bootstrap-4.0.0-dist.zip') .then(function(d) { - var file = d.files.filter(function(d) { + const file = d.files.filter(function(d) { return d.path === 'css/bootstrap-reboot.min.css'; })[0]; return file.buffer(); }) .then(function(str) { - var fileStr = fs.readFileSync(path.join(__dirname, '../testData/bootstrap-reboot.min.css'), 'utf8'); + const fileStr = fs.readFileSync(path.join(__dirname, '../testData/bootstrap-reboot.min.css'), 'utf8'); t.equal(str.toString(), fileStr); t.end(); }); diff --git a/test/parseBuffer.js b/test/parseBuffer.js index 3092751..4db8889 100644 --- a/test/parseBuffer.js +++ b/test/parseBuffer.js @@ -1,16 +1,16 @@ 'use strict'; -var test = require('tap').test; -var parseBuffer = require('../lib/parseBuffer'); +const test = require('tap').test; +const parseBuffer = require('../lib/parseBuffer'); const buf = Buffer.from([ - 0x62, - 0x75, - 0x66, - 0x68, - 0x65, - 0x72, - 0xFF, + 0x62, + 0x75, + 0x66, + 0x68, + 0x65, + 0x72, + 0xFF, 0xAE, 0x00, 0x11, @@ -35,7 +35,7 @@ test(`parse little endian values for increasing byte size`, function (t) { key4: 3824536674483896300 }); t.end(); -}) +}); test(`parse little endian values for decreasing byte size`, function (t) { const result = parseBuffer.parse(buf, [ @@ -51,7 +51,7 @@ test(`parse little endian values for decreasing byte size`, function (t) { key4: 53 }); t.end(); -}) +}); test(`parse little endian values with null keys due to small buffer`, function (t) { const result = parseBuffer.parse(buf, [ @@ -67,4 +67,4 @@ test(`parse little endian values with null keys due to small buffer`, function ( key4: null }); t.end(); -}) \ No newline at end of file +}); \ No newline at end of file diff --git a/test/parseCompressedDirectory.js b/test/parseCompressedDirectory.js index 835cded..c955f4c 100644 --- a/test/parseCompressedDirectory.js +++ b/test/parseCompressedDirectory.js @@ -1,11 +1,9 @@ -'use strict'; - -var test = require('tap').test; -var fs = require('fs'); -var path = require('path'); -var temp = require('temp'); -var dirdiff = require('dirdiff'); -var unzip = require('../'); +const test = require('tap').test; +const fs = require('fs'); +const path = require('path'); +const temp = require('temp'); +const dirdiff = require('dirdiff'); +const unzip = require('../'); /* zipinfo testData/compressed-directory-entry/archive.zip | grep META-INF/ @@ -14,13 +12,13 @@ zipinfo testData/compressed-directory-entry/archive.zip | grep META-INF/ ?rw------- 2.0 unx 244 b- defN 17-Sep-09 20:43 META-INF/container.xml */ test("extract compressed archive w/ a compressed directory entry", function (t) { - var archive = path.join(__dirname, '../testData/compressed-directory-entry/archive.zip'); + const archive = path.join(__dirname, '../testData/compressed-directory-entry/archive.zip'); temp.mkdir('node-unzip-', function (err, dirPath) { if (err) { throw err; } - var unzipExtractor = unzip.Extract({ path: dirPath }); + const unzipExtractor = unzip.Extract({ path: dirPath }); unzipExtractor.on('error', function(err) { throw err; }); diff --git a/test/parseContent.js b/test/parseContent.js index 0338897..79a4375 100644 --- a/test/parseContent.js +++ b/test/parseContent.js @@ -1,14 +1,10 @@ -'use strict'; - -var test = require('tap').test; -var fs = require('fs'); -var path = require('path'); -var temp = require('temp'); -var streamBuffers = require("stream-buffers"); -var unzip = require('../'); +const test = require('tap').test; +const fs = require('fs'); +const path = require('path'); +const unzip = require('../'); test("get content of a single file entry out of a zip", function (t) { - var archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); + const archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); fs.createReadStream(archive) .pipe(unzip.Parse()) @@ -18,7 +14,7 @@ test("get content of a single file entry out of a zip", function (t) { entry.buffer() .then(function(str) { - var fileStr = fs.readFileSync(path.join(__dirname, '../testData/compressed-standard/inflated/file.txt'), 'utf8'); + const fileStr = fs.readFileSync(path.join(__dirname, '../testData/compressed-standard/inflated/file.txt'), 'utf8'); t.equal(str.toString(), fileStr); t.end(); }); diff --git a/test/parseDateTime.js b/test/parseDateTime.js index ff46132..f24f25e 100644 --- a/test/parseDateTime.js +++ b/test/parseDateTime.js @@ -1,19 +1,17 @@ -'use strict'; +const test = require('tap').test; +const path = require('path'); +const unzip = require('../'); +const fs = require('fs'); -var test = require('tap').test; -var path = require('path'); -var unzip = require('../'); -var fs = require('fs'); - -var archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); +const archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); test('parse datetime using Open', function (t) { return unzip.Open.file(archive) .then(function(d) { - var file = d.files.filter(function(file) { + const file = d.files.filter(function(file) { return file.path == 'file.txt'; })[0]; - t.same(file.lastModifiedDateTime,new Date('2012-08-08T11:21:10.000Z')); + t.same(file.lastModifiedDateTime, new Date('2012-08-08T11:21:10.000Z')); t.end(); }); }); @@ -24,7 +22,7 @@ test('parse datetime using Parse', function(t) { .on('entry', function(entry) { if (entry.path !== 'file.txt') return entry.autodrain(); - t.same(entry.vars.lastModifiedDateTime,new Date('2012-08-08T11:21:10.000Z')); + t.same(entry.vars.lastModifiedDateTime, new Date('2012-08-08T11:21:10.000Z')); t.end(); }); }); diff --git a/test/parseOneEntry.js b/test/parseOneEntry.js index adf5f8e..a7f32ec 100644 --- a/test/parseOneEntry.js +++ b/test/parseOneEntry.js @@ -1,23 +1,17 @@ 'use strict'; -var test = require('tap').test; -var fs = require('fs'); -var path = require('path'); -var streamBuffers = require("stream-buffers"); -var unzip = require('../'); -var Stream = require('stream'); - -// Backwards compatibility for node 0.8 -if (!Stream.Writable) - Stream = require('readable-stream'); - -var archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); +const test = require('tap').test; +const fs = require('fs'); +const path = require('path'); +const streamBuffers = require("stream-buffers"); +const unzip = require('../'); +const archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); test("pipe a single file entry out of a zip", function (t) { - var writableStream = new streamBuffers.WritableStreamBuffer(); + const writableStream = new streamBuffers.WritableStreamBuffer(); writableStream.on('close', function () { - var str = writableStream.getContentsAsString('utf8'); - var fileStr = fs.readFileSync(path.join(__dirname, '../testData/compressed-standard/inflated/file.txt'), 'utf8'); + const str = writableStream.getContentsAsString('utf8'); + const fileStr = fs.readFileSync(path.join(__dirname, '../testData/compressed-standard/inflated/file.txt'), 'utf8'); t.equal(str, fileStr); t.end(); }); @@ -30,16 +24,16 @@ test("pipe a single file entry out of a zip", function (t) { test('errors if file is not found', function (t) { fs.createReadStream(archive) .pipe(unzip.ParseOne('not_exists')) - .on('error',function(e) { - t.equal(e.message,'PATTERN_NOT_FOUND'); + .on('error', function(e) { + t.equal(e.message, 'PATTERN_NOT_FOUND'); t.end(); }); }); test('error - invalid signature', function(t) { unzip.ParseOne() - .on('error',function(e) { - t.equal(e.message.indexOf('invalid signature'),0); + .on('error', function(e) { + t.equal(e.message.indexOf('invalid signature'), 0); t.end(); }) .end('this is not a zip file'); @@ -47,9 +41,9 @@ test('error - invalid signature', function(t) { test('error - file ended', function(t) { unzip.ParseOne() - .on('error',function(e) { + .on('error', function(e) { if (e.message == 'PATTERN_NOT_FOUND') return; - t.equal(e.message,'FILE_ENDED'); + t.equal(e.message, 'FILE_ENDED'); t.end(); }) .end('t'); diff --git a/test/parsePromise.js b/test/parsePromise.js index f2f7fb3..70676e3 100644 --- a/test/parsePromise.js +++ b/test/parsePromise.js @@ -1,14 +1,13 @@ 'use strict'; -var test = require('tap').test; -var fs = require('fs'); -var path = require('path'); -var temp = require('temp'); -var unzip = require('../'); -var entryRead ; +const test = require('tap').test; +const fs = require('fs'); +const path = require('path'); +const unzip = require('../'); +let entryRead ; test("promise should resolve when entries have been processed", function (t) { - var archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); + const archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); fs.createReadStream(archive) .pipe(unzip.Parse()) @@ -17,34 +16,34 @@ test("promise should resolve when entries have been processed", function (t) { return entry.autodrain(); entry.buffer() - .then(function(str) { + .then(function() { entryRead = true; }); }) .promise() .then(function() { - t.equal(entryRead,true); + t.equal(entryRead, true); t.end(); - },function() { + }, function() { t.fail('This project should resolve'); t.end(); }); }); test("promise should be rejected if there is an error in the stream", function (t) { - var archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); + const archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); fs.createReadStream(archive) .pipe(unzip.Parse()) - .on('entry', function(entry) { - this.emit('error',new Error('this is an error')); + .on('entry', function() { + this.emit('error', new Error('this is an error')); }) .promise() .then(function() { t.fail('This promise should be rejected'); t.end(); - },function(e) { - t.equal(e.message,'this is an error'); + }, function(e) { + t.equal(e.message, 'this is an error'); t.end(); }); }); \ No newline at end of file diff --git a/test/pipeSingleEntry.js b/test/pipeSingleEntry.js index d29b4eb..b3fb385 100644 --- a/test/pipeSingleEntry.js +++ b/test/pipeSingleEntry.js @@ -1,23 +1,20 @@ -'use strict'; - -var test = require('tap').test; -var fs = require('fs'); -var path = require('path'); -var temp = require('temp'); -var streamBuffers = require("stream-buffers"); -var unzip = require('../'); +const test = require('tap').test; +const fs = require('fs'); +const path = require('path'); +const streamBuffers = require("stream-buffers"); +const unzip = require('../'); test("pipe a single file entry out of a zip", function (t) { - var archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); + const archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); fs.createReadStream(archive) .pipe(unzip.Parse()) .on('entry', function(entry) { if (entry.path === 'file.txt') { - var writableStream = new streamBuffers.WritableStreamBuffer(); + const writableStream = new streamBuffers.WritableStreamBuffer(); writableStream.on('close', function () { - var str = writableStream.getContentsAsString('utf8'); - var fileStr = fs.readFileSync(path.join(__dirname, '../testData/compressed-standard/inflated/file.txt'), 'utf8') + const str = writableStream.getContentsAsString('utf8'); + const fileStr = fs.readFileSync(path.join(__dirname, '../testData/compressed-standard/inflated/file.txt'), 'utf8'); t.equal(str, fileStr); t.end(); }); diff --git a/test/streamSingleEntry.js b/test/streamSingleEntry.js index 25611d9..9fc4466 100644 --- a/test/streamSingleEntry.js +++ b/test/streamSingleEntry.js @@ -1,27 +1,18 @@ -'use strict'; - -var test = require('tap').test; -var fs = require('fs'); -var path = require('path'); -var temp = require('temp'); -var streamBuffers = require("stream-buffers"); -var unzip = require('../'); -var Stream = require('stream'); - -// Backwards compatibility for node 0.8 -if (!Stream.Writable) - Stream = require('readable-stream'); - - +const test = require('tap').test; +const fs = require('fs'); +const path = require('path'); +const streamBuffers = require("stream-buffers"); +const unzip = require('../'); +const Stream = require('stream'); test("pipe a single file entry out of a zip", function (t) { - var receiver = Stream.Transform({objectMode:true}); - receiver._transform = function(entry,e,cb) { + const receiver = Stream.Transform({objectMode:true}); + receiver._transform = function(entry, e, cb) { if (entry.path === 'file.txt') { - var writableStream = new streamBuffers.WritableStreamBuffer(); + const writableStream = new streamBuffers.WritableStreamBuffer(); writableStream.on('close', function () { - var str = writableStream.getContentsAsString('utf8'); - var fileStr = fs.readFileSync(path.join(__dirname, '../testData/compressed-standard/inflated/file.txt'), 'utf8'); + const str = writableStream.getContentsAsString('utf8'); + const fileStr = fs.readFileSync(path.join(__dirname, '../testData/compressed-standard/inflated/file.txt'), 'utf8'); t.equal(str, fileStr); t.end(); cb(); @@ -33,10 +24,10 @@ test("pipe a single file entry out of a zip", function (t) { } }; - var archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); + const archive = path.join(__dirname, '../testData/compressed-standard/archive.zip'); fs.createReadStream(archive) .pipe(unzip.Parse()) .pipe(receiver); - + }); \ No newline at end of file diff --git a/test/uncompressed.js b/test/uncompressed.js index 55479d6..94af3fd 100644 --- a/test/uncompressed.js +++ b/test/uncompressed.js @@ -1,17 +1,15 @@ -'use strict'; - -var test = require('tap').test; -var fs = require('fs'); -var os = require('os'); -var path = require('path'); -var temp = require('temp'); -var dirdiff = require('dirdiff'); -var unzip = require('../'); +const test = require('tap').test; +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const temp = require('temp'); +const dirdiff = require('dirdiff'); +const unzip = require('../'); test("parse uncompressed archive", function (t) { - var archive = path.join(__dirname, '../testData/uncompressed/archive.zip'); + const archive = path.join(__dirname, '../testData/uncompressed/archive.zip'); - var unzipParser = unzip.Parse(); + const unzipParser = unzip.Parse(); fs.createReadStream(archive).pipe(unzipParser); unzipParser.on('error', function(err) { throw err; @@ -21,13 +19,13 @@ test("parse uncompressed archive", function (t) { }); test("extract uncompressed archive", function (t) { - var archive = path.join(__dirname, '../testData/uncompressed/archive.zip'); + const archive = path.join(__dirname, '../testData/uncompressed/archive.zip'); temp.mkdir('node-unzip-', function (err, dirPath) { if (err) { throw err; } - var unzipExtractor = unzip.Extract({ path: dirPath }); + const unzipExtractor = unzip.Extract({ path: dirPath }); unzipExtractor.on('error', function(err) { throw err; }); @@ -50,13 +48,13 @@ test("extract uncompressed archive", function (t) { }); test("do not extract zip slip archive", function (t) { - var archive = path.join(__dirname, '../testData/zip-slip/zip-slip.zip'); + const archive = path.join(__dirname, '../testData/zip-slip/zip-slip.zip'); temp.mkdir('node-zipslip-', function (err, dirPath) { if (err) { throw err; } - var unzipExtractor = unzip.Extract({ path: dirPath }); + const unzipExtractor = unzip.Extract({ path: dirPath }); unzipExtractor.on('error', function(err) { throw err; }); @@ -65,12 +63,8 @@ test("do not extract zip slip archive", function (t) { fs.createReadStream(archive).pipe(unzipExtractor); function testNoSlip() { - if (fs.hasOwnProperty('access')) { - var mode = fs.F_OK | (fs.constants && fs.constants.F_OK); - return fs.access(path.join(os.tmpdir(), 'evil.txt'), mode, evilFileCallback); - } - // node 0.10 - return fs.stat(path.join(os.tmpdir(), 'evil.txt'), evilFileCallback); + const mode = fs.F_OK | (fs.constants && fs.constants.F_OK); + return fs.access(path.join(os.tmpdir(), 'evil.txt'), mode, evilFileCallback); } function evilFileCallback(err) { @@ -86,37 +80,33 @@ test("do not extract zip slip archive", function (t) { }); function testZipSlipArchive(t, slipFileName, attackPathFactory){ - var archive = path.join(__dirname, '../testData/zip-slip', slipFileName); + const archive = path.join(__dirname, '../testData/zip-slip', slipFileName); temp.mkdir('node-zipslip-' + slipFileName, function (err, dirPath) { if (err) { throw err; } - var attackPath = attackPathFactory(dirPath); + const attackPath = attackPathFactory(dirPath); CheckForSlip(attackPath, function(slipAlreadyExists){ if(slipAlreadyExists){ t.fail('Cannot check for slip because the slipped file already exists at "' + attackPath+ '"'); t.end(); } else{ - var unzipExtractor = unzip.Extract({ path: dirPath }); + const unzipExtractor = unzip.Extract({ path: dirPath }); unzipExtractor.on('error', function(err) { throw err; }); unzipExtractor.on('close', testNoSlip); - + fs.createReadStream(archive).pipe(unzipExtractor); } - }) + }); function CheckForSlip(path, resultCallback) { - var fsCallback = function(err){ return resultCallback(!err); }; - if (fs.hasOwnProperty('access')) { - var mode = fs.F_OK | (fs.constants && fs.constants.F_OK); - return fs.access(path, mode, fsCallback); - } - // node 0.10 - return fs.stat(path, fsCallback); + const fsCallback = function(err){ return resultCallback(!err); }; + const mode = fs.F_OK | (fs.constants && fs.constants.F_OK); + return fs.access(path, mode, fsCallback); } function testNoSlip() { @@ -128,20 +118,20 @@ function testZipSlipArchive(t, slipFileName, attackPathFactory){ t.pass('no zip slip from ' + slipFileName); } return t.end(); - }) + }); } }); } test("do not extract zip slip archive(Windows)", function (t) { - var pathFactory; + let pathFactory; if(process.platform === "win32") { - pathFactory = function(dirPath) { return '\\Temp\\evil.txt'; } + pathFactory = function() { return '\\Temp\\evil.txt'; }; } else{ // UNIX should treat the backslashes as escapes not directory delimiters // will be a file with slashes in the name. Looks real weird. - pathFactory = function(dirPath) { return path.join(dirPath, '..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\Temp\\evil.txt'); } + pathFactory = function(dirPath) { return path.join(dirPath, '..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\Temp\\evil.txt'); }; } testZipSlipArchive(t, 'zip-slip-win.zip', pathFactory); diff --git a/test/zip64.js b/test/zip64.js index 0819528..bd34ca0 100644 --- a/test/zip64.js +++ b/test/zip64.js @@ -1,39 +1,34 @@ 'use strict'; -var t = require('tap'); -var path = require('path'); -var unzip = require('../'); -var fs = require('fs'); -var Stream = require('stream'); -var temp = require('temp'); +const t = require('tap'); +const path = require('path'); +const unzip = require('../'); +const fs = require('fs'); +const temp = require('temp'); -var UNCOMPRESSED_SIZE = 5368709120; -var ZIP64_OFFSET = 72; -var ZIP64_SIZE = 36 - -// Backwards compatibility for node versions < 8 -if (!Stream.Writable || !Stream.Writable.prototype.destroy) - Stream = require('readable-stream'); +const UNCOMPRESSED_SIZE = 5368709120; +const ZIP64_OFFSET = 72; +const ZIP64_SIZE = 36; t.test('Correct uncompressed size for zip64', function (t) { - var archive = path.join(__dirname, '../testData/big.zip'); + const archive = path.join(__dirname, '../testData/big.zip'); t.test('in unzipper.Open', function(t) { unzip.Open.file(archive) - .then(function(d) { - var file = d.files[0]; - t.same(file.uncompressedSize, UNCOMPRESSED_SIZE, 'Open: Directory header'); - - d.files[0].stream() - .on('vars', function(vars) { - t.same(vars.uncompressedSize, UNCOMPRESSED_SIZE, 'Open: File header'); - t.end(); - }) - .on('error', function(e) { - t.same(e.message,'FILE_ENDED'); - t.end(); - }); - }); + .then(function(d) { + const file = d.files[0]; + t.same(file.uncompressedSize, UNCOMPRESSED_SIZE, 'Open: Directory header'); + + d.files[0].stream() + .on('vars', function(vars) { + t.same(vars.uncompressedSize, UNCOMPRESSED_SIZE, 'Open: File header'); + t.end(); + }) + .on('error', function(e) { + t.same(e.message, 'FILE_ENDED'); + t.end(); + }); + }); }); t.test('in unzipper.parse', function(t) { @@ -45,31 +40,31 @@ t.test('Correct uncompressed size for zip64', function (t) { }); }); - t.end(); + t.end(); }); t.test('Parse files from zip64 format correctly', function (t) { - var archive = path.join(__dirname, '../testData/zip64.zip'); + const archive = path.join(__dirname, '../testData/zip64.zip'); t.test('in unzipper.Open', function(t) { unzip.Open.file(archive) - .then(function(d) { - t.same(d.offsetToStartOfCentralDirectory, ZIP64_OFFSET, 'Open: Directory header'); - t.same(d.files.length, 1, 'Open: Files Size') - - d.files[0].stream() - .on('vars', function(vars) { - t.same(vars.offsetToLocalFileHeader, 0, 'Open: File header'); - t.same(vars.uncompressedSize, ZIP64_SIZE, 'Open: File header'); - t.same(vars.compressedSize, ZIP64_SIZE, 'Open: File header'); - t.same(vars.path, 'README', 'Open: File header'); - t.end(); - }) - .on('error', function(e) { - t.same(e.message,'FILE_ENDED'); - t.end(); - }); - }); + .then(function(d) { + t.same(d.offsetToStartOfCentralDirectory, ZIP64_OFFSET, 'Open: Directory header'); + t.same(d.files.length, 1, 'Open: Files Size'); + + d.files[0].stream() + .on('vars', function(vars) { + t.same(vars.offsetToLocalFileHeader, 0, 'Open: File header'); + t.same(vars.uncompressedSize, ZIP64_SIZE, 'Open: File header'); + t.same(vars.compressedSize, ZIP64_SIZE, 'Open: File header'); + t.same(vars.path, 'README', 'Open: File header'); + t.end(); + }) + .on('error', function(e) { + t.same(e.message, 'FILE_ENDED'); + t.end(); + }); + }); }); t.test('in unzipper.parse', function(t) { @@ -92,5 +87,5 @@ t.test('Parse files from zip64 format correctly', function (t) { }); }); - t.end(); + t.end(); });