Comparing version 0.5.14 to 0.5.15
490
adm-zip.js
@@ -6,4 +6,5 @@ const Utils = require("./util"); | ||
const get_Bool = (val, def) => (typeof val === "boolean" ? val : def); | ||
const get_Str = (val, def) => (typeof val === "string" ? val : def); | ||
const get_Bool = (...val) => Utils.findLast(val, (c) => typeof c === "boolean"); | ||
const get_Str = (...val) => Utils.findLast(val, (c) => typeof c === "string"); | ||
const get_Fun = (...val) => Utils.findLast(val, (c) => typeof c === "function"); | ||
@@ -50,2 +51,6 @@ const defaultOptions = { | ||
if (typeof opts.decoder !== "object" || typeof opts.decoder.encode !== "function" || typeof opts.decoder.decode !== "function") { | ||
opts.decoder = Utils.decoder; | ||
} | ||
// if input is file name we retrieve its content | ||
@@ -59,3 +64,3 @@ if (input && "string" === typeof input) { | ||
} else { | ||
throw new Error(Utils.Errors.INVALID_FILENAME); | ||
throw Utils.Errors.INVALID_FILENAME(); | ||
} | ||
@@ -67,3 +72,3 @@ } | ||
const { canonical, sanitize } = Utils; | ||
const { canonical, sanitize, zipnamefix } = Utils; | ||
@@ -74,3 +79,3 @@ function getEntry(/**Object*/ entry) { | ||
// If entry was given as a file name | ||
if (typeof entry === "string") item = _zip.getEntry(entry); | ||
if (typeof entry === "string") item = _zip.getEntry(pth.posix.normalize(entry)); | ||
// if entry was given as a ZipEntry object | ||
@@ -92,10 +97,32 @@ if (typeof entry === "object" && typeof entry.entryName !== "undefined" && typeof entry.header !== "undefined") item = _zip.getEntry(entry.entryName); | ||
function filenameFilter(filterfn) { | ||
if (filterfn instanceof RegExp) { | ||
// if filter is RegExp wrap it | ||
return (function (rx) { | ||
return function (filename) { | ||
return rx.test(filename); | ||
}; | ||
})(filterfn); | ||
} else if ("function" !== typeof filterfn) { | ||
// if filter is not function we will replace it | ||
return () => true; | ||
} | ||
return filterfn; | ||
} | ||
// keep last character on folders | ||
const relativePath = (local, entry) => { | ||
let lastChar = entry.slice(-1); | ||
lastChar = lastChar === filetools.sep ? filetools.sep : ""; | ||
return pth.relative(local, entry) + lastChar; | ||
}; | ||
return { | ||
/** | ||
* Extracts the given entry from the archive and returns the content as a Buffer object | ||
* @param entry ZipEntry object or String with the full path of the entry | ||
* | ||
* @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry | ||
* @param {Buffer|string} [pass] - password | ||
* @return Buffer or Null in case of error | ||
*/ | ||
readFile: function (/**Object*/ entry, /*String, Buffer*/ pass) { | ||
readFile: function (entry, pass) { | ||
var item = getEntry(entry); | ||
@@ -106,9 +133,21 @@ return (item && item.getData(pass)) || null; | ||
/** | ||
* Returns how many child elements has on entry (directories) on files it is always 0 | ||
* @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry | ||
* @returns {integer} | ||
*/ | ||
childCount: function (entry) { | ||
const item = getEntry(entry); | ||
if (item) { | ||
return _zip.getChildCount(item); | ||
} | ||
}, | ||
/** | ||
* Asynchronous readFile | ||
* @param entry ZipEntry object or String with the full path of the entry | ||
* @param callback | ||
* @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry | ||
* @param {callback} callback | ||
* | ||
* @return Buffer or Null in case of error | ||
*/ | ||
readFileAsync: function (/**Object*/ entry, /**Function*/ callback) { | ||
readFileAsync: function (entry, callback) { | ||
var item = getEntry(entry); | ||
@@ -124,8 +163,8 @@ if (item) { | ||
* Extracts the given entry from the archive and returns the content as plain text in the given encoding | ||
* @param entry ZipEntry object or String with the full path of the entry | ||
* @param encoding Optional. If no encoding is specified utf8 is used | ||
* @param {ZipEntry|string} entry - ZipEntry object or String with the full path of the entry | ||
* @param {string} encoding - Optional. If no encoding is specified utf8 is used | ||
* | ||
* @return String | ||
*/ | ||
readAsText: function (/**Object*/ entry, /**String=*/ encoding) { | ||
readAsText: function (entry, encoding) { | ||
var item = getEntry(entry); | ||
@@ -143,9 +182,9 @@ if (item) { | ||
* Asynchronous readAsText | ||
* @param entry ZipEntry object or String with the full path of the entry | ||
* @param callback | ||
* @param encoding Optional. If no encoding is specified utf8 is used | ||
* @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry | ||
* @param {callback} callback | ||
* @param {string} [encoding] - Optional. If no encoding is specified utf8 is used | ||
* | ||
* @return String | ||
*/ | ||
readAsTextAsync: function (/**Object*/ entry, /**Function*/ callback, /**String=*/ encoding) { | ||
readAsTextAsync: function (entry, callback, encoding) { | ||
var item = getEntry(entry); | ||
@@ -173,8 +212,23 @@ if (item) { | ||
* | ||
* @param entry | ||
* @param {ZipEntry|string} entry | ||
* @returns {void} | ||
*/ | ||
deleteFile: function (/**Object*/ entry) { | ||
deleteFile: function (entry, withsubfolders = true) { | ||
// @TODO: test deleteFile | ||
var item = getEntry(entry); | ||
if (item) { | ||
_zip.deleteFile(item.entryName, withsubfolders); | ||
} | ||
}, | ||
/** | ||
* Remove the entry from the file or directory without affecting any nested entries | ||
* | ||
* @param {ZipEntry|string} entry | ||
* @returns {void} | ||
*/ | ||
deleteEntry: function (entry) { | ||
// @TODO: test deleteEntry | ||
var item = getEntry(entry); | ||
if (item) { | ||
_zip.deleteEntry(item.entryName); | ||
@@ -187,5 +241,5 @@ } | ||
* | ||
* @param comment | ||
* @param {string} comment | ||
*/ | ||
addZipComment: function (/**String*/ comment) { | ||
addZipComment: function (comment) { | ||
// @TODO: test addZipComment | ||
@@ -208,6 +262,6 @@ _zip.comment = comment; | ||
* | ||
* @param entry | ||
* @param comment | ||
* @param {ZipEntry} entry | ||
* @param {string} comment | ||
*/ | ||
addZipEntryComment: function (/**Object*/ entry, /**String*/ comment) { | ||
addZipEntryComment: function (entry, comment) { | ||
var item = getEntry(entry); | ||
@@ -222,6 +276,6 @@ if (item) { | ||
* | ||
* @param entry | ||
* @param {ZipEntry} entry | ||
* @return String | ||
*/ | ||
getZipEntryComment: function (/**Object*/ entry) { | ||
getZipEntryComment: function (entry) { | ||
var item = getEntry(entry); | ||
@@ -237,6 +291,6 @@ if (item) { | ||
* | ||
* @param entry | ||
* @param content | ||
* @param {ZipEntry} entry | ||
* @param {Buffer} content | ||
*/ | ||
updateFile: function (/**Object*/ entry, /**Buffer*/ content) { | ||
updateFile: function (entry, content) { | ||
var item = getEntry(entry); | ||
@@ -251,7 +305,8 @@ if (item) { | ||
* | ||
* @param localPath File to add to zip | ||
* @param zipPath Optional path inside the zip | ||
* @param zipName Optional name for the file | ||
* @param {string} localPath File to add to zip | ||
* @param {string} [zipPath] Optional path inside the zip | ||
* @param {string} [zipName] Optional name for the file | ||
* @param {string} [comment] Optional file comment | ||
*/ | ||
addLocalFile: function (/**String*/ localPath, /**String=*/ zipPath, /**String=*/ zipName, /**String*/ comment) { | ||
addLocalFile: function (localPath, zipPath, zipName, comment) { | ||
if (filetools.fs.existsSync(localPath)) { | ||
@@ -262,3 +317,3 @@ // fix ZipPath | ||
// p - local file name | ||
var p = localPath.split("\\").join("/").split("/").pop(); | ||
const p = pth.win32.basename(pth.win32.normalize(localPath)); | ||
@@ -271,6 +326,12 @@ // add file name into zippath | ||
// get file content | ||
const data = _attr.isFile() ? filetools.fs.readFileSync(localPath) : Buffer.alloc(0); | ||
// if folder | ||
if (_attr.isDirectory()) zipPath += filetools.sep; | ||
// add file into zip file | ||
this.addFile(zipPath, filetools.fs.readFileSync(localPath), comment, _attr); | ||
this.addFile(zipPath, data, comment, _attr); | ||
} else { | ||
throw new Error(Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath)); | ||
throw Utils.Errors.FILE_NOT_FOUND(localPath); | ||
} | ||
@@ -280,25 +341,59 @@ }, | ||
/** | ||
* Callback for showing if everything was done. | ||
* | ||
* @callback doneCallback | ||
* @param {Error} err - Error object | ||
* @param {boolean} done - was request fully completed | ||
*/ | ||
/** | ||
* Adds a file from the disk to the archive | ||
* | ||
* @param {(object|string)} options - options object, if it is string it us used as localPath. | ||
* @param {string} options.localPath - Local path to the file. | ||
* @param {string} [options.comment] - Optional file comment. | ||
* @param {string} [options.zipPath] - Optional path inside the zip | ||
* @param {string} [options.zipName] - Optional name for the file | ||
* @param {doneCallback} callback - The callback that handles the response. | ||
*/ | ||
addLocalFileAsync: function (options, callback) { | ||
options = typeof options === "object" ? options : { localPath: options }; | ||
const localPath = pth.resolve(options.localPath); | ||
const { comment } = options; | ||
let { zipPath, zipName } = options; | ||
const self = this; | ||
filetools.fs.stat(localPath, function (err, stats) { | ||
if (err) return callback(err, false); | ||
// fix ZipPath | ||
zipPath = zipPath ? fixPath(zipPath) : ""; | ||
// p - local file name | ||
const p = pth.win32.basename(pth.win32.normalize(localPath)); | ||
// add file name into zippath | ||
zipPath += zipName ? zipName : p; | ||
if (stats.isFile()) { | ||
filetools.fs.readFile(localPath, function (err, data) { | ||
if (err) return callback(err, false); | ||
self.addFile(zipPath, data, comment, stats); | ||
return setImmediate(callback, undefined, true); | ||
}); | ||
} else if (stats.isDirectory()) { | ||
zipPath += filetools.sep; | ||
self.addFile(zipPath, Buffer.alloc(0), comment, stats); | ||
return setImmediate(callback, undefined, true); | ||
} | ||
}); | ||
}, | ||
/** | ||
* Adds a local directory and all its nested files and directories to the archive | ||
* | ||
* @param localPath | ||
* @param zipPath optional path inside zip | ||
* @param filter optional RegExp or Function if files match will | ||
* be included. | ||
* @param {number | object} attr - number as unix file permissions, object as filesystem Stats object | ||
* @param {string} localPath - local path to the folder | ||
* @param {string} [zipPath] - optional path inside zip | ||
* @param {(RegExp|function)} [filter] - optional RegExp or Function if files match will be included. | ||
*/ | ||
addLocalFolder: function (/**String*/ localPath, /**String=*/ zipPath, /**=RegExp|Function*/ filter, /**=number|object*/ attr) { | ||
addLocalFolder: function (localPath, zipPath, filter) { | ||
// Prepare filter | ||
if (filter instanceof RegExp) { | ||
// if filter is RegExp wrap it | ||
filter = (function (rx) { | ||
return function (filename) { | ||
return rx.test(filename); | ||
}; | ||
})(filter); | ||
} else if ("function" !== typeof filter) { | ||
// if filter is not function we will replace it | ||
filter = function () { | ||
return true; | ||
}; | ||
} | ||
filter = filenameFilter(filter); | ||
@@ -316,16 +411,11 @@ // fix ZipPath | ||
if (items.length) { | ||
items.forEach(function (filepath) { | ||
var p = pth.relative(localPath, filepath).split("\\").join("/"); //windows fix | ||
for (const filepath of items) { | ||
const p = pth.join(zipPath, relativePath(localPath, filepath)); | ||
if (filter(p)) { | ||
var stats = filetools.fs.statSync(filepath); | ||
if (stats.isFile()) { | ||
self.addFile(zipPath + p, filetools.fs.readFileSync(filepath), "", attr ? attr : stats); | ||
} else { | ||
self.addFile(zipPath + p + "/", Buffer.alloc(0), "", attr ? attr : stats); | ||
} | ||
self.addLocalFile(filepath, pth.dirname(p)); | ||
} | ||
}); | ||
} | ||
} | ||
} else { | ||
throw new Error(Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath)); | ||
throw Utils.Errors.FILE_NOT_FOUND(localPath); | ||
} | ||
@@ -335,21 +425,12 @@ }, | ||
/** | ||
* Asynchronous addLocalFile | ||
* @param localPath | ||
* @param callback | ||
* @param zipPath optional path inside zip | ||
* @param filter optional RegExp or Function if files match will | ||
* Asynchronous addLocalFolder | ||
* @param {string} localPath | ||
* @param {callback} callback | ||
* @param {string} [zipPath] optional path inside zip | ||
* @param {RegExp|function} [filter] optional RegExp or Function if files match will | ||
* be included. | ||
*/ | ||
addLocalFolderAsync: function (/*String*/ localPath, /*Function*/ callback, /*String*/ zipPath, /*RegExp|Function*/ filter) { | ||
if (filter instanceof RegExp) { | ||
filter = (function (rx) { | ||
return function (filename) { | ||
return rx.test(filename); | ||
}; | ||
})(filter); | ||
} else if ("function" !== typeof filter) { | ||
filter = function () { | ||
return true; | ||
}; | ||
} | ||
addLocalFolderAsync: function (localPath, callback, zipPath, filter) { | ||
// Prepare filter | ||
filter = filenameFilter(filter); | ||
@@ -365,3 +446,3 @@ // fix ZipPath | ||
if (err && err.code === "ENOENT") { | ||
callback(undefined, Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath)); | ||
callback(undefined, Utils.Errors.FILE_NOT_FOUND(localPath)); | ||
} else if (err) { | ||
@@ -377,3 +458,3 @@ callback(undefined, err); | ||
var filepath = items[i]; | ||
var p = pth.relative(localPath, filepath).split("\\").join("/"); //windows fix | ||
var p = relativePath(localPath, filepath).split("\\").join("/"); //windows fix | ||
p = p | ||
@@ -416,20 +497,95 @@ .normalize("NFD") | ||
/** | ||
* Adds a local directory and all its nested files and directories to the archive | ||
* | ||
* @param {object | string} options - options object, if it is string it us used as localPath. | ||
* @param {string} options.localPath - Local path to the folder. | ||
* @param {string} [options.zipPath] - optional path inside zip. | ||
* @param {RegExp|function} [options.filter] - optional RegExp or Function if files match will be included. | ||
* @param {function|string} [options.namefix] - optional function to help fix filename | ||
* @param {doneCallback} callback - The callback that handles the response. | ||
* | ||
*/ | ||
addLocalFolderAsync2: function (options, callback) { | ||
const self = this; | ||
options = typeof options === "object" ? options : { localPath: options }; | ||
localPath = pth.resolve(fixPath(options.localPath)); | ||
let { zipPath, filter, namefix } = options; | ||
if (filter instanceof RegExp) { | ||
filter = (function (rx) { | ||
return function (filename) { | ||
return rx.test(filename); | ||
}; | ||
})(filter); | ||
} else if ("function" !== typeof filter) { | ||
filter = function () { | ||
return true; | ||
}; | ||
} | ||
// fix ZipPath | ||
zipPath = zipPath ? fixPath(zipPath) : ""; | ||
// Check Namefix function | ||
if (namefix == "latin1") { | ||
namefix = (str) => | ||
str | ||
.normalize("NFD") | ||
.replace(/[\u0300-\u036f]/g, "") | ||
.replace(/[^\x20-\x7E]/g, ""); // accent fix (latin1 characers only) | ||
} | ||
if (typeof namefix !== "function") namefix = (str) => str; | ||
// internal, create relative path + fix the name | ||
const relPathFix = (entry) => pth.join(zipPath, namefix(relativePath(localPath, entry))); | ||
const fileNameFix = (entry) => pth.win32.basename(pth.win32.normalize(namefix(entry))); | ||
filetools.fs.open(localPath, "r", function (err) { | ||
if (err && err.code === "ENOENT") { | ||
callback(undefined, Utils.Errors.FILE_NOT_FOUND(localPath)); | ||
} else if (err) { | ||
callback(undefined, err); | ||
} else { | ||
filetools.findFilesAsync(localPath, function (err, fileEntries) { | ||
if (err) return callback(err); | ||
fileEntries = fileEntries.filter((dir) => filter(relPathFix(dir))); | ||
if (!fileEntries.length) callback(undefined, false); | ||
setImmediate( | ||
fileEntries.reverse().reduce(function (next, entry) { | ||
return function (err, done) { | ||
if (err || done === false) return setImmediate(next, err, false); | ||
self.addLocalFileAsync( | ||
{ | ||
localPath: entry, | ||
zipPath: pth.dirname(relPathFix(entry)), | ||
zipName: fileNameFix(entry) | ||
}, | ||
next | ||
); | ||
}; | ||
}, callback) | ||
); | ||
}); | ||
} | ||
}); | ||
}, | ||
/** | ||
* Adds a local directory and all its nested files and directories to the archive | ||
* | ||
* @param {string} localPath - path where files will be extracted | ||
* @param {object} props - optional properties | ||
* @param {string} props.zipPath - optional path inside zip | ||
* @param {regexp, function} props.filter - RegExp or Function if files match will be included. | ||
* @param {string} [props.zipPath] - optional path inside zip | ||
* @param {RegExp|function} [props.filter] - optional RegExp or Function if files match will be included. | ||
* @param {function|string} [props.namefix] - optional function to help fix filename | ||
*/ | ||
addLocalFolderPromise: function (/*String*/ localPath, /* object */ props) { | ||
addLocalFolderPromise: function (localPath, props) { | ||
return new Promise((resolve, reject) => { | ||
const { filter, zipPath } = Object.assign({}, props); | ||
this.addLocalFolderAsync( | ||
localPath, | ||
(done, err) => { | ||
if (err) reject(err); | ||
if (done) resolve(this); | ||
}, | ||
zipPath, | ||
filter | ||
); | ||
this.addLocalFolderAsync2(Object.assign({ localPath }, props), (err, done) => { | ||
if (err) reject(err); | ||
if (done) resolve(this); | ||
}); | ||
}); | ||
@@ -445,6 +601,7 @@ }, | ||
* @param {Buffer | string} content - file content as buffer or utf8 coded string | ||
* @param {string} comment - file comment | ||
* @param {number | object} attr - number as unix file permissions, object as filesystem Stats object | ||
* @param {string} [comment] - file comment | ||
* @param {number | object} [attr] - number as unix file permissions, object as filesystem Stats object | ||
*/ | ||
addFile: function (/**String*/ entryName, /**Buffer*/ content, /**String*/ comment, /**Number*/ attr) { | ||
addFile: function (entryName, content, comment, attr) { | ||
entryName = zipnamefix(entryName); | ||
let entry = getEntry(entryName); | ||
@@ -455,4 +612,4 @@ const update = entry != null; | ||
if (!update) { | ||
entry = new ZipEntry(); | ||
entry.entryName = Utils.canonical(entryName); | ||
entry = new ZipEntry(opts); | ||
entry.entryName = entryName; | ||
} | ||
@@ -499,5 +656,6 @@ entry.comment = comment || ""; | ||
* | ||
* @return Array | ||
* @param {string} [password] | ||
* @returns Array | ||
*/ | ||
getEntries: function (/**String*/ password) { | ||
getEntries: function (password) { | ||
_zip.password = password; | ||
@@ -510,3 +668,3 @@ return _zip ? _zip.entries : []; | ||
* | ||
* @param name | ||
* @param {string} name | ||
* @return ZipEntry | ||
@@ -530,30 +688,20 @@ */ | ||
* | ||
* @param entry ZipEntry object or String with the full path of the entry | ||
* @param targetPath Target folder where to write the file | ||
* @param maintainEntryPath If maintainEntryPath is true and the entry is inside a folder, the entry folder | ||
* will be created in targetPath as well. Default is TRUE | ||
* @param overwrite If the file already exists at the target path, the file will be overwriten if this is true. | ||
* Default is FALSE | ||
* @param keepOriginalPermission The file will be set as the permission from the entry if this is true. | ||
* Default is FALSE | ||
* @param outFileName String If set will override the filename of the extracted file (Only works if the entry is a file) | ||
* @param {string|ZipEntry} entry - ZipEntry object or String with the full path of the entry | ||
* @param {string} targetPath - Target folder where to write the file | ||
* @param {boolean} [maintainEntryPath=true] - If maintainEntryPath is true and the entry is inside a folder, the entry folder will be created in targetPath as well. Default is TRUE | ||
* @param {boolean} [overwrite=false] - If the file already exists at the target path, the file will be overwriten if this is true. | ||
* @param {boolean} [keepOriginalPermission=false] - The file will be set as the permission from the entry if this is true. | ||
* @param {string} [outFileName] - String If set will override the filename of the extracted file (Only works if the entry is a file) | ||
* | ||
* @return Boolean | ||
*/ | ||
extractEntryTo: function ( | ||
/**Object*/ entry, | ||
/**String*/ targetPath, | ||
/**Boolean*/ maintainEntryPath, | ||
/**Boolean*/ overwrite, | ||
/**Boolean*/ keepOriginalPermission, | ||
/**String**/ outFileName | ||
) { | ||
overwrite = get_Bool(overwrite, false); | ||
keepOriginalPermission = get_Bool(keepOriginalPermission, false); | ||
maintainEntryPath = get_Bool(maintainEntryPath, true); | ||
outFileName = get_Str(outFileName, get_Str(keepOriginalPermission, undefined)); | ||
extractEntryTo: function (entry, targetPath, maintainEntryPath, overwrite, keepOriginalPermission, outFileName) { | ||
overwrite = get_Bool(false, overwrite); | ||
keepOriginalPermission = get_Bool(false, keepOriginalPermission); | ||
maintainEntryPath = get_Bool(true, maintainEntryPath); | ||
outFileName = get_Str(keepOriginalPermission, outFileName); | ||
var item = getEntry(entry); | ||
if (!item) { | ||
throw new Error(Utils.Errors.NO_ENTRY); | ||
throw Utils.Errors.NO_ENTRY(); | ||
} | ||
@@ -571,3 +719,3 @@ | ||
if (!content) { | ||
throw new Error(Utils.Errors.CANT_EXTRACT_FILE); | ||
throw Utils.Errors.CANT_EXTRACT_FILE(); | ||
} | ||
@@ -584,6 +732,6 @@ var name = canonical(child.entryName); | ||
var content = item.getData(_zip.password); | ||
if (!content) throw new Error(Utils.Errors.CANT_EXTRACT_FILE); | ||
if (!content) throw Utils.Errors.CANT_EXTRACT_FILE(); | ||
if (filetools.fs.existsSync(target) && !overwrite) { | ||
throw new Error(Utils.Errors.CANT_OVERRIDE); | ||
throw Utils.Errors.CANT_OVERRIDE(); | ||
} | ||
@@ -599,3 +747,3 @@ // The reverse operation for attr depend on method addFile() | ||
* Test the archive | ||
* | ||
* @param {string} [pass] | ||
*/ | ||
@@ -626,17 +774,17 @@ test: function (pass) { | ||
* | ||
* @param targetPath Target location | ||
* @param overwrite If the file already exists at the target path, the file will be overwriten if this is true. | ||
* @param {string} targetPath Target location | ||
* @param {boolean} [overwrite=false] If the file already exists at the target path, the file will be overwriten if this is true. | ||
* Default is FALSE | ||
* @param keepOriginalPermission The file will be set as the permission from the entry if this is true. | ||
* @param {boolean} [keepOriginalPermission=false] The file will be set as the permission from the entry if this is true. | ||
* Default is FALSE | ||
* @param {string|Buffer} [pass] password | ||
*/ | ||
extractAllTo: function (/**String*/ targetPath, /**Boolean*/ overwrite, /**Boolean*/ keepOriginalPermission, /*String, Buffer*/ pass) { | ||
overwrite = get_Bool(overwrite, false); | ||
extractAllTo: function (targetPath, overwrite, keepOriginalPermission, pass) { | ||
keepOriginalPermission = get_Bool(false, keepOriginalPermission); | ||
pass = get_Str(keepOriginalPermission, pass); | ||
keepOriginalPermission = get_Bool(keepOriginalPermission, false); | ||
if (!_zip) { | ||
throw new Error(Utils.Errors.NO_ZIP); | ||
} | ||
overwrite = get_Bool(false, overwrite); | ||
if (!_zip) throw Utils.Errors.NO_ZIP(); | ||
_zip.entries.forEach(function (entry) { | ||
var entryName = sanitize(targetPath, canonical(entry.entryName.toString())); | ||
var entryName = sanitize(targetPath, canonical(entry.entryName)); | ||
if (entry.isDirectory) { | ||
@@ -648,3 +796,3 @@ filetools.makeDir(entryName); | ||
if (!content) { | ||
throw new Error(Utils.Errors.CANT_EXTRACT_FILE); | ||
throw Utils.Errors.CANT_EXTRACT_FILE(); | ||
} | ||
@@ -657,3 +805,3 @@ // The reverse operation for attr depend on method addFile() | ||
} catch (err) { | ||
throw new Error(Utils.Errors.CANT_EXTRACT_FILE); | ||
throw Utils.Errors.CANT_EXTRACT_FILE(); | ||
} | ||
@@ -666,14 +814,13 @@ }); | ||
* | ||
* @param targetPath Target location | ||
* @param overwrite If the file already exists at the target path, the file will be overwriten if this is true. | ||
* @param {string} targetPath Target location | ||
* @param {boolean} [overwrite=false] If the file already exists at the target path, the file will be overwriten if this is true. | ||
* Default is FALSE | ||
* @param keepOriginalPermission The file will be set as the permission from the entry if this is true. | ||
* @param {boolean} [keepOriginalPermission=false] The file will be set as the permission from the entry if this is true. | ||
* Default is FALSE | ||
* @param callback The callback will be executed when all entries are extracted successfully or any error is thrown. | ||
* @param {function} callback The callback will be executed when all entries are extracted successfully or any error is thrown. | ||
*/ | ||
extractAllToAsync: function (/**String*/ targetPath, /**Boolean*/ overwrite, /**Boolean*/ keepOriginalPermission, /**Function*/ callback) { | ||
if (typeof overwrite === "function" && !callback) callback = overwrite; | ||
overwrite = get_Bool(overwrite, false); | ||
if (typeof keepOriginalPermission === "function" && !callback) callback = keepOriginalPermission; | ||
keepOriginalPermission = get_Bool(keepOriginalPermission, false); | ||
extractAllToAsync: function (targetPath, overwrite, keepOriginalPermission, callback) { | ||
callback = get_Fun(overwrite, keepOriginalPermission, callback); | ||
keepOriginalPermission = get_Bool(false, keepOriginalPermission); | ||
overwrite = get_Bool(false, overwrite); | ||
if (!callback) { | ||
@@ -691,3 +838,3 @@ return new Promise((resolve, reject) => { | ||
if (!_zip) { | ||
callback(new Error(Utils.Errors.NO_ZIP)); | ||
callback(Utils.Errors.NO_ZIP()); | ||
return; | ||
@@ -698,3 +845,3 @@ } | ||
// convert entryName to | ||
const getPath = (entry) => sanitize(targetPath, pth.normalize(canonical(entry.entryName.toString()))); | ||
const getPath = (entry) => sanitize(targetPath, pth.normalize(canonical(entry.entryName))); | ||
const getError = (msg, file) => new Error(msg + ': "' + file + '"'); | ||
@@ -734,9 +881,9 @@ | ||
} else { | ||
const entryName = pth.normalize(canonical(entry.entryName.toString())); | ||
const entryName = pth.normalize(canonical(entry.entryName)); | ||
const filePath = sanitize(targetPath, entryName); | ||
entry.getDataAsync(function (content, err_1) { | ||
if (err_1) { | ||
next(new Error(err_1)); | ||
next(err_1); | ||
} else if (!content) { | ||
next(new Error(Utils.Errors.CANT_EXTRACT_FILE)); | ||
next(Utils.Errors.CANT_EXTRACT_FILE()); | ||
} else { | ||
@@ -767,6 +914,6 @@ // The reverse operation for attr depend on method addFile() | ||
* | ||
* @param targetFileName | ||
* @param callback | ||
* @param {string} targetFileName | ||
* @param {function} callback | ||
*/ | ||
writeZip: function (/**String*/ targetFileName, /**Function*/ callback) { | ||
writeZip: function (targetFileName, callback) { | ||
if (arguments.length === 1) { | ||
@@ -791,2 +938,11 @@ if (typeof targetFileName === "function") { | ||
/** | ||
* | ||
* @param {string} targetFileName | ||
* @param {object} [props] | ||
* @param {boolean} [props.overwrite=true] If the file already exists at the target path, the file will be overwriten if this is true. | ||
* @param {boolean} [props.perm] The file will be set as the permission from the entry if this is true. | ||
* @returns {Promise<void>} | ||
*/ | ||
writeZipPromise: function (/**String*/ targetFileName, /* object */ props) { | ||
@@ -807,2 +963,5 @@ const { overwrite, perm } = Object.assign({ overwrite: true }, props); | ||
/** | ||
* @returns {Promise<Buffer>} A promise to the Buffer. | ||
*/ | ||
toBufferPromise: function () { | ||
@@ -817,6 +976,9 @@ return new Promise((resolve, reject) => { | ||
* | ||
* @return Buffer | ||
* @prop {function} [onSuccess] | ||
* @prop {function} [onFail] | ||
* @prop {function} [onItemStart] | ||
* @prop {function} [onItemEnd] | ||
* @returns {Buffer} | ||
*/ | ||
toBuffer: function (/**Function=*/ onSuccess, /**Function=*/ onFail, /**Function=*/ onItemStart, /**Function=*/ onItemEnd) { | ||
this.valueOf = 2; | ||
toBuffer: function (onSuccess, onFail, onItemStart, onItemEnd) { | ||
if (typeof onSuccess === "function") { | ||
@@ -823,0 +985,0 @@ _zip.toAsyncBuffer(onSuccess, onFail, onItemStart, onItemEnd); |
@@ -28,17 +28,12 @@ var Utils = require("../util"), | ||
var _localHeader = {}; | ||
const _localHeader = { | ||
extraLen: 0 | ||
}; | ||
function setTime(val) { | ||
val = new Date(val); | ||
_time = | ||
(((val.getFullYear() - 1980) & 0x7f) << 25) | // b09-16 years from 1980 | ||
((val.getMonth() + 1) << 21) | // b05-08 month | ||
(val.getDate() << 16) | // b00-04 hour | ||
// 2 bytes time | ||
(val.getHours() << 11) | // b11-15 hour | ||
(val.getMinutes() << 5) | // b05-10 minute | ||
(val.getSeconds() >> 1); // b00-04 seconds divided by 2 | ||
} | ||
// casting | ||
const uint32 = (val) => Math.max(0, val) >>> 0; | ||
const uint16 = (val) => Math.max(0, val) & 0xffff; | ||
const uint8 = (val) => Math.max(0, val) & 0xff; | ||
setTime(+new Date()); | ||
_time = Utils.fromDate2DOS(new Date()); | ||
@@ -67,2 +62,24 @@ return { | ||
get flags_efs() { | ||
return (_flags & Constants.FLG_EFS) > 0; | ||
}, | ||
set flags_efs(val) { | ||
if (val) { | ||
_flags |= Constants.FLG_EFS; | ||
} else { | ||
_flags &= ~Constants.FLG_EFS; | ||
} | ||
}, | ||
get flags_desc() { | ||
return (_flags & Constants.FLG_DESC) > 0; | ||
}, | ||
set flags_desc(val) { | ||
if (val) { | ||
_flags |= Constants.FLG_DESC; | ||
} else { | ||
_flags &= ~Constants.FLG_DESC; | ||
} | ||
}, | ||
get method() { | ||
@@ -83,9 +100,17 @@ return _method; | ||
get time() { | ||
return new Date(((_time >> 25) & 0x7f) + 1980, ((_time >> 21) & 0x0f) - 1, (_time >> 16) & 0x1f, (_time >> 11) & 0x1f, (_time >> 5) & 0x3f, (_time & 0x1f) << 1); | ||
return Utils.fromDOS2Date(this.timeval); | ||
}, | ||
set time(val) { | ||
setTime(val); | ||
this.timeval = Utils.fromDate2DOS(val); | ||
}, | ||
get timeval() { | ||
return _time; | ||
}, | ||
set timeval(val) { | ||
_time = uint32(val); | ||
}, | ||
get timeHighByte() { | ||
return (_time >>> 8) & 0xff; | ||
return uint8(_time >>> 8); | ||
}, | ||
@@ -96,3 +121,3 @@ get crc() { | ||
set crc(val) { | ||
_crc = Math.max(0, val) >>> 0; | ||
_crc = uint32(val); | ||
}, | ||
@@ -104,3 +129,3 @@ | ||
set compressedSize(val) { | ||
_compressedSize = Math.max(0, val) >>> 0; | ||
_compressedSize = uint32(val); | ||
}, | ||
@@ -112,3 +137,3 @@ | ||
set size(val) { | ||
_size = Math.max(0, val) >>> 0; | ||
_size = uint32(val); | ||
}, | ||
@@ -130,2 +155,9 @@ | ||
get extraLocalLength() { | ||
return _localHeader.extraLen; | ||
}, | ||
set extraLocalLength(val) { | ||
_localHeader.extraLen = val; | ||
}, | ||
get commentLength() { | ||
@@ -142,3 +174,3 @@ return _comLen; | ||
set diskNumStart(val) { | ||
_diskStart = Math.max(0, val) >>> 0; | ||
_diskStart = uint32(val); | ||
}, | ||
@@ -150,3 +182,3 @@ | ||
set inAttr(val) { | ||
_inattr = Math.max(0, val) >>> 0; | ||
_inattr = uint32(val); | ||
}, | ||
@@ -158,3 +190,3 @@ | ||
set attr(val) { | ||
_attr = Math.max(0, val) >>> 0; | ||
_attr = uint32(val); | ||
}, | ||
@@ -164,3 +196,3 @@ | ||
get fileAttr() { | ||
return _attr ? (((_attr >>> 0) | 0) >> 16) & 0xfff : 0; | ||
return uint16(_attr >> 16) & 0xfff; | ||
}, | ||
@@ -172,7 +204,7 @@ | ||
set offset(val) { | ||
_offset = Math.max(0, val) >>> 0; | ||
_offset = uint32(val); | ||
}, | ||
get encrypted() { | ||
return (_flags & 1) === 1; | ||
return (_flags & Constants.FLG_ENC) === Constants.FLG_ENC; | ||
}, | ||
@@ -196,24 +228,28 @@ | ||
if (data.readUInt32LE(0) !== Constants.LOCSIG) { | ||
throw new Error(Utils.Errors.INVALID_LOC); | ||
throw Utils.Errors.INVALID_LOC(); | ||
} | ||
_localHeader = { | ||
// version needed to extract | ||
version: data.readUInt16LE(Constants.LOCVER), | ||
// general purpose bit flag | ||
flags: data.readUInt16LE(Constants.LOCFLG), | ||
// compression method | ||
method: data.readUInt16LE(Constants.LOCHOW), | ||
// modification time (2 bytes time, 2 bytes date) | ||
time: data.readUInt32LE(Constants.LOCTIM), | ||
// uncompressed file crc-32 value | ||
crc: data.readUInt32LE(Constants.LOCCRC), | ||
// compressed size | ||
compressedSize: data.readUInt32LE(Constants.LOCSIZ), | ||
// uncompressed size | ||
size: data.readUInt32LE(Constants.LOCLEN), | ||
// filename length | ||
fnameLen: data.readUInt16LE(Constants.LOCNAM), | ||
// extra field length | ||
extraLen: data.readUInt16LE(Constants.LOCEXT) | ||
}; | ||
// version needed to extract | ||
_localHeader.version = data.readUInt16LE(Constants.LOCVER); | ||
// general purpose bit flag | ||
_localHeader.flags = data.readUInt16LE(Constants.LOCFLG); | ||
// compression method | ||
_localHeader.method = data.readUInt16LE(Constants.LOCHOW); | ||
// modification time (2 bytes time, 2 bytes date) | ||
_localHeader.time = data.readUInt32LE(Constants.LOCTIM); | ||
// uncompressed file crc-32 valu | ||
_localHeader.crc = data.readUInt32LE(Constants.LOCCRC); | ||
// compressed size | ||
_localHeader.compressedSize = data.readUInt32LE(Constants.LOCSIZ); | ||
// uncompressed size | ||
_localHeader.size = data.readUInt32LE(Constants.LOCLEN); | ||
// filename length | ||
_localHeader.fnameLen = data.readUInt16LE(Constants.LOCNAM); | ||
// extra field length | ||
_localHeader.extraLen = data.readUInt16LE(Constants.LOCEXT); | ||
// read extra data | ||
const extraStart = _offset + Constants.LOCHDR + _localHeader.fnameLen; | ||
const extraEnd = extraStart + _localHeader.extraLen; | ||
return input.slice(extraStart, extraEnd); | ||
}, | ||
@@ -224,3 +260,3 @@ | ||
if (data.length !== Constants.CENHDR || data.readUInt32LE(0) !== Constants.CENSIG) { | ||
throw new Error(Utils.Errors.INVALID_CEN); | ||
throw Utils.Errors.INVALID_CEN(); | ||
} | ||
@@ -281,3 +317,3 @@ // version made by | ||
// extra field length | ||
data.writeUInt16LE(_extraLen, Constants.LOCEXT); | ||
data.writeUInt16LE(_localHeader.extraLen, Constants.LOCEXT); | ||
return data; | ||
@@ -321,4 +357,2 @@ }, | ||
data.writeUInt32LE(_offset, Constants.CENOFF); | ||
// fill all with | ||
data.fill(0x00, Constants.CENHDR); | ||
return data; | ||
@@ -325,0 +359,0 @@ }, |
@@ -59,3 +59,3 @@ var Utils = require("../util"), | ||
) { | ||
throw new Error(Utils.Errors.INVALID_END); | ||
throw Utils.Errors.INVALID_END(); | ||
} | ||
@@ -62,0 +62,0 @@ |
@@ -6,2 +6,3 @@ "use strict"; | ||
const { randomFillSync } = require("crypto"); | ||
const Errors = require("../util/errors"); | ||
@@ -128,3 +129,3 @@ // generate CRC32 lookup table | ||
if (salt[11] !== verifyByte) { | ||
throw "ADM-ZIP: Wrong Password"; | ||
throw Errors.WRONG_PASSWORD(); | ||
} | ||
@@ -131,0 +132,0 @@ |
{ | ||
"name": "adm-zip", | ||
"version": "0.5.14", | ||
"version": "0.5.15", | ||
"description": "Javascript implementation of zip for nodejs with support for electron original-fs. Allows user to create or extract zip files both in memory or to/from disk", | ||
@@ -44,6 +44,7 @@ "scripts": { | ||
"chai": "^4.3.4", | ||
"iconv-lite": "^0.6.3", | ||
"mocha": "^10.2.0", | ||
"prettier": "^2.2.1", | ||
"prettier": "^3.3.2", | ||
"rimraf": "^3.0.2" | ||
} | ||
} |
@@ -1,5 +0,9 @@ | ||
# ADM-ZIP for NodeJS with added support for electron original-fs | ||
# ADM-ZIP for NodeJS | ||
ADM-ZIP is a pure JavaScript implementation for zip data compression for [NodeJS](https://nodejs.org/). | ||
<a href="https://github.com/cthackers/adm-zip/actions/workflows/ci.yml"> | ||
<img src="https://github.com/cthackers/adm-zip/actions/workflows/ci.yml/badge.svg" alt="Build Status"> | ||
</a> | ||
# Installation | ||
@@ -11,2 +15,4 @@ | ||
**Electron** file system support described below. | ||
## What is it good for? | ||
@@ -67,2 +73,17 @@ | ||
[![Build Status](https://travis-ci.org/cthackers/adm-zip.svg?branch=master)](https://travis-ci.org/cthackers/adm-zip) | ||
## Electron original-fs | ||
ADM-ZIP has supported electron **original-fs** for years without any user interractions but it causes problem with bundlers like rollup etc. For continuing support **original-fs** or any other custom file system module. There is possible specify your module by **fs** option in ADM-ZIP constructor. | ||
Example: | ||
```javascript | ||
const AdmZip = require("adm-zip"); | ||
const OriginalFs = require("original-fs"); | ||
// reading archives | ||
const zip = new AdmZip("./my_file.zip", { fs: OriginalFs }); | ||
. | ||
. | ||
. | ||
``` |
@@ -1,2 +0,2 @@ | ||
module.exports = { | ||
const errors = { | ||
/* Header error messages */ | ||
@@ -7,6 +7,11 @@ INVALID_LOC: "Invalid LOC header (bad signature)", | ||
/* Descriptor */ | ||
DESCRIPTOR_NOT_EXIST: "No descriptor present", | ||
DESCRIPTOR_UNKNOWN: "Unknown descriptor format", | ||
DESCRIPTOR_FAULTY: "Descriptor data is malformed", | ||
/* ZipEntry error messages*/ | ||
NO_DATA: "Nothing to decompress", | ||
BAD_CRC: "CRC32 checksum failed", | ||
FILE_IN_THE_WAY: "There is a file in the way: %s", | ||
BAD_CRC: "CRC32 checksum failed {0}", | ||
FILE_IN_THE_WAY: "There is a file in the way: {0}", | ||
UNKNOWN_METHOD: "Invalid/unsupported compression method", | ||
@@ -33,6 +38,28 @@ | ||
DIRECTORY_CONTENT_ERROR: "A directory cannot have content", | ||
FILE_NOT_FOUND: "File not found: %s", | ||
FILE_NOT_FOUND: 'File not found: "{0}"', | ||
NOT_IMPLEMENTED: "Not implemented", | ||
INVALID_FILENAME: "Invalid filename", | ||
INVALID_FORMAT: "Invalid or unsupported zip format. No END header found" | ||
INVALID_FORMAT: "Invalid or unsupported zip format. No END header found", | ||
INVALID_PASS_PARAM: "Incompatible password parameter", | ||
WRONG_PASSWORD: "Wrong Password", | ||
/* ADM-ZIP */ | ||
COMMENT_TOO_LONG: "Comment is too long", // Comment can be max 65535 bytes long (NOTE: some non-US characters may take more space) | ||
EXTRA_FIELD_PARSE_ERROR: "Extra field parsing error" | ||
}; | ||
// template | ||
function E(message) { | ||
return function (...args) { | ||
if (args.length) { // Allow {0} .. {9} arguments in error message, based on argument number | ||
message = message.replace(/\{(\d)\}/g, (_, n) => args[n] || ''); | ||
} | ||
return new Error('ADM-ZIP: ' + message); | ||
}; | ||
} | ||
// Init errors with template | ||
for (const msg of Object.keys(errors)) { | ||
exports[msg] = E(errors[msg]); | ||
} |
@@ -1,7 +0,4 @@ | ||
const fs = require("./fileSystem").require(); | ||
const pth = require("path"); | ||
fs.existsSync = fs.existsSync || pth.existsSync; | ||
module.exports = function (/*String*/ path) { | ||
module.exports = function (/*String*/ path, /*Utils object*/ { fs }) { | ||
var _path = path || "", | ||
@@ -8,0 +5,0 @@ _obj = newAttr(), |
@@ -5,1 +5,2 @@ module.exports = require("./utils"); | ||
module.exports.FileAttr = require("./fattr"); | ||
module.exports.decoder = require("./decoder"); |
@@ -1,2 +0,2 @@ | ||
const fsystem = require("./fileSystem").require(); | ||
const fsystem = require("fs"); | ||
const pth = require("path"); | ||
@@ -7,3 +7,3 @@ const Constants = require("./constants"); | ||
const is_Obj = (obj) => obj && typeof obj === "object"; | ||
const is_Obj = (obj) => typeof obj === "object" && obj !== null; | ||
@@ -38,3 +38,3 @@ // generate CRC32 lookup table | ||
// INSTANCED functions | ||
// INSTANTIABLE functions | ||
@@ -56,3 +56,3 @@ Utils.prototype.makeDir = function (/*String*/ folder) { | ||
} | ||
if (stat && stat.isFile()) throw Errors.FILE_IN_THE_WAY.replace("%s", resolvedPath); | ||
if (stat && stat.isFile()) throw Errors.FILE_IN_THE_WAY(`"${resolvedPath}"`); | ||
}); | ||
@@ -81,6 +81,6 @@ } | ||
try { | ||
fd = self.fs.openSync(path, "w", 438); // 0666 | ||
fd = self.fs.openSync(path, "w", 0o666); // 0666 | ||
} catch (e) { | ||
self.fs.chmodSync(path, 438); | ||
fd = self.fs.openSync(path, "w", 438); | ||
self.fs.chmodSync(path, 0o666); | ||
fd = self.fs.openSync(path, "w", 0o666); | ||
} | ||
@@ -94,3 +94,3 @@ if (fd) { | ||
} | ||
self.fs.chmodSync(path, attr || 438); | ||
self.fs.chmodSync(path, attr || 0o666); | ||
return true; | ||
@@ -119,9 +119,9 @@ }; | ||
self.fs.open(path, "w", 438, function (err, fd) { | ||
self.fs.open(path, "w", 0o666, function (err, fd) { | ||
if (err) { | ||
self.fs.chmod(path, 438, function () { | ||
self.fs.open(path, "w", 438, function (err, fd) { | ||
self.fs.chmod(path, 0o666, function () { | ||
self.fs.open(path, "w", 0o666, function (err, fd) { | ||
self.fs.write(fd, content, 0, content.length, 0, function () { | ||
self.fs.close(fd, function () { | ||
self.fs.chmod(path, attr || 438, function () { | ||
self.fs.chmod(path, attr || 0o666, function () { | ||
callback(true); | ||
@@ -136,3 +136,3 @@ }); | ||
self.fs.close(fd, function () { | ||
self.fs.chmod(path, attr || 438, function () { | ||
self.fs.chmod(path, attr || 0o666, function () { | ||
callback(true); | ||
@@ -143,3 +143,3 @@ }); | ||
} else { | ||
self.fs.chmod(path, attr || 438, function () { | ||
self.fs.chmod(path, attr || 0o666, function () { | ||
callback(true); | ||
@@ -164,9 +164,10 @@ }); | ||
self.fs.readdirSync(dir).forEach(function (file) { | ||
var path = pth.join(dir, file); | ||
const path = pth.join(dir, file); | ||
const stat = self.fs.statSync(path); | ||
if (self.fs.statSync(path).isDirectory() && recursive) files = files.concat(findSync(path, pattern, recursive)); | ||
if (!pattern || pattern.test(path)) { | ||
files.push(pth.normalize(path) + (self.fs.statSync(path).isDirectory() ? self.sep : "")); | ||
files.push(pth.normalize(path) + (stat.isDirectory() ? self.sep : "")); | ||
} | ||
if (stat.isDirectory() && recursive) files = files.concat(findSync(path, pattern, recursive)); | ||
}); | ||
@@ -179,2 +180,43 @@ return files; | ||
/** | ||
* Callback for showing if everything was done. | ||
* | ||
* @callback filelistCallback | ||
* @param {Error} err - Error object | ||
* @param {string[]} list - was request fully completed | ||
*/ | ||
/** | ||
* | ||
* @param {string} dir | ||
* @param {filelistCallback} cb | ||
*/ | ||
Utils.prototype.findFilesAsync = function (dir, cb) { | ||
const self = this; | ||
let results = []; | ||
self.fs.readdir(dir, function (err, list) { | ||
if (err) return cb(err); | ||
let list_length = list.length; | ||
if (!list_length) return cb(null, results); | ||
list.forEach(function (file) { | ||
file = pth.join(dir, file); | ||
self.fs.stat(file, function (err, stat) { | ||
if (err) return cb(err); | ||
if (stat) { | ||
results.push(pth.normalize(file) + (stat.isDirectory() ? self.sep : "")); | ||
if (stat.isDirectory()) { | ||
self.findFilesAsync(file, function (err, res) { | ||
if (err) return cb(err); | ||
results = results.concat(res); | ||
if (!--list_length) cb(null, results); | ||
}); | ||
} else { | ||
if (!--list_length) cb(null, results); | ||
} | ||
} | ||
}); | ||
}); | ||
}); | ||
}; | ||
Utils.prototype.getAttributes = function () {}; | ||
@@ -195,4 +237,2 @@ | ||
} | ||
// Generate crcTable | ||
if (!crcTable.length) genCRCTable(); | ||
@@ -217,10 +257,45 @@ let len = buf.length; | ||
// removes ".." style path elements | ||
/** | ||
* removes ".." style path elements | ||
* @param {string} path - fixable path | ||
* @returns string - fixed filepath | ||
*/ | ||
Utils.canonical = function (/*string*/ path) { | ||
if (!path) return ""; | ||
// trick normalize think path is absolute | ||
var safeSuffix = pth.posix.normalize("/" + path.split("\\").join("/")); | ||
const safeSuffix = pth.posix.normalize("/" + path.split("\\").join("/")); | ||
return pth.join(".", safeSuffix); | ||
}; | ||
/** | ||
* fix file names in achive | ||
* @param {string} path - fixable path | ||
* @returns string - fixed filepath | ||
*/ | ||
Utils.zipnamefix = function (path) { | ||
if (!path) return ""; | ||
// trick normalize think path is absolute | ||
const safeSuffix = pth.posix.normalize("/" + path.split("\\").join("/")); | ||
return pth.posix.join(".", safeSuffix); | ||
}; | ||
/** | ||
* | ||
* @param {Array} arr | ||
* @param {function} callback | ||
* @returns | ||
*/ | ||
Utils.findLast = function (arr, callback) { | ||
if (!Array.isArray(arr)) throw new TypeError("arr is not array"); | ||
const len = arr.length >>> 0; | ||
for (let i = len - 1; i >= 0; i--) { | ||
if (callback(arr[i], i, arr)) { | ||
return arr[i]; | ||
} | ||
} | ||
return void 0; | ||
}; | ||
// make abolute paths taking prefix as root folder | ||
@@ -240,3 +315,3 @@ Utils.sanitize = function (/*string*/ prefix, /*string*/ name) { | ||
// converts buffer, Uint8Array, string types to buffer | ||
Utils.toBuffer = function toBuffer(/*buffer, Uint8Array, string*/ input) { | ||
Utils.toBuffer = function toBuffer(/*buffer, Uint8Array, string*/ input, /* function */ encoder) { | ||
if (Buffer.isBuffer(input)) { | ||
@@ -248,3 +323,3 @@ return input; | ||
// expect string all other values are invalid and return empty buffer | ||
return typeof input === "string" ? Buffer.from(input, "utf8") : Buffer.alloc(0); | ||
return typeof input === "string" ? encoder(input) : Buffer.alloc(0); | ||
} | ||
@@ -260,3 +335,17 @@ }; | ||
Utils.fromDOS2Date = function (val) { | ||
return new Date(((val >> 25) & 0x7f) + 1980, Math.max(((val >> 21) & 0x0f) - 1, 0), Math.max((val >> 16) & 0x1f, 1), (val >> 11) & 0x1f, (val >> 5) & 0x3f, (val & 0x1f) << 1); | ||
}; | ||
Utils.fromDate2DOS = function (val) { | ||
let date = 0; | ||
let time = 0; | ||
if (val.getFullYear() > 1979) { | ||
date = (((val.getFullYear() - 1980) & 0x7f) << 9) | ((val.getMonth() + 1) << 5) | val.getDate(); | ||
time = (val.getHours() << 11) | (val.getMinutes() << 5) | (val.getSeconds() >> 1); | ||
} | ||
return (date << 16) | time; | ||
}; | ||
Utils.isWin = isWin; // Do we have windows system | ||
Utils.crcTable = crcTable; |
139
zipEntry.js
@@ -6,3 +6,3 @@ var Utils = require("./util"), | ||
module.exports = function (/*Buffer*/ input) { | ||
module.exports = function (/** object */ options, /*Buffer*/ input) { | ||
var _centralHeader = new Headers.EntryHeader(), | ||
@@ -13,4 +13,12 @@ _entryName = Buffer.alloc(0), | ||
uncompressedData = null, | ||
_extra = Buffer.alloc(0); | ||
_extra = Buffer.alloc(0), | ||
_extralocal = Buffer.alloc(0), | ||
_efs = true; | ||
// assign options | ||
const opts = options; | ||
const decoder = typeof opts.decoder === "object" ? opts.decoder : Utils.decoder; | ||
_efs = decoder.hasOwnProperty("efs") ? decoder.efs : false; | ||
function getCompressedDataFromZip() { | ||
@@ -21,3 +29,3 @@ //if (!input || !Buffer.isBuffer(input)) { | ||
} | ||
_centralHeader.loadLocalHeaderFromBinary(input); | ||
_extralocal = _centralHeader.loadLocalHeaderFromBinary(input); | ||
return input.slice(_centralHeader.realDataOffset, _centralHeader.realDataOffset + _centralHeader.compressedSize); | ||
@@ -27,4 +35,4 @@ } | ||
function crc32OK(data) { | ||
// if bit 3 (0x08) of the general-purpose flags field is set, then the CRC-32 and file sizes are not known when the header is written | ||
if ((_centralHeader.flags & 0x8) !== 0x8) { | ||
// if bit 3 (0x08) of the general-purpose flags field is set, then the CRC-32 and file sizes are not known when the local header is written | ||
if (!_centralHeader.flags_desc) { | ||
if (Utils.crc32(data) !== _centralHeader.localHeader.crc) { | ||
@@ -34,5 +42,36 @@ return false; | ||
} else { | ||
// @TODO: load and check data descriptor header | ||
// The fields in the local header are filled with zero, and the CRC-32 and size are appended in a 12-byte structure | ||
// (optionally preceded by a 4-byte signature) immediately after the compressed data: | ||
const descriptor = {}; | ||
const dataEndOffset = _centralHeader.realDataOffset + _centralHeader.compressedSize; | ||
// no descriptor after compressed data, instead new local header | ||
if (input.readUInt32LE(dataEndOffset) == Constants.LOCSIG || input.readUInt32LE(dataEndOffset) == Constants.CENSIG) { | ||
throw Utils.Errors.DESCRIPTOR_NOT_EXIST(); | ||
} | ||
// get decriptor data | ||
if (input.readUInt32LE(dataEndOffset) == Constants.EXTSIG) { | ||
// descriptor with signature | ||
descriptor.crc = input.readUInt32LE(dataEndOffset + Constants.EXTCRC); | ||
descriptor.compressedSize = input.readUInt32LE(dataEndOffset + Constants.EXTSIZ); | ||
descriptor.size = input.readUInt32LE(dataEndOffset + Constants.EXTLEN); | ||
} else if (input.readUInt16LE(dataEndOffset + 12) === 0x4b50) { | ||
// descriptor without signature (we check is new header starting where we expect) | ||
descriptor.crc = input.readUInt32LE(dataEndOffset + Constants.EXTCRC - 4); | ||
descriptor.compressedSize = input.readUInt32LE(dataEndOffset + Constants.EXTSIZ - 4); | ||
descriptor.size = input.readUInt32LE(dataEndOffset + Constants.EXTLEN - 4); | ||
} else { | ||
throw Utils.Errors.DESCRIPTOR_UNKNOWN(); | ||
} | ||
// check data integrity | ||
if (descriptor.compressedSize !== _centralHeader.compressedSize || descriptor.size !== _centralHeader.size || descriptor.crc !== _centralHeader.crc) { | ||
throw Utils.Errors.DESCRIPTOR_FAULTY(); | ||
} | ||
if (Utils.crc32(data) !== descriptor.crc) { | ||
return false; | ||
} | ||
// @TODO: zip64 bit descriptor fields | ||
// if bit 3 is set and any value in local header "zip64 Extended information" extra field are set 0 (place holder) | ||
// then 64-bit descriptor format is used instead of 32-bit | ||
// central header - "zip64 Extended information" extra field should store real values and not place holders | ||
} | ||
@@ -49,3 +88,3 @@ return true; | ||
if (async && callback) { | ||
callback(Buffer.alloc(0), Utils.Errors.DIRECTORY_CONTENT_ERROR); //si added error. | ||
callback(Buffer.alloc(0), Utils.Errors.DIRECTORY_CONTENT_ERROR()); //si added error. | ||
} | ||
@@ -65,3 +104,3 @@ return Buffer.alloc(0); | ||
if ("string" !== typeof pass && !Buffer.isBuffer(pass)) { | ||
throw new Error("ADM-ZIP: Incompatible password parameter"); | ||
throw Utils.Errors.INVALID_PASS_PARAM(); | ||
} | ||
@@ -77,4 +116,4 @@ compressedData = Methods.ZipCrypto.decrypt(compressedData, _centralHeader, pass); | ||
if (!crc32OK(data)) { | ||
if (async && callback) callback(data, Utils.Errors.BAD_CRC); //si added error | ||
throw new Error(Utils.Errors.BAD_CRC); | ||
if (async && callback) callback(data, Utils.Errors.BAD_CRC()); //si added error | ||
throw Utils.Errors.BAD_CRC(); | ||
} else { | ||
@@ -91,3 +130,3 @@ //si added otherwise did not seem to return data. | ||
if (!crc32OK(data)) { | ||
throw new Error(Utils.Errors.BAD_CRC + " " + _entryName.toString()); | ||
throw Utils.Errors.BAD_CRC(`"${decoder.decode(_entryName)}"`); | ||
} | ||
@@ -100,3 +139,3 @@ return data; | ||
if (!crc32OK(result)) { | ||
callback(result, Utils.Errors.BAD_CRC); //si added error | ||
callback(result, Utils.Errors.BAD_CRC()); //si added error | ||
} else { | ||
@@ -110,4 +149,4 @@ callback(result); | ||
default: | ||
if (async && callback) callback(Buffer.alloc(0), Utils.Errors.UNKNOWN_METHOD); | ||
throw new Error(Utils.Errors.UNKNOWN_METHOD); | ||
if (async && callback) callback(Buffer.alloc(0), Utils.Errors.UNKNOWN_METHOD()); | ||
throw Utils.Errors.UNKNOWN_METHOD(); | ||
} | ||
@@ -165,14 +204,18 @@ } | ||
function parseExtra(data) { | ||
var offset = 0; | ||
var signature, size, part; | ||
while (offset < data.length) { | ||
signature = data.readUInt16LE(offset); | ||
offset += 2; | ||
size = data.readUInt16LE(offset); | ||
offset += 2; | ||
part = data.slice(offset, offset + size); | ||
offset += size; | ||
if (Constants.ID_ZIP64 === signature) { | ||
parseZip64ExtendedInformation(part); | ||
try { | ||
var offset = 0; | ||
var signature, size, part; | ||
while (offset + 4 < data.length) { | ||
signature = data.readUInt16LE(offset); | ||
offset += 2; | ||
size = data.readUInt16LE(offset); | ||
offset += 2; | ||
part = data.slice(offset, offset + size); | ||
offset += size; | ||
if (Constants.ID_ZIP64 === signature) { | ||
parseZip64ExtendedInformation(part); | ||
} | ||
} | ||
} catch (error) { | ||
throw Utils.Errors.EXTRA_FIELD_PARSE_ERROR(); | ||
} | ||
@@ -213,3 +256,3 @@ } | ||
get entryName() { | ||
return _entryName.toString(); | ||
return decoder.decode(_entryName); | ||
}, | ||
@@ -220,3 +263,3 @@ get rawEntryName() { | ||
set entryName(val) { | ||
_entryName = Utils.toBuffer(val); | ||
_entryName = Utils.toBuffer(val, decoder.encode); | ||
var lastChar = _entryName[_entryName.length - 1]; | ||
@@ -227,2 +270,10 @@ _isDirectory = lastChar === 47 || lastChar === 92; | ||
get efs() { | ||
if (typeof _efs === "function") { | ||
return _efs(this.entryName); | ||
} else { | ||
return _efs; | ||
} | ||
}, | ||
get extra() { | ||
@@ -238,11 +289,12 @@ return _extra; | ||
get comment() { | ||
return _comment.toString(); | ||
return decoder.decode(_comment); | ||
}, | ||
set comment(val) { | ||
_comment = Utils.toBuffer(val); | ||
_comment = Utils.toBuffer(val, decoder.encode); | ||
_centralHeader.commentLength = _comment.length; | ||
if (_comment.length > 0xffff) throw Utils.Errors.COMMENT_TOO_LONG(); | ||
}, | ||
get name() { | ||
var n = _entryName.toString(); | ||
var n = decoder.decode(_entryName); | ||
return _isDirectory | ||
@@ -268,3 +320,3 @@ ? n | ||
setData: function (value) { | ||
uncompressedData = Utils.toBuffer(value); | ||
uncompressedData = Utils.toBuffer(value, Utils.decoder.encode); | ||
if (!_isDirectory && uncompressedData.length) { | ||
@@ -313,2 +365,4 @@ _centralHeader.size = uncompressedData.length; | ||
packCentralHeader: function () { | ||
_centralHeader.flags_efs = this.efs; | ||
_centralHeader.extraLength = _extra.length; | ||
// 1. create header (buffer) | ||
@@ -321,10 +375,6 @@ var header = _centralHeader.centralHeaderToBinary(); | ||
// 3. add extra data | ||
if (_centralHeader.extraLength) { | ||
_extra.copy(header, addpos); | ||
addpos += _centralHeader.extraLength; | ||
} | ||
_extra.copy(header, addpos); | ||
addpos += _centralHeader.extraLength; | ||
// 4. add file comment | ||
if (_centralHeader.commentLength) { | ||
_comment.copy(header, addpos); | ||
} | ||
_comment.copy(header, addpos); | ||
return header; | ||
@@ -335,7 +385,8 @@ }, | ||
let addpos = 0; | ||
_centralHeader.flags_efs = this.efs; | ||
_centralHeader.extraLocalLength = _extralocal.length; | ||
// 1. construct local header Buffer | ||
const localHeaderBuf = _centralHeader.localHeaderToBinary(); | ||
// 2. localHeader - crate header buffer | ||
const localHeader = Buffer.alloc(localHeaderBuf.length + _entryName.length + _extra.length); | ||
const localHeader = Buffer.alloc(localHeaderBuf.length + _entryName.length + _centralHeader.extraLocalLength); | ||
// 2.1 add localheader | ||
@@ -348,4 +399,4 @@ localHeaderBuf.copy(localHeader, addpos); | ||
// 2.3 add extra field | ||
_extra.copy(localHeader, addpos); | ||
addpos += _extra.length; | ||
_extralocal.copy(localHeader, addpos); | ||
addpos += _extralocal.length; | ||
@@ -352,0 +403,0 @@ return localHeader; |
162
zipFile.js
@@ -12,7 +12,8 @@ const ZipEntry = require("./zipEntry"); | ||
var password = null; | ||
const temporary = new Set(); | ||
// assign options | ||
const opts = Object.assign(Object.create(null), options); | ||
const opts = options; | ||
const { noSort } = opts; | ||
const { noSort, decoder } = opts; | ||
@@ -27,16 +28,27 @@ if (inBuffer) { | ||
function iterateEntries(callback) { | ||
const totalEntries = mainHeader.diskEntries; // total number of entries | ||
let index = mainHeader.offset; // offset of first CEN header | ||
function makeTemporaryFolders() { | ||
const foldersList = new Set(); | ||
for (let i = 0; i < totalEntries; i++) { | ||
let tmp = index; | ||
const entry = new ZipEntry(inBuffer); | ||
// Make list of all folders in file | ||
for (const elem of Object.keys(entryTable)) { | ||
const elements = elem.split("/"); | ||
elements.pop(); // filename | ||
if (!elements.length) continue; // no folders | ||
for (let i = 0; i < elements.length; i++) { | ||
const sub = elements.slice(0, i + 1).join("/") + "/"; | ||
foldersList.add(sub); | ||
} | ||
} | ||
entry.header = inBuffer.slice(tmp, (tmp += Utils.Constants.CENHDR)); | ||
entry.entryName = inBuffer.slice(tmp, (tmp += entry.header.fileNameLength)); | ||
index += entry.header.centralHeaderSize; | ||
callback(entry); | ||
// create missing folders as temporary | ||
for (const elem of foldersList) { | ||
if (!(elem in entryTable)) { | ||
const tempfolder = new ZipEntry(opts); | ||
tempfolder.entryName = elem; | ||
tempfolder.attr = 0x10; | ||
tempfolder.temporary = true; | ||
entryList.push(tempfolder); | ||
entryTable[tempfolder.entryName] = tempfolder; | ||
temporary.add(tempfolder); | ||
} | ||
} | ||
@@ -49,3 +61,3 @@ } | ||
if (mainHeader.diskEntries > (inBuffer.length - mainHeader.offset) / Utils.Constants.CENHDR) { | ||
throw new Error(Utils.Errors.DISK_ENTRY_TOO_LARGE); | ||
throw Utils.Errors.DISK_ENTRY_TOO_LARGE(); | ||
} | ||
@@ -56,3 +68,3 @@ entryList = new Array(mainHeader.diskEntries); // total number of entries | ||
var tmp = index, | ||
entry = new ZipEntry(inBuffer); | ||
entry = new ZipEntry(opts, inBuffer); | ||
entry.header = inBuffer.slice(tmp, (tmp += Utils.Constants.CENHDR)); | ||
@@ -73,2 +85,4 @@ | ||
} | ||
temporary.clear(); | ||
makeTemporaryFolders(); | ||
} | ||
@@ -84,2 +98,6 @@ | ||
// option to search header form entire file | ||
const trailingSpace = typeof opts.trailingSpace === "boolean" ? opts.trailingSpace : false; | ||
if (trailingSpace) max = 0; | ||
for (i; i >= n; i--) { | ||
@@ -111,3 +129,3 @@ if (inBuffer[i] !== 0x50) continue; // quick check that the byte is 'P' | ||
if (!~endOffset) throw new Error(Utils.Errors.INVALID_FORMAT); | ||
if (endOffset == -1) throw Utils.Errors.INVALID_FORMAT(); | ||
@@ -136,3 +154,3 @@ mainHeader.loadFromBinary(inBuffer.slice(endOffset, endStart)); | ||
} | ||
return entryList; | ||
return entryList.filter((e) => !temporary.has(e)); | ||
}, | ||
@@ -145,6 +163,6 @@ | ||
get comment() { | ||
return _comment.toString(); | ||
return decoder.decode(_comment); | ||
}, | ||
set comment(val) { | ||
_comment = Utils.toBuffer(val); | ||
_comment = Utils.toBuffer(val, decoder.encode); | ||
mainHeader.commentLength = _comment.length; | ||
@@ -162,8 +180,3 @@ }, | ||
forEach: function (callback) { | ||
if (!loadedEntries) { | ||
iterateEntries(callback); | ||
return; | ||
} | ||
entryList.forEach(callback); | ||
this.entries.forEach(callback); | ||
}, | ||
@@ -199,7 +212,24 @@ | ||
/** | ||
* Removes the entry with the given name from the entry list. | ||
* Removes the file with the given name from the entry list. | ||
* | ||
* If the entry is a directory, then all nested files and directories will be removed | ||
* @param entryName | ||
* @returns {void} | ||
*/ | ||
deleteFile: function (/*String*/ entryName, withsubfolders = true) { | ||
if (!loadedEntries) { | ||
readEntries(); | ||
} | ||
const entry = entryTable[entryName]; | ||
const list = this.getEntryChildren(entry, withsubfolders).map((child) => child.entryName); | ||
list.forEach(this.deleteEntry); | ||
}, | ||
/** | ||
* Removes the entry with the given name from the entry list. | ||
* | ||
* @param {string} entryName | ||
* @returns {void} | ||
*/ | ||
deleteEntry: function (/*String*/ entryName) { | ||
@@ -209,14 +239,9 @@ if (!loadedEntries) { | ||
} | ||
var entry = entryTable[entryName]; | ||
if (entry && entry.isDirectory) { | ||
var _self = this; | ||
this.getEntryChildren(entry).forEach(function (child) { | ||
if (child.entryName !== entryName) { | ||
_self.deleteEntry(child.entryName); | ||
} | ||
}); | ||
const entry = entryTable[entryName]; | ||
const index = entryList.indexOf(entry); | ||
if (index >= 0) { | ||
entryList.splice(index, 1); | ||
delete entryTable[entryName]; | ||
mainHeader.totalEntries = entryList.length; | ||
} | ||
entryList.splice(entryList.indexOf(entry), 1); | ||
delete entryTable[entryName]; | ||
mainHeader.totalEntries = entryList.length; | ||
}, | ||
@@ -230,17 +255,20 @@ | ||
*/ | ||
getEntryChildren: function (/*ZipEntry*/ entry) { | ||
getEntryChildren: function (/*ZipEntry*/ entry, subfolders = true) { | ||
if (!loadedEntries) { | ||
readEntries(); | ||
} | ||
if (entry && entry.isDirectory) { | ||
const list = []; | ||
const name = entry.entryName; | ||
const len = name.length; | ||
if (typeof entry === "object") { | ||
if (entry.isDirectory && subfolders) { | ||
const list = []; | ||
const name = entry.entryName; | ||
entryList.forEach(function (zipEntry) { | ||
if (zipEntry.entryName.substr(0, len) === name) { | ||
list.push(zipEntry); | ||
for (const zipEntry of entryList) { | ||
if (zipEntry.entryName.startsWith(name)) { | ||
list.push(zipEntry); | ||
} | ||
} | ||
}); | ||
return list; | ||
return list; | ||
} else { | ||
return [entry]; | ||
} | ||
} | ||
@@ -251,2 +279,16 @@ return []; | ||
/** | ||
* How many child elements entry has | ||
* | ||
* @param {ZipEntry} entry | ||
* @return {integer} | ||
*/ | ||
getChildCount: function (entry) { | ||
if (entry && entry.isDirectory) { | ||
const list = this.getEntryChildren(entry); | ||
return list.includes(entry) ? list.length - 1 : list.length; | ||
} | ||
return 0; | ||
}, | ||
/** | ||
* Returns the zip file | ||
@@ -269,4 +311,5 @@ * | ||
mainHeader.offset = 0; | ||
totalEntries = 0; | ||
for (const entry of entryList) { | ||
for (const entry of this.entries) { | ||
// compress data and set local and entry header accordingly. Reason why is called first | ||
@@ -293,2 +336,3 @@ const compressedData = entry.getCompressedData(); | ||
totalSize += dataLength + centralHeader.length; | ||
totalEntries++; | ||
} | ||
@@ -299,2 +343,3 @@ | ||
mainHeader.offset = dindex; | ||
mainHeader.totalEntries = totalEntries; | ||
@@ -322,2 +367,9 @@ dindex = 0; | ||
// Since we update entry and main header offsets, | ||
// they are no longer valid and we have to reset content | ||
// (Issue 64) | ||
inBuffer = outBuffer; | ||
loadedEntries = false; | ||
return outBuffer; | ||
@@ -337,2 +389,3 @@ }, | ||
let dindex = 0; | ||
let totalEntries = 0; | ||
@@ -367,2 +420,3 @@ mainHeader.size = 0; | ||
totalSize += dataLength + centalHeader.length; | ||
totalEntries++; | ||
@@ -375,2 +429,3 @@ compress2Buffer(entryLists); | ||
mainHeader.offset = dindex; | ||
mainHeader.totalEntries = totalEntries; | ||
@@ -395,2 +450,9 @@ dindex = 0; | ||
// Since we update entry and main header offsets, they are no | ||
// longer valid and we have to reset content using our new buffer | ||
// (Issue 64) | ||
inBuffer = outBuffer; | ||
loadedEntries = false; | ||
onSuccess(outBuffer); | ||
@@ -400,3 +462,3 @@ } | ||
compress2Buffer(Array.from(entryList)); | ||
compress2Buffer(Array.from(this.entries)); | ||
} catch (e) { | ||
@@ -403,0 +465,0 @@ onFail(e); |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
121484
2804
88
5