UNPKG

zcatalyst-cli

Version:

Command Line Tool for CATALYST

276 lines (275 loc) 11.6 kB
'use strict'; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const jszip_1 = __importStar(require("jszip")); const path_1 = require("path"); const error_1 = __importDefault(require("./error")); const fs_1 = require("./util_modules/fs"); const js_1 = require("./util_modules/js"); const logger_1 = require("./util_modules/logger"); class Archiver { constructor(name = 'Archive') { this.name = name; this.jszip = Promise.resolve(new jszip_1.default()); this.promiseArr = []; } load(content, { createFolders = true } = {}) { if (!Buffer.isBuffer(content) && !js_1.JS.isString(content)) { throw new error_1.default('Unable to parse zip content, content should be either a string or buffer', { exit: 2 }); } this.content = content; this.jszip = (0, jszip_1.loadAsync)(content, { createFolders }); return this; } _writeFolder(folder, to, recursive = false, ignoreLevel = 1) { return __awaiter(this, void 0, void 0, function* () { return this._writeAllFile(folder.filter((_relPath, file) => !file.dir), to, recursive, ignoreLevel); }); } _writeAllFile(files, to, recursive = false, ignoreLevel = 0) { return __awaiter(this, void 0, void 0, function* () { while (files.length > 0) { const limit = files.length < Archiver.maxWriteLimit ? files.length : Archiver.maxWriteLimit; yield Promise.all(files.splice(0, limit).map((file) => __awaiter(this, void 0, void 0, function* () { const findIgnoreIndex = () => { let index = 0, level = ignoreLevel; while (level > 0) { index = file.name.indexOf('/', index + 1); level--; } return index; }; const filePath = (0, path_1.join)(to, (0, path_1.dirname)(ignoreLevel !== 0 ? file.name.substring(findIgnoreIndex() + 1) : file.name)); yield fs_1.ASYNC.ensureDir(filePath); if (file.name.endsWith('.zip') && recursive) { const zipContent = yield file.async('nodebuffer'); return new Archiver() .load(zipContent) .extract((0, path_1.join)(filePath, (0, path_1.basename)(file.name).replace('.zip', '')), '/', { recursive }) .finalize(); } return this._writeFile(file, filePath); }))); } }); } getFileMode(file) { const permission = file.unixPermissions; if (permission === null) { return; } if (typeof permission === 'number') { return permission; } try { return Number.parseInt(permission); } catch (er) { (0, logger_1.debug)('Zip file mode error: ', er); } return; } _writeFile(file, to) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve) => { const fileName = (0, path_1.basename)(file.name); file.nodeStream() .pipe(fs_1.SYNC.getWriteStream((0, path_1.join)(to, fileName), this.getFileMode(file))) .on('close', resolve); }); }); } readFile(relPath) { return __awaiter(this, void 0, void 0, function* () { const actualZip = yield this.jszip; const fileObjArr = []; if (typeof relPath === 'string') { const fileObj = actualZip.file(relPath); if (fileObj) { fileObjArr.push(fileObj); } } else { fileObjArr.push(...actualZip.file(relPath)); } if (fileObjArr.length === 0) { return; } return fileObjArr[0].async('string'); }); } extract(to, from = '/', { isFolder = true, recursive = false, ignoreLevel = 0 } = {}) { const extractPromise = this.jszip.then((zip) => __awaiter(this, void 0, void 0, function* () { if (isFolder) { let folder = null; if (typeof from === 'string') { folder = from === '/' ? zip : zip.folder(from); } else { const folderObjects = zip.folder(from); if (folderObjects.length > 0) { folder = zip.folder(folderObjects[0].name); if (folderObjects.length > 1) { folderObjects.forEach((folderObj) => { if (folder !== null && folderObj.name.length > folder.name.length) { folder = zip.folder(folderObj.name); } }); } } } if (!folder) { throw new error_1.default('Unable to extract zip, FolderObj is null', { exit: 2 }); } yield this._writeFolder(folder, to, recursive, ignoreLevel); return true; } const fromFileObj = []; if (typeof from === 'string') { const fileObj = zip.file(from); if (fileObj) { fromFileObj.push(fileObj); } } else { fromFileObj.concat(zip.file(from)); } if (fromFileObj.length === 0) { throw new error_1.default('Unable to extract zip, FileObj is null', { exit: 2 }); } yield this._writeAllFile(fromFileObj, to, recursive, ignoreLevel); return true; })); this.promiseArr.push(extractPromise); return this; } getUnixPath(pth) { return pth.split(path_1.sep).join('/'); } add(pth, content, { createFolders = true, mode } = {}) { this.promiseArr.push(this.jszip.then((zip) => { return zip.file(this.getUnixPath(pth), content, { createFolders, unixPermissions: mode }); })); return this; } remove(pth) { this.promiseArr.push(this.jszip.then((zip) => { return zip.remove(pth); })); return this; } get _finalizer() { return { details: () => __awaiter(this, void 0, void 0, function* () { return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { const bufArr = []; let contentLength = 0; const zip = yield this.jszip; zip.generateNodeStream() .on('data', (chunk) => { bufArr.push(chunk); }) .on('end', () => { contentLength = bufArr.reduce((sum, buf) => { return sum + buf.length; }, 0); resolve({ buffer: Buffer.concat(bufArr), contentLength, name: this.name + '.zip' }); }); })); }), nodeStream: () => __awaiter(this, void 0, void 0, function* () { const zip = yield this.jszip; return zip.generateNodeStream(); }), fsStream: () => __awaiter(this, void 0, void 0, function* () { const tempFilePath = yield fs_1.ASYNC.tempFile(this.name + '.zip'); const zip = yield this.jszip; const content = yield zip.generateAsync({ type: 'nodebuffer', platform: 'UNIX', compression: 'DEFLATE', compressionOptions: { level: 9 } }); yield fs_1.ASYNC.writeFile(tempFilePath, content); return { stream: fs_1.SYNC.getReadStream(tempFilePath), length: content.length }; }), writeZip: (pth) => __awaiter(this, void 0, void 0, function* () { const zip = yield this.jszip; const content = yield zip.generateAsync({ type: 'nodebuffer', platform: 'UNIX', compression: 'DEFLATE', compressionOptions: { level: 9 } }); if (pth.endsWith('.zip')) { pth = (0, path_1.join)((0, path_1.dirname)(pth), this.name + '.zip'); } if ((0, path_1.parse)(pth).ext === '') { pth = (0, path_1.join)(pth, this.name + '.zip'); } yield fs_1.ASYNC.writeFile(pth, content); }) }; } finalize() { return __awaiter(this, void 0, void 0, function* () { yield Promise.all(this.promiseArr); return this._finalizer; }); } } Archiver.maxWriteLimit = 50; exports.default = Archiver;