diff --git a/CHANGELOG.md b/CHANGELOG.md
index 285863ec..a49111f6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,12 @@
# Changelog
+## [3.0.3](https://github.com/OctopusDeploy/create-release-action/compare/v3.0.2...v3.0.3) (2023-01-31)
+
+
+### Bug Fixes
+
+* Updated client library to get better error messages capabilities and required Octopus version ([072c13b](https://github.com/OctopusDeploy/create-release-action/commit/072c13b5a0ddccc663a0c0d8b098229b40c65690))
+
## [3.0.2](https://github.com/OctopusDeploy/create-release-action/compare/v3.0.1...v3.0.2) (2022-12-23)
diff --git a/dist/index.js b/dist/index.js
index 676940a3..245dd4e5 100644
--- a/dist/index.js
+++ b/dist/index.js
@@ -2832,6 +2832,107 @@ exports.PackageIdentity = PackageIdentity;
Object.defineProperty(exports, "__esModule", ({ value: true }));
+/***/ }),
+
+/***/ 9849:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+"use strict";
+
+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 __generator = (this && this.__generator) || function (thisArg, body) {
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
+ function verb(n) { return function (v) { return step([n, v]); }; }
+ function step(op) {
+ if (f) throw new TypeError("Generator is already executing.");
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
+ if (y = 0, t) op = [op[0] & 2, t.value];
+ switch (op[0]) {
+ case 0: case 1: t = op; break;
+ case 4: _.label++; return { value: op[1], done: false };
+ case 5: _.label++; y = op[1]; op = [0]; continue;
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
+ default:
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
+ if (t[2]) _.ops.pop();
+ _.trys.pop(); continue;
+ }
+ op = body.call(thisArg, _);
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
+ }
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.checkForCapability = void 0;
+var apiLocation_1 = __nccwpck_require__(7083);
+var octopusError_1 = __nccwpck_require__(408);
+function checkForCapability(client, capabilityName, minimumVersionThisWouldAppearIn) {
+ return __awaiter(this, void 0, void 0, function () {
+ var response, e_1;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0:
+ _a.trys.push([0, 2, , 3]);
+ return [4 /*yield*/, client.get("".concat(apiLocation_1.apiLocation, "/capabilities"))];
+ case 1:
+ response = _a.sent();
+ return [2 /*return*/, response.Capabilities.filter(function (c) { return c === capabilityName; }).length === 1
+ ? null
+ : "The Octopus instance does not support ".concat(capabilityName, ", it needs to be at least version ").concat(minimumVersionThisWouldAppearIn, " to get access to the feature you are trying to use.")];
+ case 2:
+ e_1 = _a.sent();
+ if (e_1 instanceof octopusError_1.OctopusError) {
+ if (e_1.StatusCode && e_1.StatusCode != 200) {
+ return [2 /*return*/, "The Octopus instance does not support the Capabilities API, you will need to upgrade it at least 2022.3 to get access to the feature you are trying to use."];
+ }
+ }
+ return [2 /*return*/, "Unknown error occurred trying to determine if the Octopus instance supports ".concat(capabilityName, ".")];
+ case 3: return [2 /*return*/];
+ }
+ });
+ });
+}
+exports.checkForCapability = checkForCapability;
+
+
+/***/ }),
+
+/***/ 4615:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+"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 __exportStar = (this && this.__exportStar) || function(m, exports) {
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+__exportStar(__nccwpck_require__(9849), exports);
+
+
/***/ }),
/***/ 8318:
@@ -3284,6 +3385,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
__exportStar(__nccwpck_require__(8304), exports);
+__exportStar(__nccwpck_require__(4615), exports);
__exportStar(__nccwpck_require__(7206), exports);
__exportStar(__nccwpck_require__(599), exports);
__exportStar(__nccwpck_require__(4979), exports);
@@ -3548,6 +3650,9 @@ var NuGetPackageBuilder = /** @class */ (function () {
fs_1.default.appendFileSync(nuspecFile, " ".concat(args.version, "\n"));
fs_1.default.appendFileSync(nuspecFile, " ".concat(args.nuspecArgs.description, "\n"));
fs_1.default.appendFileSync(nuspecFile, " ".concat(args.nuspecArgs.authors.join(","), "\n"));
+ if (args.nuspecArgs.title) {
+ fs_1.default.appendFileSync(nuspecFile, "
".concat(args.nuspecArgs.title, "\n"));
+ }
if (args.nuspecArgs.releaseNotes) {
fs_1.default.appendFileSync(nuspecFile, " ".concat(args.nuspecArgs.releaseNotes, "\n"));
}
@@ -3709,7 +3814,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.doZip = void 0;
var adm_zip_1 = __importDefault(__nccwpck_require__(6761));
var fs_1 = __importDefault(__nccwpck_require__(7147));
-var glob_1 = __nccwpck_require__(2782);
+var glob_1 = __nccwpck_require__(1957);
var path_1 = __importDefault(__nccwpck_require__(1017));
var util_1 = __nccwpck_require__(3837);
var globp = (0, util_1.promisify)(glob_1.glob);
@@ -5101,15 +5206,22 @@ var DeploymentRepository = /** @class */ (function () {
return this.client.request("".concat(this.baseApiPathTemplate, "{?skip,take,ids,projects,environments,tenants,channels,taskState}"), __assign({ spaceName: this.spaceName }, args));
};
DeploymentRepository.prototype.create = function (command) {
+ var _a, _b;
return __awaiter(this, void 0, void 0, function () {
- var response, mappedTasks;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
+ var capabilityError, response, mappedTasks;
+ return __generator(this, function (_c) {
+ switch (_c.label) {
+ case 0: return [4 /*yield*/, (0, __1.checkForCapability)(this.client, "CreateDeploymentUntenantedCommandV1", "2022.3")];
+ case 1:
+ capabilityError = _c.sent();
+ if (capabilityError) {
+ (_b = (_a = this.client).error) === null || _b === void 0 ? void 0 : _b.call(_a, capabilityError);
+ throw new Error(capabilityError);
+ }
this.client.debug("Deploying a release...");
return [4 /*yield*/, this.client.doCreate("".concat(this.baseApiPathTemplate, "/create/untenanted/v1"), __assign({ spaceIdOrName: command.spaceName }, command))];
- case 1:
- response = _a.sent();
+ case 2:
+ response = _c.sent();
if (response.DeploymentServerTasks.length == 0) {
throw new Error("No server task details returned");
}
@@ -5128,15 +5240,22 @@ var DeploymentRepository = /** @class */ (function () {
});
};
DeploymentRepository.prototype.createTenanted = function (command) {
+ var _a, _b;
return __awaiter(this, void 0, void 0, function () {
- var response, mappedTasks;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
+ var capabilityError, response, mappedTasks;
+ return __generator(this, function (_c) {
+ switch (_c.label) {
+ case 0: return [4 /*yield*/, (0, __1.checkForCapability)(this.client, "CreateDeploymentTenantedCommandV1", "2022.3")];
+ case 1:
+ capabilityError = _c.sent();
+ if (capabilityError) {
+ (_b = (_a = this.client).error) === null || _b === void 0 ? void 0 : _b.call(_a, capabilityError);
+ throw new Error(capabilityError);
+ }
this.client.debug("Deploying a tenanted release...");
return [4 /*yield*/, this.client.doCreate("".concat(this.baseApiPathTemplate, "/create/tenanted/v1"), __assign({ spaceIdOrName: command.spaceName }, command))];
- case 1:
- response = _a.sent();
+ case 2:
+ response = _c.sent();
if (response.DeploymentServerTasks.length == 0) {
throw new Error("No server task details returned");
}
@@ -5300,15 +5419,22 @@ var ReleaseRepository = /** @class */ (function () {
this.spaceName = spaceName;
}
ReleaseRepository.prototype.create = function (command) {
+ var _a, _b;
return __awaiter(this, void 0, void 0, function () {
- var response;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
+ var capabilityError, response;
+ return __generator(this, function (_c) {
+ switch (_c.label) {
+ case 0: return [4 /*yield*/, (0, __1.checkForCapability)(this.client, "CreateReleaseCommandV1", "2022.3")];
+ case 1:
+ capabilityError = _c.sent();
+ if (capabilityError) {
+ (_b = (_a = this.client).error) === null || _b === void 0 ? void 0 : _b.call(_a, capabilityError);
+ throw new Error(capabilityError);
+ }
this.client.debug("Creating a release...");
return [4 /*yield*/, this.client.doCreate("".concat(__1.spaceScopedRoutePrefix, "/releases/create/v1"), __assign({ spaceIdOrName: command.spaceName }, command))];
- case 1:
- response = _a.sent();
+ case 2:
+ response = _c.sent();
this.client.debug("Release created successfully.");
return [2 /*return*/, response];
}
@@ -5740,6 +5866,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.RunbookRunRepository = void 0;
var spaceScopedRoutePrefix_1 = __nccwpck_require__(7218);
+var capabilities_1 = __nccwpck_require__(4615);
var RunbookRunRepository = /** @class */ (function () {
function RunbookRunRepository(client, spaceName) {
this.baseApiPathTemplate = "".concat(spaceScopedRoutePrefix_1.spaceScopedRoutePrefix, "/runbookRuns");
@@ -5753,15 +5880,22 @@ var RunbookRunRepository = /** @class */ (function () {
return this.client.request("".concat(this.baseApiPathTemplate, "{?skip,take,ids,projects,environments,tenants,runbooks,taskState,partialName}"), __assign({ spaceName: this.spaceName }, args));
};
RunbookRunRepository.prototype.create = function (command) {
+ var _a, _b;
return __awaiter(this, void 0, void 0, function () {
- var response, mappedTasks;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
+ var capabilityError, response, mappedTasks;
+ return __generator(this, function (_c) {
+ switch (_c.label) {
+ case 0: return [4 /*yield*/, (0, capabilities_1.checkForCapability)(this.client, "CreateRunbookRunCommandV1", "2022.3")];
+ case 1:
+ capabilityError = _c.sent();
+ if (capabilityError) {
+ (_b = (_a = this.client).error) === null || _b === void 0 ? void 0 : _b.call(_a, capabilityError);
+ throw new Error(capabilityError);
+ }
this.client.debug("Running a runbook...");
return [4 /*yield*/, this.client.doCreate("".concat(spaceScopedRoutePrefix_1.spaceScopedRoutePrefix, "/runbook-runs/create/v1"), __assign({ spaceIdOrName: command.spaceName }, command))];
- case 1:
- response = _a.sent();
+ case 2:
+ response = _c.sent();
if (response.RunbookRunServerTasks.length == 0) {
throw new Error("No server task details returned");
}
@@ -5952,48 +6086,41 @@ var ServerTaskWaiter = /** @class */ (function () {
}
ServerTaskWaiter.prototype.waitForServerTasksToComplete = function (serverTaskIds, statusCheckSleepCycle, timeout, pollingCallback) {
return __awaiter(this, void 0, void 0, function () {
- var spaceServerTaskRepository, taskPromises, serverTaskIds_1, serverTaskIds_1_1, serverTaskId;
- var e_1, _a;
- return __generator(this, function (_b) {
- switch (_b.label) {
- case 0:
- spaceServerTaskRepository = new serverTasks_1.SpaceServerTaskRepository(this.client, this.spaceName);
- taskPromises = [];
- try {
- for (serverTaskIds_1 = __values(serverTaskIds), serverTaskIds_1_1 = serverTaskIds_1.next(); !serverTaskIds_1_1.done; serverTaskIds_1_1 = serverTaskIds_1.next()) {
- serverTaskId = serverTaskIds_1_1.value;
- taskPromises.push(this.waitForTask(spaceServerTaskRepository, serverTaskId, statusCheckSleepCycle, timeout, pollingCallback));
- }
- }
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
- finally {
- try {
- if (serverTaskIds_1_1 && !serverTaskIds_1_1.done && (_a = serverTaskIds_1.return)) _a.call(serverTaskIds_1);
- }
- finally { if (e_1) throw e_1.error; }
- }
- return [4 /*yield*/, Promise.allSettled(taskPromises)];
- case 1: return [2 /*return*/, _b.sent()];
- }
+ var spaceServerTaskRepository;
+ return __generator(this, function (_a) {
+ spaceServerTaskRepository = new serverTasks_1.SpaceServerTaskRepository(this.client, this.spaceName);
+ return [2 /*return*/, this.waitForTasks(spaceServerTaskRepository, serverTaskIds, statusCheckSleepCycle, timeout, pollingCallback)];
});
});
};
ServerTaskWaiter.prototype.waitForServerTaskToComplete = function (serverTaskId, statusCheckSleepCycle, timeout, pollingCallback) {
return __awaiter(this, void 0, void 0, function () {
- var spaceServerTaskRepository;
+ var spaceServerTaskRepository, tasks;
return __generator(this, function (_a) {
- spaceServerTaskRepository = new serverTasks_1.SpaceServerTaskRepository(this.client, this.spaceName);
- return [2 /*return*/, this.waitForTask(spaceServerTaskRepository, serverTaskId, statusCheckSleepCycle, timeout, pollingCallback)];
+ switch (_a.label) {
+ case 0:
+ spaceServerTaskRepository = new serverTasks_1.SpaceServerTaskRepository(this.client, this.spaceName);
+ return [4 /*yield*/, this.waitForTasks(spaceServerTaskRepository, [serverTaskId], statusCheckSleepCycle, timeout, pollingCallback)];
+ case 1:
+ tasks = _a.sent();
+ return [2 /*return*/, tasks[0]];
+ }
});
});
};
- ServerTaskWaiter.prototype.waitForTask = function (spaceServerTaskRepository, serverTaskId, statusCheckSleepCycle, timeout, pollingCallback) {
+ ServerTaskWaiter.prototype.waitForTasks = function (spaceServerTaskRepository, serverTaskIds, statusCheckSleepCycle, timeout, pollingCallback) {
return __awaiter(this, void 0, void 0, function () {
- var sleep, stop, t, taskDetails, task;
+ var sleep, stop, t, completedTasks, _loop_1;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
+ // short circuit if no ids are passed. Sending an empty array to server here
+ // doesn't do what you may expect. To server, no ids == return every task the user
+ // has permission to see
+ if (serverTaskIds.length === 0) {
+ return [2 /*return*/, []];
+ }
sleep = function (ms) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/, new Promise(function (r) { return setTimeout(r, ms); })];
}); }); };
@@ -6001,37 +6128,67 @@ var ServerTaskWaiter = /** @class */ (function () {
t = setTimeout(function () {
stop = true;
}, timeout);
+ completedTasks = [];
+ _loop_1 = function () {
+ var tasks_2, unknownTaskIds, nowCompletedTaskIds_1, tasks_1, tasks_1_1, task;
+ var e_1, _b;
+ return __generator(this, function (_c) {
+ switch (_c.label) {
+ case 0:
+ _c.trys.push([0, , 2, 3]);
+ return [4 /*yield*/, spaceServerTaskRepository.getByIds(serverTaskIds)];
+ case 1:
+ tasks_2 = _c.sent();
+ unknownTaskIds = serverTaskIds.filter(function (id) { return tasks_2.filter(function (t) { return t.Id === id; }).length == 0; });
+ if (unknownTaskIds.length) {
+ throw new Error("Unknown task Id(s) ".concat(unknownTaskIds.join(", ")));
+ }
+ nowCompletedTaskIds_1 = [];
+ try {
+ for (tasks_1 = (e_1 = void 0, __values(tasks_2)), tasks_1_1 = tasks_1.next(); !tasks_1_1.done; tasks_1_1 = tasks_1.next()) {
+ task = tasks_1_1.value;
+ if (pollingCallback) {
+ pollingCallback(task);
+ }
+ // once the task is complete
+ if (task.IsCompleted) {
+ nowCompletedTaskIds_1.push(task.Id);
+ completedTasks.push(task);
+ }
+ }
+ }
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
+ finally {
+ try {
+ if (tasks_1_1 && !tasks_1_1.done && (_b = tasks_1.return)) _b.call(tasks_1);
+ }
+ finally { if (e_1) throw e_1.error; }
+ }
+ // filter down the ids to only those that haven't completed for the next time around the loop
+ serverTaskIds = serverTaskIds.filter(function (id) { return nowCompletedTaskIds_1.indexOf(id) < 0; });
+ // once all tasks have completed we can stop the loop
+ if (serverTaskIds.length === 0 || tasks_2.length === 0) {
+ stop = true;
+ }
+ return [3 /*break*/, 3];
+ case 2:
+ clearTimeout(t);
+ return [7 /*endfinally*/];
+ case 3: return [4 /*yield*/, sleep(statusCheckSleepCycle)];
+ case 4:
+ _c.sent();
+ return [2 /*return*/];
+ }
+ });
+ };
_a.label = 1;
case 1:
- if (!!stop) return [3 /*break*/, 10];
- _a.label = 2;
+ if (!!stop) return [3 /*break*/, 3];
+ return [5 /*yield**/, _loop_1()];
case 2:
- _a.trys.push([2, , 7, 8]);
- if (!pollingCallback) return [3 /*break*/, 4];
- return [4 /*yield*/, spaceServerTaskRepository.getDetails(serverTaskId)];
- case 3:
- taskDetails = _a.sent();
- pollingCallback(taskDetails);
- if (taskDetails.Task.IsCompleted) {
- return [2 /*return*/, taskDetails.Task];
- }
- return [3 /*break*/, 6];
- case 4: return [4 /*yield*/, spaceServerTaskRepository.getById(serverTaskId)];
- case 5:
- task = _a.sent();
- if (task.IsCompleted) {
- return [2 /*return*/, task];
- }
- _a.label = 6;
- case 6: return [3 /*break*/, 8];
- case 7:
- clearTimeout(t);
- return [7 /*endfinally*/];
- case 8: return [4 /*yield*/, sleep(statusCheckSleepCycle)];
- case 9:
_a.sent();
return [3 /*break*/, 1];
- case 10: return [2 /*return*/, null];
+ case 3: return [2 /*return*/, completedTasks];
}
});
});
@@ -7248,8751 +7405,8797 @@ exports.isPropertyDefinedAndNotNull = isPropertyDefinedAndNotNull;
/***/ }),
-/***/ 6589:
+/***/ 6761:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-var balanced = __nccwpck_require__(9417);
-
-module.exports = expandTop;
-
-var escSlash = '\0SLASH'+Math.random()+'\0';
-var escOpen = '\0OPEN'+Math.random()+'\0';
-var escClose = '\0CLOSE'+Math.random()+'\0';
-var escComma = '\0COMMA'+Math.random()+'\0';
-var escPeriod = '\0PERIOD'+Math.random()+'\0';
-
-function numeric(str) {
- return parseInt(str, 10) == str
- ? parseInt(str, 10)
- : str.charCodeAt(0);
-}
-
-function escapeBraces(str) {
- return str.split('\\\\').join(escSlash)
- .split('\\{').join(escOpen)
- .split('\\}').join(escClose)
- .split('\\,').join(escComma)
- .split('\\.').join(escPeriod);
-}
-
-function unescapeBraces(str) {
- return str.split(escSlash).join('\\')
- .split(escOpen).join('{')
- .split(escClose).join('}')
- .split(escComma).join(',')
- .split(escPeriod).join('.');
-}
-
-
-// Basically just str.split(","), but handling cases
-// where we have nested braced sections, which should be
-// treated as individual members, like {a,{b,c},d}
-function parseCommaParts(str) {
- if (!str)
- return [''];
-
- var parts = [];
- var m = balanced('{', '}', str);
-
- if (!m)
- return str.split(',');
-
- var pre = m.pre;
- var body = m.body;
- var post = m.post;
- var p = pre.split(',');
-
- p[p.length-1] += '{' + body + '}';
- var postParts = parseCommaParts(post);
- if (post.length) {
- p[p.length-1] += postParts.shift();
- p.push.apply(p, postParts);
- }
-
- parts.push.apply(parts, p);
-
- return parts;
-}
-
-function expandTop(str) {
- if (!str)
- return [];
+const Utils = __nccwpck_require__(5182);
+const pth = __nccwpck_require__(1017);
+const ZipEntry = __nccwpck_require__(4057);
+const ZipFile = __nccwpck_require__(7744);
- // I don't know why Bash 4.3 does this, but it does.
- // Anything starting with {} will have the first two bytes preserved
- // but *only* at the top level, so {},a}b will not expand to anything,
- // but a{},b}c will be expanded to [a}c,abc].
- // One could argue that this is a bug in Bash, but since the goal of
- // this module is to match Bash's rules, we escape a leading {}
- if (str.substr(0, 2) === '{}') {
- str = '\\{\\}' + str.substr(2);
- }
+const get_Bool = (val, def) => (typeof val === "boolean" ? val : def);
+const get_Str = (val, def) => (typeof val === "string" ? val : def);
- return expand(escapeBraces(str), true).map(unescapeBraces);
-}
+const defaultOptions = {
+ // option "noSort" : if true it disables files sorting
+ noSort: false,
+ // read entries during load (initial loading may be slower)
+ readEntries: false,
+ // default method is none
+ method: Utils.Constants.NONE,
+ // file system
+ fs: null
+};
-function embrace(str) {
- return '{' + str + '}';
-}
-function isPadded(el) {
- return /^-?0\d/.test(el);
-}
+module.exports = function (/**String*/ input, /** object */ options) {
+ let inBuffer = null;
-function lte(i, y) {
- return i <= y;
-}
-function gte(i, y) {
- return i >= y;
-}
+ // create object based default options, allowing them to be overwritten
+ const opts = Object.assign(Object.create(null), defaultOptions);
-function expand(str, isTop) {
- var expansions = [];
+ // test input variable
+ if (input && "object" === typeof input) {
+ // if value is not buffer we accept it to be object with options
+ if (!(input instanceof Uint8Array)) {
+ Object.assign(opts, input);
+ input = opts.input ? opts.input : undefined;
+ if (opts.input) delete opts.input;
+ }
- var m = balanced('{', '}', str);
- if (!m) return [str];
+ // if input is buffer
+ if (Buffer.isBuffer(input)) {
+ inBuffer = input;
+ opts.method = Utils.Constants.BUFFER;
+ input = undefined;
+ }
+ }
- // no need to expand pre, since it is guaranteed to be free of brace-sets
- var pre = m.pre;
- var post = m.post.length
- ? expand(m.post, false)
- : [''];
+ // assign options
+ Object.assign(opts, options);
- if (/\$$/.test(m.pre)) {
- for (var k = 0; k < post.length; k++) {
- var expansion = pre+ '{' + m.body + '}' + post[k];
- expansions.push(expansion);
- }
- } else {
- var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
- var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
- var isSequence = isNumericSequence || isAlphaSequence;
- var isOptions = m.body.indexOf(',') >= 0;
- if (!isSequence && !isOptions) {
- // {a},b}
- if (m.post.match(/,.*\}/)) {
- str = m.pre + '{' + m.body + escClose + m.post;
- return expand(str);
- }
- return [str];
- }
+ // instanciate utils filesystem
+ const filetools = new Utils(opts);
- var n;
- if (isSequence) {
- n = m.body.split(/\.\./);
- } else {
- n = parseCommaParts(m.body);
- if (n.length === 1) {
- // x{{a,b}}y ==> x{a}y x{b}y
- n = expand(n[0], false).map(embrace);
- if (n.length === 1) {
- return post.map(function(p) {
- return m.pre + n[0] + p;
- });
+ // if input is file name we retrieve its content
+ if (input && "string" === typeof input) {
+ // load zip file
+ if (filetools.fs.existsSync(input)) {
+ opts.method = Utils.Constants.FILE;
+ opts.filename = input;
+ inBuffer = filetools.fs.readFileSync(input);
+ } else {
+ throw new Error(Utils.Errors.INVALID_FILENAME);
}
- }
}
- // at this point, n is the parts, and we know it's not a comma set
- // with a single entry.
- var N;
+ // create variable
+ const _zip = new ZipFile(inBuffer, opts);
- if (isSequence) {
- var x = numeric(n[0]);
- var y = numeric(n[1]);
- var width = Math.max(n[0].length, n[1].length)
- var incr = n.length == 3
- ? Math.abs(numeric(n[2]))
- : 1;
- var test = lte;
- var reverse = y < x;
- if (reverse) {
- incr *= -1;
- test = gte;
- }
- var pad = n.some(isPadded);
+ const { canonical, sanitize } = Utils;
- N = [];
+ function getEntry(/**Object*/ entry) {
+ if (entry && _zip) {
+ var item;
+ // If entry was given as a file name
+ if (typeof entry === "string") item = _zip.getEntry(entry);
+ // if entry was given as a ZipEntry object
+ if (typeof entry === "object" && typeof entry.entryName !== "undefined" && typeof entry.header !== "undefined") item = _zip.getEntry(entry.entryName);
- for (var i = x; test(i, y); i += incr) {
- var c;
- if (isAlphaSequence) {
- c = String.fromCharCode(i);
- if (c === '\\')
- c = '';
- } else {
- c = String(i);
- if (pad) {
- var need = width - c.length;
- if (need > 0) {
- var z = new Array(need + 1).join('0');
- if (i < 0)
- c = '-' + z + c.slice(1);
- else
- c = z + c;
+ if (item) {
+ return item;
}
- }
}
- N.push(c);
- }
- } else {
- N = [];
-
- for (var j = 0; j < n.length; j++) {
- N.push.apply(N, expand(n[j], false));
- }
+ return null;
}
- for (var j = 0; j < N.length; j++) {
- for (var k = 0; k < post.length; k++) {
- var expansion = pre + N[j] + post[k];
- if (!isTop || isSequence || expansion)
- expansions.push(expansion);
- }
+ function fixPath(zipPath) {
+ const { join, normalize, sep } = pth.posix;
+ // convert windows file separators and normalize
+ return join(".", normalize(sep + zipPath.split("\\").join(sep) + sep));
}
- }
-
- return expansions;
-}
-
+ 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
+ *
+ * @return Buffer or Null in case of error
+ */
+ readFile: function (/**Object*/ entry, /*String, Buffer*/ pass) {
+ var item = getEntry(entry);
+ return (item && item.getData(pass)) || null;
+ },
-/***/ }),
+ /**
+ * Asynchronous readFile
+ * @param entry ZipEntry object or String with the full path of the entry
+ * @param callback
+ *
+ * @return Buffer or Null in case of error
+ */
+ readFileAsync: function (/**Object*/ entry, /**Function*/ callback) {
+ var item = getEntry(entry);
+ if (item) {
+ item.getDataAsync(callback);
+ } else {
+ callback(null, "getEntry failed for:" + entry);
+ }
+ },
-/***/ 150:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ /**
+ * 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
+ *
+ * @return String
+ */
+ readAsText: function (/**Object*/ entry, /**String=*/ encoding) {
+ var item = getEntry(entry);
+ if (item) {
+ var data = item.getData();
+ if (data && data.length) {
+ return data.toString(encoding || "utf8");
+ }
+ }
+ return "";
+ },
-exports.setopts = setopts
-exports.ownProp = ownProp
-exports.makeAbs = makeAbs
-exports.finish = finish
-exports.mark = mark
-exports.isIgnored = isIgnored
-exports.childrenIgnored = childrenIgnored
+ /**
+ * 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
+ *
+ * @return String
+ */
+ readAsTextAsync: function (/**Object*/ entry, /**Function*/ callback, /**String=*/ encoding) {
+ var item = getEntry(entry);
+ if (item) {
+ item.getDataAsync(function (data, err) {
+ if (err) {
+ callback(data, err);
+ return;
+ }
-function ownProp (obj, field) {
- return Object.prototype.hasOwnProperty.call(obj, field)
-}
+ if (data && data.length) {
+ callback(data.toString(encoding || "utf8"));
+ } else {
+ callback("");
+ }
+ });
+ } else {
+ callback("");
+ }
+ },
-var fs = __nccwpck_require__(7147)
-var path = __nccwpck_require__(1017)
-var minimatch = __nccwpck_require__(7787)
-var isAbsolute = (__nccwpck_require__(1017).isAbsolute)
-var Minimatch = minimatch.Minimatch
+ /**
+ * Remove the entry from the file or the entry and all it's nested directories and files if the given entry is a directory
+ *
+ * @param entry
+ */
+ deleteFile: function (/**Object*/ entry) {
+ // @TODO: test deleteFile
+ var item = getEntry(entry);
+ if (item) {
+ _zip.deleteEntry(item.entryName);
+ }
+ },
-function alphasort (a, b) {
- return a.localeCompare(b, 'en')
-}
+ /**
+ * Adds a comment to the zip. The zip must be rewritten after adding the comment.
+ *
+ * @param comment
+ */
+ addZipComment: function (/**String*/ comment) {
+ // @TODO: test addZipComment
+ _zip.comment = comment;
+ },
-function setupIgnores (self, options) {
- self.ignore = options.ignore || []
+ /**
+ * Returns the zip comment
+ *
+ * @return String
+ */
+ getZipComment: function () {
+ return _zip.comment || "";
+ },
- if (!Array.isArray(self.ignore))
- self.ignore = [self.ignore]
+ /**
+ * Adds a comment to a specified zipEntry. The zip must be rewritten after adding the comment
+ * The comment cannot exceed 65535 characters in length
+ *
+ * @param entry
+ * @param comment
+ */
+ addZipEntryComment: function (/**Object*/ entry, /**String*/ comment) {
+ var item = getEntry(entry);
+ if (item) {
+ item.comment = comment;
+ }
+ },
- if (self.ignore.length) {
- self.ignore = self.ignore.map(ignoreMap)
- }
-}
+ /**
+ * Returns the comment of the specified entry
+ *
+ * @param entry
+ * @return String
+ */
+ getZipEntryComment: function (/**Object*/ entry) {
+ var item = getEntry(entry);
+ if (item) {
+ return item.comment || "";
+ }
+ return "";
+ },
-// ignore patterns are always in dot:true mode.
-function ignoreMap (pattern) {
- var gmatcher = null
- if (pattern.slice(-3) === '/**') {
- var gpattern = pattern.replace(/(\/\*\*)+$/, '')
- gmatcher = new Minimatch(gpattern, { dot: true })
- }
+ /**
+ * Updates the content of an existing entry inside the archive. The zip must be rewritten after updating the content
+ *
+ * @param entry
+ * @param content
+ */
+ updateFile: function (/**Object*/ entry, /**Buffer*/ content) {
+ var item = getEntry(entry);
+ if (item) {
+ item.setData(content);
+ }
+ },
- return {
- matcher: new Minimatch(pattern, { dot: true }),
- gmatcher: gmatcher
- }
-}
+ /**
+ * Adds a file from the disk to the archive
+ *
+ * @param localPath File to add to zip
+ * @param zipPath Optional path inside the zip
+ * @param zipName Optional name for the file
+ */
+ addLocalFile: function (/**String*/ localPath, /**String=*/ zipPath, /**String=*/ zipName, /**String*/ comment) {
+ if (filetools.fs.existsSync(localPath)) {
+ // fix ZipPath
+ zipPath = zipPath ? fixPath(zipPath) : "";
-function setopts (self, pattern, options) {
- if (!options)
- options = {}
+ // p - local file name
+ var p = localPath.split("\\").join("/").split("/").pop();
- // base-matching: just use globstar for that.
- if (options.matchBase && -1 === pattern.indexOf("/")) {
- if (options.noglobstar) {
- throw new Error("base matching requires globstar")
- }
- pattern = "**/" + pattern
- }
+ // add file name into zippath
+ zipPath += zipName ? zipName : p;
- self.silent = !!options.silent
- self.pattern = pattern
- self.strict = options.strict !== false
- self.realpath = !!options.realpath
- self.realpathCache = options.realpathCache || Object.create(null)
- self.follow = !!options.follow
- self.dot = !!options.dot
- self.mark = !!options.mark
- self.nodir = !!options.nodir
- if (self.nodir)
- self.mark = true
- self.sync = !!options.sync
- self.nounique = !!options.nounique
- self.nonull = !!options.nonull
- self.nosort = !!options.nosort
- self.nocase = !!options.nocase
- self.stat = !!options.stat
- self.noprocess = !!options.noprocess
- self.absolute = !!options.absolute
- self.fs = options.fs || fs
+ // read file attributes
+ const _attr = filetools.fs.statSync(localPath);
- self.maxLength = options.maxLength || Infinity
- self.cache = options.cache || Object.create(null)
- self.statCache = options.statCache || Object.create(null)
- self.symlinks = options.symlinks || Object.create(null)
+ // add file into zip file
+ this.addFile(zipPath, filetools.fs.readFileSync(localPath), comment, _attr);
+ } else {
+ throw new Error(Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath));
+ }
+ },
- setupIgnores(self, options)
+ /**
+ * 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
+ */
+ addLocalFolder: function (/**String*/ localPath, /**String=*/ zipPath, /**=RegExp|Function*/ filter, /**=number|object*/ attr) {
+ // 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;
+ };
+ }
- self.changedCwd = false
- var cwd = process.cwd()
- if (!ownProp(options, "cwd"))
- self.cwd = path.resolve(cwd)
- else {
- self.cwd = path.resolve(options.cwd)
- self.changedCwd = self.cwd !== cwd
- }
+ // fix ZipPath
+ zipPath = zipPath ? fixPath(zipPath) : "";
- self.root = options.root || path.resolve(self.cwd, "/")
- self.root = path.resolve(self.root)
+ // normalize the path first
+ localPath = pth.normalize(localPath);
- // TODO: is an absolute `cwd` supposed to be resolved against `root`?
- // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
- self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd)
- self.nomount = !!options.nomount
+ if (filetools.fs.existsSync(localPath)) {
+ const items = filetools.findFiles(localPath);
+ const self = this;
- if (process.platform === "win32") {
- self.root = self.root.replace(/\\/g, "/")
- self.cwd = self.cwd.replace(/\\/g, "/")
- self.cwdAbs = self.cwdAbs.replace(/\\/g, "/")
- }
+ if (items.length) {
+ items.forEach(function (filepath) {
+ var p = pth.relative(localPath, filepath).split("\\").join("/"); //windows fix
+ 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);
+ }
+ }
+ });
+ }
+ } else {
+ throw new Error(Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath));
+ }
+ },
- // disable comments and negation in Minimatch.
- // Note that they are not supported in Glob itself anyway.
- options.nonegate = true
- options.nocomment = true
- // always treat \ in patterns as escapes, not path separators
- options.allowWindowsEscape = true
+ /**
+ * Asynchronous addLocalFile
+ * @param localPath
+ * @param callback
+ * @param zipPath optional path inside zip
+ * @param 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;
+ };
+ }
- self.minimatch = new Minimatch(pattern, options)
- self.options = self.minimatch.options
-}
+ // fix ZipPath
+ zipPath = zipPath ? fixPath(zipPath) : "";
-function finish (self) {
- var nou = self.nounique
- var all = nou ? [] : Object.create(null)
+ // normalize the path first
+ localPath = pth.normalize(localPath);
- for (var i = 0, l = self.matches.length; i < l; i ++) {
- var matches = self.matches[i]
- if (!matches || Object.keys(matches).length === 0) {
- if (self.nonull) {
- // do like the shell, and spit out the literal glob
- var literal = self.minimatch.globSet[i]
- if (nou)
- all.push(literal)
- else
- all[literal] = true
- }
- } else {
- // had matches
- var m = Object.keys(matches)
- if (nou)
- all.push.apply(all, m)
- else
- m.forEach(function (m) {
- all[m] = true
- })
- }
- }
+ var self = this;
+ filetools.fs.open(localPath, "r", function (err) {
+ if (err && err.code === "ENOENT") {
+ callback(undefined, Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath));
+ } else if (err) {
+ callback(undefined, err);
+ } else {
+ var items = filetools.findFiles(localPath);
+ var i = -1;
- if (!nou)
- all = Object.keys(all)
+ var next = function () {
+ i += 1;
+ if (i < items.length) {
+ var filepath = items[i];
+ var p = pth.relative(localPath, filepath).split("\\").join("/"); //windows fix
+ p = p
+ .normalize("NFD")
+ .replace(/[\u0300-\u036f]/g, "")
+ .replace(/[^\x20-\x7E]/g, ""); // accent fix
+ if (filter(p)) {
+ filetools.fs.stat(filepath, function (er0, stats) {
+ if (er0) callback(undefined, er0);
+ if (stats.isFile()) {
+ filetools.fs.readFile(filepath, function (er1, data) {
+ if (er1) {
+ callback(undefined, er1);
+ } else {
+ self.addFile(zipPath + p, data, "", stats);
+ next();
+ }
+ });
+ } else {
+ self.addFile(zipPath + p + "/", Buffer.alloc(0), "", stats);
+ next();
+ }
+ });
+ } else {
+ process.nextTick(() => {
+ next();
+ });
+ }
+ } else {
+ callback(true, undefined);
+ }
+ };
- if (!self.nosort)
- all = all.sort(alphasort)
+ next();
+ }
+ });
+ },
- // at *some* point we statted all of these
- if (self.mark) {
- for (var i = 0; i < all.length; i++) {
- all[i] = self._mark(all[i])
- }
- if (self.nodir) {
- all = all.filter(function (e) {
- var notDir = !(/\/$/.test(e))
- var c = self.cache[e] || self.cache[makeAbs(self, e)]
- if (notDir && c)
- notDir = c !== 'DIR' && !Array.isArray(c)
- return notDir
- })
- }
- }
+ /**
+ *
+ * @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.
+ */
+ addLocalFolderPromise: function (/*String*/ localPath, /* object */ 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
+ );
+ });
+ },
- if (self.ignore.length)
- all = all.filter(function(m) {
- return !isIgnored(self, m)
- })
+ /**
+ * Allows you to create a entry (file or directory) in the zip file.
+ * If you want to create a directory the entryName must end in / and a null buffer should be provided.
+ * Comment and attributes are optional
+ *
+ * @param {string} entryName
+ * @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
+ */
+ addFile: function (/**String*/ entryName, /**Buffer*/ content, /**String*/ comment, /**Number*/ attr) {
+ let entry = getEntry(entryName);
+ const update = entry != null;
- self.found = all
-}
+ // prepare new entry
+ if (!update) {
+ entry = new ZipEntry();
+ entry.entryName = entryName;
+ }
+ entry.comment = comment || "";
-function mark (self, p) {
- var abs = makeAbs(self, p)
- var c = self.cache[abs]
- var m = p
- if (c) {
- var isDir = c === 'DIR' || Array.isArray(c)
- var slash = p.slice(-1) === '/'
+ const isStat = "object" === typeof attr && attr instanceof filetools.fs.Stats;
- if (isDir && !slash)
- m += '/'
- else if (!isDir && slash)
- m = m.slice(0, -1)
+ // last modification time from file stats
+ if (isStat) {
+ entry.header.time = attr.mtime;
+ }
- if (m !== p) {
- var mabs = makeAbs(self, m)
- self.statCache[mabs] = self.statCache[abs]
- self.cache[mabs] = self.cache[abs]
- }
- }
+ // Set file attribute
+ var fileattr = entry.isDirectory ? 0x10 : 0; // (MS-DOS directory flag)
- return m
-}
+ // extended attributes field for Unix
+ // set file type either S_IFDIR / S_IFREG
+ let unix = entry.isDirectory ? 0x4000 : 0x8000;
-// lotta situps...
-function makeAbs (self, f) {
- var abs = f
- if (f.charAt(0) === '/') {
- abs = path.join(self.root, f)
- } else if (isAbsolute(f) || f === '') {
- abs = f
- } else if (self.changedCwd) {
- abs = path.resolve(self.cwd, f)
- } else {
- abs = path.resolve(f)
- }
+ if (isStat) {
+ // File attributes from file stats
+ unix |= 0xfff & attr.mode;
+ } else if ("number" === typeof attr) {
+ // attr from given attr values
+ unix |= 0xfff & attr;
+ } else {
+ // Default values:
+ unix |= entry.isDirectory ? 0o755 : 0o644; // permissions (drwxr-xr-x) or (-r-wr--r--)
+ }
- if (process.platform === 'win32')
- abs = abs.replace(/\\/g, '/')
+ fileattr = (fileattr | (unix << 16)) >>> 0; // add attributes
- return abs
-}
+ entry.attr = fileattr;
+ entry.setData(content);
+ if (!update) _zip.setEntry(entry);
+ },
-// Return true, if pattern ends with globstar '**', for the accompanying parent directory.
-// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
-function isIgnored (self, path) {
- if (!self.ignore.length)
- return false
+ /**
+ * Returns an array of ZipEntry objects representing the files and folders inside the archive
+ *
+ * @return Array
+ */
+ getEntries: function () {
+ return _zip ? _zip.entries : [];
+ },
- return self.ignore.some(function(item) {
- return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
- })
-}
+ /**
+ * Returns a ZipEntry object representing the file or folder specified by ``name``.
+ *
+ * @param name
+ * @return ZipEntry
+ */
+ getEntry: function (/**String*/ name) {
+ return getEntry(name);
+ },
-function childrenIgnored (self, path) {
- if (!self.ignore.length)
- return false
+ getEntryCount: function () {
+ return _zip.getEntryCount();
+ },
- return self.ignore.some(function(item) {
- return !!(item.gmatcher && item.gmatcher.match(path))
- })
-}
+ forEach: function (callback) {
+ return _zip.forEach(callback);
+ },
+ /**
+ * Extracts the given entry to the given targetPath
+ * If the entry is a directory inside the archive, the entire directory and it's subdirectories will be extracted
+ *
+ * @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)
+ *
+ * @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));
-/***/ }),
+ var item = getEntry(entry);
+ if (!item) {
+ throw new Error(Utils.Errors.NO_ENTRY);
+ }
-/***/ 2782:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ var entryName = canonical(item.entryName);
-// Approach:
-//
-// 1. Get the minimatch set
-// 2. For each pattern in the set, PROCESS(pattern, false)
-// 3. Store matches per-set, then uniq them
-//
-// PROCESS(pattern, inGlobStar)
-// Get the first [n] items from pattern that are all strings
-// Join these together. This is PREFIX.
-// If there is no more remaining, then stat(PREFIX) and
-// add to matches if it succeeds. END.
-//
-// If inGlobStar and PREFIX is symlink and points to dir
-// set ENTRIES = []
-// else readdir(PREFIX) as ENTRIES
-// If fail, END
-//
-// with ENTRIES
-// If pattern[n] is GLOBSTAR
-// // handle the case where the globstar match is empty
-// // by pruning it out, and testing the resulting pattern
-// PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
-// // handle other cases.
-// for ENTRY in ENTRIES (not dotfiles)
-// // attach globstar + tail onto the entry
-// // Mark that this entry is a globstar match
-// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
-//
-// else // not globstar
-// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
-// Test ENTRY against pattern[n]
-// If fails, continue
-// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
-//
-// Caveat:
-// Cache all stats and readdirs results to minimize syscall. Since all
-// we ever care about is existence and directory-ness, we can just keep
-// `true` for files, and [children,...] for directories, or `false` for
-// things that don't exist.
+ var target = sanitize(targetPath, outFileName && !item.isDirectory ? outFileName : maintainEntryPath ? entryName : pth.basename(entryName));
-module.exports = glob
+ if (item.isDirectory) {
+ var children = _zip.getEntryChildren(item);
+ children.forEach(function (child) {
+ if (child.isDirectory) return;
+ var content = child.getData();
+ if (!content) {
+ throw new Error(Utils.Errors.CANT_EXTRACT_FILE);
+ }
+ var name = canonical(child.entryName);
+ var childName = sanitize(targetPath, maintainEntryPath ? name : pth.basename(name));
+ // The reverse operation for attr depend on method addFile()
+ const fileAttr = keepOriginalPermission ? child.header.fileAttr : undefined;
+ filetools.writeFileTo(childName, content, overwrite, fileAttr);
+ });
+ return true;
+ }
-var rp = __nccwpck_require__(6863)
-var minimatch = __nccwpck_require__(7787)
-var Minimatch = minimatch.Minimatch
-var inherits = __nccwpck_require__(4124)
-var EE = (__nccwpck_require__(2361).EventEmitter)
-var path = __nccwpck_require__(1017)
-var assert = __nccwpck_require__(9491)
-var isAbsolute = (__nccwpck_require__(1017).isAbsolute)
-var globSync = __nccwpck_require__(2479)
-var common = __nccwpck_require__(150)
-var setopts = common.setopts
-var ownProp = common.ownProp
-var inflight = __nccwpck_require__(2492)
-var util = __nccwpck_require__(3837)
-var childrenIgnored = common.childrenIgnored
-var isIgnored = common.isIgnored
+ var content = item.getData();
+ if (!content) throw new Error(Utils.Errors.CANT_EXTRACT_FILE);
-var once = __nccwpck_require__(1223)
+ if (filetools.fs.existsSync(target) && !overwrite) {
+ throw new Error(Utils.Errors.CANT_OVERRIDE);
+ }
+ // The reverse operation for attr depend on method addFile()
+ const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;
+ filetools.writeFileTo(target, content, overwrite, fileAttr);
-function glob (pattern, options, cb) {
- if (typeof options === 'function') cb = options, options = {}
- if (!options) options = {}
+ return true;
+ },
- if (options.sync) {
- if (cb)
- throw new TypeError('callback provided to sync glob')
- return globSync(pattern, options)
- }
+ /**
+ * Test the archive
+ *
+ */
+ test: function (pass) {
+ if (!_zip) {
+ return false;
+ }
- return new Glob(pattern, options, cb)
-}
+ for (var entry in _zip.entries) {
+ try {
+ if (entry.isDirectory) {
+ continue;
+ }
+ var content = _zip.entries[entry].getData(pass);
+ if (!content) {
+ return false;
+ }
+ } catch (err) {
+ return false;
+ }
+ }
+ return true;
+ },
-glob.sync = globSync
-var GlobSync = glob.GlobSync = globSync.GlobSync
+ /**
+ * Extracts the entire archive to the given location
+ *
+ * @param targetPath Target location
+ * @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
+ */
+ extractAllTo: function (/**String*/ targetPath, /**Boolean*/ overwrite, /**Boolean*/ keepOriginalPermission, /*String, Buffer*/ pass) {
+ overwrite = get_Bool(overwrite, false);
+ pass = get_Str(keepOriginalPermission, pass);
+ keepOriginalPermission = get_Bool(keepOriginalPermission, false);
+ if (!_zip) {
+ throw new Error(Utils.Errors.NO_ZIP);
+ }
+ _zip.entries.forEach(function (entry) {
+ var entryName = sanitize(targetPath, canonical(entry.entryName.toString()));
+ if (entry.isDirectory) {
+ filetools.makeDir(entryName);
+ return;
+ }
+ var content = entry.getData(pass);
+ if (!content) {
+ throw new Error(Utils.Errors.CANT_EXTRACT_FILE);
+ }
+ // The reverse operation for attr depend on method addFile()
+ const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;
+ filetools.writeFileTo(entryName, content, overwrite, fileAttr);
+ try {
+ filetools.fs.utimesSync(entryName, entry.header.time, entry.header.time);
+ } catch (err) {
+ throw new Error(Utils.Errors.CANT_EXTRACT_FILE);
+ }
+ });
+ },
-// old api surface
-glob.glob = glob
+ /**
+ * Asynchronous extractAllTo
+ *
+ * @param targetPath Target location
+ * @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 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) {
+ overwrite = get_Bool(overwrite, false);
+ if (typeof keepOriginalPermission === "function" && !callback) callback = keepOriginalPermission;
+ keepOriginalPermission = get_Bool(keepOriginalPermission, false);
+ if (!callback) {
+ callback = function (err) {
+ throw new Error(err);
+ };
+ }
+ if (!_zip) {
+ callback(new Error(Utils.Errors.NO_ZIP));
+ return;
+ }
-function extend (origin, add) {
- if (add === null || typeof add !== 'object') {
- return origin
- }
+ targetPath = pth.resolve(targetPath);
+ // convert entryName to
+ const getPath = (entry) => sanitize(targetPath, pth.normalize(canonical(entry.entryName.toString())));
+ const getError = (msg, file) => new Error(msg + ': "' + file + '"');
- var keys = Object.keys(add)
- var i = keys.length
- while (i--) {
- origin[keys[i]] = add[keys[i]]
- }
- return origin
-}
+ // separate directories from files
+ const dirEntries = [];
+ const fileEntries = new Set();
+ _zip.entries.forEach((e) => {
+ if (e.isDirectory) {
+ dirEntries.push(e);
+ } else {
+ fileEntries.add(e);
+ }
+ });
-glob.hasMagic = function (pattern, options_) {
- var options = extend({}, options_)
- options.noprocess = true
+ // Create directory entries first synchronously
+ // this prevents race condition and assures folders are there before writing files
+ for (const entry of dirEntries) {
+ const dirPath = getPath(entry);
+ // The reverse operation for attr depend on method addFile()
+ const dirAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;
+ try {
+ filetools.makeDir(dirPath);
+ if (dirAttr) filetools.fs.chmodSync(dirPath, dirAttr);
+ // in unix timestamp will change if files are later added to folder, but still
+ filetools.fs.utimesSync(dirPath, entry.header.time, entry.header.time);
+ } catch (er) {
+ callback(getError("Unable to create folder", dirPath));
+ }
+ }
- var g = new Glob(pattern, options)
- var set = g.minimatch.set
+ // callback wrapper, for some house keeping
+ const done = () => {
+ if (fileEntries.size === 0) {
+ callback();
+ }
+ };
- if (!pattern)
- return false
+ // Extract file entries asynchronously
+ for (const entry of fileEntries.values()) {
+ const entryName = pth.normalize(canonical(entry.entryName.toString()));
+ const filePath = sanitize(targetPath, entryName);
+ entry.getDataAsync(function (content, err_1) {
+ if (err_1) {
+ callback(new Error(err_1));
+ return;
+ }
+ if (!content) {
+ callback(new Error(Utils.Errors.CANT_EXTRACT_FILE));
+ } else {
+ // The reverse operation for attr depend on method addFile()
+ const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;
+ filetools.writeFileToAsync(filePath, content, overwrite, fileAttr, function (succ) {
+ if (!succ) {
+ callback(getError("Unable to write file", filePath));
+ return;
+ }
+ filetools.fs.utimes(filePath, entry.header.time, entry.header.time, function (err_2) {
+ if (err_2) {
+ callback(getError("Unable to set times", filePath));
+ return;
+ }
+ fileEntries.delete(entry);
+ // call the callback if it was last entry
+ done();
+ });
+ });
+ }
+ });
+ }
+ // call the callback if fileEntries was empty
+ done();
+ },
- if (set.length > 1)
- return true
+ /**
+ * Writes the newly created zip file to disk at the specified location or if a zip was opened and no ``targetFileName`` is provided, it will overwrite the opened zip
+ *
+ * @param targetFileName
+ * @param callback
+ */
+ writeZip: function (/**String*/ targetFileName, /**Function*/ callback) {
+ if (arguments.length === 1) {
+ if (typeof targetFileName === "function") {
+ callback = targetFileName;
+ targetFileName = "";
+ }
+ }
- for (var j = 0; j < set[0].length; j++) {
- if (typeof set[0][j] !== 'string')
- return true
- }
+ if (!targetFileName && opts.filename) {
+ targetFileName = opts.filename;
+ }
+ if (!targetFileName) return;
- return false
-}
+ var zipData = _zip.compressToBuffer();
+ if (zipData) {
+ var ok = filetools.writeFileTo(targetFileName, zipData, true);
+ if (typeof callback === "function") callback(!ok ? new Error("failed") : null, "");
+ }
+ },
-glob.Glob = Glob
-inherits(Glob, EE)
-function Glob (pattern, options, cb) {
- if (typeof options === 'function') {
- cb = options
- options = null
- }
+ writeZipPromise: function (/**String*/ targetFileName, /* object */ props) {
+ const { overwrite, perm } = Object.assign({ overwrite: true }, props);
- if (options && options.sync) {
- if (cb)
- throw new TypeError('callback provided to sync glob')
- return new GlobSync(pattern, options)
- }
+ return new Promise((resolve, reject) => {
+ // find file name
+ if (!targetFileName && opts.filename) targetFileName = opts.filename;
+ if (!targetFileName) reject("ADM-ZIP: ZIP File Name Missing");
- if (!(this instanceof Glob))
- return new Glob(pattern, options, cb)
+ this.toBufferPromise().then((zipData) => {
+ const ret = (done) => (done ? resolve(done) : reject("ADM-ZIP: Wasn't able to write zip file"));
+ filetools.writeFileToAsync(targetFileName, zipData, overwrite, perm, ret);
+ }, reject);
+ });
+ },
- setopts(this, pattern, options)
- this._didRealPath = false
+ toBufferPromise: function () {
+ return new Promise((resolve, reject) => {
+ _zip.toAsyncBuffer(resolve, reject);
+ });
+ },
- // process each pattern in the minimatch set
- var n = this.minimatch.set.length
+ /**
+ * Returns the content of the entire zip file as a Buffer object
+ *
+ * @return Buffer
+ */
+ toBuffer: function (/**Function=*/ onSuccess, /**Function=*/ onFail, /**Function=*/ onItemStart, /**Function=*/ onItemEnd) {
+ this.valueOf = 2;
+ if (typeof onSuccess === "function") {
+ _zip.toAsyncBuffer(onSuccess, onFail, onItemStart, onItemEnd);
+ return null;
+ }
+ return _zip.compressToBuffer();
+ }
+ };
+};
- // The matches are stored as {: true,...} so that
- // duplicates are automagically pruned.
- // Later, we do an Object.keys() on these.
- // Keep them as a list so we can fill in when nonull is set.
- this.matches = new Array(n)
- if (typeof cb === 'function') {
- cb = once(cb)
- this.on('error', cb)
- this.on('end', function (matches) {
- cb(null, matches)
- })
- }
+/***/ }),
- var self = this
- this._processing = 0
+/***/ 9032:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- this._emitQueue = []
- this._processQueue = []
- this.paused = false
+var Utils = __nccwpck_require__(5182),
+ Constants = Utils.Constants;
- if (this.noprocess)
- return this
+/* The central directory file header */
+module.exports = function () {
+ var _verMade = 20, // v2.0
+ _version = 10, // v1.0
+ _flags = 0,
+ _method = 0,
+ _time = 0,
+ _crc = 0,
+ _compressedSize = 0,
+ _size = 0,
+ _fnameLen = 0,
+ _extraLen = 0,
+ _comLen = 0,
+ _diskStart = 0,
+ _inattr = 0,
+ _attr = 0,
+ _offset = 0;
- if (n === 0)
- return done()
+ _verMade |= Utils.isWin ? 0x0a00 : 0x0300;
- var sync = true
- for (var i = 0; i < n; i ++) {
- this._process(this.minimatch.set[i], i, false, done)
- }
- sync = false
+ // Set EFS flag since filename and comment fields are all by default encoded using UTF-8.
+ // Without it file names may be corrupted for other apps when file names use unicode chars
+ _flags |= Constants.FLG_EFS;
- function done () {
- --self._processing
- if (self._processing <= 0) {
- if (sync) {
- process.nextTick(function () {
- self._finish()
- })
- } else {
- self._finish()
- }
+ var _dataHeader = {};
+
+ 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
}
- }
-}
-Glob.prototype._finish = function () {
- assert(this instanceof Glob)
- if (this.aborted)
- return
+ setTime(+new Date());
- if (this.realpath && !this._didRealpath)
- return this._realpath()
+ return {
+ get made() {
+ return _verMade;
+ },
+ set made(val) {
+ _verMade = val;
+ },
- common.finish(this)
- this.emit('end', this.found)
-}
+ get version() {
+ return _version;
+ },
+ set version(val) {
+ _version = val;
+ },
-Glob.prototype._realpath = function () {
- if (this._didRealpath)
- return
+ get flags() {
+ return _flags;
+ },
+ set flags(val) {
+ _flags = val;
+ },
- this._didRealpath = true
+ get method() {
+ return _method;
+ },
+ set method(val) {
+ switch (val) {
+ case Constants.STORED:
+ this.version = 10;
+ case Constants.DEFLATED:
+ default:
+ this.version = 20;
+ }
+ _method = val;
+ },
- var n = this.matches.length
- if (n === 0)
- return this._finish()
+ 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);
+ },
+ set time(val) {
+ setTime(val);
+ },
- var self = this
- for (var i = 0; i < this.matches.length; i++)
- this._realpathSet(i, next)
+ get crc() {
+ return _crc;
+ },
+ set crc(val) {
+ _crc = Math.max(0, val) >>> 0;
+ },
- function next () {
- if (--n === 0)
- self._finish()
- }
-}
+ get compressedSize() {
+ return _compressedSize;
+ },
+ set compressedSize(val) {
+ _compressedSize = Math.max(0, val) >>> 0;
+ },
-Glob.prototype._realpathSet = function (index, cb) {
- var matchset = this.matches[index]
- if (!matchset)
- return cb()
+ get size() {
+ return _size;
+ },
+ set size(val) {
+ _size = Math.max(0, val) >>> 0;
+ },
- var found = Object.keys(matchset)
- var self = this
- var n = found.length
+ get fileNameLength() {
+ return _fnameLen;
+ },
+ set fileNameLength(val) {
+ _fnameLen = val;
+ },
- if (n === 0)
- return cb()
+ get extraLength() {
+ return _extraLen;
+ },
+ set extraLength(val) {
+ _extraLen = val;
+ },
- var set = this.matches[index] = Object.create(null)
- found.forEach(function (p, i) {
- // If there's a problem with the stat, then it means that
- // one or more of the links in the realpath couldn't be
- // resolved. just return the abs value in that case.
- p = self._makeAbs(p)
- rp.realpath(p, self.realpathCache, function (er, real) {
- if (!er)
- set[real] = true
- else if (er.syscall === 'stat')
- set[p] = true
- else
- self.emit('error', er) // srsly wtf right here
-
- if (--n === 0) {
- self.matches[index] = set
- cb()
- }
- })
- })
-}
+ get commentLength() {
+ return _comLen;
+ },
+ set commentLength(val) {
+ _comLen = val;
+ },
-Glob.prototype._mark = function (p) {
- return common.mark(this, p)
-}
+ get diskNumStart() {
+ return _diskStart;
+ },
+ set diskNumStart(val) {
+ _diskStart = Math.max(0, val) >>> 0;
+ },
-Glob.prototype._makeAbs = function (f) {
- return common.makeAbs(this, f)
-}
+ get inAttr() {
+ return _inattr;
+ },
+ set inAttr(val) {
+ _inattr = Math.max(0, val) >>> 0;
+ },
-Glob.prototype.abort = function () {
- this.aborted = true
- this.emit('abort')
-}
+ get attr() {
+ return _attr;
+ },
+ set attr(val) {
+ _attr = Math.max(0, val) >>> 0;
+ },
-Glob.prototype.pause = function () {
- if (!this.paused) {
- this.paused = true
- this.emit('pause')
- }
-}
+ // get Unix file permissions
+ get fileAttr() {
+ return _attr ? (((_attr >>> 0) | 0) >> 16) & 0xfff : 0;
+ },
-Glob.prototype.resume = function () {
- if (this.paused) {
- this.emit('resume')
- this.paused = false
- if (this._emitQueue.length) {
- var eq = this._emitQueue.slice(0)
- this._emitQueue.length = 0
- for (var i = 0; i < eq.length; i ++) {
- var e = eq[i]
- this._emitMatch(e[0], e[1])
- }
- }
- if (this._processQueue.length) {
- var pq = this._processQueue.slice(0)
- this._processQueue.length = 0
- for (var i = 0; i < pq.length; i ++) {
- var p = pq[i]
- this._processing--
- this._process(p[0], p[1], p[2], p[3])
- }
- }
- }
-}
+ get offset() {
+ return _offset;
+ },
+ set offset(val) {
+ _offset = Math.max(0, val) >>> 0;
+ },
-Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
- assert(this instanceof Glob)
- assert(typeof cb === 'function')
+ get encripted() {
+ return (_flags & 1) === 1;
+ },
- if (this.aborted)
- return
+ get entryHeaderSize() {
+ return Constants.CENHDR + _fnameLen + _extraLen + _comLen;
+ },
- this._processing++
- if (this.paused) {
- this._processQueue.push([pattern, index, inGlobStar, cb])
- return
- }
+ get realDataOffset() {
+ return _offset + Constants.LOCHDR + _dataHeader.fnameLen + _dataHeader.extraLen;
+ },
- //console.error('PROCESS %d', this._processing, pattern)
+ get dataHeader() {
+ return _dataHeader;
+ },
- // Get the first [n] parts of pattern that are all strings.
- var n = 0
- while (typeof pattern[n] === 'string') {
- n ++
- }
- // now n is the index of the first one that is *not* a string.
+ loadDataHeaderFromBinary: function (/*Buffer*/ input) {
+ var data = input.slice(_offset, _offset + Constants.LOCHDR);
+ // 30 bytes and should start with "PK\003\004"
+ if (data.readUInt32LE(0) !== Constants.LOCSIG) {
+ throw new Error(Utils.Errors.INVALID_LOC);
+ }
+ _dataHeader = {
+ // 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)
+ };
+ },
- // see if there's anything else
- var prefix
- switch (n) {
- // if not, then this is rather simple
- case pattern.length:
- this._processSimple(pattern.join('/'), index, cb)
- return
+ loadFromBinary: function (/*Buffer*/ data) {
+ // data should be 46 bytes and start with "PK 01 02"
+ if (data.length !== Constants.CENHDR || data.readUInt32LE(0) !== Constants.CENSIG) {
+ throw new Error(Utils.Errors.INVALID_CEN);
+ }
+ // version made by
+ _verMade = data.readUInt16LE(Constants.CENVEM);
+ // version needed to extract
+ _version = data.readUInt16LE(Constants.CENVER);
+ // encrypt, decrypt flags
+ _flags = data.readUInt16LE(Constants.CENFLG);
+ // compression method
+ _method = data.readUInt16LE(Constants.CENHOW);
+ // modification time (2 bytes time, 2 bytes date)
+ _time = data.readUInt32LE(Constants.CENTIM);
+ // uncompressed file crc-32 value
+ _crc = data.readUInt32LE(Constants.CENCRC);
+ // compressed size
+ _compressedSize = data.readUInt32LE(Constants.CENSIZ);
+ // uncompressed size
+ _size = data.readUInt32LE(Constants.CENLEN);
+ // filename length
+ _fnameLen = data.readUInt16LE(Constants.CENNAM);
+ // extra field length
+ _extraLen = data.readUInt16LE(Constants.CENEXT);
+ // file comment length
+ _comLen = data.readUInt16LE(Constants.CENCOM);
+ // volume number start
+ _diskStart = data.readUInt16LE(Constants.CENDSK);
+ // internal file attributes
+ _inattr = data.readUInt16LE(Constants.CENATT);
+ // external file attributes
+ _attr = data.readUInt32LE(Constants.CENATX);
+ // LOC header offset
+ _offset = data.readUInt32LE(Constants.CENOFF);
+ },
- case 0:
- // pattern *starts* with some non-trivial item.
- // going to readdir(cwd), but not include the prefix in matches.
- prefix = null
- break
+ dataHeaderToBinary: function () {
+ // LOC header size (30 bytes)
+ var data = Buffer.alloc(Constants.LOCHDR);
+ // "PK\003\004"
+ data.writeUInt32LE(Constants.LOCSIG, 0);
+ // version needed to extract
+ data.writeUInt16LE(_version, Constants.LOCVER);
+ // general purpose bit flag
+ data.writeUInt16LE(_flags, Constants.LOCFLG);
+ // compression method
+ data.writeUInt16LE(_method, Constants.LOCHOW);
+ // modification time (2 bytes time, 2 bytes date)
+ data.writeUInt32LE(_time, Constants.LOCTIM);
+ // uncompressed file crc-32 value
+ data.writeUInt32LE(_crc, Constants.LOCCRC);
+ // compressed size
+ data.writeUInt32LE(_compressedSize, Constants.LOCSIZ);
+ // uncompressed size
+ data.writeUInt32LE(_size, Constants.LOCLEN);
+ // filename length
+ data.writeUInt16LE(_fnameLen, Constants.LOCNAM);
+ // extra field length
+ data.writeUInt16LE(_extraLen, Constants.LOCEXT);
+ return data;
+ },
- default:
- // pattern has some string bits in the front.
- // whatever it starts with, whether that's 'absolute' like /foo/bar,
- // or 'relative' like '../baz'
- prefix = pattern.slice(0, n).join('/')
- break
- }
+ entryHeaderToBinary: function () {
+ // CEN header size (46 bytes)
+ var data = Buffer.alloc(Constants.CENHDR + _fnameLen + _extraLen + _comLen);
+ // "PK\001\002"
+ data.writeUInt32LE(Constants.CENSIG, 0);
+ // version made by
+ data.writeUInt16LE(_verMade, Constants.CENVEM);
+ // version needed to extract
+ data.writeUInt16LE(_version, Constants.CENVER);
+ // encrypt, decrypt flags
+ data.writeUInt16LE(_flags, Constants.CENFLG);
+ // compression method
+ data.writeUInt16LE(_method, Constants.CENHOW);
+ // modification time (2 bytes time, 2 bytes date)
+ data.writeUInt32LE(_time, Constants.CENTIM);
+ // uncompressed file crc-32 value
+ data.writeUInt32LE(_crc, Constants.CENCRC);
+ // compressed size
+ data.writeUInt32LE(_compressedSize, Constants.CENSIZ);
+ // uncompressed size
+ data.writeUInt32LE(_size, Constants.CENLEN);
+ // filename length
+ data.writeUInt16LE(_fnameLen, Constants.CENNAM);
+ // extra field length
+ data.writeUInt16LE(_extraLen, Constants.CENEXT);
+ // file comment length
+ data.writeUInt16LE(_comLen, Constants.CENCOM);
+ // volume number start
+ data.writeUInt16LE(_diskStart, Constants.CENDSK);
+ // internal file attributes
+ data.writeUInt16LE(_inattr, Constants.CENATT);
+ // external file attributes
+ data.writeUInt32LE(_attr, Constants.CENATX);
+ // LOC header offset
+ data.writeUInt32LE(_offset, Constants.CENOFF);
+ // fill all with
+ data.fill(0x00, Constants.CENHDR);
+ return data;
+ },
- var remain = pattern.slice(n)
+ toJSON: function () {
+ const bytes = function (nr) {
+ return nr + " bytes";
+ };
- // get the list of entries.
- var read
- if (prefix === null)
- read = '.'
- else if (isAbsolute(prefix) ||
- isAbsolute(pattern.map(function (p) {
- return typeof p === 'string' ? p : '[*]'
- }).join('/'))) {
- if (!prefix || !isAbsolute(prefix))
- prefix = '/' + prefix
- read = prefix
- } else
- read = prefix
+ return {
+ made: _verMade,
+ version: _version,
+ flags: _flags,
+ method: Utils.methodToString(_method),
+ time: this.time,
+ crc: "0x" + _crc.toString(16).toUpperCase(),
+ compressedSize: bytes(_compressedSize),
+ size: bytes(_size),
+ fileNameLength: bytes(_fnameLen),
+ extraLength: bytes(_extraLen),
+ commentLength: bytes(_comLen),
+ diskNumStart: _diskStart,
+ inAttr: _inattr,
+ attr: _attr,
+ offset: _offset,
+ entryHeaderSize: bytes(Constants.CENHDR + _fnameLen + _extraLen + _comLen)
+ };
+ },
- var abs = this._makeAbs(read)
+ toString: function () {
+ return JSON.stringify(this.toJSON(), null, "\t");
+ }
+ };
+};
- //if ignored, skip _processing
- if (childrenIgnored(this, read))
- return cb()
- var isGlobStar = remain[0] === minimatch.GLOBSTAR
- if (isGlobStar)
- this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb)
- else
- this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb)
-}
+/***/ }),
-Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
- var self = this
- this._readdir(abs, inGlobStar, function (er, entries) {
- return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
- })
-}
+/***/ 4958:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
+exports.EntryHeader = __nccwpck_require__(9032);
+exports.MainHeader = __nccwpck_require__(4408);
- // if the abs isn't a dir, then nothing can match!
- if (!entries)
- return cb()
- // It will only match dot entries if it starts with a dot, or if
- // dot is set. Stuff like @(.foo|.bar) isn't allowed.
- var pn = remain[0]
- var negate = !!this.minimatch.negate
- var rawGlob = pn._glob
- var dotOk = this.dot || rawGlob.charAt(0) === '.'
+/***/ }),
- var matchedEntries = []
- for (var i = 0; i < entries.length; i++) {
- var e = entries[i]
- if (e.charAt(0) !== '.' || dotOk) {
- var m
- if (negate && !prefix) {
- m = !e.match(pn)
- } else {
- m = e.match(pn)
- }
- if (m)
- matchedEntries.push(e)
- }
- }
+/***/ 4408:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
+var Utils = __nccwpck_require__(5182),
+ Constants = Utils.Constants;
- var len = matchedEntries.length
- // If there are no matched entries, then nothing matches.
- if (len === 0)
- return cb()
+/* The entries in the end of central directory */
+module.exports = function () {
+ var _volumeEntries = 0,
+ _totalEntries = 0,
+ _size = 0,
+ _offset = 0,
+ _commentLength = 0;
- // if this is the last remaining pattern bit, then no need for
- // an additional stat *unless* the user has specified mark or
- // stat explicitly. We know they exist, since readdir returned
- // them.
+ return {
+ get diskEntries() {
+ return _volumeEntries;
+ },
+ set diskEntries(/*Number*/ val) {
+ _volumeEntries = _totalEntries = val;
+ },
- if (remain.length === 1 && !this.mark && !this.stat) {
- if (!this.matches[index])
- this.matches[index] = Object.create(null)
+ get totalEntries() {
+ return _totalEntries;
+ },
+ set totalEntries(/*Number*/ val) {
+ _totalEntries = _volumeEntries = val;
+ },
- for (var i = 0; i < len; i ++) {
- var e = matchedEntries[i]
- if (prefix) {
- if (prefix !== '/')
- e = prefix + '/' + e
- else
- e = prefix + e
- }
+ get size() {
+ return _size;
+ },
+ set size(/*Number*/ val) {
+ _size = val;
+ },
- if (e.charAt(0) === '/' && !this.nomount) {
- e = path.join(this.root, e)
- }
- this._emitMatch(index, e)
- }
- // This was the last one, and no stats were needed
- return cb()
- }
+ get offset() {
+ return _offset;
+ },
+ set offset(/*Number*/ val) {
+ _offset = val;
+ },
- // now test all matched entries as stand-ins for that part
- // of the pattern.
- remain.shift()
- for (var i = 0; i < len; i ++) {
- var e = matchedEntries[i]
- var newPattern
- if (prefix) {
- if (prefix !== '/')
- e = prefix + '/' + e
- else
- e = prefix + e
- }
- this._process([e].concat(remain), index, inGlobStar, cb)
- }
- cb()
-}
+ get commentLength() {
+ return _commentLength;
+ },
+ set commentLength(/*Number*/ val) {
+ _commentLength = val;
+ },
-Glob.prototype._emitMatch = function (index, e) {
- if (this.aborted)
- return
+ get mainHeaderSize() {
+ return Constants.ENDHDR + _commentLength;
+ },
- if (isIgnored(this, e))
- return
+ loadFromBinary: function (/*Buffer*/ data) {
+ // data should be 22 bytes and start with "PK 05 06"
+ // or be 56+ bytes and start with "PK 06 06" for Zip64
+ if (
+ (data.length !== Constants.ENDHDR || data.readUInt32LE(0) !== Constants.ENDSIG) &&
+ (data.length < Constants.ZIP64HDR || data.readUInt32LE(0) !== Constants.ZIP64SIG)
+ ) {
+ throw new Error(Utils.Errors.INVALID_END);
+ }
- if (this.paused) {
- this._emitQueue.push([index, e])
- return
- }
+ if (data.readUInt32LE(0) === Constants.ENDSIG) {
+ // number of entries on this volume
+ _volumeEntries = data.readUInt16LE(Constants.ENDSUB);
+ // total number of entries
+ _totalEntries = data.readUInt16LE(Constants.ENDTOT);
+ // central directory size in bytes
+ _size = data.readUInt32LE(Constants.ENDSIZ);
+ // offset of first CEN header
+ _offset = data.readUInt32LE(Constants.ENDOFF);
+ // zip file comment length
+ _commentLength = data.readUInt16LE(Constants.ENDCOM);
+ } else {
+ // number of entries on this volume
+ _volumeEntries = Utils.readBigUInt64LE(data, Constants.ZIP64SUB);
+ // total number of entries
+ _totalEntries = Utils.readBigUInt64LE(data, Constants.ZIP64TOT);
+ // central directory size in bytes
+ _size = Utils.readBigUInt64LE(data, Constants.ZIP64SIZE);
+ // offset of first CEN header
+ _offset = Utils.readBigUInt64LE(data, Constants.ZIP64OFF);
- var abs = isAbsolute(e) ? e : this._makeAbs(e)
+ _commentLength = 0;
+ }
+ },
- if (this.mark)
- e = this._mark(e)
+ toBinary: function () {
+ var b = Buffer.alloc(Constants.ENDHDR + _commentLength);
+ // "PK 05 06" signature
+ b.writeUInt32LE(Constants.ENDSIG, 0);
+ b.writeUInt32LE(0, 4);
+ // number of entries on this volume
+ b.writeUInt16LE(_volumeEntries, Constants.ENDSUB);
+ // total number of entries
+ b.writeUInt16LE(_totalEntries, Constants.ENDTOT);
+ // central directory size in bytes
+ b.writeUInt32LE(_size, Constants.ENDSIZ);
+ // offset of first CEN header
+ b.writeUInt32LE(_offset, Constants.ENDOFF);
+ // zip file comment length
+ b.writeUInt16LE(_commentLength, Constants.ENDCOM);
+ // fill comment memory with spaces so no garbage is left there
+ b.fill(" ", Constants.ENDHDR);
- if (this.absolute)
- e = abs
+ return b;
+ },
- if (this.matches[index][e])
- return
+ toJSON: function () {
+ // creates 0x0000 style output
+ const offset = function (nr, len) {
+ let offs = nr.toString(16).toUpperCase();
+ while (offs.length < len) offs = "0" + offs;
+ return "0x" + offs;
+ };
- if (this.nodir) {
- var c = this.cache[abs]
- if (c === 'DIR' || Array.isArray(c))
- return
- }
-
- this.matches[index][e] = true
-
- var st = this.statCache[abs]
- if (st)
- this.emit('stat', e, st)
-
- this.emit('match', e)
-}
-
-Glob.prototype._readdirInGlobStar = function (abs, cb) {
- if (this.aborted)
- return
-
- // follow all symlinked directories forever
- // just proceed as if this is a non-globstar situation
- if (this.follow)
- return this._readdir(abs, false, cb)
-
- var lstatkey = 'lstat\0' + abs
- var self = this
- var lstatcb = inflight(lstatkey, lstatcb_)
-
- if (lstatcb)
- self.fs.lstat(abs, lstatcb)
-
- function lstatcb_ (er, lstat) {
- if (er && er.code === 'ENOENT')
- return cb()
+ return {
+ diskEntries: _volumeEntries,
+ totalEntries: _totalEntries,
+ size: _size + " bytes",
+ offset: offset(_offset, 4),
+ commentLength: _commentLength
+ };
+ },
- var isSym = lstat && lstat.isSymbolicLink()
- self.symlinks[abs] = isSym
+ toString: function () {
+ return JSON.stringify(this.toJSON(), null, "\t");
+ }
+ };
+};
+ // Misspelled
- // If it's not a symlink or a dir, then it's definitely a regular file.
- // don't bother doing a readdir in that case.
- if (!isSym && lstat && !lstat.isDirectory()) {
- self.cache[abs] = 'FILE'
- cb()
- } else
- self._readdir(abs, false, cb)
- }
-}
+/***/ }),
-Glob.prototype._readdir = function (abs, inGlobStar, cb) {
- if (this.aborted)
- return
+/***/ 7686:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb)
- if (!cb)
- return
+module.exports = function (/*Buffer*/ inbuf) {
+ var zlib = __nccwpck_require__(9796);
- //console.error('RD %j %j', +inGlobStar, abs)
- if (inGlobStar && !ownProp(this.symlinks, abs))
- return this._readdirInGlobStar(abs, cb)
+ var opts = { chunkSize: (parseInt(inbuf.length / 1024) + 1) * 1024 };
- if (ownProp(this.cache, abs)) {
- var c = this.cache[abs]
- if (!c || c === 'FILE')
- return cb()
+ return {
+ deflate: function () {
+ return zlib.deflateRawSync(inbuf, opts);
+ },
- if (Array.isArray(c))
- return cb(null, c)
- }
+ deflateAsync: function (/*Function*/ callback) {
+ var tmp = zlib.createDeflateRaw(opts),
+ parts = [],
+ total = 0;
+ tmp.on("data", function (data) {
+ parts.push(data);
+ total += data.length;
+ });
+ tmp.on("end", function () {
+ var buf = Buffer.alloc(total),
+ written = 0;
+ buf.fill(0);
+ for (var i = 0; i < parts.length; i++) {
+ var part = parts[i];
+ part.copy(buf, written);
+ written += part.length;
+ }
+ callback && callback(buf);
+ });
+ tmp.end(inbuf);
+ }
+ };
+};
- var self = this
- self.fs.readdir(abs, readdirCb(this, abs, cb))
-}
-function readdirCb (self, abs, cb) {
- return function (er, entries) {
- if (er)
- self._readdirError(abs, er, cb)
- else
- self._readdirEntries(abs, entries, cb)
- }
-}
+/***/ }),
-Glob.prototype._readdirEntries = function (abs, entries, cb) {
- if (this.aborted)
- return
+/***/ 3928:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // if we haven't asked to stat everything, then just
- // assume that everything in there exists, so we can avoid
- // having to stat it a second time.
- if (!this.mark && !this.stat) {
- for (var i = 0; i < entries.length; i ++) {
- var e = entries[i]
- if (abs === '/')
- e = abs + e
- else
- e = abs + '/' + e
- this.cache[e] = true
- }
- }
+exports.Deflater = __nccwpck_require__(7686);
+exports.Inflater = __nccwpck_require__(2153);
+exports.ZipCrypto = __nccwpck_require__(3228);
- this.cache[abs] = entries
- return cb(null, entries)
-}
-Glob.prototype._readdirError = function (f, er, cb) {
- if (this.aborted)
- return
+/***/ }),
- // handle errors, and cache the information
- switch (er.code) {
- case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
- case 'ENOTDIR': // totally normal. means it *does* exist.
- var abs = this._makeAbs(f)
- this.cache[abs] = 'FILE'
- if (abs === this.cwdAbs) {
- var error = new Error(er.code + ' invalid cwd ' + this.cwd)
- error.path = this.cwd
- error.code = er.code
- this.emit('error', error)
- this.abort()
- }
- break
+/***/ 2153:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- case 'ENOENT': // not terribly unusual
- case 'ELOOP':
- case 'ENAMETOOLONG':
- case 'UNKNOWN':
- this.cache[this._makeAbs(f)] = false
- break
+module.exports = function (/*Buffer*/ inbuf) {
+ var zlib = __nccwpck_require__(9796);
- default: // some unusual error. Treat as failure.
- this.cache[this._makeAbs(f)] = false
- if (this.strict) {
- this.emit('error', er)
- // If the error is handled, then we abort
- // if not, we threw out of here
- this.abort()
- }
- if (!this.silent)
- console.error('glob error', er)
- break
- }
+ return {
+ inflate: function () {
+ return zlib.inflateRawSync(inbuf);
+ },
- return cb()
-}
+ inflateAsync: function (/*Function*/ callback) {
+ var tmp = zlib.createInflateRaw(),
+ parts = [],
+ total = 0;
+ tmp.on("data", function (data) {
+ parts.push(data);
+ total += data.length;
+ });
+ tmp.on("end", function () {
+ var buf = Buffer.alloc(total),
+ written = 0;
+ buf.fill(0);
+ for (var i = 0; i < parts.length; i++) {
+ var part = parts[i];
+ part.copy(buf, written);
+ written += part.length;
+ }
+ callback && callback(buf);
+ });
+ tmp.end(inbuf);
+ }
+ };
+};
-Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
- var self = this
- this._readdir(abs, inGlobStar, function (er, entries) {
- self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
- })
-}
+/***/ }),
-Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
- //console.error('pgs2', prefix, remain[0], entries)
+/***/ 3228:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // no entries means not a dir, so it can never have matches
- // foo.txt/** doesn't match foo.txt
- if (!entries)
- return cb()
+"use strict";
- // test without the globstar, and with every child both below
- // and replacing the globstar.
- var remainWithoutGlobStar = remain.slice(1)
- var gspref = prefix ? [ prefix ] : []
- var noGlobStar = gspref.concat(remainWithoutGlobStar)
- // the noGlobStar pattern exits the inGlobStar state
- this._process(noGlobStar, index, false, cb)
+// node crypt, we use it for generate salt
+// eslint-disable-next-line node/no-unsupported-features/node-builtins
+const { randomFillSync } = __nccwpck_require__(6113);
- var isSym = this.symlinks[abs]
- var len = entries.length
+// generate CRC32 lookup table
+const crctable = new Uint32Array(256).map((t, crc) => {
+ for (let j = 0; j < 8; j++) {
+ if (0 !== (crc & 1)) {
+ crc = (crc >>> 1) ^ 0xedb88320;
+ } else {
+ crc >>>= 1;
+ }
+ }
+ return crc >>> 0;
+});
- // If it's a symlink, and we're in a globstar, then stop
- if (isSym && inGlobStar)
- return cb()
+// C-style uInt32 Multiply (discards higher bits, when JS multiply discards lower bits)
+const uMul = (a, b) => Math.imul(a, b) >>> 0;
- for (var i = 0; i < len; i++) {
- var e = entries[i]
- if (e.charAt(0) === '.' && !this.dot)
- continue
+// crc32 byte single update (actually same function is part of utils.crc32 function :) )
+const crc32update = (pCrc32, bval) => {
+ return crctable[(pCrc32 ^ bval) & 0xff] ^ (pCrc32 >>> 8);
+};
- // these two cases enter the inGlobStar state
- var instead = gspref.concat(entries[i], remainWithoutGlobStar)
- this._process(instead, index, true, cb)
+// function for generating salt for encrytion header
+const genSalt = () => {
+ if ("function" === typeof randomFillSync) {
+ return randomFillSync(Buffer.alloc(12));
+ } else {
+ // fallback if function is not defined
+ return genSalt.node();
+ }
+};
- var below = gspref.concat(entries[i], remain)
- this._process(below, index, true, cb)
- }
+// salt generation with node random function (mainly as fallback)
+genSalt.node = () => {
+ const salt = Buffer.alloc(12);
+ const len = salt.length;
+ for (let i = 0; i < len; i++) salt[i] = (Math.random() * 256) & 0xff;
+ return salt;
+};
- cb()
-}
+// general config
+const config = {
+ genSalt
+};
-Glob.prototype._processSimple = function (prefix, index, cb) {
- // XXX review this. Shouldn't it be doing the mounting etc
- // before doing stat? kinda weird?
- var self = this
- this._stat(prefix, function (er, exists) {
- self._processSimple2(prefix, index, er, exists, cb)
- })
+// Class Initkeys handles same basic ops with keys
+function Initkeys(pw) {
+ const pass = Buffer.isBuffer(pw) ? pw : Buffer.from(pw);
+ this.keys = new Uint32Array([0x12345678, 0x23456789, 0x34567890]);
+ for (let i = 0; i < pass.length; i++) {
+ this.updateKeys(pass[i]);
+ }
}
-Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
-
- //console.error('ps2', prefix, exists)
-
- if (!this.matches[index])
- this.matches[index] = Object.create(null)
- // If it doesn't exist, then just mark the lack of results
- if (!exists)
- return cb()
+Initkeys.prototype.updateKeys = function (byteValue) {
+ const keys = this.keys;
+ keys[0] = crc32update(keys[0], byteValue);
+ keys[1] += keys[0] & 0xff;
+ keys[1] = uMul(keys[1], 134775813) + 1;
+ keys[2] = crc32update(keys[2], keys[1] >>> 24);
+ return byteValue;
+};
- if (prefix && isAbsolute(prefix) && !this.nomount) {
- var trail = /[\/\\]$/.test(prefix)
- if (prefix.charAt(0) === '/') {
- prefix = path.join(this.root, prefix)
- } else {
- prefix = path.resolve(this.root, prefix)
- if (trail)
- prefix += '/'
- }
- }
+Initkeys.prototype.next = function () {
+ const k = (this.keys[2] | 2) >>> 0; // key
+ return (uMul(k, k ^ 1) >> 8) & 0xff; // decode
+};
- if (process.platform === 'win32')
- prefix = prefix.replace(/\\/g, '/')
+function make_decrypter(/*Buffer*/ pwd) {
+ // 1. Stage initialize key
+ const keys = new Initkeys(pwd);
- // Mark this as a match
- this._emitMatch(index, prefix)
- cb()
+ // return decrypter function
+ return function (/*Buffer*/ data) {
+ // result - we create new Buffer for results
+ const result = Buffer.alloc(data.length);
+ let pos = 0;
+ // process input data
+ for (let c of data) {
+ //c ^= keys.next();
+ //result[pos++] = c; // decode & Save Value
+ result[pos++] = keys.updateKeys(c ^ keys.next()); // update keys with decoded byte
+ }
+ return result;
+ };
}
-// Returns either 'DIR', 'FILE', or false
-Glob.prototype._stat = function (f, cb) {
- var abs = this._makeAbs(f)
- var needDir = f.slice(-1) === '/'
-
- if (f.length > this.maxLength)
- return cb()
-
- if (!this.stat && ownProp(this.cache, abs)) {
- var c = this.cache[abs]
+function make_encrypter(/*Buffer*/ pwd) {
+ // 1. Stage initialize key
+ const keys = new Initkeys(pwd);
- if (Array.isArray(c))
- c = 'DIR'
+ // return encrypting function, result and pos is here so we dont have to merge buffers later
+ return function (/*Buffer*/ data, /*Buffer*/ result, /* Number */ pos = 0) {
+ // result - we create new Buffer for results
+ if (!result) result = Buffer.alloc(data.length);
+ // process input data
+ for (let c of data) {
+ const k = keys.next(); // save key byte
+ result[pos++] = c ^ k; // save val
+ keys.updateKeys(c); // update keys with decoded byte
+ }
+ return result;
+ };
+}
- // It exists, but maybe not how we need it
- if (!needDir || c === 'DIR')
- return cb(null, c)
+function decrypt(/*Buffer*/ data, /*Object*/ header, /*String, Buffer*/ pwd) {
+ if (!data || !Buffer.isBuffer(data) || data.length < 12) {
+ return Buffer.alloc(0);
+ }
- if (needDir && c === 'FILE')
- return cb()
+ // 1. We Initialize and generate decrypting function
+ const decrypter = make_decrypter(pwd);
- // otherwise we have to stat, because maybe c=true
- // if we know it exists, but not what it is.
- }
+ // 2. decrypt salt what is always 12 bytes and is a part of file content
+ const salt = decrypter(data.slice(0, 12));
- var exists
- var stat = this.statCache[abs]
- if (stat !== undefined) {
- if (stat === false)
- return cb(null, stat)
- else {
- var type = stat.isDirectory() ? 'DIR' : 'FILE'
- if (needDir && type === 'FILE')
- return cb()
- else
- return cb(null, type, stat)
+ // 3. does password meet expectations
+ if (salt[11] !== header.crc >>> 24) {
+ throw "ADM-ZIP: Wrong Password";
}
- }
- var self = this
- var statcb = inflight('stat\0' + abs, lstatcb_)
- if (statcb)
- self.fs.lstat(abs, statcb)
+ // 4. decode content
+ return decrypter(data.slice(12));
+}
- function lstatcb_ (er, lstat) {
- if (lstat && lstat.isSymbolicLink()) {
- // If it's a symlink, then treat it as the target, unless
- // the target does not exist, then treat it as a file.
- return self.fs.stat(abs, function (er, stat) {
- if (er)
- self._stat2(f, abs, null, lstat, cb)
- else
- self._stat2(f, abs, er, stat, cb)
- })
+// lets add way to populate salt, NOT RECOMMENDED for production but maybe useful for testing general functionality
+function _salter(data) {
+ if (Buffer.isBuffer(data) && data.length >= 12) {
+ // be aware - currently salting buffer data is modified
+ config.genSalt = function () {
+ return data.slice(0, 12);
+ };
+ } else if (data === "node") {
+ // test salt generation with node random function
+ config.genSalt = genSalt.node;
} else {
- self._stat2(f, abs, er, lstat, cb)
+ // if value is not acceptable config gets reset.
+ config.genSalt = genSalt;
}
- }
}
-Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
- if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
- this.statCache[abs] = false
- return cb()
- }
+function encrypt(/*Buffer*/ data, /*Object*/ header, /*String, Buffer*/ pwd, /*Boolean*/ oldlike = false) {
+ // 1. test data if data is not Buffer we make buffer from it
+ if (data == null) data = Buffer.alloc(0);
+ // if data is not buffer be make buffer from it
+ if (!Buffer.isBuffer(data)) data = Buffer.from(data.toString());
- var needDir = f.slice(-1) === '/'
- this.statCache[abs] = stat
+ // 2. We Initialize and generate encrypting function
+ const encrypter = make_encrypter(pwd);
- if (abs.slice(-1) === '/' && stat && !stat.isDirectory())
- return cb(null, false, stat)
+ // 3. generate salt (12-bytes of random data)
+ const salt = config.genSalt();
+ salt[11] = (header.crc >>> 24) & 0xff;
- var c = true
- if (stat)
- c = stat.isDirectory() ? 'DIR' : 'FILE'
- this.cache[abs] = this.cache[abs] || c
+ // old implementations (before PKZip 2.04g) used two byte check
+ if (oldlike) salt[10] = (header.crc >>> 16) & 0xff;
- if (needDir && c === 'FILE')
- return cb()
+ // 4. create output
+ const result = Buffer.alloc(data.length + 12);
+ encrypter(salt, result);
- return cb(null, c, stat)
+ // finally encode content
+ return encrypter(data, result, 12);
}
+module.exports = { decrypt, encrypt, _salter };
-/***/ }),
-/***/ 2479:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ }),
-module.exports = globSync
-globSync.GlobSync = GlobSync
+/***/ 4522:
+/***/ ((module) => {
-var rp = __nccwpck_require__(6863)
-var minimatch = __nccwpck_require__(7787)
-var Minimatch = minimatch.Minimatch
-var Glob = (__nccwpck_require__(2782).Glob)
-var util = __nccwpck_require__(3837)
-var path = __nccwpck_require__(1017)
-var assert = __nccwpck_require__(9491)
-var isAbsolute = (__nccwpck_require__(1017).isAbsolute)
-var common = __nccwpck_require__(150)
-var setopts = common.setopts
-var ownProp = common.ownProp
-var childrenIgnored = common.childrenIgnored
-var isIgnored = common.isIgnored
+module.exports = {
+ /* The local file header */
+ LOCHDR : 30, // LOC header size
+ LOCSIG : 0x04034b50, // "PK\003\004"
+ LOCVER : 4, // version needed to extract
+ LOCFLG : 6, // general purpose bit flag
+ LOCHOW : 8, // compression method
+ LOCTIM : 10, // modification time (2 bytes time, 2 bytes date)
+ LOCCRC : 14, // uncompressed file crc-32 value
+ LOCSIZ : 18, // compressed size
+ LOCLEN : 22, // uncompressed size
+ LOCNAM : 26, // filename length
+ LOCEXT : 28, // extra field length
-function globSync (pattern, options) {
- if (typeof options === 'function' || arguments.length === 3)
- throw new TypeError('callback provided to sync glob\n'+
- 'See: https://github.com/isaacs/node-glob/issues/167')
+ /* The Data descriptor */
+ EXTSIG : 0x08074b50, // "PK\007\008"
+ EXTHDR : 16, // EXT header size
+ EXTCRC : 4, // uncompressed file crc-32 value
+ EXTSIZ : 8, // compressed size
+ EXTLEN : 12, // uncompressed size
- return new GlobSync(pattern, options).found
-}
+ /* The central directory file header */
+ CENHDR : 46, // CEN header size
+ CENSIG : 0x02014b50, // "PK\001\002"
+ CENVEM : 4, // version made by
+ CENVER : 6, // version needed to extract
+ CENFLG : 8, // encrypt, decrypt flags
+ CENHOW : 10, // compression method
+ CENTIM : 12, // modification time (2 bytes time, 2 bytes date)
+ CENCRC : 16, // uncompressed file crc-32 value
+ CENSIZ : 20, // compressed size
+ CENLEN : 24, // uncompressed size
+ CENNAM : 28, // filename length
+ CENEXT : 30, // extra field length
+ CENCOM : 32, // file comment length
+ CENDSK : 34, // volume number start
+ CENATT : 36, // internal file attributes
+ CENATX : 38, // external file attributes (host system dependent)
+ CENOFF : 42, // LOC header offset
-function GlobSync (pattern, options) {
- if (!pattern)
- throw new Error('must provide pattern')
+ /* The entries in the end of central directory */
+ ENDHDR : 22, // END header size
+ ENDSIG : 0x06054b50, // "PK\005\006"
+ ENDSUB : 8, // number of entries on this disk
+ ENDTOT : 10, // total number of entries
+ ENDSIZ : 12, // central directory size in bytes
+ ENDOFF : 16, // offset of first CEN header
+ ENDCOM : 20, // zip file comment length
- if (typeof options === 'function' || arguments.length === 3)
- throw new TypeError('callback provided to sync glob\n'+
- 'See: https://github.com/isaacs/node-glob/issues/167')
+ END64HDR : 20, // zip64 END header size
+ END64SIG : 0x07064b50, // zip64 Locator signature, "PK\006\007"
+ END64START : 4, // number of the disk with the start of the zip64
+ END64OFF : 8, // relative offset of the zip64 end of central directory
+ END64NUMDISKS : 16, // total number of disks
- if (!(this instanceof GlobSync))
- return new GlobSync(pattern, options)
+ ZIP64SIG : 0x06064b50, // zip64 signature, "PK\006\006"
+ ZIP64HDR : 56, // zip64 record minimum size
+ ZIP64LEAD : 12, // leading bytes at the start of the record, not counted by the value stored in ZIP64SIZE
+ ZIP64SIZE : 4, // zip64 size of the central directory record
+ ZIP64VEM : 12, // zip64 version made by
+ ZIP64VER : 14, // zip64 version needed to extract
+ ZIP64DSK : 16, // zip64 number of this disk
+ ZIP64DSKDIR : 20, // number of the disk with the start of the record directory
+ ZIP64SUB : 24, // number of entries on this disk
+ ZIP64TOT : 32, // total number of entries
+ ZIP64SIZB : 40, // zip64 central directory size in bytes
+ ZIP64OFF : 48, // offset of start of central directory with respect to the starting disk number
+ ZIP64EXTRA : 56, // extensible data sector
- setopts(this, pattern, options)
+ /* Compression methods */
+ STORED : 0, // no compression
+ SHRUNK : 1, // shrunk
+ REDUCED1 : 2, // reduced with compression factor 1
+ REDUCED2 : 3, // reduced with compression factor 2
+ REDUCED3 : 4, // reduced with compression factor 3
+ REDUCED4 : 5, // reduced with compression factor 4
+ IMPLODED : 6, // imploded
+ // 7 reserved for Tokenizing compression algorithm
+ DEFLATED : 8, // deflated
+ ENHANCED_DEFLATED: 9, // enhanced deflated
+ PKWARE : 10,// PKWare DCL imploded
+ // 11 reserved by PKWARE
+ BZIP2 : 12, // compressed using BZIP2
+ // 13 reserved by PKWARE
+ LZMA : 14, // LZMA
+ // 15-17 reserved by PKWARE
+ IBM_TERSE : 18, // compressed using IBM TERSE
+ IBM_LZ77 : 19, // IBM LZ77 z
+ AES_ENCRYPT : 99, // WinZIP AES encryption method
- if (this.noprocess)
- return this
+ /* General purpose bit flag */
+ // values can obtained with expression 2**bitnr
+ FLG_ENC : 1, // Bit 0: encrypted file
+ FLG_COMP1 : 2, // Bit 1, compression option
+ FLG_COMP2 : 4, // Bit 2, compression option
+ FLG_DESC : 8, // Bit 3, data descriptor
+ FLG_ENH : 16, // Bit 4, enhanced deflating
+ FLG_PATCH : 32, // Bit 5, indicates that the file is compressed patched data.
+ FLG_STR : 64, // Bit 6, strong encryption (patented)
+ // Bits 7-10: Currently unused.
+ FLG_EFS : 2048, // Bit 11: Language encoding flag (EFS)
+ // Bit 12: Reserved by PKWARE for enhanced compression.
+ // Bit 13: encrypted the Central Directory (patented).
+ // Bits 14-15: Reserved by PKWARE.
+ FLG_MSK : 4096, // mask header values
- var n = this.minimatch.set.length
- this.matches = new Array(n)
- for (var i = 0; i < n; i ++) {
- this._process(this.minimatch.set[i], i, false)
- }
- this._finish()
-}
+ /* Load type */
+ FILE : 2,
+ BUFFER : 1,
+ NONE : 0,
-GlobSync.prototype._finish = function () {
- assert.ok(this instanceof GlobSync)
- if (this.realpath) {
- var self = this
- this.matches.forEach(function (matchset, index) {
- var set = self.matches[index] = Object.create(null)
- for (var p in matchset) {
- try {
- p = self._makeAbs(p)
- var real = rp.realpathSync(p, self.realpathCache)
- set[real] = true
- } catch (er) {
- if (er.syscall === 'stat')
- set[self._makeAbs(p)] = true
- else
- throw er
- }
- }
- })
- }
- common.finish(this)
-}
+ /* 4.5 Extensible data fields */
+ EF_ID : 0,
+ EF_SIZE : 2,
+ /* Header IDs */
+ ID_ZIP64 : 0x0001,
+ ID_AVINFO : 0x0007,
+ ID_PFS : 0x0008,
+ ID_OS2 : 0x0009,
+ ID_NTFS : 0x000a,
+ ID_OPENVMS : 0x000c,
+ ID_UNIX : 0x000d,
+ ID_FORK : 0x000e,
+ ID_PATCH : 0x000f,
+ ID_X509_PKCS7 : 0x0014,
+ ID_X509_CERTID_F : 0x0015,
+ ID_X509_CERTID_C : 0x0016,
+ ID_STRONGENC : 0x0017,
+ ID_RECORD_MGT : 0x0018,
+ ID_X509_PKCS7_RL : 0x0019,
+ ID_IBM1 : 0x0065,
+ ID_IBM2 : 0x0066,
+ ID_POSZIP : 0x4690,
-GlobSync.prototype._process = function (pattern, index, inGlobStar) {
- assert.ok(this instanceof GlobSync)
+ EF_ZIP64_OR_32 : 0xffffffff,
+ EF_ZIP64_OR_16 : 0xffff,
+ EF_ZIP64_SUNCOMP : 0,
+ EF_ZIP64_SCOMP : 8,
+ EF_ZIP64_RHO : 16,
+ EF_ZIP64_DSN : 24
+};
- // Get the first [n] parts of pattern that are all strings.
- var n = 0
- while (typeof pattern[n] === 'string') {
- n ++
- }
- // now n is the index of the first one that is *not* a string.
- // See if there's anything else
- var prefix
- switch (n) {
- // if not, then this is rather simple
- case pattern.length:
- this._processSimple(pattern.join('/'), index)
- return
+/***/ }),
- case 0:
- // pattern *starts* with some non-trivial item.
- // going to readdir(cwd), but not include the prefix in matches.
- prefix = null
- break
+/***/ 1255:
+/***/ ((module) => {
- default:
- // pattern has some string bits in the front.
- // whatever it starts with, whether that's 'absolute' like /foo/bar,
- // or 'relative' like '../baz'
- prefix = pattern.slice(0, n).join('/')
- break
- }
+module.exports = {
+ /* Header error messages */
+ INVALID_LOC: "Invalid LOC header (bad signature)",
+ INVALID_CEN: "Invalid CEN header (bad signature)",
+ INVALID_END: "Invalid END header (bad signature)",
- var remain = pattern.slice(n)
+ /* 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",
+ UNKNOWN_METHOD: "Invalid/unsupported compression method",
- // get the list of entries.
- var read
- if (prefix === null)
- read = '.'
- else if (isAbsolute(prefix) ||
- isAbsolute(pattern.map(function (p) {
- return typeof p === 'string' ? p : '[*]'
- }).join('/'))) {
- if (!prefix || !isAbsolute(prefix))
- prefix = '/' + prefix
- read = prefix
- } else
- read = prefix
+ /* Inflater error messages */
+ AVAIL_DATA: "inflate::Available inflate data did not terminate",
+ INVALID_DISTANCE: "inflate::Invalid literal/length or distance code in fixed or dynamic block",
+ TO_MANY_CODES: "inflate::Dynamic block code description: too many length or distance codes",
+ INVALID_REPEAT_LEN: "inflate::Dynamic block code description: repeat more than specified lengths",
+ INVALID_REPEAT_FIRST: "inflate::Dynamic block code description: repeat lengths with no first length",
+ INCOMPLETE_CODES: "inflate::Dynamic block code description: code lengths codes incomplete",
+ INVALID_DYN_DISTANCE: "inflate::Dynamic block code description: invalid distance code lengths",
+ INVALID_CODES_LEN: "inflate::Dynamic block code description: invalid literal/length code lengths",
+ INVALID_STORE_BLOCK: "inflate::Stored block length did not match one's complement",
+ INVALID_BLOCK_TYPE: "inflate::Invalid block type (type == 3)",
- var abs = this._makeAbs(read)
+ /* ADM-ZIP error messages */
+ CANT_EXTRACT_FILE: "Could not extract the file",
+ CANT_OVERRIDE: "Target file already exists",
+ NO_ZIP: "No zip file was loaded",
+ NO_ENTRY: "Entry doesn't exist",
+ DIRECTORY_CONTENT_ERROR: "A directory cannot have content",
+ FILE_NOT_FOUND: "File not found: %s",
+ NOT_IMPLEMENTED: "Not implemented",
+ INVALID_FILENAME: "Invalid filename",
+ INVALID_FORMAT: "Invalid or unsupported zip format. No END header found"
+};
- //if ignored, skip processing
- if (childrenIgnored(this, read))
- return
- var isGlobStar = remain[0] === minimatch.GLOBSTAR
- if (isGlobStar)
- this._processGlobStar(prefix, read, abs, remain, index, inGlobStar)
- else
- this._processReaddir(prefix, read, abs, remain, index, inGlobStar)
-}
+/***/ }),
+/***/ 8321:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
- var entries = this._readdir(abs, inGlobStar)
+const fs = (__nccwpck_require__(2895).require)();
+const pth = __nccwpck_require__(1017);
- // if the abs isn't a dir, then nothing can match!
- if (!entries)
- return
+fs.existsSync = fs.existsSync || pth.existsSync;
- // It will only match dot entries if it starts with a dot, or if
- // dot is set. Stuff like @(.foo|.bar) isn't allowed.
- var pn = remain[0]
- var negate = !!this.minimatch.negate
- var rawGlob = pn._glob
- var dotOk = this.dot || rawGlob.charAt(0) === '.'
+module.exports = function (/*String*/ path) {
+ var _path = path || "",
+ _obj = newAttr(),
+ _stat = null;
- var matchedEntries = []
- for (var i = 0; i < entries.length; i++) {
- var e = entries[i]
- if (e.charAt(0) !== '.' || dotOk) {
- var m
- if (negate && !prefix) {
- m = !e.match(pn)
- } else {
- m = e.match(pn)
- }
- if (m)
- matchedEntries.push(e)
+ function newAttr() {
+ return {
+ directory: false,
+ readonly: false,
+ hidden: false,
+ executable: false,
+ mtime: 0,
+ atime: 0
+ };
}
- }
- var len = matchedEntries.length
- // If there are no matched entries, then nothing matches.
- if (len === 0)
- return
+ if (_path && fs.existsSync(_path)) {
+ _stat = fs.statSync(_path);
+ _obj.directory = _stat.isDirectory();
+ _obj.mtime = _stat.mtime;
+ _obj.atime = _stat.atime;
+ _obj.executable = (0o111 & _stat.mode) !== 0; // file is executable who ever har right not just owner
+ _obj.readonly = (0o200 & _stat.mode) === 0; // readonly if owner has no write right
+ _obj.hidden = pth.basename(_path)[0] === ".";
+ } else {
+ console.warn("Invalid path: " + _path);
+ }
- // if this is the last remaining pattern bit, then no need for
- // an additional stat *unless* the user has specified mark or
- // stat explicitly. We know they exist, since readdir returned
- // them.
+ return {
+ get directory() {
+ return _obj.directory;
+ },
- if (remain.length === 1 && !this.mark && !this.stat) {
- if (!this.matches[index])
- this.matches[index] = Object.create(null)
+ get readOnly() {
+ return _obj.readonly;
+ },
- for (var i = 0; i < len; i ++) {
- var e = matchedEntries[i]
- if (prefix) {
- if (prefix.slice(-1) !== '/')
- e = prefix + '/' + e
- else
- e = prefix + e
- }
+ get hidden() {
+ return _obj.hidden;
+ },
- if (e.charAt(0) === '/' && !this.nomount) {
- e = path.join(this.root, e)
- }
- this._emitMatch(index, e)
- }
- // This was the last one, and no stats were needed
- return
- }
+ get mtime() {
+ return _obj.mtime;
+ },
- // now test all matched entries as stand-ins for that part
- // of the pattern.
- remain.shift()
- for (var i = 0; i < len; i ++) {
- var e = matchedEntries[i]
- var newPattern
- if (prefix)
- newPattern = [prefix, e]
- else
- newPattern = [e]
- this._process(newPattern.concat(remain), index, inGlobStar)
- }
-}
+ get atime() {
+ return _obj.atime;
+ },
+ get executable() {
+ return _obj.executable;
+ },
-GlobSync.prototype._emitMatch = function (index, e) {
- if (isIgnored(this, e))
- return
+ decodeAttributes: function () {},
- var abs = this._makeAbs(e)
+ encodeAttributes: function () {},
- if (this.mark)
- e = this._mark(e)
+ toJSON: function () {
+ return {
+ path: _path,
+ isDirectory: _obj.directory,
+ isReadOnly: _obj.readonly,
+ isHidden: _obj.hidden,
+ isExecutable: _obj.executable,
+ mTime: _obj.mtime,
+ aTime: _obj.atime
+ };
+ },
- if (this.absolute) {
- e = abs
- }
+ toString: function () {
+ return JSON.stringify(this.toJSON(), null, "\t");
+ }
+ };
+};
- if (this.matches[index][e])
- return
- if (this.nodir) {
- var c = this.cache[abs]
- if (c === 'DIR' || Array.isArray(c))
- return
- }
+/***/ }),
- this.matches[index][e] = true
+/***/ 2895:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- if (this.stat)
- this._stat(e)
-}
+exports.require = function () {
+ if (typeof process === "object" && process.versions && process.versions["electron"]) {
+ try {
+ const originalFs = __nccwpck_require__(2941);
+ if (Object.keys(originalFs).length > 0) {
+ return originalFs;
+ }
+ } catch (e) {}
+ }
+ return __nccwpck_require__(7147);
+};
-GlobSync.prototype._readdirInGlobStar = function (abs) {
- // follow all symlinked directories forever
- // just proceed as if this is a non-globstar situation
- if (this.follow)
- return this._readdir(abs, false)
+/***/ }),
- var entries
- var lstat
- var stat
- try {
- lstat = this.fs.lstatSync(abs)
- } catch (er) {
- if (er.code === 'ENOENT') {
- // lstat failed, doesn't exist
- return null
- }
- }
+/***/ 5182:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- var isSym = lstat && lstat.isSymbolicLink()
- this.symlinks[abs] = isSym
+module.exports = __nccwpck_require__(1291);
+module.exports.Constants = __nccwpck_require__(4522);
+module.exports.Errors = __nccwpck_require__(1255);
+module.exports.FileAttr = __nccwpck_require__(8321);
- // If it's not a symlink or a dir, then it's definitely a regular file.
- // don't bother doing a readdir in that case.
- if (!isSym && lstat && !lstat.isDirectory())
- this.cache[abs] = 'FILE'
- else
- entries = this._readdir(abs, false)
- return entries
-}
+/***/ }),
-GlobSync.prototype._readdir = function (abs, inGlobStar) {
- var entries
+/***/ 1291:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- if (inGlobStar && !ownProp(this.symlinks, abs))
- return this._readdirInGlobStar(abs)
+const fsystem = (__nccwpck_require__(2895).require)();
+const pth = __nccwpck_require__(1017);
+const Constants = __nccwpck_require__(4522);
+const Errors = __nccwpck_require__(1255);
+const isWin = typeof process === "object" && "win32" === process.platform;
- if (ownProp(this.cache, abs)) {
- var c = this.cache[abs]
- if (!c || c === 'FILE')
- return null
+const is_Obj = (obj) => obj && typeof obj === "object";
- if (Array.isArray(c))
- return c
- }
+// generate CRC32 lookup table
+const crcTable = new Uint32Array(256).map((t, c) => {
+ for (let k = 0; k < 8; k++) {
+ if ((c & 1) !== 0) {
+ c = 0xedb88320 ^ (c >>> 1);
+ } else {
+ c >>>= 1;
+ }
+ }
+ return c >>> 0;
+});
- try {
- return this._readdirEntries(abs, this.fs.readdirSync(abs))
- } catch (er) {
- this._readdirError(abs, er)
- return null
- }
-}
+// UTILS functions
-GlobSync.prototype._readdirEntries = function (abs, entries) {
- // if we haven't asked to stat everything, then just
- // assume that everything in there exists, so we can avoid
- // having to stat it a second time.
- if (!this.mark && !this.stat) {
- for (var i = 0; i < entries.length; i ++) {
- var e = entries[i]
- if (abs === '/')
- e = abs + e
- else
- e = abs + '/' + e
- this.cache[e] = true
+function Utils(opts) {
+ this.sep = pth.sep;
+ this.fs = fsystem;
+
+ if (is_Obj(opts)) {
+ // custom filesystem
+ if (is_Obj(opts.fs) && typeof opts.fs.statSync === "function") {
+ this.fs = opts.fs;
+ }
}
- }
+}
- this.cache[abs] = entries
+module.exports = Utils;
- // mark and cache dir-ness
- return entries
-}
+// INSTANCED functions
-GlobSync.prototype._readdirError = function (f, er) {
- // handle errors, and cache the information
- switch (er.code) {
- case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
- case 'ENOTDIR': // totally normal. means it *does* exist.
- var abs = this._makeAbs(f)
- this.cache[abs] = 'FILE'
- if (abs === this.cwdAbs) {
- var error = new Error(er.code + ' invalid cwd ' + this.cwd)
- error.path = this.cwd
- error.code = er.code
- throw error
- }
- break
-
- case 'ENOENT': // not terribly unusual
- case 'ELOOP':
- case 'ENAMETOOLONG':
- case 'UNKNOWN':
- this.cache[this._makeAbs(f)] = false
- break
+Utils.prototype.makeDir = function (/*String*/ folder) {
+ const self = this;
- default: // some unusual error. Treat as failure.
- this.cache[this._makeAbs(f)] = false
- if (this.strict)
- throw er
- if (!this.silent)
- console.error('glob error', er)
- break
- }
-}
+ // Sync - make directories tree
+ function mkdirSync(/*String*/ fpath) {
+ let resolvedPath = fpath.split(self.sep)[0];
+ fpath.split(self.sep).forEach(function (name) {
+ if (!name || name.substr(-1, 1) === ":") return;
+ resolvedPath += self.sep + name;
+ var stat;
+ try {
+ stat = self.fs.statSync(resolvedPath);
+ } catch (e) {
+ self.fs.mkdirSync(resolvedPath);
+ }
+ if (stat && stat.isFile()) throw Errors.FILE_IN_THE_WAY.replace("%s", resolvedPath);
+ });
+ }
-GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
+ mkdirSync(folder);
+};
- var entries = this._readdir(abs, inGlobStar)
+Utils.prototype.writeFileTo = function (/*String*/ path, /*Buffer*/ content, /*Boolean*/ overwrite, /*Number*/ attr) {
+ const self = this;
+ if (self.fs.existsSync(path)) {
+ if (!overwrite) return false; // cannot overwrite
- // no entries means not a dir, so it can never have matches
- // foo.txt/** doesn't match foo.txt
- if (!entries)
- return
+ var stat = self.fs.statSync(path);
+ if (stat.isDirectory()) {
+ return false;
+ }
+ }
+ var folder = pth.dirname(path);
+ if (!self.fs.existsSync(folder)) {
+ self.makeDir(folder);
+ }
- // test without the globstar, and with every child both below
- // and replacing the globstar.
- var remainWithoutGlobStar = remain.slice(1)
- var gspref = prefix ? [ prefix ] : []
- var noGlobStar = gspref.concat(remainWithoutGlobStar)
+ var fd;
+ try {
+ fd = self.fs.openSync(path, "w", 438); // 0666
+ } catch (e) {
+ self.fs.chmodSync(path, 438);
+ fd = self.fs.openSync(path, "w", 438);
+ }
+ if (fd) {
+ try {
+ self.fs.writeSync(fd, content, 0, content.length, 0);
+ } finally {
+ self.fs.closeSync(fd);
+ }
+ }
+ self.fs.chmodSync(path, attr || 438);
+ return true;
+};
- // the noGlobStar pattern exits the inGlobStar state
- this._process(noGlobStar, index, false)
+Utils.prototype.writeFileToAsync = function (/*String*/ path, /*Buffer*/ content, /*Boolean*/ overwrite, /*Number*/ attr, /*Function*/ callback) {
+ if (typeof attr === "function") {
+ callback = attr;
+ attr = undefined;
+ }
- var len = entries.length
- var isSym = this.symlinks[abs]
+ const self = this;
- // If it's a symlink, and we're in a globstar, then stop
- if (isSym && inGlobStar)
- return
+ self.fs.exists(path, function (exist) {
+ if (exist && !overwrite) return callback(false);
- for (var i = 0; i < len; i++) {
- var e = entries[i]
- if (e.charAt(0) === '.' && !this.dot)
- continue
+ self.fs.stat(path, function (err, stat) {
+ if (exist && stat.isDirectory()) {
+ return callback(false);
+ }
- // these two cases enter the inGlobStar state
- var instead = gspref.concat(entries[i], remainWithoutGlobStar)
- this._process(instead, index, true)
+ var folder = pth.dirname(path);
+ self.fs.exists(folder, function (exists) {
+ if (!exists) self.makeDir(folder);
- var below = gspref.concat(entries[i], remain)
- this._process(below, index, true)
- }
-}
+ self.fs.open(path, "w", 438, function (err, fd) {
+ if (err) {
+ self.fs.chmod(path, 438, function () {
+ self.fs.open(path, "w", 438, 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 () {
+ callback(true);
+ });
+ });
+ });
+ });
+ });
+ } else if (fd) {
+ self.fs.write(fd, content, 0, content.length, 0, function () {
+ self.fs.close(fd, function () {
+ self.fs.chmod(path, attr || 438, function () {
+ callback(true);
+ });
+ });
+ });
+ } else {
+ self.fs.chmod(path, attr || 438, function () {
+ callback(true);
+ });
+ }
+ });
+ });
+ });
+ });
+};
-GlobSync.prototype._processSimple = function (prefix, index) {
- // XXX review this. Shouldn't it be doing the mounting etc
- // before doing stat? kinda weird?
- var exists = this._stat(prefix)
+Utils.prototype.findFiles = function (/*String*/ path) {
+ const self = this;
- if (!this.matches[index])
- this.matches[index] = Object.create(null)
+ function findSync(/*String*/ dir, /*RegExp*/ pattern, /*Boolean*/ recursive) {
+ if (typeof pattern === "boolean") {
+ recursive = pattern;
+ pattern = undefined;
+ }
+ let files = [];
+ self.fs.readdirSync(dir).forEach(function (file) {
+ var path = pth.join(dir, file);
- // If it doesn't exist, then just mark the lack of results
- if (!exists)
- return
+ if (self.fs.statSync(path).isDirectory() && recursive) files = files.concat(findSync(path, pattern, recursive));
- if (prefix && isAbsolute(prefix) && !this.nomount) {
- var trail = /[\/\\]$/.test(prefix)
- if (prefix.charAt(0) === '/') {
- prefix = path.join(this.root, prefix)
- } else {
- prefix = path.resolve(this.root, prefix)
- if (trail)
- prefix += '/'
+ if (!pattern || pattern.test(path)) {
+ files.push(pth.normalize(path) + (self.fs.statSync(path).isDirectory() ? self.sep : ""));
+ }
+ });
+ return files;
}
- }
- if (process.platform === 'win32')
- prefix = prefix.replace(/\\/g, '/')
+ return findSync(path, undefined, true);
+};
- // Mark this as a match
- this._emitMatch(index, prefix)
-}
+Utils.prototype.getAttributes = function () {};
-// Returns either 'DIR', 'FILE', or false
-GlobSync.prototype._stat = function (f) {
- var abs = this._makeAbs(f)
- var needDir = f.slice(-1) === '/'
+Utils.prototype.setAttributes = function () {};
- if (f.length > this.maxLength)
- return false
+// STATIC functions
- if (!this.stat && ownProp(this.cache, abs)) {
- var c = this.cache[abs]
+// crc32 single update (it is part of crc32)
+Utils.crc32update = function (crc, byte) {
+ return crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8);
+};
- if (Array.isArray(c))
- c = 'DIR'
+Utils.crc32 = function (buf) {
+ if (typeof buf === "string") {
+ buf = Buffer.from(buf, "utf8");
+ }
+ // Generate crcTable
+ if (!crcTable.length) genCRCTable();
- // It exists, but maybe not how we need it
- if (!needDir || c === 'DIR')
- return c
+ let len = buf.length;
+ let crc = ~0;
+ for (let off = 0; off < len; ) crc = Utils.crc32update(crc, buf[off++]);
+ // xor and cast as uint32 number
+ return ~crc >>> 0;
+};
- if (needDir && c === 'FILE')
- return false
+Utils.methodToString = function (/*Number*/ method) {
+ switch (method) {
+ case Constants.STORED:
+ return "STORED (" + method + ")";
+ case Constants.DEFLATED:
+ return "DEFLATED (" + method + ")";
+ default:
+ return "UNSUPPORTED (" + method + ")";
+ }
+};
- // otherwise we have to stat, because maybe c=true
- // if we know it exists, but not what it is.
- }
+// removes ".." style path elements
+Utils.canonical = function (/*string*/ path) {
+ if (!path) return "";
+ // trick normalize think path is absolute
+ var safeSuffix = pth.posix.normalize("/" + path.split("\\").join("/"));
+ return pth.join(".", safeSuffix);
+};
- var exists
- var stat = this.statCache[abs]
- if (!stat) {
- var lstat
- try {
- lstat = this.fs.lstatSync(abs)
- } catch (er) {
- if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
- this.statCache[abs] = false
- return false
- }
+// make abolute paths taking prefix as root folder
+Utils.sanitize = function (/*string*/ prefix, /*string*/ name) {
+ prefix = pth.resolve(pth.normalize(prefix));
+ var parts = name.split("/");
+ for (var i = 0, l = parts.length; i < l; i++) {
+ var path = pth.normalize(pth.join(prefix, parts.slice(i, l).join(pth.sep)));
+ if (path.indexOf(prefix) === 0) {
+ return path;
+ }
}
+ return pth.normalize(pth.join(prefix, pth.basename(name)));
+};
- if (lstat && lstat.isSymbolicLink()) {
- try {
- stat = this.fs.statSync(abs)
- } catch (er) {
- stat = lstat
- }
+// converts buffer, Uint8Array, string types to buffer
+Utils.toBuffer = function toBuffer(/*buffer, Uint8Array, string*/ input) {
+ if (Buffer.isBuffer(input)) {
+ return input;
+ } else if (input instanceof Uint8Array) {
+ return Buffer.from(input);
} else {
- stat = lstat
+ // expect string all other values are invalid and return empty buffer
+ return typeof input === "string" ? Buffer.from(input, "utf8") : Buffer.alloc(0);
}
- }
-
- this.statCache[abs] = stat
-
- var c = true
- if (stat)
- c = stat.isDirectory() ? 'DIR' : 'FILE'
-
- this.cache[abs] = this.cache[abs] || c
-
- if (needDir && c === 'FILE')
- return false
-
- return c
-}
-
-GlobSync.prototype._mark = function (p) {
- return common.mark(this, p)
-}
-
-GlobSync.prototype._makeAbs = function (f) {
- return common.makeAbs(this, f)
-}
-
+};
-/***/ }),
+Utils.readBigUInt64LE = function (/*Buffer*/ buffer, /*int*/ index) {
+ var slice = Buffer.from(buffer.slice(index, index + 8));
+ slice.swap64();
-/***/ 6798:
-/***/ ((module) => {
+ return parseInt(`0x${slice.toString("hex")}`);
+};
-const isWindows = typeof process === 'object' &&
- process &&
- process.platform === 'win32'
-module.exports = isWindows ? { sep: '\\' } : { sep: '/' }
+Utils.isWin = isWin; // Do we have windows system
+Utils.crcTable = crcTable;
/***/ }),
-/***/ 7787:
+/***/ 4057:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const minimatch = module.exports = (p, pattern, options = {}) => {
- assertValidPattern(pattern)
-
- // shortcut: comments match nothing.
- if (!options.nocomment && pattern.charAt(0) === '#') {
- return false
- }
-
- return new Minimatch(pattern, options).match(p)
-}
+var Utils = __nccwpck_require__(5182),
+ Headers = __nccwpck_require__(4958),
+ Constants = Utils.Constants,
+ Methods = __nccwpck_require__(3928);
-module.exports = minimatch
+module.exports = function (/*Buffer*/ input) {
+ var _entryHeader = new Headers.EntryHeader(),
+ _entryName = Buffer.alloc(0),
+ _comment = Buffer.alloc(0),
+ _isDirectory = false,
+ uncompressedData = null,
+ _extra = Buffer.alloc(0);
-const path = __nccwpck_require__(6798)
-minimatch.sep = path.sep
+ function getCompressedDataFromZip() {
+ if (!input || !Buffer.isBuffer(input)) {
+ return Buffer.alloc(0);
+ }
+ _entryHeader.loadDataHeaderFromBinary(input);
+ return input.slice(_entryHeader.realDataOffset, _entryHeader.realDataOffset + _entryHeader.compressedSize);
+ }
-const GLOBSTAR = Symbol('globstar **')
-minimatch.GLOBSTAR = GLOBSTAR
-const expand = __nccwpck_require__(6589)
+ 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 ((_entryHeader.flags & 0x8) !== 0x8) {
+ if (Utils.crc32(data) !== _entryHeader.dataHeader.crc) {
+ 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:
+ }
+ return true;
+ }
-const plTypes = {
- '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
- '?': { open: '(?:', close: ')?' },
- '+': { open: '(?:', close: ')+' },
- '*': { open: '(?:', close: ')*' },
- '@': { open: '(?:', close: ')' }
-}
+ function decompress(/*Boolean*/ async, /*Function*/ callback, /*String, Buffer*/ pass) {
+ if (typeof callback === "undefined" && typeof async === "string") {
+ pass = async;
+ async = void 0;
+ }
+ if (_isDirectory) {
+ if (async && callback) {
+ callback(Buffer.alloc(0), Utils.Errors.DIRECTORY_CONTENT_ERROR); //si added error.
+ }
+ return Buffer.alloc(0);
+ }
-// any single thing other than /
-// don't need to escape / when using new RegExp()
-const qmark = '[^/]'
+ var compressedData = getCompressedDataFromZip();
-// * => any number of characters
-const star = qmark + '*?'
+ if (compressedData.length === 0) {
+ // File is empty, nothing to decompress.
+ if (async && callback) callback(compressedData);
+ return compressedData;
+ }
-// ** when dots are allowed. Anything goes, except .. and .
-// not (^ or / followed by one or two dots followed by $ or /),
-// followed by anything, any number of times.
-const twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'
+ if (_entryHeader.encripted) {
+ if ("string" !== typeof pass && !Buffer.isBuffer(pass)) {
+ throw new Error("ADM-ZIP: Incompatible password parameter");
+ }
+ compressedData = Methods.ZipCrypto.decrypt(compressedData, _entryHeader, pass);
+ }
-// not a ^ or / followed by a dot,
-// followed by anything, any number of times.
-const twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'
+ var data = Buffer.alloc(_entryHeader.size);
-// "abc" -> { a:true, b:true, c:true }
-const charSet = s => s.split('').reduce((set, c) => {
- set[c] = true
- return set
-}, {})
+ switch (_entryHeader.method) {
+ case Utils.Constants.STORED:
+ compressedData.copy(data);
+ if (!crc32OK(data)) {
+ if (async && callback) callback(data, Utils.Errors.BAD_CRC); //si added error
+ throw new Error(Utils.Errors.BAD_CRC);
+ } else {
+ //si added otherwise did not seem to return data.
+ if (async && callback) callback(data);
+ return data;
+ }
+ case Utils.Constants.DEFLATED:
+ var inflater = new Methods.Inflater(compressedData);
+ if (!async) {
+ const result = inflater.inflate(data);
+ result.copy(data, 0);
+ if (!crc32OK(data)) {
+ throw new Error(Utils.Errors.BAD_CRC + " " + _entryName.toString());
+ }
+ return data;
+ } else {
+ inflater.inflateAsync(function (result) {
+ result.copy(result, 0);
+ if (callback) {
+ if (!crc32OK(result)) {
+ callback(result, Utils.Errors.BAD_CRC); //si added error
+ } else {
+ callback(result);
+ }
+ }
+ });
+ }
+ break;
+ default:
+ if (async && callback) callback(Buffer.alloc(0), Utils.Errors.UNKNOWN_METHOD);
+ throw new Error(Utils.Errors.UNKNOWN_METHOD);
+ }
+ }
-// characters that need to be escaped in RegExp.
-const reSpecials = charSet('().*{}+?[]^$\\!')
+ function compress(/*Boolean*/ async, /*Function*/ callback) {
+ if ((!uncompressedData || !uncompressedData.length) && Buffer.isBuffer(input)) {
+ // no data set or the data wasn't changed to require recompression
+ if (async && callback) callback(getCompressedDataFromZip());
+ return getCompressedDataFromZip();
+ }
-// characters that indicate we have to add the pattern start
-const addPatternStartSet = charSet('[.(')
+ if (uncompressedData.length && !_isDirectory) {
+ var compressedData;
+ // Local file header
+ switch (_entryHeader.method) {
+ case Utils.Constants.STORED:
+ _entryHeader.compressedSize = _entryHeader.size;
-// normalizes slashes.
-const slashSplit = /\/+/
+ compressedData = Buffer.alloc(uncompressedData.length);
+ uncompressedData.copy(compressedData);
-minimatch.filter = (pattern, options = {}) =>
- (p, i, list) => minimatch(p, pattern, options)
+ if (async && callback) callback(compressedData);
+ return compressedData;
+ default:
+ case Utils.Constants.DEFLATED:
+ var deflater = new Methods.Deflater(uncompressedData);
+ if (!async) {
+ var deflated = deflater.deflate();
+ _entryHeader.compressedSize = deflated.length;
+ return deflated;
+ } else {
+ deflater.deflateAsync(function (data) {
+ compressedData = Buffer.alloc(data.length);
+ _entryHeader.compressedSize = data.length;
+ data.copy(compressedData);
+ callback && callback(compressedData);
+ });
+ }
+ deflater = null;
+ break;
+ }
+ } else if (async && callback) {
+ callback(Buffer.alloc(0));
+ } else {
+ return Buffer.alloc(0);
+ }
+ }
-const ext = (a, b = {}) => {
- const t = {}
- Object.keys(a).forEach(k => t[k] = a[k])
- Object.keys(b).forEach(k => t[k] = b[k])
- return t
-}
+ function readUInt64LE(buffer, offset) {
+ return (buffer.readUInt32LE(offset + 4) << 4) + buffer.readUInt32LE(offset);
+ }
-minimatch.defaults = def => {
- if (!def || typeof def !== 'object' || !Object.keys(def).length) {
- return minimatch
- }
+ 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);
+ }
+ }
+ }
- const orig = minimatch
+ //Override header field values with values from the ZIP64 extra field
+ function parseZip64ExtendedInformation(data) {
+ var size, compressedSize, offset, diskNumStart;
- const m = (p, pattern, options) => orig(p, pattern, ext(def, options))
- m.Minimatch = class Minimatch extends orig.Minimatch {
- constructor (pattern, options) {
- super(pattern, ext(def, options))
+ if (data.length >= Constants.EF_ZIP64_SCOMP) {
+ size = readUInt64LE(data, Constants.EF_ZIP64_SUNCOMP);
+ if (_entryHeader.size === Constants.EF_ZIP64_OR_32) {
+ _entryHeader.size = size;
+ }
+ }
+ if (data.length >= Constants.EF_ZIP64_RHO) {
+ compressedSize = readUInt64LE(data, Constants.EF_ZIP64_SCOMP);
+ if (_entryHeader.compressedSize === Constants.EF_ZIP64_OR_32) {
+ _entryHeader.compressedSize = compressedSize;
+ }
+ }
+ if (data.length >= Constants.EF_ZIP64_DSN) {
+ offset = readUInt64LE(data, Constants.EF_ZIP64_RHO);
+ if (_entryHeader.offset === Constants.EF_ZIP64_OR_32) {
+ _entryHeader.offset = offset;
+ }
+ }
+ if (data.length >= Constants.EF_ZIP64_DSN + 4) {
+ diskNumStart = data.readUInt32LE(Constants.EF_ZIP64_DSN);
+ if (_entryHeader.diskNumStart === Constants.EF_ZIP64_OR_16) {
+ _entryHeader.diskNumStart = diskNumStart;
+ }
+ }
}
- }
- m.Minimatch.defaults = options => orig.defaults(ext(def, options)).Minimatch
- m.filter = (pattern, options) => orig.filter(pattern, ext(def, options))
- m.defaults = options => orig.defaults(ext(def, options))
- m.makeRe = (pattern, options) => orig.makeRe(pattern, ext(def, options))
- m.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext(def, options))
- m.match = (list, pattern, options) => orig.match(list, pattern, ext(def, options))
-
- return m
-}
+ return {
+ get entryName() {
+ return _entryName.toString();
+ },
+ get rawEntryName() {
+ return _entryName;
+ },
+ set entryName(val) {
+ _entryName = Utils.toBuffer(val);
+ var lastChar = _entryName[_entryName.length - 1];
+ _isDirectory = lastChar === 47 || lastChar === 92;
+ _entryHeader.fileNameLength = _entryName.length;
+ },
+ get extra() {
+ return _extra;
+ },
+ set extra(val) {
+ _extra = val;
+ _entryHeader.extraLength = val.length;
+ parseExtra(val);
+ },
+ get comment() {
+ return _comment.toString();
+ },
+ set comment(val) {
+ _comment = Utils.toBuffer(val);
+ _entryHeader.commentLength = _comment.length;
+ },
+ get name() {
+ var n = _entryName.toString();
+ return _isDirectory
+ ? n
+ .substr(n.length - 1)
+ .split("/")
+ .pop()
+ : n.split("/").pop();
+ },
+ get isDirectory() {
+ return _isDirectory;
+ },
-// Brace expansion:
-// a{b,c}d -> abd acd
-// a{b,}c -> abc ac
-// a{0..3}d -> a0d a1d a2d a3d
-// a{b,c{d,e}f}g -> abg acdfg acefg
-// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
-//
-// Invalid sets are not expanded.
-// a{2..}b -> a{2..}b
-// a{b}c -> a{b}c
-minimatch.braceExpand = (pattern, options) => braceExpand(pattern, options)
+ getCompressedData: function () {
+ return compress(false, null);
+ },
-const braceExpand = (pattern, options = {}) => {
- assertValidPattern(pattern)
+ getCompressedDataAsync: function (/*Function*/ callback) {
+ compress(true, callback);
+ },
- // Thanks to Yeting Li for
- // improving this regexp to avoid a ReDOS vulnerability.
- if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
- // shortcut. no need to expand.
- return [pattern]
- }
+ setData: function (value) {
+ uncompressedData = Utils.toBuffer(value);
+ if (!_isDirectory && uncompressedData.length) {
+ _entryHeader.size = uncompressedData.length;
+ _entryHeader.method = Utils.Constants.DEFLATED;
+ _entryHeader.crc = Utils.crc32(value);
+ _entryHeader.changed = true;
+ } else {
+ // folders and blank files should be stored
+ _entryHeader.method = Utils.Constants.STORED;
+ }
+ },
- return expand(pattern)
-}
+ getData: function (pass) {
+ if (_entryHeader.changed) {
+ return uncompressedData;
+ } else {
+ return decompress(false, null, pass);
+ }
+ },
-const MAX_PATTERN_LENGTH = 1024 * 64
-const assertValidPattern = pattern => {
- if (typeof pattern !== 'string') {
- throw new TypeError('invalid pattern')
- }
+ getDataAsync: function (/*Function*/ callback, pass) {
+ if (_entryHeader.changed) {
+ callback(uncompressedData);
+ } else {
+ decompress(true, callback, pass);
+ }
+ },
- if (pattern.length > MAX_PATTERN_LENGTH) {
- throw new TypeError('pattern is too long')
- }
-}
+ set attr(attr) {
+ _entryHeader.attr = attr;
+ },
+ get attr() {
+ return _entryHeader.attr;
+ },
-// parse a component of the expanded set.
-// At this point, no pattern may contain "/" in it
-// so we're going to return a 2d array, where each entry is the full
-// pattern, split on '/', and then turned into a regular expression.
-// A regexp is made at the end which joins each array with an
-// escaped /, and another full one which joins each regexp with |.
-//
-// Following the lead of Bash 4.1, note that "**" only has special meaning
-// when it is the *only* thing in a path portion. Otherwise, any series
-// of * is equivalent to a single *. Globstar behavior is enabled by
-// default, and can be disabled by setting options.noglobstar.
-const SUBPARSE = Symbol('subparse')
+ set header(/*Buffer*/ data) {
+ _entryHeader.loadFromBinary(data);
+ },
-minimatch.makeRe = (pattern, options) =>
- new Minimatch(pattern, options || {}).makeRe()
+ get header() {
+ return _entryHeader;
+ },
-minimatch.match = (list, pattern, options = {}) => {
- const mm = new Minimatch(pattern, options)
- list = list.filter(f => mm.match(f))
- if (mm.options.nonull && !list.length) {
- list.push(pattern)
- }
- return list
-}
+ packHeader: function () {
+ // 1. create header (buffer)
+ var header = _entryHeader.entryHeaderToBinary();
+ var addpos = Utils.Constants.CENHDR;
+ // 2. add file name
+ _entryName.copy(header, addpos);
+ addpos += _entryName.length;
+ // 3. add extra data
+ if (_entryHeader.extraLength) {
+ _extra.copy(header, addpos);
+ addpos += _entryHeader.extraLength;
+ }
+ // 4. add file comment
+ if (_entryHeader.commentLength) {
+ _comment.copy(header, addpos);
+ }
+ return header;
+ },
-// replace stuff like \* with *
-const globUnescape = s => s.replace(/\\(.)/g, '$1')
-const regExpEscape = s => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
+ toJSON: function () {
+ const bytes = function (nr) {
+ return "<" + ((nr && nr.length + " bytes buffer") || "null") + ">";
+ };
-class Minimatch {
- constructor (pattern, options) {
- assertValidPattern(pattern)
+ return {
+ entryName: this.entryName,
+ name: this.name,
+ comment: this.comment,
+ isDirectory: this.isDirectory,
+ header: _entryHeader.toJSON(),
+ compressedData: bytes(input),
+ data: bytes(uncompressedData)
+ };
+ },
- if (!options) options = {}
+ toString: function () {
+ return JSON.stringify(this.toJSON(), null, "\t");
+ }
+ };
+};
- this.options = options
- this.set = []
- this.pattern = pattern
- this.windowsPathsNoEscape = !!options.windowsPathsNoEscape ||
- options.allowWindowsEscape === false
- if (this.windowsPathsNoEscape) {
- this.pattern = this.pattern.replace(/\\/g, '/')
- }
- this.regexp = null
- this.negate = false
- this.comment = false
- this.empty = false
- this.partial = !!options.partial
- // make the set of regexps etc.
- this.make()
- }
+/***/ }),
- debug () {}
+/***/ 7744:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- make () {
- const pattern = this.pattern
- const options = this.options
+const ZipEntry = __nccwpck_require__(4057);
+const Headers = __nccwpck_require__(4958);
+const Utils = __nccwpck_require__(5182);
- // empty patterns and comments match nothing.
- if (!options.nocomment && pattern.charAt(0) === '#') {
- this.comment = true
- return
- }
- if (!pattern) {
- this.empty = true
- return
- }
+module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) {
+ var entryList = [],
+ entryTable = {},
+ _comment = Buffer.alloc(0),
+ mainHeader = new Headers.MainHeader(),
+ loadedEntries = false;
- // step 1: figure out negation, etc.
- this.parseNegate()
+ // assign options
+ const opts = Object.assign(Object.create(null), options);
- // step 2: expand braces
- let set = this.globSet = this.braceExpand()
+ const { noSort } = opts;
- if (options.debug) this.debug = (...args) => console.error(...args)
+ if (inBuffer) {
+ // is a memory buffer
+ readMainHeader(opts.readEntries);
+ } else {
+ // none. is a new file
+ loadedEntries = true;
+ }
- this.debug(this.pattern, set)
+ function iterateEntries(callback) {
+ const totalEntries = mainHeader.diskEntries; // total number of entries
+ let index = mainHeader.offset; // offset of first CEN header
- // step 3: now we have a set, so turn each one into a series of path-portion
- // matching patterns.
- // These will be regexps, except in the case of "**", which is
- // set to the GLOBSTAR object for globstar behavior,
- // and will not contain any / characters
- set = this.globParts = set.map(s => s.split(slashSplit))
+ for (let i = 0; i < totalEntries; i++) {
+ let tmp = index;
+ const entry = new ZipEntry(inBuffer);
- this.debug(this.pattern, set)
+ entry.header = inBuffer.slice(tmp, (tmp += Utils.Constants.CENHDR));
+ entry.entryName = inBuffer.slice(tmp, (tmp += entry.header.fileNameLength));
- // glob --> regexps
- set = set.map((s, si, set) => s.map(this.parse, this))
+ index += entry.header.entryHeaderSize;
- this.debug(this.pattern, set)
+ callback(entry);
+ }
+ }
- // filter out everything that didn't compile properly.
- set = set.filter(s => s.indexOf(false) === -1)
+ function readEntries() {
+ loadedEntries = true;
+ entryTable = {};
+ entryList = new Array(mainHeader.diskEntries); // total number of entries
+ var index = mainHeader.offset; // offset of first CEN header
+ for (var i = 0; i < entryList.length; i++) {
+ var tmp = index,
+ entry = new ZipEntry(inBuffer);
+ entry.header = inBuffer.slice(tmp, (tmp += Utils.Constants.CENHDR));
- this.debug(this.pattern, set)
+ entry.entryName = inBuffer.slice(tmp, (tmp += entry.header.fileNameLength));
- this.set = set
- }
+ if (entry.header.extraLength) {
+ entry.extra = inBuffer.slice(tmp, (tmp += entry.header.extraLength));
+ }
- parseNegate () {
- if (this.options.nonegate) return
+ if (entry.header.commentLength) entry.comment = inBuffer.slice(tmp, tmp + entry.header.commentLength);
- const pattern = this.pattern
- let negate = false
- let negateOffset = 0
+ index += entry.header.entryHeaderSize;
- for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
- negate = !negate
- negateOffset++
+ entryList[i] = entry;
+ entryTable[entry.entryName] = entry;
+ }
}
- if (negateOffset) this.pattern = pattern.slice(negateOffset)
- this.negate = negate
- }
-
- // set partial to true to test if, for example,
- // "/a/b" matches the start of "/*/b/*/d"
- // Partial means, if you run out of file before you run
- // out of pattern, then that's fine, as long as all
- // the parts match.
- matchOne (file, pattern, partial) {
- var options = this.options
-
- this.debug('matchOne',
- { 'this': this, file: file, pattern: pattern })
+ function readMainHeader(/*Boolean*/ readNow) {
+ var i = inBuffer.length - Utils.Constants.ENDHDR, // END header size
+ max = Math.max(0, i - 0xffff), // 0xFFFF is the max zip file comment length
+ n = max,
+ endStart = inBuffer.length,
+ endOffset = -1, // Start offset of the END header
+ commentEnd = 0;
- this.debug('matchOne', file.length, pattern.length)
+ for (i; i >= n; i--) {
+ if (inBuffer[i] !== 0x50) continue; // quick check that the byte is 'P'
+ if (inBuffer.readUInt32LE(i) === Utils.Constants.ENDSIG) {
+ // "PK\005\006"
+ endOffset = i;
+ commentEnd = i;
+ endStart = i + Utils.Constants.ENDHDR;
+ // We already found a regular signature, let's look just a bit further to check if there's any zip64 signature
+ n = i - Utils.Constants.END64HDR;
+ continue;
+ }
- for (var fi = 0,
- pi = 0,
- fl = file.length,
- pl = pattern.length
- ; (fi < fl) && (pi < pl)
- ; fi++, pi++) {
- this.debug('matchOne loop')
- var p = pattern[pi]
- var f = file[fi]
+ if (inBuffer.readUInt32LE(i) === Utils.Constants.END64SIG) {
+ // Found a zip64 signature, let's continue reading the whole zip64 record
+ n = max;
+ continue;
+ }
- this.debug(pattern, p, f)
+ if (inBuffer.readUInt32LE(i) === Utils.Constants.ZIP64SIG) {
+ // Found the zip64 record, let's determine it's size
+ endOffset = i;
+ endStart = i + Utils.readBigUInt64LE(inBuffer, i + Utils.Constants.ZIP64SIZE) + Utils.Constants.ZIP64LEAD;
+ break;
+ }
+ }
- // should be impossible.
- // some invalid regexp stuff in the set.
- /* istanbul ignore if */
- if (p === false) return false
+ if (!~endOffset) throw new Error(Utils.Errors.INVALID_FORMAT);
- if (p === GLOBSTAR) {
- this.debug('GLOBSTAR', [pattern, p, f])
+ mainHeader.loadFromBinary(inBuffer.slice(endOffset, endStart));
+ if (mainHeader.commentLength) {
+ _comment = inBuffer.slice(commentEnd + Utils.Constants.ENDHDR);
+ }
+ if (readNow) readEntries();
+ }
- // "**"
- // a/**/b/**/c would match the following:
- // a/b/x/y/z/c
- // a/x/y/z/b/c
- // a/b/x/b/x/c
- // a/b/c
- // To do this, take the rest of the pattern after
- // the **, and see if it would match the file remainder.
- // If so, return success.
- // If not, the ** "swallows" a segment, and try again.
- // This is recursively awful.
- //
- // a/**/b/**/c matching a/b/x/y/z/c
- // - a matches a
- // - doublestar
- // - matchOne(b/x/y/z/c, b/**/c)
- // - b matches b
- // - doublestar
- // - matchOne(x/y/z/c, c) -> no
- // - matchOne(y/z/c, c) -> no
- // - matchOne(z/c, c) -> no
- // - matchOne(c, c) yes, hit
- var fr = fi
- var pr = pi + 1
- if (pr === pl) {
- this.debug('** at the end')
- // a ** at the end will just swallow the rest.
- // We have found a match.
- // however, it will not swallow /.x, unless
- // options.dot is set.
- // . and .. are *never* matched by **, for explosively
- // exponential reasons.
- for (; fi < fl; fi++) {
- if (file[fi] === '.' || file[fi] === '..' ||
- (!options.dot && file[fi].charAt(0) === '.')) return false
- }
- return true
+ function sortEntries() {
+ if (entryList.length > 1 && !noSort) {
+ entryList.sort((a, b) => a.entryName.toLowerCase().localeCompare(b.entryName.toLowerCase()));
}
+ }
- // ok, let's see if we can swallow whatever we can.
- while (fr < fl) {
- var swallowee = file[fr]
+ return {
+ /**
+ * Returns an array of ZipEntry objects existent in the current opened archive
+ * @return Array
+ */
+ get entries() {
+ if (!loadedEntries) {
+ readEntries();
+ }
+ return entryList;
+ },
- this.debug('\nglobstar while', file, fr, pattern, pr, swallowee)
+ /**
+ * Archive comment
+ * @return {String}
+ */
+ get comment() {
+ return _comment.toString();
+ },
+ set comment(val) {
+ _comment = Utils.toBuffer(val);
+ mainHeader.commentLength = _comment.length;
+ },
- // XXX remove this slice. Just pass the start index.
- if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
- this.debug('globstar found match!', fr, fl, swallowee)
- // found a match.
- return true
- } else {
- // can't swallow "." or ".." ever.
- // can only swallow ".foo" when explicitly asked.
- if (swallowee === '.' || swallowee === '..' ||
- (!options.dot && swallowee.charAt(0) === '.')) {
- this.debug('dot detected!', file, fr, pattern, pr)
- break
+ getEntryCount: function () {
+ if (!loadedEntries) {
+ return mainHeader.diskEntries;
}
- // ** swallows a segment, and continue.
- this.debug('globstar swallow a segment, and continue')
- fr++
- }
- }
+ return entryList.length;
+ },
- // no match was found.
- // However, in partial mode, we can't say this is necessarily over.
- // If there's more *pattern* left, then
- /* istanbul ignore if */
- if (partial) {
- // ran out of file
- this.debug('\n>>> no match, partial?', file, fr, pattern, pr)
- if (fr === fl) return true
- }
- return false
- }
+ forEach: function (callback) {
+ if (!loadedEntries) {
+ iterateEntries(callback);
+ return;
+ }
- // something other than **
- // non-magic patterns just have to match exactly
- // patterns with magic have been turned into regexps.
- var hit
- if (typeof p === 'string') {
- hit = f === p
- this.debug('string match', p, f, hit)
- } else {
- hit = f.match(p)
- this.debug('pattern match', p, f, hit)
- }
+ entryList.forEach(callback);
+ },
- if (!hit) return false
- }
+ /**
+ * Returns a reference to the entry with the given name or null if entry is inexistent
+ *
+ * @param entryName
+ * @return ZipEntry
+ */
+ getEntry: function (/*String*/ entryName) {
+ if (!loadedEntries) {
+ readEntries();
+ }
+ return entryTable[entryName] || null;
+ },
- // Note: ending in / means that we'll get a final ""
- // at the end of the pattern. This can only match a
- // corresponding "" at the end of the file.
- // If the file ends in /, then it can only match a
- // a pattern that ends in /, unless the pattern just
- // doesn't have any more for it. But, a/b/ should *not*
- // match "a/b/*", even though "" matches against the
- // [^/]*? pattern, except in partial mode, where it might
- // simply not be reached yet.
- // However, a/b/ should still satisfy a/*
+ /**
+ * Adds the given entry to the entry list
+ *
+ * @param entry
+ */
+ setEntry: function (/*ZipEntry*/ entry) {
+ if (!loadedEntries) {
+ readEntries();
+ }
+ entryList.push(entry);
+ entryTable[entry.entryName] = entry;
+ mainHeader.totalEntries = entryList.length;
+ },
- // now either we fell off the end of the pattern, or we're done.
- if (fi === fl && pi === pl) {
- // ran out of pattern and filename at the same time.
- // an exact hit!
- return true
- } else if (fi === fl) {
- // ran out of file, but still had pattern left.
- // this is ok if we're doing the match as part of
- // a glob fs traversal.
- return partial
- } else /* istanbul ignore else */ if (pi === pl) {
- // ran out of pattern, still have file left.
- // this is only acceptable if we're on the very last
- // empty segment of a file with a trailing slash.
- // a/* should match a/b/
- return (fi === fl - 1) && (file[fi] === '')
- }
+ /**
+ * Removes the entry 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
+ */
+ deleteEntry: function (/*String*/ entryName) {
+ if (!loadedEntries) {
+ readEntries();
+ }
+ 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);
+ }
+ });
+ }
+ entryList.splice(entryList.indexOf(entry), 1);
+ delete entryTable[entryName];
+ mainHeader.totalEntries = entryList.length;
+ },
- // should be unreachable.
- /* istanbul ignore next */
- throw new Error('wtf?')
- }
+ /**
+ * Iterates and returns all nested files and directories of the given entry
+ *
+ * @param entry
+ * @return Array
+ */
+ getEntryChildren: function (/*ZipEntry*/ entry) {
+ if (!loadedEntries) {
+ readEntries();
+ }
+ if (entry && entry.isDirectory) {
+ const list = [];
+ const name = entry.entryName;
+ const len = name.length;
- braceExpand () {
- return braceExpand(this.pattern, this.options)
- }
+ entryList.forEach(function (zipEntry) {
+ if (zipEntry.entryName.substr(0, len) === name) {
+ list.push(zipEntry);
+ }
+ });
+ return list;
+ }
+ return [];
+ },
- parse (pattern, isSub) {
- assertValidPattern(pattern)
+ /**
+ * Returns the zip file
+ *
+ * @return Buffer
+ */
+ compressToBuffer: function () {
+ if (!loadedEntries) {
+ readEntries();
+ }
+ sortEntries();
- const options = this.options
+ const dataBlock = [];
+ const entryHeaders = [];
+ let totalSize = 0;
+ let dindex = 0;
- // shortcuts
- if (pattern === '**') {
- if (!options.noglobstar)
- return GLOBSTAR
- else
- pattern = '*'
- }
- if (pattern === '') return ''
+ mainHeader.size = 0;
+ mainHeader.offset = 0;
- let re = ''
- let hasMagic = !!options.nocase
- let escaping = false
- // ? => one single character
- const patternListStack = []
- const negativeLists = []
- let stateChar
- let inClass = false
- let reClassStart = -1
- let classStart = -1
- let cs
- let pl
- let sp
- // . and .. never match anything that doesn't start with .,
- // even when options.dot is set.
- const patternStart = pattern.charAt(0) === '.' ? '' // anything
- // not (start or / followed by . or .. followed by / or end)
- : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
- : '(?!\\.)'
+ for (const entry of entryList) {
+ // compress data and set local and entry header accordingly. Reason why is called first
+ const compressedData = entry.getCompressedData();
+ // 1. construct data header
+ entry.header.offset = dindex;
+ const dataHeader = entry.header.dataHeaderToBinary();
+ const entryNameLen = entry.rawEntryName.length;
+ // 1.2. postheader - data after data header
+ const postHeader = Buffer.alloc(entryNameLen + entry.extra.length);
+ entry.rawEntryName.copy(postHeader, 0);
+ postHeader.copy(entry.extra, entryNameLen);
- const clearStateChar = () => {
- if (stateChar) {
- // we had some state-tracking character
- // that wasn't consumed by this pass.
- switch (stateChar) {
- case '*':
- re += star
- hasMagic = true
- break
- case '?':
- re += qmark
- hasMagic = true
- break
- default:
- re += '\\' + stateChar
- break
- }
- this.debug('clearStateChar %j %j', stateChar, re)
- stateChar = false
- }
- }
+ // 2. offsets
+ const dataLength = dataHeader.length + postHeader.length + compressedData.length;
+ dindex += dataLength;
- for (let i = 0, c; (i < pattern.length) && (c = pattern.charAt(i)); i++) {
- this.debug('%s\t%s %s %j', pattern, i, re, c)
+ // 3. store values in sequence
+ dataBlock.push(dataHeader);
+ dataBlock.push(postHeader);
+ dataBlock.push(compressedData);
- // skip over any that are escaped.
- if (escaping) {
- /* istanbul ignore next - completely not allowed, even escaped. */
- if (c === '/') {
- return false
- }
+ // 4. construct entry header
+ const entryHeader = entry.packHeader();
+ entryHeaders.push(entryHeader);
+ // 5. update main header
+ mainHeader.size += entryHeader.length;
+ totalSize += dataLength + entryHeader.length;
+ }
- if (reSpecials[c]) {
- re += '\\'
- }
- re += c
- escaping = false
- continue
- }
+ totalSize += mainHeader.mainHeaderSize; // also includes zip file comment length
+ // point to end of data and beginning of central directory first record
+ mainHeader.offset = dindex;
- switch (c) {
- /* istanbul ignore next */
- case '/': {
- // Should already be path-split by now.
- return false
- }
+ dindex = 0;
+ const outBuffer = Buffer.alloc(totalSize);
+ // write data blocks
+ for (const content of dataBlock) {
+ content.copy(outBuffer, dindex);
+ dindex += content.length;
+ }
- case '\\':
- clearStateChar()
- escaping = true
- continue
+ // write central directory entries
+ for (const content of entryHeaders) {
+ content.copy(outBuffer, dindex);
+ dindex += content.length;
+ }
- // the various stateChar values
- // for the "extglob" stuff.
- case '?':
- case '*':
- case '+':
- case '@':
- case '!':
- this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c)
+ // write main header
+ const mh = mainHeader.toBinary();
+ if (_comment) {
+ _comment.copy(mh, Utils.Constants.ENDHDR); // add zip file comment
+ }
+ mh.copy(outBuffer, dindex);
- // all of those are literals inside a class, except that
- // the glob [!a] means [^a] in regexp
- if (inClass) {
- this.debug(' in class')
- if (c === '!' && i === classStart + 1) c = '^'
- re += c
- continue
- }
+ return outBuffer;
+ },
- // if we already have a stateChar, then it means
- // that there was something like ** or +? in there.
- // Handle the stateChar, then proceed with this one.
- this.debug('call clearStateChar %j', stateChar)
- clearStateChar()
- stateChar = c
- // if extglob is disabled, then +(asdf|foo) isn't a thing.
- // just clear the statechar *now*, rather than even diving into
- // the patternList stuff.
- if (options.noext) clearStateChar()
- continue
+ toAsyncBuffer: function (/*Function*/ onSuccess, /*Function*/ onFail, /*Function*/ onItemStart, /*Function*/ onItemEnd) {
+ try {
+ if (!loadedEntries) {
+ readEntries();
+ }
+ sortEntries();
- case '(':
- if (inClass) {
- re += '('
- continue
- }
+ const dataBlock = [];
+ const entryHeaders = [];
+ let totalSize = 0;
+ let dindex = 0;
- if (!stateChar) {
- re += '\\('
- continue
- }
+ mainHeader.size = 0;
+ mainHeader.offset = 0;
- patternListStack.push({
- type: stateChar,
- start: i - 1,
- reStart: re.length,
- open: plTypes[stateChar].open,
- close: plTypes[stateChar].close
- })
- // negation is (?:(?!js)[^/]*)
- re += stateChar === '!' ? '(?:(?!(?:' : '(?:'
- this.debug('plType %j %j', stateChar, re)
- stateChar = false
- continue
+ const compress2Buffer = function (entryLists) {
+ if (entryLists.length) {
+ const entry = entryLists.pop();
+ const name = entry.entryName + entry.extra.toString();
+ if (onItemStart) onItemStart(name);
+ entry.getCompressedDataAsync(function (compressedData) {
+ if (onItemEnd) onItemEnd(name);
- case ')':
- if (inClass || !patternListStack.length) {
- re += '\\)'
- continue
- }
+ entry.header.offset = dindex;
+ // data header
+ const dataHeader = entry.header.dataHeaderToBinary();
+ const postHeader = Buffer.alloc(name.length, name);
+ const dataLength = dataHeader.length + postHeader.length + compressedData.length;
- clearStateChar()
- hasMagic = true
- pl = patternListStack.pop()
- // negation is (?:(?!js)[^/]*)
- // The others are (?:)
- re += pl.close
- if (pl.type === '!') {
- negativeLists.push(pl)
- }
- pl.reEnd = re.length
- continue
+ dindex += dataLength;
- case '|':
- if (inClass || !patternListStack.length) {
- re += '\\|'
- continue
- }
+ dataBlock.push(dataHeader);
+ dataBlock.push(postHeader);
+ dataBlock.push(compressedData);
- clearStateChar()
- re += '|'
- continue
+ const entryHeader = entry.packHeader();
+ entryHeaders.push(entryHeader);
+ mainHeader.size += entryHeader.length;
+ totalSize += dataLength + entryHeader.length;
- // these are mostly the same in regexp and glob
- case '[':
- // swallow any state-tracking char before the [
- clearStateChar()
+ compress2Buffer(entryLists);
+ });
+ } else {
+ totalSize += mainHeader.mainHeaderSize; // also includes zip file comment length
+ // point to end of data and beginning of central directory first record
+ mainHeader.offset = dindex;
- if (inClass) {
- re += '\\' + c
- continue
- }
+ dindex = 0;
+ const outBuffer = Buffer.alloc(totalSize);
+ dataBlock.forEach(function (content) {
+ content.copy(outBuffer, dindex); // write data blocks
+ dindex += content.length;
+ });
+ entryHeaders.forEach(function (content) {
+ content.copy(outBuffer, dindex); // write central directory entries
+ dindex += content.length;
+ });
- inClass = true
- classStart = i
- reClassStart = re.length
- re += c
- continue
+ const mh = mainHeader.toBinary();
+ if (_comment) {
+ _comment.copy(mh, Utils.Constants.ENDHDR); // add zip file comment
+ }
- case ']':
- // a right bracket shall lose its special
- // meaning and represent itself in
- // a bracket expression if it occurs
- // first in the list. -- POSIX.2 2.8.3.2
- if (i === classStart + 1 || !inClass) {
- re += '\\' + c
- continue
- }
+ mh.copy(outBuffer, dindex); // write main header
- // handle the case where we left a class open.
- // "[z-a]" is valid, equivalent to "\[z-a\]"
- // split where the last [ was, make sure we don't have
- // an invalid re. if so, re-walk the contents of the
- // would-be class to re-translate any characters that
- // were passed through as-is
- // TODO: It would probably be faster to determine this
- // without a try/catch and a new RegExp, but it's tricky
- // to do safely. For now, this is safe and works.
- cs = pattern.substring(classStart + 1, i)
- try {
- RegExp('[' + cs + ']')
- } catch (er) {
- // not a valid class!
- sp = this.parse(cs, SUBPARSE)
- re = re.substring(0, reClassStart) + '\\[' + sp[0] + '\\]'
- hasMagic = hasMagic || sp[1]
- inClass = false
- continue
- }
+ onSuccess(outBuffer);
+ }
+ };
- // finish up the class.
- hasMagic = true
- inClass = false
- re += c
- continue
+ compress2Buffer(entryList);
+ } catch (e) {
+ onFail(e);
+ }
+ }
+ };
+};
- default:
- // swallow any state char that wasn't consumed
- clearStateChar()
- if (reSpecials[c] && !(c === '^' && inClass)) {
- re += '\\'
- }
+/***/ }),
- re += c
- break
+/***/ 4812:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- } // switch
- } // for
+module.exports =
+{
+ parallel : __nccwpck_require__(8210),
+ serial : __nccwpck_require__(445),
+ serialOrdered : __nccwpck_require__(3578)
+};
- // handle the case where we left a class open.
- // "[abc" is valid, equivalent to "\[abc"
- if (inClass) {
- // split where the last [ was, and escape it
- // this is a huge pita. We now have to re-walk
- // the contents of the would-be class to re-translate
- // any characters that were passed through as-is
- cs = pattern.slice(classStart + 1)
- sp = this.parse(cs, SUBPARSE)
- re = re.substring(0, reClassStart) + '\\[' + sp[0]
- hasMagic = hasMagic || sp[1]
- }
- // handle the case where we had a +( thing at the *end*
- // of the pattern.
- // each pattern list stack adds 3 chars, and we need to go through
- // and escape any | chars that were passed through as-is for the regexp.
- // Go through and escape them, taking care not to double-escape any
- // | chars that were already escaped.
- for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
- let tail
- tail = re.slice(pl.reStart + pl.open.length)
- this.debug('setting tail', re, pl)
- // maybe some even number of \, then maybe 1 \, followed by a |
- tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_, $1, $2) => {
- /* istanbul ignore else - should already be done */
- if (!$2) {
- // the | isn't already escaped, so escape it.
- $2 = '\\'
- }
+/***/ }),
- // need to escape all those slashes *again*, without escaping the
- // one that we need for escaping the | character. As it works out,
- // escaping an even number of slashes can be done by simply repeating
- // it exactly after itself. That's why this trick works.
- //
- // I am sorry that you have to see this.
- return $1 + $1 + $2 + '|'
- })
+/***/ 1700:
+/***/ ((module) => {
- this.debug('tail=%j\n %s', tail, tail, pl, re)
- const t = pl.type === '*' ? star
- : pl.type === '?' ? qmark
- : '\\' + pl.type
+// API
+module.exports = abort;
- hasMagic = true
- re = re.slice(0, pl.reStart) + t + '\\(' + tail
- }
+/**
+ * Aborts leftover active jobs
+ *
+ * @param {object} state - current state object
+ */
+function abort(state)
+{
+ Object.keys(state.jobs).forEach(clean.bind(state));
- // handle trailing things that only matter at the very end.
- clearStateChar()
- if (escaping) {
- // trailing \\
- re += '\\\\'
- }
+ // reset leftover jobs
+ state.jobs = {};
+}
- // only need to apply the nodot start if the re starts with
- // something that could conceivably capture a dot
- const addPatternStart = addPatternStartSet[re.charAt(0)]
+/**
+ * Cleans up leftover job by invoking abort function for the provided job id
+ *
+ * @this state
+ * @param {string|number} key - job id to abort
+ */
+function clean(key)
+{
+ if (typeof this.jobs[key] == 'function')
+ {
+ this.jobs[key]();
+ }
+}
- // Hack to work around lack of negative lookbehind in JS
- // A pattern like: *.!(x).!(y|z) needs to ensure that a name
- // like 'a.xyz.yz' doesn't match. So, the first negative
- // lookahead, has to look ALL the way ahead, to the end of
- // the pattern.
- for (let n = negativeLists.length - 1; n > -1; n--) {
- const nl = negativeLists[n]
- const nlBefore = re.slice(0, nl.reStart)
- const nlFirst = re.slice(nl.reStart, nl.reEnd - 8)
- let nlAfter = re.slice(nl.reEnd)
- const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter
+/***/ }),
- // Handle nested stuff like *(*.js|!(*.json)), where open parens
- // mean that we should *not* include the ) in the bit that is considered
- // "after" the negated section.
- const openParensBefore = nlBefore.split('(').length - 1
- let cleanAfter = nlAfter
- for (let i = 0; i < openParensBefore; i++) {
- cleanAfter = cleanAfter.replace(/\)[+*?]?/, '')
- }
- nlAfter = cleanAfter
+/***/ 2794:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- const dollar = nlAfter === '' && isSub !== SUBPARSE ? '$' : ''
- re = nlBefore + nlFirst + nlAfter + dollar + nlLast
- }
+var defer = __nccwpck_require__(5295);
- // if the re is not "" at this point, then we need to make sure
- // it doesn't match against an empty path part.
- // Otherwise a/* will match a/, which it should not.
- if (re !== '' && hasMagic) {
- re = '(?=.)' + re
- }
+// API
+module.exports = async;
- if (addPatternStart) {
- re = patternStart + re
- }
+/**
+ * Runs provided callback asynchronously
+ * even if callback itself is not
+ *
+ * @param {function} callback - callback to invoke
+ * @returns {function} - augmented callback
+ */
+function async(callback)
+{
+ var isAsync = false;
- // parsing just a piece of a larger pattern.
- if (isSub === SUBPARSE) {
- return [re, hasMagic]
- }
+ // check if async happened
+ defer(function() { isAsync = true; });
- // skip the regexp for non-magical patterns
- // unescape anything in it, though, so that it'll be
- // an exact match against a file etc.
- if (!hasMagic) {
- return globUnescape(pattern)
+ return function async_callback(err, result)
+ {
+ if (isAsync)
+ {
+ callback(err, result);
}
-
- const flags = options.nocase ? 'i' : ''
- try {
- return Object.assign(new RegExp('^' + re + '$', flags), {
- _glob: pattern,
- _src: re,
- })
- } catch (er) /* istanbul ignore next - should be impossible */ {
- // If it was an invalid regular expression, then it can't match
- // anything. This trick looks for a character after the end of
- // the string, which is of course impossible, except in multi-line
- // mode, but it's not a /m regex.
- return new RegExp('$.')
+ else
+ {
+ defer(function nextTick_callback()
+ {
+ callback(err, result);
+ });
}
+ };
+}
+
+
+/***/ }),
+
+/***/ 5295:
+/***/ ((module) => {
+
+module.exports = defer;
+
+/**
+ * Runs provided function on next iteration of the event loop
+ *
+ * @param {function} fn - function to run
+ */
+function defer(fn)
+{
+ var nextTick = typeof setImmediate == 'function'
+ ? setImmediate
+ : (
+ typeof process == 'object' && typeof process.nextTick == 'function'
+ ? process.nextTick
+ : null
+ );
+
+ if (nextTick)
+ {
+ nextTick(fn);
+ }
+ else
+ {
+ setTimeout(fn, 0);
}
+}
- makeRe () {
- if (this.regexp || this.regexp === false) return this.regexp
- // at this point, this.set is a 2d array of partial
- // pattern strings, or "**".
- //
- // It's better to use .match(). This function shouldn't
- // be used, really, but it's pretty convenient sometimes,
- // when you just want to work with a regex.
- const set = this.set
+/***/ }),
- if (!set.length) {
- this.regexp = false
- return this.regexp
- }
- const options = this.options
+/***/ 9023:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- const twoStar = options.noglobstar ? star
- : options.dot ? twoStarDot
- : twoStarNoDot
- const flags = options.nocase ? 'i' : ''
+var async = __nccwpck_require__(2794)
+ , abort = __nccwpck_require__(1700)
+ ;
- // coalesce globstars and regexpify non-globstar patterns
- // if it's the only item, then we just do one twoStar
- // if it's the first, and there are more, prepend (\/|twoStar\/)? to next
- // if it's the last, append (\/twoStar|) to previous
- // if it's in the middle, append (\/|\/twoStar\/) to previous
- // then filter out GLOBSTAR symbols
- let re = set.map(pattern => {
- pattern = pattern.map(p =>
- typeof p === 'string' ? regExpEscape(p)
- : p === GLOBSTAR ? GLOBSTAR
- : p._src
- ).reduce((set, p) => {
- if (!(set[set.length - 1] === GLOBSTAR && p === GLOBSTAR)) {
- set.push(p)
- }
- return set
- }, [])
- pattern.forEach((p, i) => {
- if (p !== GLOBSTAR || pattern[i-1] === GLOBSTAR) {
- return
- }
- if (i === 0) {
- if (pattern.length > 1) {
- pattern[i+1] = '(?:\\\/|' + twoStar + '\\\/)?' + pattern[i+1]
- } else {
- pattern[i] = twoStar
- }
- } else if (i === pattern.length - 1) {
- pattern[i-1] += '(?:\\\/|' + twoStar + ')?'
- } else {
- pattern[i-1] += '(?:\\\/|\\\/' + twoStar + '\\\/)' + pattern[i+1]
- pattern[i+1] = GLOBSTAR
- }
- })
- return pattern.filter(p => p !== GLOBSTAR).join('/')
- }).join('|')
+// API
+module.exports = iterate;
- // must match entire pattern
- // ending in a * or ** will make it less strict.
- re = '^(?:' + re + ')$'
+/**
+ * Iterates over each job object
+ *
+ * @param {array|object} list - array or object (named list) to iterate over
+ * @param {function} iterator - iterator to run
+ * @param {object} state - current job status
+ * @param {function} callback - invoked when all elements processed
+ */
+function iterate(list, iterator, state, callback)
+{
+ // store current index
+ var key = state['keyedList'] ? state['keyedList'][state.index] : state.index;
- // can match anything, as long as it's not this.
- if (this.negate) re = '^(?!' + re + ').*$'
+ state.jobs[key] = runJob(iterator, key, list[key], function(error, output)
+ {
+ // don't repeat yourself
+ // skip secondary callbacks
+ if (!(key in state.jobs))
+ {
+ return;
+ }
- try {
- this.regexp = new RegExp(re, flags)
- } catch (ex) /* istanbul ignore next - should be impossible */ {
- this.regexp = false
+ // clean up jobs
+ delete state.jobs[key];
+
+ if (error)
+ {
+ // don't process rest of the results
+ // stop still active jobs
+ // and reset the list
+ abort(state);
+ }
+ else
+ {
+ state.results[key] = output;
}
- return this.regexp
- }
- match (f, partial = this.partial) {
- this.debug('match', f, this.pattern)
- // short-circuit in the case of busted things.
- // comments, etc.
- if (this.comment) return false
- if (this.empty) return f === ''
+ // return salvaged results
+ callback(error, state.results);
+ });
+}
- if (f === '/' && partial) return true
+/**
+ * Runs iterator over provided job element
+ *
+ * @param {function} iterator - iterator to invoke
+ * @param {string|number} key - key/index of the element in the list of jobs
+ * @param {mixed} item - job description
+ * @param {function} callback - invoked after iterator is done with the job
+ * @returns {function|mixed} - job abort function or something else
+ */
+function runJob(iterator, key, item, callback)
+{
+ var aborter;
- const options = this.options
+ // allow shortcut if iterator expects only two arguments
+ if (iterator.length == 2)
+ {
+ aborter = iterator(item, async(callback));
+ }
+ // otherwise go with full three arguments
+ else
+ {
+ aborter = iterator(item, key, async(callback));
+ }
- // windows: need to use /, not \
- if (path.sep !== '/') {
- f = f.split(path.sep).join('/')
- }
+ return aborter;
+}
- // treat the test path as a set of pathparts.
- f = f.split(slashSplit)
- this.debug(this.pattern, 'split', f)
- // just ONE of the pattern sets in this.set needs to match
- // in order for it to be valid. If negating, then just one
- // match means that we have failed.
- // Either way, return on the first hit.
+/***/ }),
- const set = this.set
- this.debug(this.pattern, 'set', set)
+/***/ 2474:
+/***/ ((module) => {
- // Find the basename of the path by looking for the last non-empty segment
- let filename
- for (let i = f.length - 1; i >= 0; i--) {
- filename = f[i]
- if (filename) break
- }
+// API
+module.exports = state;
- for (let i = 0; i < set.length; i++) {
- const pattern = set[i]
- let file = f
- if (options.matchBase && pattern.length === 1) {
- file = [filename]
- }
- const hit = this.matchOne(file, pattern, partial)
- if (hit) {
- if (options.flipNegate) return true
- return !this.negate
- }
+/**
+ * Creates initial state object
+ * for iteration over list
+ *
+ * @param {array|object} list - list to iterate over
+ * @param {function|null} sortMethod - function to use for keys sort,
+ * or `null` to keep them as is
+ * @returns {object} - initial state object
+ */
+function state(list, sortMethod)
+{
+ var isNamedList = !Array.isArray(list)
+ , initState =
+ {
+ index : 0,
+ keyedList: isNamedList || sortMethod ? Object.keys(list) : null,
+ jobs : {},
+ results : isNamedList ? {} : [],
+ size : isNamedList ? Object.keys(list).length : list.length
}
+ ;
- // didn't get any hits. this is success if it's a negative
- // pattern, failure otherwise.
- if (options.flipNegate) return false
- return this.negate
+ if (sortMethod)
+ {
+ // sort array keys based on it's values
+ // sort object's keys just on own merit
+ initState.keyedList.sort(isNamedList ? sortMethod : function(a, b)
+ {
+ return sortMethod(list[a], list[b]);
+ });
}
- static defaults (def) {
- return minimatch.defaults(def).Minimatch
- }
+ return initState;
}
-minimatch.Minimatch = Minimatch
-
/***/ }),
-/***/ 6761:
+/***/ 7942:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const Utils = __nccwpck_require__(5182);
-const pth = __nccwpck_require__(1017);
-const ZipEntry = __nccwpck_require__(4057);
-const ZipFile = __nccwpck_require__(7744);
+var abort = __nccwpck_require__(1700)
+ , async = __nccwpck_require__(2794)
+ ;
-const get_Bool = (val, def) => (typeof val === "boolean" ? val : def);
-const get_Str = (val, def) => (typeof val === "string" ? val : def);
+// API
+module.exports = terminator;
-const defaultOptions = {
- // option "noSort" : if true it disables files sorting
- noSort: false,
- // read entries during load (initial loading may be slower)
- readEntries: false,
- // default method is none
- method: Utils.Constants.NONE,
- // file system
- fs: null
-};
+/**
+ * Terminates jobs in the attached state context
+ *
+ * @this AsyncKitState#
+ * @param {function} callback - final callback to invoke after termination
+ */
+function terminator(callback)
+{
+ if (!Object.keys(this.jobs).length)
+ {
+ return;
+ }
-module.exports = function (/**String*/ input, /** object */ options) {
- let inBuffer = null;
+ // fast forward iteration index
+ this.index = this.size;
- // create object based default options, allowing them to be overwritten
- const opts = Object.assign(Object.create(null), defaultOptions);
+ // abort jobs
+ abort(this);
- // test input variable
- if (input && "object" === typeof input) {
- // if value is not buffer we accept it to be object with options
- if (!(input instanceof Uint8Array)) {
- Object.assign(opts, input);
- input = opts.input ? opts.input : undefined;
- if (opts.input) delete opts.input;
- }
+ // send back results we have so far
+ async(callback)(null, this.results);
+}
- // if input is buffer
- if (Buffer.isBuffer(input)) {
- inBuffer = input;
- opts.method = Utils.Constants.BUFFER;
- input = undefined;
- }
- }
- // assign options
- Object.assign(opts, options);
+/***/ }),
- // instanciate utils filesystem
- const filetools = new Utils(opts);
+/***/ 8210:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // if input is file name we retrieve its content
- if (input && "string" === typeof input) {
- // load zip file
- if (filetools.fs.existsSync(input)) {
- opts.method = Utils.Constants.FILE;
- opts.filename = input;
- inBuffer = filetools.fs.readFileSync(input);
- } else {
- throw new Error(Utils.Errors.INVALID_FILENAME);
- }
- }
+var iterate = __nccwpck_require__(9023)
+ , initState = __nccwpck_require__(2474)
+ , terminator = __nccwpck_require__(7942)
+ ;
- // create variable
- const _zip = new ZipFile(inBuffer, opts);
+// Public API
+module.exports = parallel;
- const { canonical, sanitize } = Utils;
+/**
+ * Runs iterator over provided array elements in parallel
+ *
+ * @param {array|object} list - array or object (named list) to iterate over
+ * @param {function} iterator - iterator to run
+ * @param {function} callback - invoked when all elements processed
+ * @returns {function} - jobs terminator
+ */
+function parallel(list, iterator, callback)
+{
+ var state = initState(list);
- function getEntry(/**Object*/ entry) {
- if (entry && _zip) {
- var item;
- // If entry was given as a file name
- if (typeof entry === "string") item = _zip.getEntry(entry);
- // if entry was given as a ZipEntry object
- if (typeof entry === "object" && typeof entry.entryName !== "undefined" && typeof entry.header !== "undefined") item = _zip.getEntry(entry.entryName);
+ while (state.index < (state['keyedList'] || list).length)
+ {
+ iterate(list, iterator, state, function(error, result)
+ {
+ if (error)
+ {
+ callback(error, result);
+ return;
+ }
- if (item) {
- return item;
- }
- }
- return null;
- }
+ // looks like it's the last one
+ if (Object.keys(state.jobs).length === 0)
+ {
+ callback(null, state.results);
+ return;
+ }
+ });
- function fixPath(zipPath) {
- const { join, normalize, sep } = pth.posix;
- // convert windows file separators and normalize
- return join(".", normalize(sep + zipPath.split("\\").join(sep) + sep));
- }
+ state.index++;
+ }
- 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
- *
- * @return Buffer or Null in case of error
- */
- readFile: function (/**Object*/ entry, /*String, Buffer*/ pass) {
- var item = getEntry(entry);
- return (item && item.getData(pass)) || null;
- },
+ return terminator.bind(state, callback);
+}
- /**
- * Asynchronous readFile
- * @param entry ZipEntry object or String with the full path of the entry
- * @param callback
- *
- * @return Buffer or Null in case of error
- */
- readFileAsync: function (/**Object*/ entry, /**Function*/ callback) {
- var item = getEntry(entry);
- if (item) {
- item.getDataAsync(callback);
- } else {
- callback(null, "getEntry failed for:" + entry);
- }
- },
- /**
- * 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
- *
- * @return String
- */
- readAsText: function (/**Object*/ entry, /**String=*/ encoding) {
- var item = getEntry(entry);
- if (item) {
- var data = item.getData();
- if (data && data.length) {
- return data.toString(encoding || "utf8");
- }
- }
- return "";
- },
+/***/ }),
- /**
- * 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
- *
- * @return String
- */
- readAsTextAsync: function (/**Object*/ entry, /**Function*/ callback, /**String=*/ encoding) {
- var item = getEntry(entry);
- if (item) {
- item.getDataAsync(function (data, err) {
- if (err) {
- callback(data, err);
- return;
- }
+/***/ 445:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- if (data && data.length) {
- callback(data.toString(encoding || "utf8"));
- } else {
- callback("");
- }
- });
- } else {
- callback("");
- }
- },
+var serialOrdered = __nccwpck_require__(3578);
- /**
- * Remove the entry from the file or the entry and all it's nested directories and files if the given entry is a directory
- *
- * @param entry
- */
- deleteFile: function (/**Object*/ entry) {
- // @TODO: test deleteFile
- var item = getEntry(entry);
- if (item) {
- _zip.deleteEntry(item.entryName);
- }
- },
+// Public API
+module.exports = serial;
- /**
- * Adds a comment to the zip. The zip must be rewritten after adding the comment.
- *
- * @param comment
- */
- addZipComment: function (/**String*/ comment) {
- // @TODO: test addZipComment
- _zip.comment = comment;
- },
+/**
+ * Runs iterator over provided array elements in series
+ *
+ * @param {array|object} list - array or object (named list) to iterate over
+ * @param {function} iterator - iterator to run
+ * @param {function} callback - invoked when all elements processed
+ * @returns {function} - jobs terminator
+ */
+function serial(list, iterator, callback)
+{
+ return serialOrdered(list, iterator, null, callback);
+}
- /**
- * Returns the zip comment
- *
- * @return String
- */
- getZipComment: function () {
- return _zip.comment || "";
- },
- /**
- * Adds a comment to a specified zipEntry. The zip must be rewritten after adding the comment
- * The comment cannot exceed 65535 characters in length
- *
- * @param entry
- * @param comment
- */
- addZipEntryComment: function (/**Object*/ entry, /**String*/ comment) {
- var item = getEntry(entry);
- if (item) {
- item.comment = comment;
- }
- },
+/***/ }),
- /**
- * Returns the comment of the specified entry
- *
- * @param entry
- * @return String
- */
- getZipEntryComment: function (/**Object*/ entry) {
- var item = getEntry(entry);
- if (item) {
- return item.comment || "";
- }
- return "";
- },
+/***/ 3578:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- /**
- * Updates the content of an existing entry inside the archive. The zip must be rewritten after updating the content
- *
- * @param entry
- * @param content
- */
- updateFile: function (/**Object*/ entry, /**Buffer*/ content) {
- var item = getEntry(entry);
- if (item) {
- item.setData(content);
- }
- },
+var iterate = __nccwpck_require__(9023)
+ , initState = __nccwpck_require__(2474)
+ , terminator = __nccwpck_require__(7942)
+ ;
- /**
- * Adds a file from the disk to the archive
- *
- * @param localPath File to add to zip
- * @param zipPath Optional path inside the zip
- * @param zipName Optional name for the file
- */
- addLocalFile: function (/**String*/ localPath, /**String=*/ zipPath, /**String=*/ zipName, /**String*/ comment) {
- if (filetools.fs.existsSync(localPath)) {
- // fix ZipPath
- zipPath = zipPath ? fixPath(zipPath) : "";
+// Public API
+module.exports = serialOrdered;
+// sorting helpers
+module.exports.ascending = ascending;
+module.exports.descending = descending;
- // p - local file name
- var p = localPath.split("\\").join("/").split("/").pop();
+/**
+ * Runs iterator over provided sorted array elements in series
+ *
+ * @param {array|object} list - array or object (named list) to iterate over
+ * @param {function} iterator - iterator to run
+ * @param {function} sortMethod - custom sort function
+ * @param {function} callback - invoked when all elements processed
+ * @returns {function} - jobs terminator
+ */
+function serialOrdered(list, iterator, sortMethod, callback)
+{
+ var state = initState(list, sortMethod);
- // add file name into zippath
- zipPath += zipName ? zipName : p;
+ iterate(list, iterator, state, function iteratorHandler(error, result)
+ {
+ if (error)
+ {
+ callback(error, result);
+ return;
+ }
- // read file attributes
- const _attr = filetools.fs.statSync(localPath);
+ state.index++;
- // add file into zip file
- this.addFile(zipPath, filetools.fs.readFileSync(localPath), comment, _attr);
- } else {
- throw new Error(Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath));
- }
- },
+ // are we there yet?
+ if (state.index < (state['keyedList'] || list).length)
+ {
+ iterate(list, iterator, state, iteratorHandler);
+ return;
+ }
- /**
- * 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.
- */
- addLocalFolder: function (/**String*/ localPath, /**String=*/ zipPath, /**=RegExp|Function*/ 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;
- };
- }
+ // done here
+ callback(null, state.results);
+ });
- // fix ZipPath
- zipPath = zipPath ? fixPath(zipPath) : "";
+ return terminator.bind(state, callback);
+}
- // normalize the path first
- localPath = pth.normalize(localPath);
+/*
+ * -- Sort methods
+ */
- if (filetools.fs.existsSync(localPath)) {
- const items = filetools.findFiles(localPath);
- const self = this;
+/**
+ * sort helper to sort array elements in ascending order
+ *
+ * @param {mixed} a - an item to compare
+ * @param {mixed} b - an item to compare
+ * @returns {number} - comparison result
+ */
+function ascending(a, b)
+{
+ return a < b ? -1 : a > b ? 1 : 0;
+}
- if (items.length) {
- items.forEach(function (filepath) {
- var p = pth.relative(localPath, filepath).split("\\").join("/"); //windows fix
- if (filter(p)) {
- var stats = filetools.fs.statSync(filepath);
- if (stats.isFile()) {
- self.addFile(zipPath + p, filetools.fs.readFileSync(filepath), "", stats);
- } else {
- self.addFile(zipPath + p + "/", Buffer.alloc(0), "", stats);
- }
- }
- });
- }
- } else {
- throw new Error(Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath));
- }
- },
+/**
+ * sort helper to sort array elements in descending order
+ *
+ * @param {mixed} a - an item to compare
+ * @param {mixed} b - an item to compare
+ * @returns {number} - comparison result
+ */
+function descending(a, b)
+{
+ return -1 * ascending(a, b);
+}
- /**
- * Asynchronous addLocalFile
- * @param localPath
- * @param callback
- * @param zipPath optional path inside zip
- * @param 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;
- };
- }
- // fix ZipPath
- zipPath = zipPath ? fixPath(zipPath) : "";
+/***/ }),
- // normalize the path first
- localPath = pth.normalize(localPath);
+/***/ 9417:
+/***/ ((module) => {
- var self = this;
- filetools.fs.open(localPath, "r", function (err) {
- if (err && err.code === "ENOENT") {
- callback(undefined, Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath));
- } else if (err) {
- callback(undefined, err);
- } else {
- var items = filetools.findFiles(localPath);
- var i = -1;
+"use strict";
- var next = function () {
- i += 1;
- if (i < items.length) {
- var filepath = items[i];
- var p = pth.relative(localPath, filepath).split("\\").join("/"); //windows fix
- p = p
- .normalize("NFD")
- .replace(/[\u0300-\u036f]/g, "")
- .replace(/[^\x20-\x7E]/g, ""); // accent fix
- if (filter(p)) {
- filetools.fs.stat(filepath, function (er0, stats) {
- if (er0) callback(undefined, er0);
- if (stats.isFile()) {
- filetools.fs.readFile(filepath, function (er1, data) {
- if (er1) {
- callback(undefined, er1);
- } else {
- self.addFile(zipPath + p, data, "", stats);
- next();
- }
- });
- } else {
- self.addFile(zipPath + p + "/", Buffer.alloc(0), "", stats);
- next();
- }
- });
- } else {
- next();
- }
- } else {
- callback(true, undefined);
- }
- };
+module.exports = balanced;
+function balanced(a, b, str) {
+ if (a instanceof RegExp) a = maybeMatch(a, str);
+ if (b instanceof RegExp) b = maybeMatch(b, str);
- next();
- }
- });
- },
+ var r = range(a, b, str);
- /**
- *
- * @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.
- */
- addLocalFolderPromise: function (/*String*/ localPath, /* object */ 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
- );
- });
- },
+ return r && {
+ start: r[0],
+ end: r[1],
+ pre: str.slice(0, r[0]),
+ body: str.slice(r[0] + a.length, r[1]),
+ post: str.slice(r[1] + b.length)
+ };
+}
- /**
- * Allows you to create a entry (file or directory) in the zip file.
- * If you want to create a directory the entryName must end in / and a null buffer should be provided.
- * Comment and attributes are optional
- *
- * @param {string} entryName
- * @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
- */
- addFile: function (/**String*/ entryName, /**Buffer*/ content, /**String*/ comment, /**Number*/ attr) {
- let entry = getEntry(entryName);
- const update = entry != null;
+function maybeMatch(reg, str) {
+ var m = str.match(reg);
+ return m ? m[0] : null;
+}
- // prepare new entry
- if (!update) {
- entry = new ZipEntry();
- entry.entryName = entryName;
- }
- entry.comment = comment || "";
+balanced.range = range;
+function range(a, b, str) {
+ var begs, beg, left, right, result;
+ var ai = str.indexOf(a);
+ var bi = str.indexOf(b, ai + 1);
+ var i = ai;
- const isStat = "object" === typeof attr && attr instanceof filetools.fs.Stats;
+ if (ai >= 0 && bi > 0) {
+ if(a===b) {
+ return [ai, bi];
+ }
+ begs = [];
+ left = str.length;
- // last modification time from file stats
- if (isStat) {
- entry.header.time = attr.mtime;
- }
+ while (i >= 0 && !result) {
+ if (i == ai) {
+ begs.push(i);
+ ai = str.indexOf(a, i + 1);
+ } else if (begs.length == 1) {
+ result = [ begs.pop(), bi ];
+ } else {
+ beg = begs.pop();
+ if (beg < left) {
+ left = beg;
+ right = bi;
+ }
- // Set file attribute
- var fileattr = entry.isDirectory ? 0x10 : 0; // (MS-DOS directory flag)
+ bi = str.indexOf(b, i + 1);
+ }
- // extended attributes field for Unix
- if (!Utils.isWin) {
- // set file type either S_IFDIR / S_IFREG
- let unix = entry.isDirectory ? 0x4000 : 0x8000;
-
- if (isStat) {
- // File attributes from file stats
- unix |= 0xfff & attr.mode;
- } else if ("number" === typeof attr) {
- // attr from given attr values
- unix |= 0xfff & attr;
- } else {
- // Default values:
- unix |= entry.isDirectory ? 0o755 : 0o644; // permissions (drwxr-xr-x) or (-r-wr--r--)
- }
+ i = ai < bi && ai >= 0 ? ai : bi;
+ }
- fileattr = (fileattr | (unix << 16)) >>> 0; // add attributes
- }
+ if (begs.length) {
+ result = [ left, right ];
+ }
+ }
- entry.attr = fileattr;
+ return result;
+}
- entry.setData(content);
- if (!update) _zip.setEntry(entry);
- },
- /**
- * Returns an array of ZipEntry objects representing the files and folders inside the archive
- *
- * @return Array
- */
- getEntries: function () {
- return _zip ? _zip.entries : [];
- },
+/***/ }),
- /**
- * Returns a ZipEntry object representing the file or folder specified by ``name``.
- *
- * @param name
- * @return ZipEntry
- */
- getEntry: function (/**String*/ name) {
- return getEntry(name);
- },
+/***/ 5443:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- getEntryCount: function () {
- return _zip.getEntryCount();
- },
+var util = __nccwpck_require__(3837);
+var Stream = (__nccwpck_require__(2781).Stream);
+var DelayedStream = __nccwpck_require__(8611);
- forEach: function (callback) {
- return _zip.forEach(callback);
- },
+module.exports = CombinedStream;
+function CombinedStream() {
+ this.writable = false;
+ this.readable = true;
+ this.dataSize = 0;
+ this.maxDataSize = 2 * 1024 * 1024;
+ this.pauseStreams = true;
- /**
- * Extracts the given entry to the given targetPath
- * If the entry is a directory inside the archive, the entire directory and it's subdirectories will be extracted
- *
- * @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)
- *
- * @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));
+ this._released = false;
+ this._streams = [];
+ this._currentStream = null;
+ this._insideLoop = false;
+ this._pendingNext = false;
+}
+util.inherits(CombinedStream, Stream);
- var item = getEntry(entry);
- if (!item) {
- throw new Error(Utils.Errors.NO_ENTRY);
- }
-
- var entryName = canonical(item.entryName);
+CombinedStream.create = function(options) {
+ var combinedStream = new this();
- var target = sanitize(targetPath, outFileName && !item.isDirectory ? outFileName : maintainEntryPath ? entryName : pth.basename(entryName));
+ options = options || {};
+ for (var option in options) {
+ combinedStream[option] = options[option];
+ }
- if (item.isDirectory) {
- var children = _zip.getEntryChildren(item);
- children.forEach(function (child) {
- if (child.isDirectory) return;
- var content = child.getData();
- if (!content) {
- throw new Error(Utils.Errors.CANT_EXTRACT_FILE);
- }
- var name = canonical(child.entryName);
- var childName = sanitize(targetPath, maintainEntryPath ? name : pth.basename(name));
- // The reverse operation for attr depend on method addFile()
- const fileAttr = keepOriginalPermission ? child.header.fileAttr : undefined;
- filetools.writeFileTo(childName, content, overwrite, fileAttr);
- });
- return true;
- }
+ return combinedStream;
+};
- var content = item.getData();
- if (!content) throw new Error(Utils.Errors.CANT_EXTRACT_FILE);
+CombinedStream.isStreamLike = function(stream) {
+ return (typeof stream !== 'function')
+ && (typeof stream !== 'string')
+ && (typeof stream !== 'boolean')
+ && (typeof stream !== 'number')
+ && (!Buffer.isBuffer(stream));
+};
- if (filetools.fs.existsSync(target) && !overwrite) {
- throw new Error(Utils.Errors.CANT_OVERRIDE);
- }
- // The reverse operation for attr depend on method addFile()
- const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;
- filetools.writeFileTo(target, content, overwrite, fileAttr);
+CombinedStream.prototype.append = function(stream) {
+ var isStreamLike = CombinedStream.isStreamLike(stream);
- return true;
- },
+ if (isStreamLike) {
+ if (!(stream instanceof DelayedStream)) {
+ var newStream = DelayedStream.create(stream, {
+ maxDataSize: Infinity,
+ pauseStream: this.pauseStreams,
+ });
+ stream.on('data', this._checkDataSize.bind(this));
+ stream = newStream;
+ }
- /**
- * Test the archive
- *
- */
- test: function (pass) {
- if (!_zip) {
- return false;
- }
+ this._handleErrors(stream);
- for (var entry in _zip.entries) {
- try {
- if (entry.isDirectory) {
- continue;
- }
- var content = _zip.entries[entry].getData(pass);
- if (!content) {
- return false;
- }
- } catch (err) {
- return false;
- }
- }
- return true;
- },
+ if (this.pauseStreams) {
+ stream.pause();
+ }
+ }
- /**
- * Extracts the entire archive to the given location
- *
- * @param targetPath Target location
- * @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
- */
- extractAllTo: function (/**String*/ targetPath, /**Boolean*/ overwrite, /**Boolean*/ keepOriginalPermission, /*String, Buffer*/ pass) {
- overwrite = get_Bool(overwrite, false);
- pass = get_Str(keepOriginalPermission, pass);
- keepOriginalPermission = get_Bool(keepOriginalPermission, false);
- if (!_zip) {
- throw new Error(Utils.Errors.NO_ZIP);
- }
- _zip.entries.forEach(function (entry) {
- var entryName = sanitize(targetPath, canonical(entry.entryName.toString()));
- if (entry.isDirectory) {
- filetools.makeDir(entryName);
- return;
- }
- var content = entry.getData(pass);
- if (!content) {
- throw new Error(Utils.Errors.CANT_EXTRACT_FILE);
- }
- // The reverse operation for attr depend on method addFile()
- const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;
- filetools.writeFileTo(entryName, content, overwrite, fileAttr);
- try {
- filetools.fs.utimesSync(entryName, entry.header.time, entry.header.time);
- } catch (err) {
- throw new Error(Utils.Errors.CANT_EXTRACT_FILE);
- }
- });
- },
+ this._streams.push(stream);
+ return this;
+};
- /**
- * Asynchronous extractAllTo
- *
- * @param targetPath Target location
- * @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 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 (!callback) {
- callback = function () {};
- }
- overwrite = get_Bool(overwrite, false);
- if (typeof keepOriginalPermission === "function" && !callback) callback = keepOriginalPermission;
- keepOriginalPermission = get_Bool(keepOriginalPermission, false);
- if (!_zip) {
- callback(new Error(Utils.Errors.NO_ZIP));
- return;
- }
+CombinedStream.prototype.pipe = function(dest, options) {
+ Stream.prototype.pipe.call(this, dest, options);
+ this.resume();
+ return dest;
+};
- targetPath = pth.resolve(targetPath);
- // convert entryName to
- const getPath = (entry) => sanitize(targetPath, pth.normalize(canonical(entry.entryName.toString())));
- const getError = (msg, file) => new Error(msg + ': "' + file + '"');
+CombinedStream.prototype._getNext = function() {
+ this._currentStream = null;
- // separate directories from files
- const dirEntries = [];
- const fileEntries = new Set();
- _zip.entries.forEach((e) => {
- if (e.isDirectory) {
- dirEntries.push(e);
- } else {
- fileEntries.add(e);
- }
- });
+ if (this._insideLoop) {
+ this._pendingNext = true;
+ return; // defer call
+ }
- // Create directory entries first synchronously
- // this prevents race condition and assures folders are there before writing files
- for (const entry of dirEntries) {
- const dirPath = getPath(entry);
- // The reverse operation for attr depend on method addFile()
- const dirAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;
- try {
- filetools.makeDir(dirPath);
- if (dirAttr) filetools.fs.chmodSync(dirPath, dirAttr);
- // in unix timestamp will change if files are later added to folder, but still
- filetools.fs.utimesSync(dirPath, entry.header.time, entry.header.time);
- } catch (er) {
- callback(getError("Unable to create folder", dirPath));
- }
- }
+ this._insideLoop = true;
+ try {
+ do {
+ this._pendingNext = false;
+ this._realGetNext();
+ } while (this._pendingNext);
+ } finally {
+ this._insideLoop = false;
+ }
+};
- // callback wrapper, for some house keeping
- const done = () => {
- if (fileEntries.size === 0) {
- callback();
- }
- };
+CombinedStream.prototype._realGetNext = function() {
+ var stream = this._streams.shift();
- // Extract file entries asynchronously
- for (const entry of fileEntries.values()) {
- const entryName = pth.normalize(canonical(entry.entryName.toString()));
- const filePath = sanitize(targetPath, entryName);
- entry.getDataAsync(function (content, err_1) {
- if (err_1) {
- callback(new Error(err_1));
- return;
- }
- if (!content) {
- callback(new Error(Utils.Errors.CANT_EXTRACT_FILE));
- } else {
- // The reverse operation for attr depend on method addFile()
- const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;
- filetools.writeFileToAsync(filePath, content, overwrite, fileAttr, function (succ) {
- if (!succ) {
- callback(getError("Unable to write file", filePath));
- return;
- }
- filetools.fs.utimes(filePath, entry.header.time, entry.header.time, function (err_2) {
- if (err_2) {
- callback(getError("Unable to set times", filePath));
- return;
- }
- fileEntries.delete(entry);
- // call the callback if it was last entry
- done();
- });
- });
- }
- });
- }
- // call the callback if fileEntries was empty
- done();
- },
- /**
- * Writes the newly created zip file to disk at the specified location or if a zip was opened and no ``targetFileName`` is provided, it will overwrite the opened zip
- *
- * @param targetFileName
- * @param callback
- */
- writeZip: function (/**String*/ targetFileName, /**Function*/ callback) {
- if (arguments.length === 1) {
- if (typeof targetFileName === "function") {
- callback = targetFileName;
- targetFileName = "";
- }
- }
+ if (typeof stream == 'undefined') {
+ this.end();
+ return;
+ }
- if (!targetFileName && opts.filename) {
- targetFileName = opts.filename;
- }
- if (!targetFileName) return;
+ if (typeof stream !== 'function') {
+ this._pipeNext(stream);
+ return;
+ }
- var zipData = _zip.compressToBuffer();
- if (zipData) {
- var ok = filetools.writeFileTo(targetFileName, zipData, true);
- if (typeof callback === "function") callback(!ok ? new Error("failed") : null, "");
- }
- },
+ var getStream = stream;
+ getStream(function(stream) {
+ var isStreamLike = CombinedStream.isStreamLike(stream);
+ if (isStreamLike) {
+ stream.on('data', this._checkDataSize.bind(this));
+ this._handleErrors(stream);
+ }
- writeZipPromise: function (/**String*/ targetFileName, /* object */ props) {
- const { overwrite, perm } = Object.assign({ overwrite: true }, props);
+ this._pipeNext(stream);
+ }.bind(this));
+};
- return new Promise((resolve, reject) => {
- // find file name
- if (!targetFileName && opts.filename) targetFileName = opts.filename;
- if (!targetFileName) reject("ADM-ZIP: ZIP File Name Missing");
+CombinedStream.prototype._pipeNext = function(stream) {
+ this._currentStream = stream;
- this.toBufferPromise().then((zipData) => {
- const ret = (done) => (done ? resolve(done) : reject("ADM-ZIP: Wasn't able to write zip file"));
- filetools.writeFileToAsync(targetFileName, zipData, overwrite, perm, ret);
- }, reject);
- });
- },
+ var isStreamLike = CombinedStream.isStreamLike(stream);
+ if (isStreamLike) {
+ stream.on('end', this._getNext.bind(this));
+ stream.pipe(this, {end: false});
+ return;
+ }
- toBufferPromise: function () {
- return new Promise((resolve, reject) => {
- _zip.toAsyncBuffer(resolve, reject);
- });
- },
+ var value = stream;
+ this.write(value);
+ this._getNext();
+};
- /**
- * Returns the content of the entire zip file as a Buffer object
- *
- * @return Buffer
- */
- toBuffer: function (/**Function=*/ onSuccess, /**Function=*/ onFail, /**Function=*/ onItemStart, /**Function=*/ onItemEnd) {
- this.valueOf = 2;
- if (typeof onSuccess === "function") {
- _zip.toAsyncBuffer(onSuccess, onFail, onItemStart, onItemEnd);
- return null;
- }
- return _zip.compressToBuffer();
- }
- };
+CombinedStream.prototype._handleErrors = function(stream) {
+ var self = this;
+ stream.on('error', function(err) {
+ self._emitError(err);
+ });
};
+CombinedStream.prototype.write = function(data) {
+ this.emit('data', data);
+};
-/***/ }),
+CombinedStream.prototype.pause = function() {
+ if (!this.pauseStreams) {
+ return;
+ }
-/***/ 9032:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause();
+ this.emit('pause');
+};
-var Utils = __nccwpck_require__(5182),
- Constants = Utils.Constants;
+CombinedStream.prototype.resume = function() {
+ if (!this._released) {
+ this._released = true;
+ this.writable = true;
+ this._getNext();
+ }
-/* The central directory file header */
-module.exports = function () {
- var _verMade = 20, // v2.0
- _version = 10, // v1.0
- _flags = 0,
- _method = 0,
- _time = 0,
- _crc = 0,
- _compressedSize = 0,
- _size = 0,
- _fnameLen = 0,
- _extraLen = 0,
- _comLen = 0,
- _diskStart = 0,
- _inattr = 0,
- _attr = 0,
- _offset = 0;
+ if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume();
+ this.emit('resume');
+};
- _verMade |= Utils.isWin ? 0x0a00 : 0x0300;
+CombinedStream.prototype.end = function() {
+ this._reset();
+ this.emit('end');
+};
- // Set EFS flag since filename and comment fields are all by default encoded using UTF-8.
- // Without it file names may be corrupted for other apps when file names use unicode chars
- _flags |= Constants.FLG_EFS;
+CombinedStream.prototype.destroy = function() {
+ this._reset();
+ this.emit('close');
+};
- var _dataHeader = {};
+CombinedStream.prototype._reset = function() {
+ this.writable = false;
+ this._streams = [];
+ this._currentStream = null;
+};
- 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
- }
+CombinedStream.prototype._checkDataSize = function() {
+ this._updateDataSize();
+ if (this.dataSize <= this.maxDataSize) {
+ return;
+ }
- setTime(+new Date());
+ var message =
+ 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.';
+ this._emitError(new Error(message));
+};
- return {
- get made() {
- return _verMade;
- },
- set made(val) {
- _verMade = val;
- },
+CombinedStream.prototype._updateDataSize = function() {
+ this.dataSize = 0;
- get version() {
- return _version;
- },
- set version(val) {
- _version = val;
- },
+ var self = this;
+ this._streams.forEach(function(stream) {
+ if (!stream.dataSize) {
+ return;
+ }
- get flags() {
- return _flags;
- },
- set flags(val) {
- _flags = val;
- },
+ self.dataSize += stream.dataSize;
+ });
- get method() {
- return _method;
- },
- set method(val) {
- switch (val) {
- case Constants.STORED:
- this.version = 10;
- case Constants.DEFLATED:
- default:
- this.version = 20;
- }
- _method = val;
- },
+ if (this._currentStream && this._currentStream.dataSize) {
+ this.dataSize += this._currentStream.dataSize;
+ }
+};
- 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);
- },
- set time(val) {
- setTime(val);
- },
+CombinedStream.prototype._emitError = function(err) {
+ this._reset();
+ this.emit('error', err);
+};
- get crc() {
- return _crc;
- },
- set crc(val) {
- _crc = Math.max(0, val) >>> 0;
- },
- get compressedSize() {
- return _compressedSize;
- },
- set compressedSize(val) {
- _compressedSize = Math.max(0, val) >>> 0;
- },
+/***/ }),
- get size() {
- return _size;
- },
- set size(val) {
- _size = Math.max(0, val) >>> 0;
- },
+/***/ 8222:
+/***/ ((module, exports, __nccwpck_require__) => {
- get fileNameLength() {
- return _fnameLen;
- },
- set fileNameLength(val) {
- _fnameLen = val;
- },
+/* eslint-env browser */
- get extraLength() {
- return _extraLen;
- },
- set extraLength(val) {
- _extraLen = val;
- },
+/**
+ * This is the web browser implementation of `debug()`.
+ */
- get commentLength() {
- return _comLen;
- },
- set commentLength(val) {
- _comLen = val;
- },
+exports.formatArgs = formatArgs;
+exports.save = save;
+exports.load = load;
+exports.useColors = useColors;
+exports.storage = localstorage();
+exports.destroy = (() => {
+ let warned = false;
- get diskNumStart() {
- return _diskStart;
- },
- set diskNumStart(val) {
- _diskStart = Math.max(0, val) >>> 0;
- },
-
- get inAttr() {
- return _inattr;
- },
- set inAttr(val) {
- _inattr = Math.max(0, val) >>> 0;
- },
-
- get attr() {
- return _attr;
- },
- set attr(val) {
- _attr = Math.max(0, val) >>> 0;
- },
-
- // get Unix file permissions
- get fileAttr() {
- return _attr ? (((_attr >>> 0) | 0) >> 16) & 0xfff : 0;
- },
-
- get offset() {
- return _offset;
- },
- set offset(val) {
- _offset = Math.max(0, val) >>> 0;
- },
-
- get encripted() {
- return (_flags & 1) === 1;
- },
-
- get entryHeaderSize() {
- return Constants.CENHDR + _fnameLen + _extraLen + _comLen;
- },
-
- get realDataOffset() {
- return _offset + Constants.LOCHDR + _dataHeader.fnameLen + _dataHeader.extraLen;
- },
-
- get dataHeader() {
- return _dataHeader;
- },
-
- loadDataHeaderFromBinary: function (/*Buffer*/ input) {
- var data = input.slice(_offset, _offset + Constants.LOCHDR);
- // 30 bytes and should start with "PK\003\004"
- if (data.readUInt32LE(0) !== Constants.LOCSIG) {
- throw new Error(Utils.Errors.INVALID_LOC);
- }
- _dataHeader = {
- // 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)
- };
- },
-
- loadFromBinary: function (/*Buffer*/ data) {
- // data should be 46 bytes and start with "PK 01 02"
- if (data.length !== Constants.CENHDR || data.readUInt32LE(0) !== Constants.CENSIG) {
- throw new Error(Utils.Errors.INVALID_CEN);
- }
- // version made by
- _verMade = data.readUInt16LE(Constants.CENVEM);
- // version needed to extract
- _version = data.readUInt16LE(Constants.CENVER);
- // encrypt, decrypt flags
- _flags = data.readUInt16LE(Constants.CENFLG);
- // compression method
- _method = data.readUInt16LE(Constants.CENHOW);
- // modification time (2 bytes time, 2 bytes date)
- _time = data.readUInt32LE(Constants.CENTIM);
- // uncompressed file crc-32 value
- _crc = data.readUInt32LE(Constants.CENCRC);
- // compressed size
- _compressedSize = data.readUInt32LE(Constants.CENSIZ);
- // uncompressed size
- _size = data.readUInt32LE(Constants.CENLEN);
- // filename length
- _fnameLen = data.readUInt16LE(Constants.CENNAM);
- // extra field length
- _extraLen = data.readUInt16LE(Constants.CENEXT);
- // file comment length
- _comLen = data.readUInt16LE(Constants.CENCOM);
- // volume number start
- _diskStart = data.readUInt16LE(Constants.CENDSK);
- // internal file attributes
- _inattr = data.readUInt16LE(Constants.CENATT);
- // external file attributes
- _attr = data.readUInt32LE(Constants.CENATX);
- // LOC header offset
- _offset = data.readUInt32LE(Constants.CENOFF);
- },
-
- dataHeaderToBinary: function () {
- // LOC header size (30 bytes)
- var data = Buffer.alloc(Constants.LOCHDR);
- // "PK\003\004"
- data.writeUInt32LE(Constants.LOCSIG, 0);
- // version needed to extract
- data.writeUInt16LE(_version, Constants.LOCVER);
- // general purpose bit flag
- data.writeUInt16LE(_flags, Constants.LOCFLG);
- // compression method
- data.writeUInt16LE(_method, Constants.LOCHOW);
- // modification time (2 bytes time, 2 bytes date)
- data.writeUInt32LE(_time, Constants.LOCTIM);
- // uncompressed file crc-32 value
- data.writeUInt32LE(_crc, Constants.LOCCRC);
- // compressed size
- data.writeUInt32LE(_compressedSize, Constants.LOCSIZ);
- // uncompressed size
- data.writeUInt32LE(_size, Constants.LOCLEN);
- // filename length
- data.writeUInt16LE(_fnameLen, Constants.LOCNAM);
- // extra field length
- data.writeUInt16LE(_extraLen, Constants.LOCEXT);
- return data;
- },
-
- entryHeaderToBinary: function () {
- // CEN header size (46 bytes)
- var data = Buffer.alloc(Constants.CENHDR + _fnameLen + _extraLen + _comLen);
- // "PK\001\002"
- data.writeUInt32LE(Constants.CENSIG, 0);
- // version made by
- data.writeUInt16LE(_verMade, Constants.CENVEM);
- // version needed to extract
- data.writeUInt16LE(_version, Constants.CENVER);
- // encrypt, decrypt flags
- data.writeUInt16LE(_flags, Constants.CENFLG);
- // compression method
- data.writeUInt16LE(_method, Constants.CENHOW);
- // modification time (2 bytes time, 2 bytes date)
- data.writeUInt32LE(_time, Constants.CENTIM);
- // uncompressed file crc-32 value
- data.writeUInt32LE(_crc, Constants.CENCRC);
- // compressed size
- data.writeUInt32LE(_compressedSize, Constants.CENSIZ);
- // uncompressed size
- data.writeUInt32LE(_size, Constants.CENLEN);
- // filename length
- data.writeUInt16LE(_fnameLen, Constants.CENNAM);
- // extra field length
- data.writeUInt16LE(_extraLen, Constants.CENEXT);
- // file comment length
- data.writeUInt16LE(_comLen, Constants.CENCOM);
- // volume number start
- data.writeUInt16LE(_diskStart, Constants.CENDSK);
- // internal file attributes
- data.writeUInt16LE(_inattr, Constants.CENATT);
- // external file attributes
- data.writeUInt32LE(_attr, Constants.CENATX);
- // LOC header offset
- data.writeUInt32LE(_offset, Constants.CENOFF);
- // fill all with
- data.fill(0x00, Constants.CENHDR);
- return data;
- },
-
- toJSON: function () {
- const bytes = function (nr) {
- return nr + " bytes";
- };
-
- return {
- made: _verMade,
- version: _version,
- flags: _flags,
- method: Utils.methodToString(_method),
- time: this.time,
- crc: "0x" + _crc.toString(16).toUpperCase(),
- compressedSize: bytes(_compressedSize),
- size: bytes(_size),
- fileNameLength: bytes(_fnameLen),
- extraLength: bytes(_extraLen),
- commentLength: bytes(_comLen),
- diskNumStart: _diskStart,
- inAttr: _inattr,
- attr: _attr,
- offset: _offset,
- entryHeaderSize: bytes(Constants.CENHDR + _fnameLen + _extraLen + _comLen)
- };
- },
-
- toString: function () {
- return JSON.stringify(this.toJSON(), null, "\t");
- }
- };
-};
+ return () => {
+ if (!warned) {
+ warned = true;
+ console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
+ }
+ };
+})();
+/**
+ * Colors.
+ */
-/***/ }),
+exports.colors = [
+ '#0000CC',
+ '#0000FF',
+ '#0033CC',
+ '#0033FF',
+ '#0066CC',
+ '#0066FF',
+ '#0099CC',
+ '#0099FF',
+ '#00CC00',
+ '#00CC33',
+ '#00CC66',
+ '#00CC99',
+ '#00CCCC',
+ '#00CCFF',
+ '#3300CC',
+ '#3300FF',
+ '#3333CC',
+ '#3333FF',
+ '#3366CC',
+ '#3366FF',
+ '#3399CC',
+ '#3399FF',
+ '#33CC00',
+ '#33CC33',
+ '#33CC66',
+ '#33CC99',
+ '#33CCCC',
+ '#33CCFF',
+ '#6600CC',
+ '#6600FF',
+ '#6633CC',
+ '#6633FF',
+ '#66CC00',
+ '#66CC33',
+ '#9900CC',
+ '#9900FF',
+ '#9933CC',
+ '#9933FF',
+ '#99CC00',
+ '#99CC33',
+ '#CC0000',
+ '#CC0033',
+ '#CC0066',
+ '#CC0099',
+ '#CC00CC',
+ '#CC00FF',
+ '#CC3300',
+ '#CC3333',
+ '#CC3366',
+ '#CC3399',
+ '#CC33CC',
+ '#CC33FF',
+ '#CC6600',
+ '#CC6633',
+ '#CC9900',
+ '#CC9933',
+ '#CCCC00',
+ '#CCCC33',
+ '#FF0000',
+ '#FF0033',
+ '#FF0066',
+ '#FF0099',
+ '#FF00CC',
+ '#FF00FF',
+ '#FF3300',
+ '#FF3333',
+ '#FF3366',
+ '#FF3399',
+ '#FF33CC',
+ '#FF33FF',
+ '#FF6600',
+ '#FF6633',
+ '#FF9900',
+ '#FF9933',
+ '#FFCC00',
+ '#FFCC33'
+];
-/***/ 4958:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/**
+ * Currently only WebKit-based Web Inspectors, Firefox >= v31,
+ * and the Firebug extension (any Firefox version) are known
+ * to support "%c" CSS customizations.
+ *
+ * TODO: add a `localStorage` variable to explicitly enable/disable colors
+ */
-exports.EntryHeader = __nccwpck_require__(9032);
-exports.MainHeader = __nccwpck_require__(4408);
+// eslint-disable-next-line complexity
+function useColors() {
+ // NB: In an Electron preload script, document will be defined but not fully
+ // initialized. Since we know we're in Chrome, we'll just detect this case
+ // explicitly
+ if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
+ return true;
+ }
+ // Internet Explorer and Edge do not support colors.
+ if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
+ return false;
+ }
-/***/ }),
+ // Is webkit? http://stackoverflow.com/a/16459606/376773
+ // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
+ return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
+ // Is firebug? http://stackoverflow.com/a/398120/376773
+ (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
+ // Is firefox >= v31?
+ // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
+ (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
+ // Double check webkit in userAgent just in case we are in a worker
+ (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
+}
-/***/ 4408:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/**
+ * Colorize log arguments if enabled.
+ *
+ * @api public
+ */
-var Utils = __nccwpck_require__(5182),
- Constants = Utils.Constants;
+function formatArgs(args) {
+ args[0] = (this.useColors ? '%c' : '') +
+ this.namespace +
+ (this.useColors ? ' %c' : ' ') +
+ args[0] +
+ (this.useColors ? '%c ' : ' ') +
+ '+' + module.exports.humanize(this.diff);
-/* The entries in the end of central directory */
-module.exports = function () {
- var _volumeEntries = 0,
- _totalEntries = 0,
- _size = 0,
- _offset = 0,
- _commentLength = 0;
+ if (!this.useColors) {
+ return;
+ }
- return {
- get diskEntries() {
- return _volumeEntries;
- },
- set diskEntries(/*Number*/ val) {
- _volumeEntries = _totalEntries = val;
- },
+ const c = 'color: ' + this.color;
+ args.splice(1, 0, c, 'color: inherit');
- get totalEntries() {
- return _totalEntries;
- },
- set totalEntries(/*Number*/ val) {
- _totalEntries = _volumeEntries = val;
- },
+ // The final "%c" is somewhat tricky, because there could be other
+ // arguments passed either before or after the %c, so we need to
+ // figure out the correct index to insert the CSS into
+ let index = 0;
+ let lastC = 0;
+ args[0].replace(/%[a-zA-Z%]/g, match => {
+ if (match === '%%') {
+ return;
+ }
+ index++;
+ if (match === '%c') {
+ // We only are interested in the *last* %c
+ // (the user may have provided their own)
+ lastC = index;
+ }
+ });
- get size() {
- return _size;
- },
- set size(/*Number*/ val) {
- _size = val;
- },
+ args.splice(lastC, 0, c);
+}
- get offset() {
- return _offset;
- },
- set offset(/*Number*/ val) {
- _offset = val;
- },
+/**
+ * Invokes `console.debug()` when available.
+ * No-op when `console.debug` is not a "function".
+ * If `console.debug` is not available, falls back
+ * to `console.log`.
+ *
+ * @api public
+ */
+exports.log = console.debug || console.log || (() => {});
- get commentLength() {
- return _commentLength;
- },
- set commentLength(/*Number*/ val) {
- _commentLength = val;
- },
+/**
+ * Save `namespaces`.
+ *
+ * @param {String} namespaces
+ * @api private
+ */
+function save(namespaces) {
+ try {
+ if (namespaces) {
+ exports.storage.setItem('debug', namespaces);
+ } else {
+ exports.storage.removeItem('debug');
+ }
+ } catch (error) {
+ // Swallow
+ // XXX (@Qix-) should we be logging these?
+ }
+}
- get mainHeaderSize() {
- return Constants.ENDHDR + _commentLength;
- },
+/**
+ * Load `namespaces`.
+ *
+ * @return {String} returns the previously persisted debug modes
+ * @api private
+ */
+function load() {
+ let r;
+ try {
+ r = exports.storage.getItem('debug');
+ } catch (error) {
+ // Swallow
+ // XXX (@Qix-) should we be logging these?
+ }
- loadFromBinary: function (/*Buffer*/ data) {
- // data should be 22 bytes and start with "PK 05 06"
- // or be 56+ bytes and start with "PK 06 06" for Zip64
- if (
- (data.length !== Constants.ENDHDR || data.readUInt32LE(0) !== Constants.ENDSIG) &&
- (data.length < Constants.ZIP64HDR || data.readUInt32LE(0) !== Constants.ZIP64SIG)
- ) {
- throw new Error(Utils.Errors.INVALID_END);
- }
+ // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
+ if (!r && typeof process !== 'undefined' && 'env' in process) {
+ r = process.env.DEBUG;
+ }
- if (data.readUInt32LE(0) === Constants.ENDSIG) {
- // number of entries on this volume
- _volumeEntries = data.readUInt16LE(Constants.ENDSUB);
- // total number of entries
- _totalEntries = data.readUInt16LE(Constants.ENDTOT);
- // central directory size in bytes
- _size = data.readUInt32LE(Constants.ENDSIZ);
- // offset of first CEN header
- _offset = data.readUInt32LE(Constants.ENDOFF);
- // zip file comment length
- _commentLength = data.readUInt16LE(Constants.ENDCOM);
- } else {
- // number of entries on this volume
- _volumeEntries = Utils.readBigUInt64LE(data, Constants.ZIP64SUB);
- // total number of entries
- _totalEntries = Utils.readBigUInt64LE(data, Constants.ZIP64TOT);
- // central directory size in bytes
- _size = Utils.readBigUInt64LE(data, Constants.ZIP64SIZ);
- // offset of first CEN header
- _offset = Utils.readBigUInt64LE(data, Constants.ZIP64OFF);
+ return r;
+}
- _commentLength = 0;
- }
- },
+/**
+ * Localstorage attempts to return the localstorage.
+ *
+ * This is necessary because safari throws
+ * when a user disables cookies/localstorage
+ * and you attempt to access it.
+ *
+ * @return {LocalStorage}
+ * @api private
+ */
- toBinary: function () {
- var b = Buffer.alloc(Constants.ENDHDR + _commentLength);
- // "PK 05 06" signature
- b.writeUInt32LE(Constants.ENDSIG, 0);
- b.writeUInt32LE(0, 4);
- // number of entries on this volume
- b.writeUInt16LE(_volumeEntries, Constants.ENDSUB);
- // total number of entries
- b.writeUInt16LE(_totalEntries, Constants.ENDTOT);
- // central directory size in bytes
- b.writeUInt32LE(_size, Constants.ENDSIZ);
- // offset of first CEN header
- b.writeUInt32LE(_offset, Constants.ENDOFF);
- // zip file comment length
- b.writeUInt16LE(_commentLength, Constants.ENDCOM);
- // fill comment memory with spaces so no garbage is left there
- b.fill(" ", Constants.ENDHDR);
+function localstorage() {
+ try {
+ // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
+ // The Browser also has localStorage in the global context.
+ return localStorage;
+ } catch (error) {
+ // Swallow
+ // XXX (@Qix-) should we be logging these?
+ }
+}
- return b;
- },
+module.exports = __nccwpck_require__(6243)(exports);
- toJSON: function () {
- // creates 0x0000 style output
- const offset = function (nr, len) {
- let offs = nr.toString(16).toUpperCase();
- while (offs.length < len) offs = "0" + offs;
- return "0x" + offs;
- };
+const {formatters} = module.exports;
- return {
- diskEntries: _volumeEntries,
- totalEntries: _totalEntries,
- size: _size + " bytes",
- offset: offset(_offset, 4),
- commentLength: _commentLength
- };
- },
+/**
+ * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
+ */
- toString: function () {
- return JSON.stringify(this.toJSON(), null, "\t");
- }
- };
+formatters.j = function (v) {
+ try {
+ return JSON.stringify(v);
+ } catch (error) {
+ return '[UnexpectedJSONParseError]: ' + error.message;
+ }
};
/***/ }),
-/***/ 7686:
+/***/ 6243:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-module.exports = function (/*Buffer*/ inbuf) {
- var zlib = __nccwpck_require__(9796);
-
- var opts = { chunkSize: (parseInt(inbuf.length / 1024) + 1) * 1024 };
-
- return {
- deflate: function () {
- return zlib.deflateRawSync(inbuf, opts);
- },
-
- deflateAsync: function (/*Function*/ callback) {
- var tmp = zlib.createDeflateRaw(opts),
- parts = [],
- total = 0;
- tmp.on("data", function (data) {
- parts.push(data);
- total += data.length;
- });
- tmp.on("end", function () {
- var buf = Buffer.alloc(total),
- written = 0;
- buf.fill(0);
- for (var i = 0; i < parts.length; i++) {
- var part = parts[i];
- part.copy(buf, written);
- written += part.length;
- }
- callback && callback(buf);
- });
- tmp.end(inbuf);
- }
- };
-};
-
-
-/***/ }),
-/***/ 3928:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-exports.Deflater = __nccwpck_require__(7686);
-exports.Inflater = __nccwpck_require__(2153);
-exports.ZipCrypto = __nccwpck_require__(3228);
-
-
-/***/ }),
-
-/***/ 2153:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-module.exports = function (/*Buffer*/ inbuf) {
- var zlib = __nccwpck_require__(9796);
+/**
+ * This is the common logic for both the Node.js and web browser
+ * implementations of `debug()`.
+ */
- return {
- inflate: function () {
- return zlib.inflateRawSync(inbuf);
- },
+function setup(env) {
+ createDebug.debug = createDebug;
+ createDebug.default = createDebug;
+ createDebug.coerce = coerce;
+ createDebug.disable = disable;
+ createDebug.enable = enable;
+ createDebug.enabled = enabled;
+ createDebug.humanize = __nccwpck_require__(900);
+ createDebug.destroy = destroy;
- inflateAsync: function (/*Function*/ callback) {
- var tmp = zlib.createInflateRaw(),
- parts = [],
- total = 0;
- tmp.on("data", function (data) {
- parts.push(data);
- total += data.length;
- });
- tmp.on("end", function () {
- var buf = Buffer.alloc(total),
- written = 0;
- buf.fill(0);
- for (var i = 0; i < parts.length; i++) {
- var part = parts[i];
- part.copy(buf, written);
- written += part.length;
- }
- callback && callback(buf);
- });
- tmp.end(inbuf);
- }
- };
-};
+ Object.keys(env).forEach(key => {
+ createDebug[key] = env[key];
+ });
+ /**
+ * The currently active debug mode names, and names to skip.
+ */
-/***/ }),
+ createDebug.names = [];
+ createDebug.skips = [];
-/***/ 3228:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ /**
+ * Map of special "%n" handling functions, for the debug "format" argument.
+ *
+ * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
+ */
+ createDebug.formatters = {};
-"use strict";
+ /**
+ * Selects a color for a debug namespace
+ * @param {String} namespace The namespace string for the debug instance to be colored
+ * @return {Number|String} An ANSI color code for the given namespace
+ * @api private
+ */
+ function selectColor(namespace) {
+ let hash = 0;
+ for (let i = 0; i < namespace.length; i++) {
+ hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
+ hash |= 0; // Convert to 32bit integer
+ }
-// node crypt, we use it for generate salt
-// eslint-disable-next-line node/no-unsupported-features/node-builtins
-const { randomFillSync } = __nccwpck_require__(6113);
+ return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
+ }
+ createDebug.selectColor = selectColor;
-// generate CRC32 lookup table
-const crctable = new Uint32Array(256).map((t, crc) => {
- for (let j = 0; j < 8; j++) {
- if (0 !== (crc & 1)) {
- crc = (crc >>> 1) ^ 0xedb88320;
- } else {
- crc >>>= 1;
- }
- }
- return crc >>> 0;
-});
+ /**
+ * Create a debugger with the given `namespace`.
+ *
+ * @param {String} namespace
+ * @return {Function}
+ * @api public
+ */
+ function createDebug(namespace) {
+ let prevTime;
+ let enableOverride = null;
+ let namespacesCache;
+ let enabledCache;
-// C-style uInt32 Multiply (discards higher bits, when JS multiply discards lower bits)
-const uMul = (a, b) => Math.imul(a, b) >>> 0;
+ function debug(...args) {
+ // Disabled?
+ if (!debug.enabled) {
+ return;
+ }
-// crc32 byte single update (actually same function is part of utils.crc32 function :) )
-const crc32update = (pCrc32, bval) => {
- return crctable[(pCrc32 ^ bval) & 0xff] ^ (pCrc32 >>> 8);
-};
+ const self = debug;
-// function for generating salt for encrytion header
-const genSalt = () => {
- if ("function" === typeof randomFillSync) {
- return randomFillSync(Buffer.alloc(12));
- } else {
- // fallback if function is not defined
- return genSalt.node();
- }
-};
+ // Set `diff` timestamp
+ const curr = Number(new Date());
+ const ms = curr - (prevTime || curr);
+ self.diff = ms;
+ self.prev = prevTime;
+ self.curr = curr;
+ prevTime = curr;
-// salt generation with node random function (mainly as fallback)
-genSalt.node = () => {
- const salt = Buffer.alloc(12);
- const len = salt.length;
- for (let i = 0; i < len; i++) salt[i] = (Math.random() * 256) & 0xff;
- return salt;
-};
+ args[0] = createDebug.coerce(args[0]);
-// general config
-const config = {
- genSalt
-};
+ if (typeof args[0] !== 'string') {
+ // Anything else let's inspect with %O
+ args.unshift('%O');
+ }
-// Class Initkeys handles same basic ops with keys
-function Initkeys(pw) {
- const pass = Buffer.isBuffer(pw) ? pw : Buffer.from(pw);
- this.keys = new Uint32Array([0x12345678, 0x23456789, 0x34567890]);
- for (let i = 0; i < pass.length; i++) {
- this.updateKeys(pass[i]);
- }
-}
+ // Apply any `formatters` transformations
+ let index = 0;
+ args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
+ // If we encounter an escaped % then don't increase the array index
+ if (match === '%%') {
+ return '%';
+ }
+ index++;
+ const formatter = createDebug.formatters[format];
+ if (typeof formatter === 'function') {
+ const val = args[index];
+ match = formatter.call(self, val);
-Initkeys.prototype.updateKeys = function (byteValue) {
- const keys = this.keys;
- keys[0] = crc32update(keys[0], byteValue);
- keys[1] += keys[0] & 0xff;
- keys[1] = uMul(keys[1], 134775813) + 1;
- keys[2] = crc32update(keys[2], keys[1] >>> 24);
- return byteValue;
-};
+ // Now we need to remove `args[index]` since it's inlined in the `format`
+ args.splice(index, 1);
+ index--;
+ }
+ return match;
+ });
-Initkeys.prototype.next = function () {
- const k = (this.keys[2] | 2) >>> 0; // key
- return (uMul(k, k ^ 1) >> 8) & 0xff; // decode
-};
+ // Apply env-specific formatting (colors, etc.)
+ createDebug.formatArgs.call(self, args);
-function make_decrypter(/*Buffer*/ pwd) {
- // 1. Stage initialize key
- const keys = new Initkeys(pwd);
+ const logFn = self.log || createDebug.log;
+ logFn.apply(self, args);
+ }
- // return decrypter function
- return function (/*Buffer*/ data) {
- // result - we create new Buffer for results
- const result = Buffer.alloc(data.length);
- let pos = 0;
- // process input data
- for (let c of data) {
- //c ^= keys.next();
- //result[pos++] = c; // decode & Save Value
- result[pos++] = keys.updateKeys(c ^ keys.next()); // update keys with decoded byte
- }
- return result;
- };
-}
+ debug.namespace = namespace;
+ debug.useColors = createDebug.useColors();
+ debug.color = createDebug.selectColor(namespace);
+ debug.extend = extend;
+ debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
-function make_encrypter(/*Buffer*/ pwd) {
- // 1. Stage initialize key
- const keys = new Initkeys(pwd);
+ Object.defineProperty(debug, 'enabled', {
+ enumerable: true,
+ configurable: false,
+ get: () => {
+ if (enableOverride !== null) {
+ return enableOverride;
+ }
+ if (namespacesCache !== createDebug.namespaces) {
+ namespacesCache = createDebug.namespaces;
+ enabledCache = createDebug.enabled(namespace);
+ }
- // return encrypting function, result and pos is here so we dont have to merge buffers later
- return function (/*Buffer*/ data, /*Buffer*/ result, /* Number */ pos = 0) {
- // result - we create new Buffer for results
- if (!result) result = Buffer.alloc(data.length);
- // process input data
- for (let c of data) {
- const k = keys.next(); // save key byte
- result[pos++] = c ^ k; // save val
- keys.updateKeys(c); // update keys with decoded byte
- }
- return result;
- };
-}
+ return enabledCache;
+ },
+ set: v => {
+ enableOverride = v;
+ }
+ });
-function decrypt(/*Buffer*/ data, /*Object*/ header, /*String, Buffer*/ pwd) {
- if (!data || !Buffer.isBuffer(data) || data.length < 12) {
- return Buffer.alloc(0);
- }
+ // Env-specific initialization logic for debug instances
+ if (typeof createDebug.init === 'function') {
+ createDebug.init(debug);
+ }
- // 1. We Initialize and generate decrypting function
- const decrypter = make_decrypter(pwd);
+ return debug;
+ }
- // 2. decrypt salt what is always 12 bytes and is a part of file content
- const salt = decrypter(data.slice(0, 12));
+ function extend(namespace, delimiter) {
+ const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
+ newDebug.log = this.log;
+ return newDebug;
+ }
- // 3. does password meet expectations
- if (salt[11] !== header.crc >>> 24) {
- throw "ADM-ZIP: Wrong Password";
- }
+ /**
+ * Enables a debug mode by namespaces. This can include modes
+ * separated by a colon and wildcards.
+ *
+ * @param {String} namespaces
+ * @api public
+ */
+ function enable(namespaces) {
+ createDebug.save(namespaces);
+ createDebug.namespaces = namespaces;
- // 4. decode content
- return decrypter(data.slice(12));
-}
+ createDebug.names = [];
+ createDebug.skips = [];
-// lets add way to populate salt, NOT RECOMMENDED for production but maybe useful for testing general functionality
-function _salter(data) {
- if (Buffer.isBuffer(data) && data.length >= 12) {
- // be aware - currently salting buffer data is modified
- config.genSalt = function () {
- return data.slice(0, 12);
- };
- } else if (data === "node") {
- // test salt generation with node random function
- config.genSalt = genSalt.node;
- } else {
- // if value is not acceptable config gets reset.
- config.genSalt = genSalt;
- }
-}
+ let i;
+ const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
+ const len = split.length;
-function encrypt(/*Buffer*/ data, /*Object*/ header, /*String, Buffer*/ pwd, /*Boolean*/ oldlike = false) {
- // 1. test data if data is not Buffer we make buffer from it
- if (data == null) data = Buffer.alloc(0);
- // if data is not buffer be make buffer from it
- if (!Buffer.isBuffer(data)) data = Buffer.from(data.toString());
+ for (i = 0; i < len; i++) {
+ if (!split[i]) {
+ // ignore empty strings
+ continue;
+ }
- // 2. We Initialize and generate encrypting function
- const encrypter = make_encrypter(pwd);
+ namespaces = split[i].replace(/\*/g, '.*?');
- // 3. generate salt (12-bytes of random data)
- const salt = config.genSalt();
- salt[11] = (header.crc >>> 24) & 0xff;
+ if (namespaces[0] === '-') {
+ createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
+ } else {
+ createDebug.names.push(new RegExp('^' + namespaces + '$'));
+ }
+ }
+ }
- // old implementations (before PKZip 2.04g) used two byte check
- if (oldlike) salt[10] = (header.crc >>> 16) & 0xff;
+ /**
+ * Disable debug output.
+ *
+ * @return {String} namespaces
+ * @api public
+ */
+ function disable() {
+ const namespaces = [
+ ...createDebug.names.map(toNamespace),
+ ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
+ ].join(',');
+ createDebug.enable('');
+ return namespaces;
+ }
- // 4. create output
- const result = Buffer.alloc(data.length + 12);
- encrypter(salt, result);
+ /**
+ * Returns true if the given mode name is enabled, false otherwise.
+ *
+ * @param {String} name
+ * @return {Boolean}
+ * @api public
+ */
+ function enabled(name) {
+ if (name[name.length - 1] === '*') {
+ return true;
+ }
- // finally encode content
- return encrypter(data, result, 12);
-}
+ let i;
+ let len;
-module.exports = { decrypt, encrypt, _salter };
+ for (i = 0, len = createDebug.skips.length; i < len; i++) {
+ if (createDebug.skips[i].test(name)) {
+ return false;
+ }
+ }
+ for (i = 0, len = createDebug.names.length; i < len; i++) {
+ if (createDebug.names[i].test(name)) {
+ return true;
+ }
+ }
-/***/ }),
+ return false;
+ }
-/***/ 4522:
-/***/ ((module) => {
+ /**
+ * Convert regexp to namespace
+ *
+ * @param {RegExp} regxep
+ * @return {String} namespace
+ * @api private
+ */
+ function toNamespace(regexp) {
+ return regexp.toString()
+ .substring(2, regexp.toString().length - 2)
+ .replace(/\.\*\?$/, '*');
+ }
-module.exports = {
- /* The local file header */
- LOCHDR : 30, // LOC header size
- LOCSIG : 0x04034b50, // "PK\003\004"
- LOCVER : 4, // version needed to extract
- LOCFLG : 6, // general purpose bit flag
- LOCHOW : 8, // compression method
- LOCTIM : 10, // modification time (2 bytes time, 2 bytes date)
- LOCCRC : 14, // uncompressed file crc-32 value
- LOCSIZ : 18, // compressed size
- LOCLEN : 22, // uncompressed size
- LOCNAM : 26, // filename length
- LOCEXT : 28, // extra field length
+ /**
+ * Coerce `val`.
+ *
+ * @param {Mixed} val
+ * @return {Mixed}
+ * @api private
+ */
+ function coerce(val) {
+ if (val instanceof Error) {
+ return val.stack || val.message;
+ }
+ return val;
+ }
- /* The Data descriptor */
- EXTSIG : 0x08074b50, // "PK\007\008"
- EXTHDR : 16, // EXT header size
- EXTCRC : 4, // uncompressed file crc-32 value
- EXTSIZ : 8, // compressed size
- EXTLEN : 12, // uncompressed size
+ /**
+ * XXX DO NOT USE. This is a temporary stub function.
+ * XXX It WILL be removed in the next major release.
+ */
+ function destroy() {
+ console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
+ }
- /* The central directory file header */
- CENHDR : 46, // CEN header size
- CENSIG : 0x02014b50, // "PK\001\002"
- CENVEM : 4, // version made by
- CENVER : 6, // version needed to extract
- CENFLG : 8, // encrypt, decrypt flags
- CENHOW : 10, // compression method
- CENTIM : 12, // modification time (2 bytes time, 2 bytes date)
- CENCRC : 16, // uncompressed file crc-32 value
- CENSIZ : 20, // compressed size
- CENLEN : 24, // uncompressed size
- CENNAM : 28, // filename length
- CENEXT : 30, // extra field length
- CENCOM : 32, // file comment length
- CENDSK : 34, // volume number start
- CENATT : 36, // internal file attributes
- CENATX : 38, // external file attributes (host system dependent)
- CENOFF : 42, // LOC header offset
+ createDebug.enable(createDebug.load());
- /* The entries in the end of central directory */
- ENDHDR : 22, // END header size
- ENDSIG : 0x06054b50, // "PK\005\006"
- ENDSUB : 8, // number of entries on this disk
- ENDTOT : 10, // total number of entries
- ENDSIZ : 12, // central directory size in bytes
- ENDOFF : 16, // offset of first CEN header
- ENDCOM : 20, // zip file comment length
+ return createDebug;
+}
- END64HDR : 20, // zip64 END header size
- END64SIG : 0x07064b50, // zip64 Locator signature, "PK\006\007"
- END64START : 4, // number of the disk with the start of the zip64
- END64OFF : 8, // relative offset of the zip64 end of central directory
- END64NUMDISKS : 16, // total number of disks
+module.exports = setup;
- ZIP64SIG : 0x06064b50, // zip64 signature, "PK\006\006"
- ZIP64HDR : 56, // zip64 record minimum size
- ZIP64LEAD : 12, // leading bytes at the start of the record, not counted by the value stored in ZIP64SIZE
- ZIP64SIZE : 4, // zip64 size of the central directory record
- ZIP64VEM : 12, // zip64 version made by
- ZIP64VER : 14, // zip64 version needed to extract
- ZIP64DSK : 16, // zip64 number of this disk
- ZIP64DSKDIR : 20, // number of the disk with the start of the record directory
- ZIP64SUB : 24, // number of entries on this disk
- ZIP64TOT : 32, // total number of entries
- ZIP64SIZB : 40, // zip64 central directory size in bytes
- ZIP64OFF : 48, // offset of start of central directory with respect to the starting disk number
- ZIP64EXTRA : 56, // extensible data sector
- /* Compression methods */
- STORED : 0, // no compression
- SHRUNK : 1, // shrunk
- REDUCED1 : 2, // reduced with compression factor 1
- REDUCED2 : 3, // reduced with compression factor 2
- REDUCED3 : 4, // reduced with compression factor 3
- REDUCED4 : 5, // reduced with compression factor 4
- IMPLODED : 6, // imploded
- // 7 reserved for Tokenizing compression algorithm
- DEFLATED : 8, // deflated
- ENHANCED_DEFLATED: 9, // enhanced deflated
- PKWARE : 10,// PKWare DCL imploded
- // 11 reserved by PKWARE
- BZIP2 : 12, // compressed using BZIP2
- // 13 reserved by PKWARE
- LZMA : 14, // LZMA
- // 15-17 reserved by PKWARE
- IBM_TERSE : 18, // compressed using IBM TERSE
- IBM_LZ77 : 19, // IBM LZ77 z
- AES_ENCRYPT : 99, // WinZIP AES encryption method
+/***/ }),
- /* General purpose bit flag */
- // values can obtained with expression 2**bitnr
- FLG_ENC : 1, // Bit 0: encrypted file
- FLG_COMP1 : 2, // Bit 1, compression option
- FLG_COMP2 : 4, // Bit 2, compression option
- FLG_DESC : 8, // Bit 3, data descriptor
- FLG_ENH : 16, // Bit 4, enhanced deflating
- FLG_PATCH : 32, // Bit 5, indicates that the file is compressed patched data.
- FLG_STR : 64, // Bit 6, strong encryption (patented)
- // Bits 7-10: Currently unused.
- FLG_EFS : 2048, // Bit 11: Language encoding flag (EFS)
- // Bit 12: Reserved by PKWARE for enhanced compression.
- // Bit 13: encrypted the Central Directory (patented).
- // Bits 14-15: Reserved by PKWARE.
- FLG_MSK : 4096, // mask header values
+/***/ 8237:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- /* Load type */
- FILE : 2,
- BUFFER : 1,
- NONE : 0,
+/**
+ * Detect Electron renderer / nwjs process, which is node, but we should
+ * treat as a browser.
+ */
- /* 4.5 Extensible data fields */
- EF_ID : 0,
- EF_SIZE : 2,
+if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
+ module.exports = __nccwpck_require__(8222);
+} else {
+ module.exports = __nccwpck_require__(4874);
+}
- /* Header IDs */
- ID_ZIP64 : 0x0001,
- ID_AVINFO : 0x0007,
- ID_PFS : 0x0008,
- ID_OS2 : 0x0009,
- ID_NTFS : 0x000a,
- ID_OPENVMS : 0x000c,
- ID_UNIX : 0x000d,
- ID_FORK : 0x000e,
- ID_PATCH : 0x000f,
- ID_X509_PKCS7 : 0x0014,
- ID_X509_CERTID_F : 0x0015,
- ID_X509_CERTID_C : 0x0016,
- ID_STRONGENC : 0x0017,
- ID_RECORD_MGT : 0x0018,
- ID_X509_PKCS7_RL : 0x0019,
- ID_IBM1 : 0x0065,
- ID_IBM2 : 0x0066,
- ID_POSZIP : 0x4690,
- EF_ZIP64_OR_32 : 0xffffffff,
- EF_ZIP64_OR_16 : 0xffff,
- EF_ZIP64_SUNCOMP : 0,
- EF_ZIP64_SCOMP : 8,
- EF_ZIP64_RHO : 16,
- EF_ZIP64_DSN : 24
-};
+/***/ }),
+/***/ 4874:
+/***/ ((module, exports, __nccwpck_require__) => {
-/***/ }),
+/**
+ * Module dependencies.
+ */
-/***/ 1255:
-/***/ ((module) => {
+const tty = __nccwpck_require__(6224);
+const util = __nccwpck_require__(3837);
-module.exports = {
- /* Header error messages */
- INVALID_LOC: "Invalid LOC header (bad signature)",
- INVALID_CEN: "Invalid CEN header (bad signature)",
- INVALID_END: "Invalid END header (bad signature)",
+/**
+ * This is the Node.js implementation of `debug()`.
+ */
- /* 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",
- UNKNOWN_METHOD: "Invalid/unsupported compression method",
+exports.init = init;
+exports.log = log;
+exports.formatArgs = formatArgs;
+exports.save = save;
+exports.load = load;
+exports.useColors = useColors;
+exports.destroy = util.deprecate(
+ () => {},
+ 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
+);
- /* Inflater error messages */
- AVAIL_DATA: "inflate::Available inflate data did not terminate",
- INVALID_DISTANCE: "inflate::Invalid literal/length or distance code in fixed or dynamic block",
- TO_MANY_CODES: "inflate::Dynamic block code description: too many length or distance codes",
- INVALID_REPEAT_LEN: "inflate::Dynamic block code description: repeat more than specified lengths",
- INVALID_REPEAT_FIRST: "inflate::Dynamic block code description: repeat lengths with no first length",
- INCOMPLETE_CODES: "inflate::Dynamic block code description: code lengths codes incomplete",
- INVALID_DYN_DISTANCE: "inflate::Dynamic block code description: invalid distance code lengths",
- INVALID_CODES_LEN: "inflate::Dynamic block code description: invalid literal/length code lengths",
- INVALID_STORE_BLOCK: "inflate::Stored block length did not match one's complement",
- INVALID_BLOCK_TYPE: "inflate::Invalid block type (type == 3)",
+/**
+ * Colors.
+ */
- /* ADM-ZIP error messages */
- CANT_EXTRACT_FILE: "Could not extract the file",
- CANT_OVERRIDE: "Target file already exists",
- NO_ZIP: "No zip file was loaded",
- NO_ENTRY: "Entry doesn't exist",
- DIRECTORY_CONTENT_ERROR: "A directory cannot have content",
- FILE_NOT_FOUND: "File not found: %s",
- NOT_IMPLEMENTED: "Not implemented",
- INVALID_FILENAME: "Invalid filename",
- INVALID_FORMAT: "Invalid or unsupported zip format. No END header found"
-};
+exports.colors = [6, 2, 3, 4, 5, 1];
+try {
+ // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
+ // eslint-disable-next-line import/no-extraneous-dependencies
+ const supportsColor = __nccwpck_require__(9318);
-/***/ }),
+ if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
+ exports.colors = [
+ 20,
+ 21,
+ 26,
+ 27,
+ 32,
+ 33,
+ 38,
+ 39,
+ 40,
+ 41,
+ 42,
+ 43,
+ 44,
+ 45,
+ 56,
+ 57,
+ 62,
+ 63,
+ 68,
+ 69,
+ 74,
+ 75,
+ 76,
+ 77,
+ 78,
+ 79,
+ 80,
+ 81,
+ 92,
+ 93,
+ 98,
+ 99,
+ 112,
+ 113,
+ 128,
+ 129,
+ 134,
+ 135,
+ 148,
+ 149,
+ 160,
+ 161,
+ 162,
+ 163,
+ 164,
+ 165,
+ 166,
+ 167,
+ 168,
+ 169,
+ 170,
+ 171,
+ 172,
+ 173,
+ 178,
+ 179,
+ 184,
+ 185,
+ 196,
+ 197,
+ 198,
+ 199,
+ 200,
+ 201,
+ 202,
+ 203,
+ 204,
+ 205,
+ 206,
+ 207,
+ 208,
+ 209,
+ 214,
+ 215,
+ 220,
+ 221
+ ];
+ }
+} catch (error) {
+ // Swallow - we only care if `supports-color` is available; it doesn't have to be.
+}
-/***/ 8321:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/**
+ * Build up the default `inspectOpts` object from the environment variables.
+ *
+ * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
+ */
-const fs = (__nccwpck_require__(2895).require)();
-const pth = __nccwpck_require__(1017);
+exports.inspectOpts = Object.keys(process.env).filter(key => {
+ return /^debug_/i.test(key);
+}).reduce((obj, key) => {
+ // Camel-case
+ const prop = key
+ .substring(6)
+ .toLowerCase()
+ .replace(/_([a-z])/g, (_, k) => {
+ return k.toUpperCase();
+ });
-fs.existsSync = fs.existsSync || pth.existsSync;
+ // Coerce string value into JS value
+ let val = process.env[key];
+ if (/^(yes|on|true|enabled)$/i.test(val)) {
+ val = true;
+ } else if (/^(no|off|false|disabled)$/i.test(val)) {
+ val = false;
+ } else if (val === 'null') {
+ val = null;
+ } else {
+ val = Number(val);
+ }
-module.exports = function (/*String*/ path) {
- var _path = path || "",
- _obj = newAttr(),
- _stat = null;
+ obj[prop] = val;
+ return obj;
+}, {});
- function newAttr() {
- return {
- directory: false,
- readonly: false,
- hidden: false,
- executable: false,
- mtime: 0,
- atime: 0
- };
- }
+/**
+ * Is stdout a TTY? Colored output is enabled when `true`.
+ */
+
+function useColors() {
+ return 'colors' in exports.inspectOpts ?
+ Boolean(exports.inspectOpts.colors) :
+ tty.isatty(process.stderr.fd);
+}
- if (_path && fs.existsSync(_path)) {
- _stat = fs.statSync(_path);
- _obj.directory = _stat.isDirectory();
- _obj.mtime = _stat.mtime;
- _obj.atime = _stat.atime;
- _obj.executable = (0o111 & _stat.mode) !== 0; // file is executable who ever har right not just owner
- _obj.readonly = (0o200 & _stat.mode) === 0; // readonly if owner has no write right
- _obj.hidden = pth.basename(_path)[0] === ".";
- } else {
- console.warn("Invalid path: " + _path);
- }
+/**
+ * Adds ANSI color escape codes if enabled.
+ *
+ * @api public
+ */
- return {
- get directory() {
- return _obj.directory;
- },
+function formatArgs(args) {
+ const {namespace: name, useColors} = this;
- get readOnly() {
- return _obj.readonly;
- },
+ if (useColors) {
+ const c = this.color;
+ const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
+ const prefix = ` ${colorCode};1m${name} \u001B[0m`;
- get hidden() {
- return _obj.hidden;
- },
+ args[0] = prefix + args[0].split('\n').join('\n' + prefix);
+ args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
+ } else {
+ args[0] = getDate() + name + ' ' + args[0];
+ }
+}
- get mtime() {
- return _obj.mtime;
- },
+function getDate() {
+ if (exports.inspectOpts.hideDate) {
+ return '';
+ }
+ return new Date().toISOString() + ' ';
+}
- get atime() {
- return _obj.atime;
- },
+/**
+ * Invokes `util.format()` with the specified arguments and writes to stderr.
+ */
- get executable() {
- return _obj.executable;
- },
+function log(...args) {
+ return process.stderr.write(util.format(...args) + '\n');
+}
- decodeAttributes: function () {},
+/**
+ * Save `namespaces`.
+ *
+ * @param {String} namespaces
+ * @api private
+ */
+function save(namespaces) {
+ if (namespaces) {
+ process.env.DEBUG = namespaces;
+ } else {
+ // If you set a process.env field to null or undefined, it gets cast to the
+ // string 'null' or 'undefined'. Just delete instead.
+ delete process.env.DEBUG;
+ }
+}
- encodeAttributes: function () {},
+/**
+ * Load `namespaces`.
+ *
+ * @return {String} returns the previously persisted debug modes
+ * @api private
+ */
- toJSON: function () {
- return {
- path: _path,
- isDirectory: _obj.directory,
- isReadOnly: _obj.readonly,
- isHidden: _obj.hidden,
- isExecutable: _obj.executable,
- mTime: _obj.mtime,
- aTime: _obj.atime
- };
- },
+function load() {
+ return process.env.DEBUG;
+}
- toString: function () {
- return JSON.stringify(this.toJSON(), null, "\t");
- }
- };
-};
+/**
+ * Init logic for `debug` instances.
+ *
+ * Create a new `inspectOpts` object in case `useColors` is set
+ * differently for a particular `debug` instance.
+ */
+function init(debug) {
+ debug.inspectOpts = {};
-/***/ }),
+ const keys = Object.keys(exports.inspectOpts);
+ for (let i = 0; i < keys.length; i++) {
+ debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
+ }
+}
-/***/ 2895:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+module.exports = __nccwpck_require__(6243)(exports);
-exports.require = function () {
- if (typeof process === "object" && process.versions && process.versions["electron"]) {
- try {
- const originalFs = __nccwpck_require__(2941);
- if (Object.keys(originalFs).length > 0) {
- return originalFs;
- }
- } catch (e) {}
- }
- return __nccwpck_require__(7147);
-};
+const {formatters} = module.exports;
+/**
+ * Map %o to `util.inspect()`, all on a single line.
+ */
-/***/ }),
+formatters.o = function (v) {
+ this.inspectOpts.colors = this.useColors;
+ return util.inspect(v, this.inspectOpts)
+ .split('\n')
+ .map(str => str.trim())
+ .join(' ');
+};
-/***/ 5182:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/**
+ * Map %O to `util.inspect()`, allowing multiple lines if needed.
+ */
-module.exports = __nccwpck_require__(1291);
-module.exports.Constants = __nccwpck_require__(4522);
-module.exports.Errors = __nccwpck_require__(1255);
-module.exports.FileAttr = __nccwpck_require__(8321);
+formatters.O = function (v) {
+ this.inspectOpts.colors = this.useColors;
+ return util.inspect(v, this.inspectOpts);
+};
/***/ }),
-/***/ 1291:
+/***/ 8611:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const fsystem = (__nccwpck_require__(2895).require)();
-const pth = __nccwpck_require__(1017);
-const Constants = __nccwpck_require__(4522);
-const isWin = typeof process === "object" && "win32" === process.platform;
+var Stream = (__nccwpck_require__(2781).Stream);
+var util = __nccwpck_require__(3837);
-const is_Obj = (obj) => obj && typeof obj === "object";
+module.exports = DelayedStream;
+function DelayedStream() {
+ this.source = null;
+ this.dataSize = 0;
+ this.maxDataSize = 1024 * 1024;
+ this.pauseStream = true;
-// generate CRC32 lookup table
-const crcTable = new Uint32Array(256).map((t, c) => {
- for (let k = 0; k < 8; k++) {
- if ((c & 1) !== 0) {
- c = 0xedb88320 ^ (c >>> 1);
- } else {
- c >>>= 1;
- }
- }
- return c >>> 0;
-});
+ this._maxDataSizeExceeded = false;
+ this._released = false;
+ this._bufferedEvents = [];
+}
+util.inherits(DelayedStream, Stream);
-// UTILS functions
+DelayedStream.create = function(source, options) {
+ var delayedStream = new this();
-function Utils(opts) {
- this.sep = pth.sep;
- this.fs = fsystem;
+ options = options || {};
+ for (var option in options) {
+ delayedStream[option] = options[option];
+ }
- if (is_Obj(opts)) {
- // custom filesystem
- if (is_Obj(opts.fs) && typeof opts.fs.statSync === "function") {
- this.fs = opts.fs;
- }
- }
-}
+ delayedStream.source = source;
-module.exports = Utils;
+ var realEmit = source.emit;
+ source.emit = function() {
+ delayedStream._handleEmit(arguments);
+ return realEmit.apply(source, arguments);
+ };
-// INSTANCED functions
+ source.on('error', function() {});
+ if (delayedStream.pauseStream) {
+ source.pause();
+ }
-Utils.prototype.makeDir = function (/*String*/ folder) {
- const self = this;
+ return delayedStream;
+};
- // Sync - make directories tree
- function mkdirSync(/*String*/ fpath) {
- let resolvedPath = fpath.split(self.sep)[0];
- fpath.split(self.sep).forEach(function (name) {
- if (!name || name.substr(-1, 1) === ":") return;
- resolvedPath += self.sep + name;
- var stat;
- try {
- stat = self.fs.statSync(resolvedPath);
- } catch (e) {
- self.fs.mkdirSync(resolvedPath);
- }
- if (stat && stat.isFile()) throw Errors.FILE_IN_THE_WAY.replace("%s", resolvedPath);
- });
- }
+Object.defineProperty(DelayedStream.prototype, 'readable', {
+ configurable: true,
+ enumerable: true,
+ get: function() {
+ return this.source.readable;
+ }
+});
- mkdirSync(folder);
+DelayedStream.prototype.setEncoding = function() {
+ return this.source.setEncoding.apply(this.source, arguments);
};
-Utils.prototype.writeFileTo = function (/*String*/ path, /*Buffer*/ content, /*Boolean*/ overwrite, /*Number*/ attr) {
- const self = this;
- if (self.fs.existsSync(path)) {
- if (!overwrite) return false; // cannot overwrite
+DelayedStream.prototype.resume = function() {
+ if (!this._released) {
+ this.release();
+ }
- var stat = self.fs.statSync(path);
- if (stat.isDirectory()) {
- return false;
- }
- }
- var folder = pth.dirname(path);
- if (!self.fs.existsSync(folder)) {
- self.makeDir(folder);
- }
+ this.source.resume();
+};
- var fd;
- try {
- fd = self.fs.openSync(path, "w", 438); // 0666
- } catch (e) {
- self.fs.chmodSync(path, 438);
- fd = self.fs.openSync(path, "w", 438);
- }
- if (fd) {
- try {
- self.fs.writeSync(fd, content, 0, content.length, 0);
- } finally {
- self.fs.closeSync(fd);
- }
- }
- self.fs.chmodSync(path, attr || 438);
- return true;
+DelayedStream.prototype.pause = function() {
+ this.source.pause();
};
-Utils.prototype.writeFileToAsync = function (/*String*/ path, /*Buffer*/ content, /*Boolean*/ overwrite, /*Number*/ attr, /*Function*/ callback) {
- if (typeof attr === "function") {
- callback = attr;
- attr = undefined;
- }
+DelayedStream.prototype.release = function() {
+ this._released = true;
- const self = this;
+ this._bufferedEvents.forEach(function(args) {
+ this.emit.apply(this, args);
+ }.bind(this));
+ this._bufferedEvents = [];
+};
- self.fs.exists(path, function (exist) {
- if (exist && !overwrite) return callback(false);
+DelayedStream.prototype.pipe = function() {
+ var r = Stream.prototype.pipe.apply(this, arguments);
+ this.resume();
+ return r;
+};
- self.fs.stat(path, function (err, stat) {
- if (exist && stat.isDirectory()) {
- return callback(false);
- }
+DelayedStream.prototype._handleEmit = function(args) {
+ if (this._released) {
+ this.emit.apply(this, args);
+ return;
+ }
- var folder = pth.dirname(path);
- self.fs.exists(folder, function (exists) {
- if (!exists) self.makeDir(folder);
+ if (args[0] === 'data') {
+ this.dataSize += args[1].length;
+ this._checkIfMaxDataSizeExceeded();
+ }
- self.fs.open(path, "w", 438, function (err, fd) {
- if (err) {
- self.fs.chmod(path, 438, function () {
- self.fs.open(path, "w", 438, 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 () {
- callback(true);
- });
- });
- });
- });
- });
- } else if (fd) {
- self.fs.write(fd, content, 0, content.length, 0, function () {
- self.fs.close(fd, function () {
- self.fs.chmod(path, attr || 438, function () {
- callback(true);
- });
- });
- });
- } else {
- self.fs.chmod(path, attr || 438, function () {
- callback(true);
- });
- }
- });
- });
- });
- });
+ this._bufferedEvents.push(args);
};
-Utils.prototype.findFiles = function (/*String*/ path) {
- const self = this;
-
- function findSync(/*String*/ dir, /*RegExp*/ pattern, /*Boolean*/ recursive) {
- if (typeof pattern === "boolean") {
- recursive = pattern;
- pattern = undefined;
- }
- let files = [];
- self.fs.readdirSync(dir).forEach(function (file) {
- var path = pth.join(dir, file);
-
- if (self.fs.statSync(path).isDirectory() && recursive) files = files.concat(findSync(path, pattern, recursive));
+DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() {
+ if (this._maxDataSizeExceeded) {
+ return;
+ }
- if (!pattern || pattern.test(path)) {
- files.push(pth.normalize(path) + (self.fs.statSync(path).isDirectory() ? self.sep : ""));
- }
- });
- return files;
- }
+ if (this.dataSize <= this.maxDataSize) {
+ return;
+ }
- return findSync(path, undefined, true);
+ this._maxDataSizeExceeded = true;
+ var message =
+ 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'
+ this.emit('error', new Error(message));
};
-Utils.prototype.getAttributes = function () {};
-Utils.prototype.setAttributes = function () {};
+/***/ }),
-// STATIC functions
+/***/ 1133:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-// crc32 single update (it is part of crc32)
-Utils.crc32update = function (crc, byte) {
- return crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8);
-};
+var debug;
-Utils.crc32 = function (buf) {
- if (typeof buf === "string") {
- buf = Buffer.from(buf, "utf8");
+module.exports = function () {
+ if (!debug) {
+ try {
+ /* eslint global-require: off */
+ debug = __nccwpck_require__(8237)("follow-redirects");
}
- // Generate crcTable
- if (!crcTable.length) genCRCTable();
-
- let len = buf.length;
- let crc = ~0;
- for (let off = 0; off < len; ) crc = Utils.crc32update(crc, buf[off++]);
- // xor and cast as uint32 number
- return ~crc >>> 0;
-};
-
-Utils.methodToString = function (/*Number*/ method) {
- switch (method) {
- case Constants.STORED:
- return "STORED (" + method + ")";
- case Constants.DEFLATED:
- return "DEFLATED (" + method + ")";
- default:
- return "UNSUPPORTED (" + method + ")";
+ catch (error) { /* */ }
+ if (typeof debug !== "function") {
+ debug = function () { /* */ };
}
+ }
+ debug.apply(null, arguments);
};
-// removes ".." style path elements
-Utils.canonical = function (/*string*/ path) {
- if (!path) return "";
- // trick normalize think path is absolute
- var safeSuffix = pth.posix.normalize("/" + path.split("\\").join("/"));
- return pth.join(".", safeSuffix);
-};
-// make abolute paths taking prefix as root folder
-Utils.sanitize = function (/*string*/ prefix, /*string*/ name) {
- prefix = pth.resolve(pth.normalize(prefix));
- var parts = name.split("/");
- for (var i = 0, l = parts.length; i < l; i++) {
- var path = pth.normalize(pth.join(prefix, parts.slice(i, l).join(pth.sep)));
- if (path.indexOf(prefix) === 0) {
- return path;
- }
- }
- return pth.normalize(pth.join(prefix, pth.basename(name)));
-};
+/***/ }),
-// converts buffer, Uint8Array, string types to buffer
-Utils.toBuffer = function toBuffer(/*buffer, Uint8Array, string*/ input) {
- if (Buffer.isBuffer(input)) {
- return input;
- } else if (input instanceof Uint8Array) {
- return Buffer.from(input);
- } else {
- // expect string all other values are invalid and return empty buffer
- return typeof input === "string" ? Buffer.from(input, "utf8") : Buffer.alloc(0);
- }
-};
+/***/ 7707:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-Utils.readBigUInt64LE = function (/*Buffer*/ buffer, /*int*/ index) {
- var slice = Buffer.from(buffer.slice(index, index + 8));
- slice.swap64();
+var url = __nccwpck_require__(7310);
+var URL = url.URL;
+var http = __nccwpck_require__(3685);
+var https = __nccwpck_require__(5687);
+var Writable = (__nccwpck_require__(2781).Writable);
+var assert = __nccwpck_require__(9491);
+var debug = __nccwpck_require__(1133);
- return parseInt(`0x${slice.toString("hex")}`);
-};
+// Create handlers that pass events from native requests
+var events = ["abort", "aborted", "connect", "error", "socket", "timeout"];
+var eventHandlers = Object.create(null);
+events.forEach(function (event) {
+ eventHandlers[event] = function (arg1, arg2, arg3) {
+ this._redirectable.emit(event, arg1, arg2, arg3);
+ };
+});
-Utils.isWin = isWin; // Do we have windows system
-Utils.crcTable = crcTable;
+var InvalidUrlError = createErrorType(
+ "ERR_INVALID_URL",
+ "Invalid URL",
+ TypeError
+);
+// Error types with codes
+var RedirectionError = createErrorType(
+ "ERR_FR_REDIRECTION_FAILURE",
+ "Redirected request failed"
+);
+var TooManyRedirectsError = createErrorType(
+ "ERR_FR_TOO_MANY_REDIRECTS",
+ "Maximum number of redirects exceeded"
+);
+var MaxBodyLengthExceededError = createErrorType(
+ "ERR_FR_MAX_BODY_LENGTH_EXCEEDED",
+ "Request body larger than maxBodyLength limit"
+);
+var WriteAfterEndError = createErrorType(
+ "ERR_STREAM_WRITE_AFTER_END",
+ "write after end"
+);
+
+// An HTTP(S) request that can be redirected
+function RedirectableRequest(options, responseCallback) {
+ // Initialize the request
+ Writable.call(this);
+ this._sanitizeOptions(options);
+ this._options = options;
+ this._ended = false;
+ this._ending = false;
+ this._redirectCount = 0;
+ this._redirects = [];
+ this._requestBodyLength = 0;
+ this._requestBodyBuffers = [];
+ // Attach a callback if passed
+ if (responseCallback) {
+ this.on("response", responseCallback);
+ }
-/***/ }),
+ // React to responses of native requests
+ var self = this;
+ this._onNativeResponse = function (response) {
+ self._processResponse(response);
+ };
-/***/ 4057:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // Perform the first request
+ this._performRequest();
+}
+RedirectableRequest.prototype = Object.create(Writable.prototype);
-var Utils = __nccwpck_require__(5182),
- Headers = __nccwpck_require__(4958),
- Constants = Utils.Constants,
- Methods = __nccwpck_require__(3928);
+RedirectableRequest.prototype.abort = function () {
+ abortRequest(this._currentRequest);
+ this.emit("abort");
+};
-module.exports = function (/*Buffer*/ input) {
- var _entryHeader = new Headers.EntryHeader(),
- _entryName = Buffer.alloc(0),
- _comment = Buffer.alloc(0),
- _isDirectory = false,
- uncompressedData = null,
- _extra = Buffer.alloc(0);
+// Writes buffered data to the current native request
+RedirectableRequest.prototype.write = function (data, encoding, callback) {
+ // Writing is not allowed if end has been called
+ if (this._ending) {
+ throw new WriteAfterEndError();
+ }
- function getCompressedDataFromZip() {
- if (!input || !Buffer.isBuffer(input)) {
- return Buffer.alloc(0);
- }
- _entryHeader.loadDataHeaderFromBinary(input);
- return input.slice(_entryHeader.realDataOffset, _entryHeader.realDataOffset + _entryHeader.compressedSize);
- }
+ // Validate input and shift parameters if necessary
+ if (!isString(data) && !isBuffer(data)) {
+ throw new TypeError("data should be a string, Buffer or Uint8Array");
+ }
+ if (isFunction(encoding)) {
+ callback = encoding;
+ encoding = null;
+ }
- 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 ((_entryHeader.flags & 0x8) !== 0x8) {
- if (Utils.crc32(data) !== _entryHeader.dataHeader.crc) {
- 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:
- }
- return true;
+ // Ignore empty buffers, since writing them doesn't invoke the callback
+ // https://github.com/nodejs/node/issues/22066
+ if (data.length === 0) {
+ if (callback) {
+ callback();
}
+ return;
+ }
+ // Only write when we don't exceed the maximum body length
+ if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {
+ this._requestBodyLength += data.length;
+ this._requestBodyBuffers.push({ data: data, encoding: encoding });
+ this._currentRequest.write(data, encoding, callback);
+ }
+ // Error when we exceed the maximum body length
+ else {
+ this.emit("error", new MaxBodyLengthExceededError());
+ this.abort();
+ }
+};
- function decompress(/*Boolean*/ async, /*Function*/ callback, /*String, Buffer*/ pass) {
- if (typeof callback === "undefined" && typeof async === "string") {
- pass = async;
- async = void 0;
- }
- if (_isDirectory) {
- if (async && callback) {
- callback(Buffer.alloc(0), Utils.Errors.DIRECTORY_CONTENT_ERROR); //si added error.
- }
- return Buffer.alloc(0);
- }
-
- var compressedData = getCompressedDataFromZip();
-
- if (compressedData.length === 0) {
- // File is empty, nothing to decompress.
- if (async && callback) callback(compressedData);
- return compressedData;
- }
-
- if (_entryHeader.encripted) {
- if ("string" !== typeof pass && !Buffer.isBuffer(pass)) {
- throw new Error("ADM-ZIP: Incompatible password parameter");
- }
- compressedData = Methods.ZipCrypto.decrypt(compressedData, _entryHeader, pass);
- }
+// Ends the current native request
+RedirectableRequest.prototype.end = function (data, encoding, callback) {
+ // Shift parameters if necessary
+ if (isFunction(data)) {
+ callback = data;
+ data = encoding = null;
+ }
+ else if (isFunction(encoding)) {
+ callback = encoding;
+ encoding = null;
+ }
- var data = Buffer.alloc(_entryHeader.size);
+ // Write data if needed and end
+ if (!data) {
+ this._ended = this._ending = true;
+ this._currentRequest.end(null, null, callback);
+ }
+ else {
+ var self = this;
+ var currentRequest = this._currentRequest;
+ this.write(data, encoding, function () {
+ self._ended = true;
+ currentRequest.end(null, null, callback);
+ });
+ this._ending = true;
+ }
+};
- switch (_entryHeader.method) {
- case Utils.Constants.STORED:
- compressedData.copy(data);
- if (!crc32OK(data)) {
- if (async && callback) callback(data, Utils.Errors.BAD_CRC); //si added error
- throw new Error(Utils.Errors.BAD_CRC);
- } else {
- //si added otherwise did not seem to return data.
- if (async && callback) callback(data);
- return data;
- }
- case Utils.Constants.DEFLATED:
- var inflater = new Methods.Inflater(compressedData);
- if (!async) {
- const result = inflater.inflate(data);
- result.copy(data, 0);
- if (!crc32OK(data)) {
- throw new Error(Utils.Errors.BAD_CRC + " " + _entryName.toString());
- }
- return data;
- } else {
- inflater.inflateAsync(function (result) {
- result.copy(result, 0);
- if (callback) {
- if (!crc32OK(result)) {
- callback(result, Utils.Errors.BAD_CRC); //si added error
- } else {
- callback(result);
- }
- }
- });
- }
- break;
- default:
- if (async && callback) callback(Buffer.alloc(0), Utils.Errors.UNKNOWN_METHOD);
- throw new Error(Utils.Errors.UNKNOWN_METHOD);
- }
- }
+// Sets a header value on the current native request
+RedirectableRequest.prototype.setHeader = function (name, value) {
+ this._options.headers[name] = value;
+ this._currentRequest.setHeader(name, value);
+};
- function compress(/*Boolean*/ async, /*Function*/ callback) {
- if ((!uncompressedData || !uncompressedData.length) && Buffer.isBuffer(input)) {
- // no data set or the data wasn't changed to require recompression
- if (async && callback) callback(getCompressedDataFromZip());
- return getCompressedDataFromZip();
- }
+// Clears a header value on the current native request
+RedirectableRequest.prototype.removeHeader = function (name) {
+ delete this._options.headers[name];
+ this._currentRequest.removeHeader(name);
+};
- if (uncompressedData.length && !_isDirectory) {
- var compressedData;
- // Local file header
- switch (_entryHeader.method) {
- case Utils.Constants.STORED:
- _entryHeader.compressedSize = _entryHeader.size;
+// Global timeout for all underlying requests
+RedirectableRequest.prototype.setTimeout = function (msecs, callback) {
+ var self = this;
- compressedData = Buffer.alloc(uncompressedData.length);
- uncompressedData.copy(compressedData);
+ // Destroys the socket on timeout
+ function destroyOnTimeout(socket) {
+ socket.setTimeout(msecs);
+ socket.removeListener("timeout", socket.destroy);
+ socket.addListener("timeout", socket.destroy);
+ }
- if (async && callback) callback(compressedData);
- return compressedData;
- default:
- case Utils.Constants.DEFLATED:
- var deflater = new Methods.Deflater(uncompressedData);
- if (!async) {
- var deflated = deflater.deflate();
- _entryHeader.compressedSize = deflated.length;
- return deflated;
- } else {
- deflater.deflateAsync(function (data) {
- compressedData = Buffer.alloc(data.length);
- _entryHeader.compressedSize = data.length;
- data.copy(compressedData);
- callback && callback(compressedData);
- });
- }
- deflater = null;
- break;
- }
- } else if (async && callback) {
- callback(Buffer.alloc(0));
- } else {
- return Buffer.alloc(0);
- }
+ // Sets up a timer to trigger a timeout event
+ function startTimer(socket) {
+ if (self._timeout) {
+ clearTimeout(self._timeout);
}
+ self._timeout = setTimeout(function () {
+ self.emit("timeout");
+ clearTimer();
+ }, msecs);
+ destroyOnTimeout(socket);
+ }
- function readUInt64LE(buffer, offset) {
- return (buffer.readUInt32LE(offset + 4) << 4) + buffer.readUInt32LE(offset);
+ // Stops a timeout from triggering
+ function clearTimer() {
+ // Clear the timeout
+ if (self._timeout) {
+ clearTimeout(self._timeout);
+ self._timeout = null;
}
- 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);
- }
- }
+ // Clean up all attached listeners
+ self.removeListener("abort", clearTimer);
+ self.removeListener("error", clearTimer);
+ self.removeListener("response", clearTimer);
+ if (callback) {
+ self.removeListener("timeout", callback);
}
-
- //Override header field values with values from the ZIP64 extra field
- function parseZip64ExtendedInformation(data) {
- var size, compressedSize, offset, diskNumStart;
-
- if (data.length >= Constants.EF_ZIP64_SCOMP) {
- size = readUInt64LE(data, Constants.EF_ZIP64_SUNCOMP);
- if (_entryHeader.size === Constants.EF_ZIP64_OR_32) {
- _entryHeader.size = size;
- }
- }
- if (data.length >= Constants.EF_ZIP64_RHO) {
- compressedSize = readUInt64LE(data, Constants.EF_ZIP64_SCOMP);
- if (_entryHeader.compressedSize === Constants.EF_ZIP64_OR_32) {
- _entryHeader.compressedSize = compressedSize;
- }
- }
- if (data.length >= Constants.EF_ZIP64_DSN) {
- offset = readUInt64LE(data, Constants.EF_ZIP64_RHO);
- if (_entryHeader.offset === Constants.EF_ZIP64_OR_32) {
- _entryHeader.offset = offset;
- }
- }
- if (data.length >= Constants.EF_ZIP64_DSN + 4) {
- diskNumStart = data.readUInt32LE(Constants.EF_ZIP64_DSN);
- if (_entryHeader.diskNumStart === Constants.EF_ZIP64_OR_16) {
- _entryHeader.diskNumStart = diskNumStart;
- }
- }
+ if (!self.socket) {
+ self._currentRequest.removeListener("socket", startTimer);
}
+ }
- return {
- get entryName() {
- return _entryName.toString();
- },
- get rawEntryName() {
- return _entryName;
- },
- set entryName(val) {
- _entryName = Utils.toBuffer(val);
- var lastChar = _entryName[_entryName.length - 1];
- _isDirectory = lastChar === 47 || lastChar === 92;
- _entryHeader.fileNameLength = _entryName.length;
- },
-
- get extra() {
- return _extra;
- },
- set extra(val) {
- _extra = val;
- _entryHeader.extraLength = val.length;
- parseExtra(val);
- },
+ // Attach callback if passed
+ if (callback) {
+ this.on("timeout", callback);
+ }
- get comment() {
- return _comment.toString();
- },
- set comment(val) {
- _comment = Utils.toBuffer(val);
- _entryHeader.commentLength = _comment.length;
- },
+ // Start the timer if or when the socket is opened
+ if (this.socket) {
+ startTimer(this.socket);
+ }
+ else {
+ this._currentRequest.once("socket", startTimer);
+ }
- get name() {
- var n = _entryName.toString();
- return _isDirectory
- ? n
- .substr(n.length - 1)
- .split("/")
- .pop()
- : n.split("/").pop();
- },
- get isDirectory() {
- return _isDirectory;
- },
+ // Clean up on events
+ this.on("socket", destroyOnTimeout);
+ this.on("abort", clearTimer);
+ this.on("error", clearTimer);
+ this.on("response", clearTimer);
- getCompressedData: function () {
- return compress(false, null);
- },
+ return this;
+};
- getCompressedDataAsync: function (/*Function*/ callback) {
- compress(true, callback);
- },
+// Proxy all other public ClientRequest methods
+[
+ "flushHeaders", "getHeader",
+ "setNoDelay", "setSocketKeepAlive",
+].forEach(function (method) {
+ RedirectableRequest.prototype[method] = function (a, b) {
+ return this._currentRequest[method](a, b);
+ };
+});
- setData: function (value) {
- uncompressedData = Utils.toBuffer(value);
- if (!_isDirectory && uncompressedData.length) {
- _entryHeader.size = uncompressedData.length;
- _entryHeader.method = Utils.Constants.DEFLATED;
- _entryHeader.crc = Utils.crc32(value);
- _entryHeader.changed = true;
- } else {
- // folders and blank files should be stored
- _entryHeader.method = Utils.Constants.STORED;
- }
- },
+// Proxy all public ClientRequest properties
+["aborted", "connection", "socket"].forEach(function (property) {
+ Object.defineProperty(RedirectableRequest.prototype, property, {
+ get: function () { return this._currentRequest[property]; },
+ });
+});
- getData: function (pass) {
- if (_entryHeader.changed) {
- return uncompressedData;
- } else {
- return decompress(false, null, pass);
- }
- },
+RedirectableRequest.prototype._sanitizeOptions = function (options) {
+ // Ensure headers are always present
+ if (!options.headers) {
+ options.headers = {};
+ }
- getDataAsync: function (/*Function*/ callback, pass) {
- if (_entryHeader.changed) {
- callback(uncompressedData);
- } else {
- decompress(true, callback, pass);
- }
- },
+ // Since http.request treats host as an alias of hostname,
+ // but the url module interprets host as hostname plus port,
+ // eliminate the host property to avoid confusion.
+ if (options.host) {
+ // Use hostname if set, because it has precedence
+ if (!options.hostname) {
+ options.hostname = options.host;
+ }
+ delete options.host;
+ }
- set attr(attr) {
- _entryHeader.attr = attr;
- },
- get attr() {
- return _entryHeader.attr;
- },
+ // Complete the URL object when necessary
+ if (!options.pathname && options.path) {
+ var searchPos = options.path.indexOf("?");
+ if (searchPos < 0) {
+ options.pathname = options.path;
+ }
+ else {
+ options.pathname = options.path.substring(0, searchPos);
+ options.search = options.path.substring(searchPos);
+ }
+ }
+};
- set header(/*Buffer*/ data) {
- _entryHeader.loadFromBinary(data);
- },
- get header() {
- return _entryHeader;
- },
+// Executes the next native request (initial or redirect)
+RedirectableRequest.prototype._performRequest = function () {
+ // Load the native protocol
+ var protocol = this._options.protocol;
+ var nativeProtocol = this._options.nativeProtocols[protocol];
+ if (!nativeProtocol) {
+ this.emit("error", new TypeError("Unsupported protocol " + protocol));
+ return;
+ }
- packHeader: function () {
- // 1. create header (buffer)
- var header = _entryHeader.entryHeaderToBinary();
- var addpos = Utils.Constants.CENHDR;
- // 2. add file name
- _entryName.copy(header, addpos);
- addpos += _entryName.length;
- // 3. add extra data
- if (_entryHeader.extraLength) {
- _extra.copy(header, addpos);
- addpos += _entryHeader.extraLength;
- }
- // 4. add file comment
- if (_entryHeader.commentLength) {
- _comment.copy(header, addpos);
- }
- return header;
- },
+ // If specified, use the agent corresponding to the protocol
+ // (HTTP and HTTPS use different types of agents)
+ if (this._options.agents) {
+ var scheme = protocol.slice(0, -1);
+ this._options.agent = this._options.agents[scheme];
+ }
- toJSON: function () {
- const bytes = function (nr) {
- return "<" + ((nr && nr.length + " bytes buffer") || "null") + ">";
- };
+ // Create the native request and set up its event handlers
+ var request = this._currentRequest =
+ nativeProtocol.request(this._options, this._onNativeResponse);
+ request._redirectable = this;
+ for (var event of events) {
+ request.on(event, eventHandlers[event]);
+ }
- return {
- entryName: this.entryName,
- name: this.name,
- comment: this.comment,
- isDirectory: this.isDirectory,
- header: _entryHeader.toJSON(),
- compressedData: bytes(input),
- data: bytes(uncompressedData)
- };
- },
+ // RFC7230§5.3.1: When making a request directly to an origin server, […]
+ // a client MUST send only the absolute path […] as the request-target.
+ this._currentUrl = /^\//.test(this._options.path) ?
+ url.format(this._options) :
+ // When making a request to a proxy, […]
+ // a client MUST send the target URI in absolute-form […].
+ this._options.path;
- toString: function () {
- return JSON.stringify(this.toJSON(), null, "\t");
+ // End a redirected request
+ // (The first request must be ended explicitly with RedirectableRequest#end)
+ if (this._isRedirect) {
+ // Write the request entity and end
+ var i = 0;
+ var self = this;
+ var buffers = this._requestBodyBuffers;
+ (function writeNext(error) {
+ // Only write if this request has not been redirected yet
+ /* istanbul ignore else */
+ if (request === self._currentRequest) {
+ // Report any write errors
+ /* istanbul ignore if */
+ if (error) {
+ self.emit("error", error);
}
- };
+ // Write the next buffer if there are still left
+ else if (i < buffers.length) {
+ var buffer = buffers[i++];
+ /* istanbul ignore else */
+ if (!request.finished) {
+ request.write(buffer.data, buffer.encoding, writeNext);
+ }
+ }
+ // End the request if `end` has been called on us
+ else if (self._ended) {
+ request.end();
+ }
+ }
+ }());
+ }
};
+// Processes a response from the current native request
+RedirectableRequest.prototype._processResponse = function (response) {
+ // Store the redirected response
+ var statusCode = response.statusCode;
+ if (this._options.trackRedirects) {
+ this._redirects.push({
+ url: this._currentUrl,
+ headers: response.headers,
+ statusCode: statusCode,
+ });
+ }
-/***/ }),
+ // RFC7231§6.4: The 3xx (Redirection) class of status code indicates
+ // that further action needs to be taken by the user agent in order to
+ // fulfill the request. If a Location header field is provided,
+ // the user agent MAY automatically redirect its request to the URI
+ // referenced by the Location field value,
+ // even if the specific status code is not understood.
-/***/ 7744:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // If the response is not a redirect; return it as-is
+ var location = response.headers.location;
+ if (!location || this._options.followRedirects === false ||
+ statusCode < 300 || statusCode >= 400) {
+ response.responseUrl = this._currentUrl;
+ response.redirects = this._redirects;
+ this.emit("response", response);
-const ZipEntry = __nccwpck_require__(4057);
-const Headers = __nccwpck_require__(4958);
-const Utils = __nccwpck_require__(5182);
+ // Clean up
+ this._requestBodyBuffers = [];
+ return;
+ }
-module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) {
- var entryList = [],
- entryTable = {},
- _comment = Buffer.alloc(0),
- mainHeader = new Headers.MainHeader(),
- loadedEntries = false;
+ // The response is a redirect, so abort the current request
+ abortRequest(this._currentRequest);
+ // Discard the remainder of the response to avoid waiting for data
+ response.destroy();
- // assign options
- const opts = Object.assign(Object.create(null), options);
+ // RFC7231§6.4: A client SHOULD detect and intervene
+ // in cyclical redirections (i.e., "infinite" redirection loops).
+ if (++this._redirectCount > this._options.maxRedirects) {
+ this.emit("error", new TooManyRedirectsError());
+ return;
+ }
- const { noSort } = opts;
+ // Store the request headers if applicable
+ var requestHeaders;
+ var beforeRedirect = this._options.beforeRedirect;
+ if (beforeRedirect) {
+ requestHeaders = Object.assign({
+ // The Host header was set by nativeProtocol.request
+ Host: response.req.getHeader("host"),
+ }, this._options.headers);
+ }
- if (inBuffer) {
- // is a memory buffer
- readMainHeader(opts.readEntries);
- } else {
- // none. is a new file
- loadedEntries = true;
- }
+ // RFC7231§6.4: Automatic redirection needs to done with
+ // care for methods not known to be safe, […]
+ // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change
+ // the request method from POST to GET for the subsequent request.
+ var method = this._options.method;
+ if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" ||
+ // RFC7231§6.4.4: The 303 (See Other) status code indicates that
+ // the server is redirecting the user agent to a different resource […]
+ // A user agent can perform a retrieval request targeting that URI
+ // (a GET or HEAD request if using HTTP) […]
+ (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) {
+ this._options.method = "GET";
+ // Drop a possible entity and headers related to it
+ this._requestBodyBuffers = [];
+ removeMatchingHeaders(/^content-/i, this._options.headers);
+ }
- function iterateEntries(callback) {
- const totalEntries = mainHeader.diskEntries; // total number of entries
- let index = mainHeader.offset; // offset of first CEN header
+ // Drop the Host header, as the redirect might lead to a different host
+ var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers);
- for (let i = 0; i < totalEntries; i++) {
- let tmp = index;
- const entry = new ZipEntry(inBuffer);
+ // If the redirect is relative, carry over the host of the last request
+ var currentUrlParts = url.parse(this._currentUrl);
+ var currentHost = currentHostHeader || currentUrlParts.host;
+ var currentUrl = /^\w+:/.test(location) ? this._currentUrl :
+ url.format(Object.assign(currentUrlParts, { host: currentHost }));
- entry.header = inBuffer.slice(tmp, (tmp += Utils.Constants.CENHDR));
- entry.entryName = inBuffer.slice(tmp, (tmp += entry.header.fileNameLength));
+ // Determine the URL of the redirection
+ var redirectUrl;
+ try {
+ redirectUrl = url.resolve(currentUrl, location);
+ }
+ catch (cause) {
+ this.emit("error", new RedirectionError({ cause: cause }));
+ return;
+ }
- index += entry.header.entryHeaderSize;
+ // Create the redirected request
+ debug("redirecting to", redirectUrl);
+ this._isRedirect = true;
+ var redirectUrlParts = url.parse(redirectUrl);
+ Object.assign(this._options, redirectUrlParts);
- callback(entry);
- }
+ // Drop confidential headers when redirecting to a less secure protocol
+ // or to a different domain that is not a superdomain
+ if (redirectUrlParts.protocol !== currentUrlParts.protocol &&
+ redirectUrlParts.protocol !== "https:" ||
+ redirectUrlParts.host !== currentHost &&
+ !isSubdomain(redirectUrlParts.host, currentHost)) {
+ removeMatchingHeaders(/^(?:authorization|cookie)$/i, this._options.headers);
+ }
+
+ // Evaluate the beforeRedirect callback
+ if (isFunction(beforeRedirect)) {
+ var responseDetails = {
+ headers: response.headers,
+ statusCode: statusCode,
+ };
+ var requestDetails = {
+ url: currentUrl,
+ method: method,
+ headers: requestHeaders,
+ };
+ try {
+ beforeRedirect(this._options, responseDetails, requestDetails);
}
+ catch (err) {
+ this.emit("error", err);
+ return;
+ }
+ this._sanitizeOptions(this._options);
+ }
- function readEntries() {
- loadedEntries = true;
- entryTable = {};
- entryList = new Array(mainHeader.diskEntries); // total number of entries
- var index = mainHeader.offset; // offset of first CEN header
- for (var i = 0; i < entryList.length; i++) {
- var tmp = index,
- entry = new ZipEntry(inBuffer);
- entry.header = inBuffer.slice(tmp, (tmp += Utils.Constants.CENHDR));
+ // Perform the redirected request
+ try {
+ this._performRequest();
+ }
+ catch (cause) {
+ this.emit("error", new RedirectionError({ cause: cause }));
+ }
+};
- entry.entryName = inBuffer.slice(tmp, (tmp += entry.header.fileNameLength));
+// Wraps the key/value object of protocols with redirect functionality
+function wrap(protocols) {
+ // Default settings
+ var exports = {
+ maxRedirects: 21,
+ maxBodyLength: 10 * 1024 * 1024,
+ };
- if (entry.header.extraLength) {
- entry.extra = inBuffer.slice(tmp, (tmp += entry.header.extraLength));
- }
+ // Wrap each protocol
+ var nativeProtocols = {};
+ Object.keys(protocols).forEach(function (scheme) {
+ var protocol = scheme + ":";
+ var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];
+ var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol);
- if (entry.header.commentLength) entry.comment = inBuffer.slice(tmp, tmp + entry.header.commentLength);
+ // Executes a request, following redirects
+ function request(input, options, callback) {
+ // Parse parameters
+ if (isString(input)) {
+ var parsed;
+ try {
+ parsed = urlToOptions(new URL(input));
+ }
+ catch (err) {
+ /* istanbul ignore next */
+ parsed = url.parse(input);
+ }
+ if (!isString(parsed.protocol)) {
+ throw new InvalidUrlError({ input });
+ }
+ input = parsed;
+ }
+ else if (URL && (input instanceof URL)) {
+ input = urlToOptions(input);
+ }
+ else {
+ callback = options;
+ options = input;
+ input = { protocol: protocol };
+ }
+ if (isFunction(options)) {
+ callback = options;
+ options = null;
+ }
- index += entry.header.entryHeaderSize;
+ // Set defaults
+ options = Object.assign({
+ maxRedirects: exports.maxRedirects,
+ maxBodyLength: exports.maxBodyLength,
+ }, input, options);
+ options.nativeProtocols = nativeProtocols;
+ if (!isString(options.host) && !isString(options.hostname)) {
+ options.hostname = "::1";
+ }
- entryList[i] = entry;
- entryTable[entry.entryName] = entry;
- }
+ assert.equal(options.protocol, protocol, "protocol mismatch");
+ debug("options", options);
+ return new RedirectableRequest(options, callback);
}
- function readMainHeader(/*Boolean*/ readNow) {
- var i = inBuffer.length - Utils.Constants.ENDHDR, // END header size
- max = Math.max(0, i - 0xffff), // 0xFFFF is the max zip file comment length
- n = max,
- endStart = inBuffer.length,
- endOffset = -1, // Start offset of the END header
- commentEnd = 0;
-
- for (i; i >= n; i--) {
- if (inBuffer[i] !== 0x50) continue; // quick check that the byte is 'P'
- if (inBuffer.readUInt32LE(i) === Utils.Constants.ENDSIG) {
- // "PK\005\006"
- endOffset = i;
- commentEnd = i;
- endStart = i + Utils.Constants.ENDHDR;
- // We already found a regular signature, let's look just a bit further to check if there's any zip64 signature
- n = i - Utils.Constants.END64HDR;
- continue;
- }
+ // Executes a GET request, following redirects
+ function get(input, options, callback) {
+ var wrappedRequest = wrappedProtocol.request(input, options, callback);
+ wrappedRequest.end();
+ return wrappedRequest;
+ }
- if (inBuffer.readUInt32LE(i) === Utils.Constants.END64SIG) {
- // Found a zip64 signature, let's continue reading the whole zip64 record
- n = max;
- continue;
- }
+ // Expose the properties on the wrapped protocol
+ Object.defineProperties(wrappedProtocol, {
+ request: { value: request, configurable: true, enumerable: true, writable: true },
+ get: { value: get, configurable: true, enumerable: true, writable: true },
+ });
+ });
+ return exports;
+}
- if (inBuffer.readUInt32LE(i) === Utils.Constants.ZIP64SIG) {
- // Found the zip64 record, let's determine it's size
- endOffset = i;
- endStart = i + Utils.readBigUInt64LE(inBuffer, i + Utils.Constants.ZIP64SIZE) + Utils.Constants.ZIP64LEAD;
- break;
- }
- }
+/* istanbul ignore next */
+function noop() { /* empty */ }
- if (!~endOffset) throw new Error(Utils.Errors.INVALID_FORMAT);
+// from https://github.com/nodejs/node/blob/master/lib/internal/url.js
+function urlToOptions(urlObject) {
+ var options = {
+ protocol: urlObject.protocol,
+ hostname: urlObject.hostname.startsWith("[") ?
+ /* istanbul ignore next */
+ urlObject.hostname.slice(1, -1) :
+ urlObject.hostname,
+ hash: urlObject.hash,
+ search: urlObject.search,
+ pathname: urlObject.pathname,
+ path: urlObject.pathname + urlObject.search,
+ href: urlObject.href,
+ };
+ if (urlObject.port !== "") {
+ options.port = Number(urlObject.port);
+ }
+ return options;
+}
- mainHeader.loadFromBinary(inBuffer.slice(endOffset, endStart));
- if (mainHeader.commentLength) {
- _comment = inBuffer.slice(commentEnd + Utils.Constants.ENDHDR);
- }
- if (readNow) readEntries();
+function removeMatchingHeaders(regex, headers) {
+ var lastValue;
+ for (var header in headers) {
+ if (regex.test(header)) {
+ lastValue = headers[header];
+ delete headers[header];
}
+ }
+ return (lastValue === null || typeof lastValue === "undefined") ?
+ undefined : String(lastValue).trim();
+}
- function sortEntries() {
- if (entryList.length > 1 && !noSort) {
- entryList.sort((a, b) => a.entryName.toLowerCase().localeCompare(b.entryName.toLowerCase()));
- }
- }
+function createErrorType(code, message, baseClass) {
+ // Create constructor
+ function CustomError(properties) {
+ Error.captureStackTrace(this, this.constructor);
+ Object.assign(this, properties || {});
+ this.code = code;
+ this.message = this.cause ? message + ": " + this.cause.message : message;
+ }
- return {
- /**
- * Returns an array of ZipEntry objects existent in the current opened archive
- * @return Array
- */
- get entries() {
- if (!loadedEntries) {
- readEntries();
- }
- return entryList;
- },
+ // Attach constructor and set default properties
+ CustomError.prototype = new (baseClass || Error)();
+ CustomError.prototype.constructor = CustomError;
+ CustomError.prototype.name = "Error [" + code + "]";
+ return CustomError;
+}
- /**
- * Archive comment
- * @return {String}
- */
- get comment() {
- return _comment.toString();
- },
- set comment(val) {
- _comment = Utils.toBuffer(val);
- mainHeader.commentLength = _comment.length;
- },
+function abortRequest(request) {
+ for (var event of events) {
+ request.removeListener(event, eventHandlers[event]);
+ }
+ request.on("error", noop);
+ request.abort();
+}
- getEntryCount: function () {
- if (!loadedEntries) {
- return mainHeader.diskEntries;
- }
+function isSubdomain(subdomain, domain) {
+ assert(isString(subdomain) && isString(domain));
+ var dot = subdomain.length - domain.length - 1;
+ return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain);
+}
- return entryList.length;
- },
+function isString(value) {
+ return typeof value === "string" || value instanceof String;
+}
- forEach: function (callback) {
- if (!loadedEntries) {
- iterateEntries(callback);
- return;
- }
+function isFunction(value) {
+ return typeof value === "function";
+}
- entryList.forEach(callback);
- },
+function isBuffer(value) {
+ return typeof value === "object" && ("length" in value);
+}
- /**
- * Returns a reference to the entry with the given name or null if entry is inexistent
- *
- * @param entryName
- * @return ZipEntry
- */
- getEntry: function (/*String*/ entryName) {
- if (!loadedEntries) {
- readEntries();
- }
- return entryTable[entryName] || null;
- },
+// Exports
+module.exports = wrap({ http: http, https: https });
+module.exports.wrap = wrap;
- /**
- * Adds the given entry to the entry list
- *
- * @param entry
- */
- setEntry: function (/*ZipEntry*/ entry) {
- if (!loadedEntries) {
- readEntries();
- }
- entryList.push(entry);
- entryTable[entry.entryName] = entry;
- mainHeader.totalEntries = entryList.length;
- },
- /**
- * Removes the entry 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
- */
- deleteEntry: function (/*String*/ entryName) {
- if (!loadedEntries) {
- readEntries();
- }
- 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);
- }
- });
- }
- entryList.splice(entryList.indexOf(entry), 1);
- delete entryTable[entryName];
- mainHeader.totalEntries = entryList.length;
- },
+/***/ }),
- /**
- * Iterates and returns all nested files and directories of the given entry
- *
- * @param entry
- * @return Array
- */
- getEntryChildren: function (/*ZipEntry*/ entry) {
- if (!loadedEntries) {
- readEntries();
- }
- if (entry && entry.isDirectory) {
- const list = [];
- const name = entry.entryName;
- const len = name.length;
+/***/ 4334:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- entryList.forEach(function (zipEntry) {
- if (zipEntry.entryName.substr(0, len) === name) {
- list.push(zipEntry);
- }
- });
- return list;
- }
- return [];
- },
+var CombinedStream = __nccwpck_require__(5443);
+var util = __nccwpck_require__(3837);
+var path = __nccwpck_require__(1017);
+var http = __nccwpck_require__(3685);
+var https = __nccwpck_require__(5687);
+var parseUrl = (__nccwpck_require__(7310).parse);
+var fs = __nccwpck_require__(7147);
+var Stream = (__nccwpck_require__(2781).Stream);
+var mime = __nccwpck_require__(3583);
+var asynckit = __nccwpck_require__(4812);
+var populate = __nccwpck_require__(7142);
+
+// Public API
+module.exports = FormData;
+
+// make it a Stream
+util.inherits(FormData, CombinedStream);
+
+/**
+ * Create readable "multipart/form-data" streams.
+ * Can be used to submit forms
+ * and file uploads to other web applications.
+ *
+ * @constructor
+ * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream
+ */
+function FormData(options) {
+ if (!(this instanceof FormData)) {
+ return new FormData(options);
+ }
- /**
- * Returns the zip file
- *
- * @return Buffer
- */
- compressToBuffer: function () {
- if (!loadedEntries) {
- readEntries();
- }
- sortEntries();
+ this._overheadLength = 0;
+ this._valueLength = 0;
+ this._valuesToMeasure = [];
- const dataBlock = [];
- const entryHeaders = [];
- let totalSize = 0;
- let dindex = 0;
+ CombinedStream.call(this);
- mainHeader.size = 0;
- mainHeader.offset = 0;
+ options = options || {};
+ for (var option in options) {
+ this[option] = options[option];
+ }
+}
- for (const entry of entryList) {
- // compress data and set local and entry header accordingly. Reason why is called first
- const compressedData = entry.getCompressedData();
- // 1. construct data header
- entry.header.offset = dindex;
- const dataHeader = entry.header.dataHeaderToBinary();
- const entryNameLen = entry.rawEntryName.length;
- // 1.2. postheader - data after data header
- const postHeader = Buffer.alloc(entryNameLen + entry.extra.length);
- entry.rawEntryName.copy(postHeader, 0);
- postHeader.copy(entry.extra, entryNameLen);
+FormData.LINE_BREAK = '\r\n';
+FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream';
- // 2. offsets
- const dataLength = dataHeader.length + postHeader.length + compressedData.length;
- dindex += dataLength;
+FormData.prototype.append = function(field, value, options) {
- // 3. store values in sequence
- dataBlock.push(dataHeader);
- dataBlock.push(postHeader);
- dataBlock.push(compressedData);
+ options = options || {};
- // 4. construct entry header
- const entryHeader = entry.packHeader();
- entryHeaders.push(entryHeader);
- // 5. update main header
- mainHeader.size += entryHeader.length;
- totalSize += dataLength + entryHeader.length;
- }
+ // allow filename as single option
+ if (typeof options == 'string') {
+ options = {filename: options};
+ }
- totalSize += mainHeader.mainHeaderSize; // also includes zip file comment length
- // point to end of data and beginning of central directory first record
- mainHeader.offset = dindex;
+ var append = CombinedStream.prototype.append.bind(this);
- dindex = 0;
- const outBuffer = Buffer.alloc(totalSize);
- // write data blocks
- for (const content of dataBlock) {
- content.copy(outBuffer, dindex);
- dindex += content.length;
- }
+ // all that streamy business can't handle numbers
+ if (typeof value == 'number') {
+ value = '' + value;
+ }
- // write central directory entries
- for (const content of entryHeaders) {
- content.copy(outBuffer, dindex);
- dindex += content.length;
- }
+ // https://github.com/felixge/node-form-data/issues/38
+ if (util.isArray(value)) {
+ // Please convert your array into string
+ // the way web server expects it
+ this._error(new Error('Arrays are not supported.'));
+ return;
+ }
- // write main header
- const mh = mainHeader.toBinary();
- if (_comment) {
- _comment.copy(mh, Utils.Constants.ENDHDR); // add zip file comment
- }
- mh.copy(outBuffer, dindex);
+ var header = this._multiPartHeader(field, value, options);
+ var footer = this._multiPartFooter();
- return outBuffer;
- },
+ append(header);
+ append(value);
+ append(footer);
- toAsyncBuffer: function (/*Function*/ onSuccess, /*Function*/ onFail, /*Function*/ onItemStart, /*Function*/ onItemEnd) {
- try {
- if (!loadedEntries) {
- readEntries();
- }
- sortEntries();
+ // pass along options.knownLength
+ this._trackLength(header, value, options);
+};
- const dataBlock = [];
- const entryHeaders = [];
- let totalSize = 0;
- let dindex = 0;
+FormData.prototype._trackLength = function(header, value, options) {
+ var valueLength = 0;
- mainHeader.size = 0;
- mainHeader.offset = 0;
+ // used w/ getLengthSync(), when length is known.
+ // e.g. for streaming directly from a remote server,
+ // w/ a known file a size, and not wanting to wait for
+ // incoming file to finish to get its size.
+ if (options.knownLength != null) {
+ valueLength += +options.knownLength;
+ } else if (Buffer.isBuffer(value)) {
+ valueLength = value.length;
+ } else if (typeof value === 'string') {
+ valueLength = Buffer.byteLength(value);
+ }
- const compress2Buffer = function (entryLists) {
- if (entryLists.length) {
- const entry = entryLists.pop();
- const name = entry.entryName + entry.extra.toString();
- if (onItemStart) onItemStart(name);
- entry.getCompressedDataAsync(function (compressedData) {
- if (onItemEnd) onItemEnd(name);
+ this._valueLength += valueLength;
- entry.header.offset = dindex;
- // data header
- const dataHeader = entry.header.dataHeaderToBinary();
- const postHeader = Buffer.alloc(name.length, name);
- const dataLength = dataHeader.length + postHeader.length + compressedData.length;
+ // @check why add CRLF? does this account for custom/multiple CRLFs?
+ this._overheadLength +=
+ Buffer.byteLength(header) +
+ FormData.LINE_BREAK.length;
- dindex += dataLength;
+ // empty or either doesn't have path or not an http response or not a stream
+ if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) && !(value instanceof Stream))) {
+ return;
+ }
- dataBlock.push(dataHeader);
- dataBlock.push(postHeader);
- dataBlock.push(compressedData);
+ // no need to bother with the length
+ if (!options.knownLength) {
+ this._valuesToMeasure.push(value);
+ }
+};
- const entryHeader = entry.packHeader();
- entryHeaders.push(entryHeader);
- mainHeader.size += entryHeader.length;
- totalSize += dataLength + entryHeader.length;
+FormData.prototype._lengthRetriever = function(value, callback) {
- compress2Buffer(entryLists);
- });
- } else {
- totalSize += mainHeader.mainHeaderSize; // also includes zip file comment length
- // point to end of data and beginning of central directory first record
- mainHeader.offset = dindex;
+ if (value.hasOwnProperty('fd')) {
- dindex = 0;
- const outBuffer = Buffer.alloc(totalSize);
- dataBlock.forEach(function (content) {
- content.copy(outBuffer, dindex); // write data blocks
- dindex += content.length;
- });
- entryHeaders.forEach(function (content) {
- content.copy(outBuffer, dindex); // write central directory entries
- dindex += content.length;
- });
+ // take read range into a account
+ // `end` = Infinity –> read file till the end
+ //
+ // TODO: Looks like there is bug in Node fs.createReadStream
+ // it doesn't respect `end` options without `start` options
+ // Fix it when node fixes it.
+ // https://github.com/joyent/node/issues/7819
+ if (value.end != undefined && value.end != Infinity && value.start != undefined) {
- const mh = mainHeader.toBinary();
- if (_comment) {
- _comment.copy(mh, Utils.Constants.ENDHDR); // add zip file comment
- }
+ // when end specified
+ // no need to calculate range
+ // inclusive, starts with 0
+ callback(null, value.end + 1 - (value.start ? value.start : 0));
- mh.copy(outBuffer, dindex); // write main header
+ // not that fast snoopy
+ } else {
+ // still need to fetch file size from fs
+ fs.stat(value.path, function(err, stat) {
- onSuccess(outBuffer);
- }
- };
+ var fileSize;
- compress2Buffer(entryList);
- } catch (e) {
- onFail(e);
- }
+ if (err) {
+ callback(err);
+ return;
}
- };
-};
+ // update final size based on the range options
+ fileSize = stat.size - (value.start ? value.start : 0);
+ callback(null, fileSize);
+ });
+ }
-/***/ }),
+ // or http response
+ } else if (value.hasOwnProperty('httpVersion')) {
+ callback(null, +value.headers['content-length']);
-/***/ 4812:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // or request stream http://github.com/mikeal/request
+ } else if (value.hasOwnProperty('httpModule')) {
+ // wait till response come back
+ value.on('response', function(response) {
+ value.pause();
+ callback(null, +response.headers['content-length']);
+ });
+ value.resume();
-module.exports =
-{
- parallel : __nccwpck_require__(8210),
- serial : __nccwpck_require__(445),
- serialOrdered : __nccwpck_require__(3578)
+ // something else
+ } else {
+ callback('Unknown stream');
+ }
};
+FormData.prototype._multiPartHeader = function(field, value, options) {
+ // custom header specified (as string)?
+ // it becomes responsible for boundary
+ // (e.g. to handle extra CRLFs on .NET servers)
+ if (typeof options.header == 'string') {
+ return options.header;
+ }
-/***/ }),
-
-/***/ 1700:
-/***/ ((module) => {
+ var contentDisposition = this._getContentDisposition(value, options);
+ var contentType = this._getContentType(value, options);
-// API
-module.exports = abort;
+ var contents = '';
+ var headers = {
+ // add custom disposition as third element or keep it two elements if not
+ 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []),
+ // if no content type. allow it to be empty array
+ 'Content-Type': [].concat(contentType || [])
+ };
-/**
- * Aborts leftover active jobs
- *
- * @param {object} state - current state object
- */
-function abort(state)
-{
- Object.keys(state.jobs).forEach(clean.bind(state));
+ // allow custom headers.
+ if (typeof options.header == 'object') {
+ populate(headers, options.header);
+ }
- // reset leftover jobs
- state.jobs = {};
-}
+ var header;
+ for (var prop in headers) {
+ if (!headers.hasOwnProperty(prop)) continue;
+ header = headers[prop];
-/**
- * Cleans up leftover job by invoking abort function for the provided job id
- *
- * @this state
- * @param {string|number} key - job id to abort
- */
-function clean(key)
-{
- if (typeof this.jobs[key] == 'function')
- {
- this.jobs[key]();
- }
-}
+ // skip nullish headers.
+ if (header == null) {
+ continue;
+ }
+ // convert all headers to arrays.
+ if (!Array.isArray(header)) {
+ header = [header];
+ }
-/***/ }),
+ // add non-empty headers.
+ if (header.length) {
+ contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK;
+ }
+ }
-/***/ 2794:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK;
+};
-var defer = __nccwpck_require__(5295);
+FormData.prototype._getContentDisposition = function(value, options) {
-// API
-module.exports = async;
+ var filename
+ , contentDisposition
+ ;
-/**
- * Runs provided callback asynchronously
- * even if callback itself is not
- *
- * @param {function} callback - callback to invoke
- * @returns {function} - augmented callback
- */
-function async(callback)
-{
- var isAsync = false;
+ if (typeof options.filepath === 'string') {
+ // custom filepath for relative paths
+ filename = path.normalize(options.filepath).replace(/\\/g, '/');
+ } else if (options.filename || value.name || value.path) {
+ // custom filename take precedence
+ // formidable and the browser add a name property
+ // fs- and request- streams have path property
+ filename = path.basename(options.filename || value.name || value.path);
+ } else if (value.readable && value.hasOwnProperty('httpVersion')) {
+ // or try http response
+ filename = path.basename(value.client._httpMessage.path || '');
+ }
- // check if async happened
- defer(function() { isAsync = true; });
+ if (filename) {
+ contentDisposition = 'filename="' + filename + '"';
+ }
- return function async_callback(err, result)
- {
- if (isAsync)
- {
- callback(err, result);
- }
- else
- {
- defer(function nextTick_callback()
- {
- callback(err, result);
- });
- }
- };
-}
+ return contentDisposition;
+};
+FormData.prototype._getContentType = function(value, options) {
-/***/ }),
+ // use custom content-type above all
+ var contentType = options.contentType;
-/***/ 5295:
-/***/ ((module) => {
+ // or try `name` from formidable, browser
+ if (!contentType && value.name) {
+ contentType = mime.lookup(value.name);
+ }
-module.exports = defer;
+ // or try `path` from fs-, request- streams
+ if (!contentType && value.path) {
+ contentType = mime.lookup(value.path);
+ }
-/**
- * Runs provided function on next iteration of the event loop
- *
- * @param {function} fn - function to run
- */
-function defer(fn)
-{
- var nextTick = typeof setImmediate == 'function'
- ? setImmediate
- : (
- typeof process == 'object' && typeof process.nextTick == 'function'
- ? process.nextTick
- : null
- );
+ // or if it's http-reponse
+ if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) {
+ contentType = value.headers['content-type'];
+ }
- if (nextTick)
- {
- nextTick(fn);
+ // or guess it from the filepath or filename
+ if (!contentType && (options.filepath || options.filename)) {
+ contentType = mime.lookup(options.filepath || options.filename);
}
- else
- {
- setTimeout(fn, 0);
+
+ // fallback to the default content type if `value` is not simple value
+ if (!contentType && typeof value == 'object') {
+ contentType = FormData.DEFAULT_CONTENT_TYPE;
}
-}
+ return contentType;
+};
-/***/ }),
+FormData.prototype._multiPartFooter = function() {
+ return function(next) {
+ var footer = FormData.LINE_BREAK;
-/***/ 9023:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ var lastPart = (this._streams.length === 0);
+ if (lastPart) {
+ footer += this._lastBoundary();
+ }
-var async = __nccwpck_require__(2794)
- , abort = __nccwpck_require__(1700)
- ;
+ next(footer);
+ }.bind(this);
+};
-// API
-module.exports = iterate;
+FormData.prototype._lastBoundary = function() {
+ return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK;
+};
-/**
- * Iterates over each job object
- *
- * @param {array|object} list - array or object (named list) to iterate over
- * @param {function} iterator - iterator to run
- * @param {object} state - current job status
- * @param {function} callback - invoked when all elements processed
- */
-function iterate(list, iterator, state, callback)
-{
- // store current index
- var key = state['keyedList'] ? state['keyedList'][state.index] : state.index;
+FormData.prototype.getHeaders = function(userHeaders) {
+ var header;
+ var formHeaders = {
+ 'content-type': 'multipart/form-data; boundary=' + this.getBoundary()
+ };
- state.jobs[key] = runJob(iterator, key, list[key], function(error, output)
- {
- // don't repeat yourself
- // skip secondary callbacks
- if (!(key in state.jobs))
- {
- return;
+ for (header in userHeaders) {
+ if (userHeaders.hasOwnProperty(header)) {
+ formHeaders[header.toLowerCase()] = userHeaders[header];
}
+ }
- // clean up jobs
- delete state.jobs[key];
+ return formHeaders;
+};
- if (error)
- {
- // don't process rest of the results
- // stop still active jobs
- // and reset the list
- abort(state);
- }
- else
- {
- state.results[key] = output;
+FormData.prototype.setBoundary = function(boundary) {
+ this._boundary = boundary;
+};
+
+FormData.prototype.getBoundary = function() {
+ if (!this._boundary) {
+ this._generateBoundary();
+ }
+
+ return this._boundary;
+};
+
+FormData.prototype.getBuffer = function() {
+ var dataBuffer = new Buffer.alloc( 0 );
+ var boundary = this.getBoundary();
+
+ // Create the form content. Add Line breaks to the end of data.
+ for (var i = 0, len = this._streams.length; i < len; i++) {
+ if (typeof this._streams[i] !== 'function') {
+
+ // Add content to the buffer.
+ if(Buffer.isBuffer(this._streams[i])) {
+ dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]);
+ }else {
+ dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]);
+ }
+
+ // Add break after content.
+ if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) {
+ dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData.LINE_BREAK)] );
+ }
}
+ }
- // return salvaged results
- callback(error, state.results);
- });
-}
+ // Add the footer and return the Buffer object.
+ return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] );
+};
-/**
- * Runs iterator over provided job element
- *
- * @param {function} iterator - iterator to invoke
- * @param {string|number} key - key/index of the element in the list of jobs
- * @param {mixed} item - job description
- * @param {function} callback - invoked after iterator is done with the job
- * @returns {function|mixed} - job abort function or something else
- */
-function runJob(iterator, key, item, callback)
-{
- var aborter;
+FormData.prototype._generateBoundary = function() {
+ // This generates a 50 character boundary similar to those used by Firefox.
+ // They are optimized for boyer-moore parsing.
+ var boundary = '--------------------------';
+ for (var i = 0; i < 24; i++) {
+ boundary += Math.floor(Math.random() * 10).toString(16);
+ }
- // allow shortcut if iterator expects only two arguments
- if (iterator.length == 2)
- {
- aborter = iterator(item, async(callback));
+ this._boundary = boundary;
+};
+
+// Note: getLengthSync DOESN'T calculate streams length
+// As workaround one can calculate file size manually
+// and add it as knownLength option
+FormData.prototype.getLengthSync = function() {
+ var knownLength = this._overheadLength + this._valueLength;
+
+ // Don't get confused, there are 3 "internal" streams for each keyval pair
+ // so it basically checks if there is any value added to the form
+ if (this._streams.length) {
+ knownLength += this._lastBoundary().length;
}
- // otherwise go with full three arguments
- else
- {
- aborter = iterator(item, key, async(callback));
+
+ // https://github.com/form-data/form-data/issues/40
+ if (!this.hasKnownLength()) {
+ // Some async length retrievers are present
+ // therefore synchronous length calculation is false.
+ // Please use getLength(callback) to get proper length
+ this._error(new Error('Cannot calculate proper length in synchronous way.'));
}
- return aborter;
-}
+ return knownLength;
+};
+// Public API to check if length of added values is known
+// https://github.com/form-data/form-data/issues/196
+// https://github.com/form-data/form-data/issues/262
+FormData.prototype.hasKnownLength = function() {
+ var hasKnownLength = true;
-/***/ }),
+ if (this._valuesToMeasure.length) {
+ hasKnownLength = false;
+ }
-/***/ 2474:
-/***/ ((module) => {
+ return hasKnownLength;
+};
-// API
-module.exports = state;
+FormData.prototype.getLength = function(cb) {
+ var knownLength = this._overheadLength + this._valueLength;
-/**
- * Creates initial state object
- * for iteration over list
- *
- * @param {array|object} list - list to iterate over
- * @param {function|null} sortMethod - function to use for keys sort,
- * or `null` to keep them as is
- * @returns {object} - initial state object
- */
-function state(list, sortMethod)
-{
- var isNamedList = !Array.isArray(list)
- , initState =
- {
- index : 0,
- keyedList: isNamedList || sortMethod ? Object.keys(list) : null,
- jobs : {},
- results : isNamedList ? {} : [],
- size : isNamedList ? Object.keys(list).length : list.length
- }
- ;
+ if (this._streams.length) {
+ knownLength += this._lastBoundary().length;
+ }
- if (sortMethod)
- {
- // sort array keys based on it's values
- // sort object's keys just on own merit
- initState.keyedList.sort(isNamedList ? sortMethod : function(a, b)
- {
- return sortMethod(list[a], list[b]);
- });
+ if (!this._valuesToMeasure.length) {
+ process.nextTick(cb.bind(this, null, knownLength));
+ return;
}
- return initState;
-}
+ asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) {
+ if (err) {
+ cb(err);
+ return;
+ }
+ values.forEach(function(length) {
+ knownLength += length;
+ });
-/***/ }),
+ cb(null, knownLength);
+ });
+};
-/***/ 7942:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+FormData.prototype.submit = function(params, cb) {
+ var request
+ , options
+ , defaults = {method: 'post'}
+ ;
-var abort = __nccwpck_require__(1700)
- , async = __nccwpck_require__(2794)
- ;
+ // parse provided url if it's string
+ // or treat it as options object
+ if (typeof params == 'string') {
-// API
-module.exports = terminator;
+ params = parseUrl(params);
+ options = populate({
+ port: params.port,
+ path: params.pathname,
+ host: params.hostname,
+ protocol: params.protocol
+ }, defaults);
-/**
- * Terminates jobs in the attached state context
- *
- * @this AsyncKitState#
- * @param {function} callback - final callback to invoke after termination
- */
-function terminator(callback)
-{
- if (!Object.keys(this.jobs).length)
- {
- return;
- }
+ // use custom params
+ } else {
- // fast forward iteration index
- this.index = this.size;
+ options = populate(params, defaults);
+ // if no port provided use default one
+ if (!options.port) {
+ options.port = options.protocol == 'https:' ? 443 : 80;
+ }
+ }
- // abort jobs
- abort(this);
+ // put that good code in getHeaders to some use
+ options.headers = this.getHeaders(params.headers);
- // send back results we have so far
- async(callback)(null, this.results);
-}
+ // https if specified, fallback to http in any other case
+ if (options.protocol == 'https:') {
+ request = https.request(options);
+ } else {
+ request = http.request(options);
+ }
+ // get content length and fire away
+ this.getLength(function(err, length) {
+ if (err && err !== 'Unknown stream') {
+ this._error(err);
+ return;
+ }
-/***/ }),
+ // add content length
+ if (length) {
+ request.setHeader('Content-Length', length);
+ }
-/***/ 8210:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ this.pipe(request);
+ if (cb) {
+ var onResponse;
-var iterate = __nccwpck_require__(9023)
- , initState = __nccwpck_require__(2474)
- , terminator = __nccwpck_require__(7942)
- ;
+ var callback = function (error, responce) {
+ request.removeListener('error', callback);
+ request.removeListener('response', onResponse);
-// Public API
-module.exports = parallel;
+ return cb.call(this, error, responce);
+ };
-/**
- * Runs iterator over provided array elements in parallel
- *
- * @param {array|object} list - array or object (named list) to iterate over
- * @param {function} iterator - iterator to run
- * @param {function} callback - invoked when all elements processed
- * @returns {function} - jobs terminator
- */
-function parallel(list, iterator, callback)
-{
- var state = initState(list);
+ onResponse = callback.bind(this, null);
- while (state.index < (state['keyedList'] || list).length)
- {
- iterate(list, iterator, state, function(error, result)
- {
- if (error)
- {
- callback(error, result);
- return;
- }
+ request.on('error', callback);
+ request.on('response', onResponse);
+ }
+ }.bind(this));
- // looks like it's the last one
- if (Object.keys(state.jobs).length === 0)
- {
- callback(null, state.results);
- return;
- }
- });
+ return request;
+};
- state.index++;
+FormData.prototype._error = function(err) {
+ if (!this.error) {
+ this.error = err;
+ this.pause();
+ this.emit('error', err);
}
+};
- return terminator.bind(state, callback);
-}
+FormData.prototype.toString = function () {
+ return '[object FormData]';
+};
/***/ }),
-/***/ 445:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 7142:
+/***/ ((module) => {
-var serialOrdered = __nccwpck_require__(3578);
+// populates missing values
+module.exports = function(dst, src) {
-// Public API
-module.exports = serial;
+ Object.keys(src).forEach(function(prop)
+ {
+ dst[prop] = dst[prop] || src[prop];
+ });
-/**
- * Runs iterator over provided array elements in series
- *
- * @param {array|object} list - array or object (named list) to iterate over
- * @param {function} iterator - iterator to run
- * @param {function} callback - invoked when all elements processed
- * @returns {function} - jobs terminator
- */
-function serial(list, iterator, callback)
-{
- return serialOrdered(list, iterator, null, callback);
-}
+ return dst;
+};
/***/ }),
-/***/ 3578:
+/***/ 6863:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-var iterate = __nccwpck_require__(9023)
- , initState = __nccwpck_require__(2474)
- , terminator = __nccwpck_require__(7942)
- ;
+module.exports = realpath
+realpath.realpath = realpath
+realpath.sync = realpathSync
+realpath.realpathSync = realpathSync
+realpath.monkeypatch = monkeypatch
+realpath.unmonkeypatch = unmonkeypatch
-// Public API
-module.exports = serialOrdered;
-// sorting helpers
-module.exports.ascending = ascending;
-module.exports.descending = descending;
+var fs = __nccwpck_require__(7147)
+var origRealpath = fs.realpath
+var origRealpathSync = fs.realpathSync
-/**
- * Runs iterator over provided sorted array elements in series
- *
- * @param {array|object} list - array or object (named list) to iterate over
- * @param {function} iterator - iterator to run
- * @param {function} sortMethod - custom sort function
- * @param {function} callback - invoked when all elements processed
- * @returns {function} - jobs terminator
- */
-function serialOrdered(list, iterator, sortMethod, callback)
-{
- var state = initState(list, sortMethod);
+var version = process.version
+var ok = /^v[0-5]\./.test(version)
+var old = __nccwpck_require__(1734)
- iterate(list, iterator, state, function iteratorHandler(error, result)
- {
- if (error)
- {
- callback(error, result);
- return;
- }
+function newError (er) {
+ return er && er.syscall === 'realpath' && (
+ er.code === 'ELOOP' ||
+ er.code === 'ENOMEM' ||
+ er.code === 'ENAMETOOLONG'
+ )
+}
- state.index++;
+function realpath (p, cache, cb) {
+ if (ok) {
+ return origRealpath(p, cache, cb)
+ }
- // are we there yet?
- if (state.index < (state['keyedList'] || list).length)
- {
- iterate(list, iterator, state, iteratorHandler);
- return;
+ if (typeof cache === 'function') {
+ cb = cache
+ cache = null
+ }
+ origRealpath(p, cache, function (er, result) {
+ if (newError(er)) {
+ old.realpath(p, cache, cb)
+ } else {
+ cb(er, result)
}
+ })
+}
- // done here
- callback(null, state.results);
- });
+function realpathSync (p, cache) {
+ if (ok) {
+ return origRealpathSync(p, cache)
+ }
- return terminator.bind(state, callback);
+ try {
+ return origRealpathSync(p, cache)
+ } catch (er) {
+ if (newError(er)) {
+ return old.realpathSync(p, cache)
+ } else {
+ throw er
+ }
+ }
}
-/*
- * -- Sort methods
- */
-
-/**
- * sort helper to sort array elements in ascending order
- *
- * @param {mixed} a - an item to compare
- * @param {mixed} b - an item to compare
- * @returns {number} - comparison result
- */
-function ascending(a, b)
-{
- return a < b ? -1 : a > b ? 1 : 0;
+function monkeypatch () {
+ fs.realpath = realpath
+ fs.realpathSync = realpathSync
}
-/**
- * sort helper to sort array elements in descending order
- *
- * @param {mixed} a - an item to compare
- * @param {mixed} b - an item to compare
- * @returns {number} - comparison result
- */
-function descending(a, b)
-{
- return -1 * ascending(a, b);
+function unmonkeypatch () {
+ fs.realpath = origRealpath
+ fs.realpathSync = origRealpathSync
}
/***/ }),
-/***/ 9417:
-/***/ ((module) => {
+/***/ 1734:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-"use strict";
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
-module.exports = balanced;
-function balanced(a, b, str) {
- if (a instanceof RegExp) a = maybeMatch(a, str);
- if (b instanceof RegExp) b = maybeMatch(b, str);
+var pathModule = __nccwpck_require__(1017);
+var isWindows = process.platform === 'win32';
+var fs = __nccwpck_require__(7147);
- var r = range(a, b, str);
+// JavaScript implementation of realpath, ported from node pre-v6
- return r && {
- start: r[0],
- end: r[1],
- pre: str.slice(0, r[0]),
- body: str.slice(r[0] + a.length, r[1]),
- post: str.slice(r[1] + b.length)
- };
-}
+var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
-function maybeMatch(reg, str) {
- var m = str.match(reg);
- return m ? m[0] : null;
-}
+function rethrow() {
+ // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
+ // is fairly slow to generate.
+ var callback;
+ if (DEBUG) {
+ var backtrace = new Error;
+ callback = debugCallback;
+ } else
+ callback = missingCallback;
-balanced.range = range;
-function range(a, b, str) {
- var begs, beg, left, right, result;
- var ai = str.indexOf(a);
- var bi = str.indexOf(b, ai + 1);
- var i = ai;
+ return callback;
- if (ai >= 0 && bi > 0) {
- if(a===b) {
- return [ai, bi];
+ function debugCallback(err) {
+ if (err) {
+ backtrace.message = err.message;
+ err = backtrace;
+ missingCallback(err);
}
- begs = [];
- left = str.length;
-
- while (i >= 0 && !result) {
- if (i == ai) {
- begs.push(i);
- ai = str.indexOf(a, i + 1);
- } else if (begs.length == 1) {
- result = [ begs.pop(), bi ];
- } else {
- beg = begs.pop();
- if (beg < left) {
- left = beg;
- right = bi;
- }
+ }
- bi = str.indexOf(b, i + 1);
+ function missingCallback(err) {
+ if (err) {
+ if (process.throwDeprecation)
+ throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
+ else if (!process.noDeprecation) {
+ var msg = 'fs: missing callback ' + (err.stack || err.message);
+ if (process.traceDeprecation)
+ console.trace(msg);
+ else
+ console.error(msg);
}
-
- i = ai < bi && ai >= 0 ? ai : bi;
- }
-
- if (begs.length) {
- result = [ left, right ];
}
}
+}
- return result;
+function maybeCallback(cb) {
+ return typeof cb === 'function' ? cb : rethrow();
+}
+
+var normalize = pathModule.normalize;
+
+// Regexp that finds the next partion of a (partial) path
+// result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
+if (isWindows) {
+ var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
+} else {
+ var nextPartRe = /(.*?)(?:[\/]+|$)/g;
}
+// Regex to find the device root, including trailing slash. E.g. 'c:\\'.
+if (isWindows) {
+ var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
+} else {
+ var splitRootRe = /^[\/]*/;
+}
-/***/ }),
+exports.realpathSync = function realpathSync(p, cache) {
+ // make p is absolute
+ p = pathModule.resolve(p);
-/***/ 5443:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
+ return cache[p];
+ }
-var util = __nccwpck_require__(3837);
-var Stream = (__nccwpck_require__(2781).Stream);
-var DelayedStream = __nccwpck_require__(8611);
+ var original = p,
+ seenLinks = {},
+ knownHard = {};
-module.exports = CombinedStream;
-function CombinedStream() {
- this.writable = false;
- this.readable = true;
- this.dataSize = 0;
- this.maxDataSize = 2 * 1024 * 1024;
- this.pauseStreams = true;
+ // current character position in p
+ var pos;
+ // the partial path so far, including a trailing slash if any
+ var current;
+ // the partial path without a trailing slash (except when pointing at a root)
+ var base;
+ // the partial path scanned in the previous round, with slash
+ var previous;
- this._released = false;
- this._streams = [];
- this._currentStream = null;
- this._insideLoop = false;
- this._pendingNext = false;
-}
-util.inherits(CombinedStream, Stream);
+ start();
-CombinedStream.create = function(options) {
- var combinedStream = new this();
+ function start() {
+ // Skip over roots
+ var m = splitRootRe.exec(p);
+ pos = m[0].length;
+ current = m[0];
+ base = m[0];
+ previous = '';
- options = options || {};
- for (var option in options) {
- combinedStream[option] = options[option];
+ // On windows, check that the root exists. On unix there is no need.
+ if (isWindows && !knownHard[base]) {
+ fs.lstatSync(base);
+ knownHard[base] = true;
+ }
}
- return combinedStream;
-};
-
-CombinedStream.isStreamLike = function(stream) {
- return (typeof stream !== 'function')
- && (typeof stream !== 'string')
- && (typeof stream !== 'boolean')
- && (typeof stream !== 'number')
- && (!Buffer.isBuffer(stream));
-};
-
-CombinedStream.prototype.append = function(stream) {
- var isStreamLike = CombinedStream.isStreamLike(stream);
+ // walk down the path, swapping out linked pathparts for their real
+ // values
+ // NB: p.length changes.
+ while (pos < p.length) {
+ // find the next part
+ nextPartRe.lastIndex = pos;
+ var result = nextPartRe.exec(p);
+ previous = current;
+ current += result[0];
+ base = previous + result[1];
+ pos = nextPartRe.lastIndex;
- if (isStreamLike) {
- if (!(stream instanceof DelayedStream)) {
- var newStream = DelayedStream.create(stream, {
- maxDataSize: Infinity,
- pauseStream: this.pauseStreams,
- });
- stream.on('data', this._checkDataSize.bind(this));
- stream = newStream;
+ // continue if not a symlink
+ if (knownHard[base] || (cache && cache[base] === base)) {
+ continue;
}
- this._handleErrors(stream);
+ var resolvedLink;
+ if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
+ // some known symbolic link. no need to stat again.
+ resolvedLink = cache[base];
+ } else {
+ var stat = fs.lstatSync(base);
+ if (!stat.isSymbolicLink()) {
+ knownHard[base] = true;
+ if (cache) cache[base] = base;
+ continue;
+ }
- if (this.pauseStreams) {
- stream.pause();
+ // read the link if it wasn't read before
+ // dev/ino always return 0 on windows, so skip the check.
+ var linkTarget = null;
+ if (!isWindows) {
+ var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
+ if (seenLinks.hasOwnProperty(id)) {
+ linkTarget = seenLinks[id];
+ }
+ }
+ if (linkTarget === null) {
+ fs.statSync(base);
+ linkTarget = fs.readlinkSync(base);
+ }
+ resolvedLink = pathModule.resolve(previous, linkTarget);
+ // track this, if given a cache.
+ if (cache) cache[base] = resolvedLink;
+ if (!isWindows) seenLinks[id] = linkTarget;
}
+
+ // resolve the link, then start over
+ p = pathModule.resolve(resolvedLink, p.slice(pos));
+ start();
}
- this._streams.push(stream);
- return this;
-};
+ if (cache) cache[original] = p;
-CombinedStream.prototype.pipe = function(dest, options) {
- Stream.prototype.pipe.call(this, dest, options);
- this.resume();
- return dest;
+ return p;
};
-CombinedStream.prototype._getNext = function() {
- this._currentStream = null;
- if (this._insideLoop) {
- this._pendingNext = true;
- return; // defer call
+exports.realpath = function realpath(p, cache, cb) {
+ if (typeof cb !== 'function') {
+ cb = maybeCallback(cache);
+ cache = null;
}
- this._insideLoop = true;
- try {
- do {
- this._pendingNext = false;
- this._realGetNext();
- } while (this._pendingNext);
- } finally {
- this._insideLoop = false;
+ // make p is absolute
+ p = pathModule.resolve(p);
+
+ if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
+ return process.nextTick(cb.bind(null, null, cache[p]));
}
-};
-CombinedStream.prototype._realGetNext = function() {
- var stream = this._streams.shift();
+ var original = p,
+ seenLinks = {},
+ knownHard = {};
+ // current character position in p
+ var pos;
+ // the partial path so far, including a trailing slash if any
+ var current;
+ // the partial path without a trailing slash (except when pointing at a root)
+ var base;
+ // the partial path scanned in the previous round, with slash
+ var previous;
- if (typeof stream == 'undefined') {
- this.end();
- return;
- }
+ start();
- if (typeof stream !== 'function') {
- this._pipeNext(stream);
- return;
+ function start() {
+ // Skip over roots
+ var m = splitRootRe.exec(p);
+ pos = m[0].length;
+ current = m[0];
+ base = m[0];
+ previous = '';
+
+ // On windows, check that the root exists. On unix there is no need.
+ if (isWindows && !knownHard[base]) {
+ fs.lstat(base, function(err) {
+ if (err) return cb(err);
+ knownHard[base] = true;
+ LOOP();
+ });
+ } else {
+ process.nextTick(LOOP);
+ }
}
- var getStream = stream;
- getStream(function(stream) {
- var isStreamLike = CombinedStream.isStreamLike(stream);
- if (isStreamLike) {
- stream.on('data', this._checkDataSize.bind(this));
- this._handleErrors(stream);
+ // walk down the path, swapping out linked pathparts for their real
+ // values
+ function LOOP() {
+ // stop if scanned past end of path
+ if (pos >= p.length) {
+ if (cache) cache[original] = p;
+ return cb(null, p);
}
- this._pipeNext(stream);
- }.bind(this));
-};
+ // find the next part
+ nextPartRe.lastIndex = pos;
+ var result = nextPartRe.exec(p);
+ previous = current;
+ current += result[0];
+ base = previous + result[1];
+ pos = nextPartRe.lastIndex;
-CombinedStream.prototype._pipeNext = function(stream) {
- this._currentStream = stream;
+ // continue if not a symlink
+ if (knownHard[base] || (cache && cache[base] === base)) {
+ return process.nextTick(LOOP);
+ }
- var isStreamLike = CombinedStream.isStreamLike(stream);
- if (isStreamLike) {
- stream.on('end', this._getNext.bind(this));
- stream.pipe(this, {end: false});
- return;
+ if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
+ // known symbolic link. no need to stat again.
+ return gotResolvedLink(cache[base]);
+ }
+
+ return fs.lstat(base, gotStat);
}
- var value = stream;
- this.write(value);
- this._getNext();
-};
+ function gotStat(err, stat) {
+ if (err) return cb(err);
-CombinedStream.prototype._handleErrors = function(stream) {
- var self = this;
- stream.on('error', function(err) {
- self._emitError(err);
- });
-};
+ // if not a symlink, skip to the next path part
+ if (!stat.isSymbolicLink()) {
+ knownHard[base] = true;
+ if (cache) cache[base] = base;
+ return process.nextTick(LOOP);
+ }
-CombinedStream.prototype.write = function(data) {
- this.emit('data', data);
-};
+ // stat & read the link if not read before
+ // call gotTarget as soon as the link target is known
+ // dev/ino always return 0 on windows, so skip the check.
+ if (!isWindows) {
+ var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
+ if (seenLinks.hasOwnProperty(id)) {
+ return gotTarget(null, seenLinks[id], base);
+ }
+ }
+ fs.stat(base, function(err) {
+ if (err) return cb(err);
-CombinedStream.prototype.pause = function() {
- if (!this.pauseStreams) {
- return;
+ fs.readlink(base, function(err, target) {
+ if (!isWindows) seenLinks[id] = target;
+ gotTarget(err, target);
+ });
+ });
}
- if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause();
- this.emit('pause');
-};
+ function gotTarget(err, target, base) {
+ if (err) return cb(err);
-CombinedStream.prototype.resume = function() {
- if (!this._released) {
- this._released = true;
- this.writable = true;
- this._getNext();
+ var resolvedLink = pathModule.resolve(previous, target);
+ if (cache) cache[base] = resolvedLink;
+ gotResolvedLink(resolvedLink);
}
- if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume();
- this.emit('resume');
-};
-
-CombinedStream.prototype.end = function() {
- this._reset();
- this.emit('end');
-};
-
-CombinedStream.prototype.destroy = function() {
- this._reset();
- this.emit('close');
-};
-
-CombinedStream.prototype._reset = function() {
- this.writable = false;
- this._streams = [];
- this._currentStream = null;
+ function gotResolvedLink(resolvedLink) {
+ // resolve the link, then start over
+ p = pathModule.resolve(resolvedLink, p.slice(pos));
+ start();
+ }
};
-CombinedStream.prototype._checkDataSize = function() {
- this._updateDataSize();
- if (this.dataSize <= this.maxDataSize) {
- return;
- }
- var message =
- 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.';
- this._emitError(new Error(message));
-};
+/***/ }),
-CombinedStream.prototype._updateDataSize = function() {
- this.dataSize = 0;
+/***/ 7625:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- var self = this;
- this._streams.forEach(function(stream) {
- if (!stream.dataSize) {
- return;
- }
+exports.setopts = setopts
+exports.ownProp = ownProp
+exports.makeAbs = makeAbs
+exports.finish = finish
+exports.mark = mark
+exports.isIgnored = isIgnored
+exports.childrenIgnored = childrenIgnored
- self.dataSize += stream.dataSize;
- });
+function ownProp (obj, field) {
+ return Object.prototype.hasOwnProperty.call(obj, field)
+}
- if (this._currentStream && this._currentStream.dataSize) {
- this.dataSize += this._currentStream.dataSize;
- }
-};
+var fs = __nccwpck_require__(7147)
+var path = __nccwpck_require__(1017)
+var minimatch = __nccwpck_require__(6453)
+var isAbsolute = (__nccwpck_require__(1017).isAbsolute)
+var Minimatch = minimatch.Minimatch
-CombinedStream.prototype._emitError = function(err) {
- this._reset();
- this.emit('error', err);
-};
+function alphasort (a, b) {
+ return a.localeCompare(b, 'en')
+}
+function setupIgnores (self, options) {
+ self.ignore = options.ignore || []
-/***/ }),
+ if (!Array.isArray(self.ignore))
+ self.ignore = [self.ignore]
-/***/ 8222:
-/***/ ((module, exports, __nccwpck_require__) => {
+ if (self.ignore.length) {
+ self.ignore = self.ignore.map(ignoreMap)
+ }
+}
-/* eslint-env browser */
+// ignore patterns are always in dot:true mode.
+function ignoreMap (pattern) {
+ var gmatcher = null
+ if (pattern.slice(-3) === '/**') {
+ var gpattern = pattern.replace(/(\/\*\*)+$/, '')
+ gmatcher = new Minimatch(gpattern, { dot: true })
+ }
-/**
- * This is the web browser implementation of `debug()`.
- */
+ return {
+ matcher: new Minimatch(pattern, { dot: true }),
+ gmatcher: gmatcher
+ }
+}
-exports.formatArgs = formatArgs;
-exports.save = save;
-exports.load = load;
-exports.useColors = useColors;
-exports.storage = localstorage();
-exports.destroy = (() => {
- let warned = false;
+function setopts (self, pattern, options) {
+ if (!options)
+ options = {}
- return () => {
- if (!warned) {
- warned = true;
- console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
- }
- };
-})();
+ // base-matching: just use globstar for that.
+ if (options.matchBase && -1 === pattern.indexOf("/")) {
+ if (options.noglobstar) {
+ throw new Error("base matching requires globstar")
+ }
+ pattern = "**/" + pattern
+ }
-/**
- * Colors.
- */
+ self.windowsPathsNoEscape = !!options.windowsPathsNoEscape ||
+ options.allowWindowsEscape === false
+ if (self.windowsPathsNoEscape) {
+ pattern = pattern.replace(/\\/g, '/')
+ }
-exports.colors = [
- '#0000CC',
- '#0000FF',
- '#0033CC',
- '#0033FF',
- '#0066CC',
- '#0066FF',
- '#0099CC',
- '#0099FF',
- '#00CC00',
- '#00CC33',
- '#00CC66',
- '#00CC99',
- '#00CCCC',
- '#00CCFF',
- '#3300CC',
- '#3300FF',
- '#3333CC',
- '#3333FF',
- '#3366CC',
- '#3366FF',
- '#3399CC',
- '#3399FF',
- '#33CC00',
- '#33CC33',
- '#33CC66',
- '#33CC99',
- '#33CCCC',
- '#33CCFF',
- '#6600CC',
- '#6600FF',
- '#6633CC',
- '#6633FF',
- '#66CC00',
- '#66CC33',
- '#9900CC',
- '#9900FF',
- '#9933CC',
- '#9933FF',
- '#99CC00',
- '#99CC33',
- '#CC0000',
- '#CC0033',
- '#CC0066',
- '#CC0099',
- '#CC00CC',
- '#CC00FF',
- '#CC3300',
- '#CC3333',
- '#CC3366',
- '#CC3399',
- '#CC33CC',
- '#CC33FF',
- '#CC6600',
- '#CC6633',
- '#CC9900',
- '#CC9933',
- '#CCCC00',
- '#CCCC33',
- '#FF0000',
- '#FF0033',
- '#FF0066',
- '#FF0099',
- '#FF00CC',
- '#FF00FF',
- '#FF3300',
- '#FF3333',
- '#FF3366',
- '#FF3399',
- '#FF33CC',
- '#FF33FF',
- '#FF6600',
- '#FF6633',
- '#FF9900',
- '#FF9933',
- '#FFCC00',
- '#FFCC33'
-];
+ self.silent = !!options.silent
+ self.pattern = pattern
+ self.strict = options.strict !== false
+ self.realpath = !!options.realpath
+ self.realpathCache = options.realpathCache || Object.create(null)
+ self.follow = !!options.follow
+ self.dot = !!options.dot
+ self.mark = !!options.mark
+ self.nodir = !!options.nodir
+ if (self.nodir)
+ self.mark = true
+ self.sync = !!options.sync
+ self.nounique = !!options.nounique
+ self.nonull = !!options.nonull
+ self.nosort = !!options.nosort
+ self.nocase = !!options.nocase
+ self.stat = !!options.stat
+ self.noprocess = !!options.noprocess
+ self.absolute = !!options.absolute
+ self.fs = options.fs || fs
-/**
- * Currently only WebKit-based Web Inspectors, Firefox >= v31,
- * and the Firebug extension (any Firefox version) are known
- * to support "%c" CSS customizations.
- *
- * TODO: add a `localStorage` variable to explicitly enable/disable colors
- */
+ self.maxLength = options.maxLength || Infinity
+ self.cache = options.cache || Object.create(null)
+ self.statCache = options.statCache || Object.create(null)
+ self.symlinks = options.symlinks || Object.create(null)
-// eslint-disable-next-line complexity
-function useColors() {
- // NB: In an Electron preload script, document will be defined but not fully
- // initialized. Since we know we're in Chrome, we'll just detect this case
- // explicitly
- if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
- return true;
- }
+ setupIgnores(self, options)
- // Internet Explorer and Edge do not support colors.
- if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
- return false;
- }
+ self.changedCwd = false
+ var cwd = process.cwd()
+ if (!ownProp(options, "cwd"))
+ self.cwd = path.resolve(cwd)
+ else {
+ self.cwd = path.resolve(options.cwd)
+ self.changedCwd = self.cwd !== cwd
+ }
- // Is webkit? http://stackoverflow.com/a/16459606/376773
- // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
- return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
- // Is firebug? http://stackoverflow.com/a/398120/376773
- (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
- // Is firefox >= v31?
- // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
- (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
- // Double check webkit in userAgent just in case we are in a worker
- (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
-}
+ self.root = options.root || path.resolve(self.cwd, "/")
+ self.root = path.resolve(self.root)
-/**
- * Colorize log arguments if enabled.
- *
- * @api public
- */
+ // TODO: is an absolute `cwd` supposed to be resolved against `root`?
+ // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
+ self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd)
+ self.nomount = !!options.nomount
-function formatArgs(args) {
- args[0] = (this.useColors ? '%c' : '') +
- this.namespace +
- (this.useColors ? ' %c' : ' ') +
- args[0] +
- (this.useColors ? '%c ' : ' ') +
- '+' + module.exports.humanize(this.diff);
+ if (process.platform === "win32") {
+ self.root = self.root.replace(/\\/g, "/")
+ self.cwd = self.cwd.replace(/\\/g, "/")
+ self.cwdAbs = self.cwdAbs.replace(/\\/g, "/")
+ }
- if (!this.useColors) {
- return;
- }
+ // disable comments and negation in Minimatch.
+ // Note that they are not supported in Glob itself anyway.
+ options.nonegate = true
+ options.nocomment = true
- const c = 'color: ' + this.color;
- args.splice(1, 0, c, 'color: inherit');
+ self.minimatch = new Minimatch(pattern, options)
+ self.options = self.minimatch.options
+}
- // The final "%c" is somewhat tricky, because there could be other
- // arguments passed either before or after the %c, so we need to
- // figure out the correct index to insert the CSS into
- let index = 0;
- let lastC = 0;
- args[0].replace(/%[a-zA-Z%]/g, match => {
- if (match === '%%') {
- return;
- }
- index++;
- if (match === '%c') {
- // We only are interested in the *last* %c
- // (the user may have provided their own)
- lastC = index;
- }
- });
+function finish (self) {
+ var nou = self.nounique
+ var all = nou ? [] : Object.create(null)
- args.splice(lastC, 0, c);
-}
+ for (var i = 0, l = self.matches.length; i < l; i ++) {
+ var matches = self.matches[i]
+ if (!matches || Object.keys(matches).length === 0) {
+ if (self.nonull) {
+ // do like the shell, and spit out the literal glob
+ var literal = self.minimatch.globSet[i]
+ if (nou)
+ all.push(literal)
+ else
+ all[literal] = true
+ }
+ } else {
+ // had matches
+ var m = Object.keys(matches)
+ if (nou)
+ all.push.apply(all, m)
+ else
+ m.forEach(function (m) {
+ all[m] = true
+ })
+ }
+ }
-/**
- * Invokes `console.debug()` when available.
- * No-op when `console.debug` is not a "function".
- * If `console.debug` is not available, falls back
- * to `console.log`.
- *
- * @api public
- */
-exports.log = console.debug || console.log || (() => {});
+ if (!nou)
+ all = Object.keys(all)
-/**
- * Save `namespaces`.
- *
- * @param {String} namespaces
- * @api private
- */
-function save(namespaces) {
- try {
- if (namespaces) {
- exports.storage.setItem('debug', namespaces);
- } else {
- exports.storage.removeItem('debug');
- }
- } catch (error) {
- // Swallow
- // XXX (@Qix-) should we be logging these?
- }
+ if (!self.nosort)
+ all = all.sort(alphasort)
+
+ // at *some* point we statted all of these
+ if (self.mark) {
+ for (var i = 0; i < all.length; i++) {
+ all[i] = self._mark(all[i])
+ }
+ if (self.nodir) {
+ all = all.filter(function (e) {
+ var notDir = !(/\/$/.test(e))
+ var c = self.cache[e] || self.cache[makeAbs(self, e)]
+ if (notDir && c)
+ notDir = c !== 'DIR' && !Array.isArray(c)
+ return notDir
+ })
+ }
+ }
+
+ if (self.ignore.length)
+ all = all.filter(function(m) {
+ return !isIgnored(self, m)
+ })
+
+ self.found = all
}
-/**
- * Load `namespaces`.
- *
- * @return {String} returns the previously persisted debug modes
- * @api private
- */
-function load() {
- let r;
- try {
- r = exports.storage.getItem('debug');
- } catch (error) {
- // Swallow
- // XXX (@Qix-) should we be logging these?
- }
+function mark (self, p) {
+ var abs = makeAbs(self, p)
+ var c = self.cache[abs]
+ var m = p
+ if (c) {
+ var isDir = c === 'DIR' || Array.isArray(c)
+ var slash = p.slice(-1) === '/'
- // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
- if (!r && typeof process !== 'undefined' && 'env' in process) {
- r = process.env.DEBUG;
- }
+ if (isDir && !slash)
+ m += '/'
+ else if (!isDir && slash)
+ m = m.slice(0, -1)
- return r;
+ if (m !== p) {
+ var mabs = makeAbs(self, m)
+ self.statCache[mabs] = self.statCache[abs]
+ self.cache[mabs] = self.cache[abs]
+ }
+ }
+
+ return m
}
-/**
- * Localstorage attempts to return the localstorage.
- *
- * This is necessary because safari throws
- * when a user disables cookies/localstorage
- * and you attempt to access it.
- *
- * @return {LocalStorage}
- * @api private
- */
+// lotta situps...
+function makeAbs (self, f) {
+ var abs = f
+ if (f.charAt(0) === '/') {
+ abs = path.join(self.root, f)
+ } else if (isAbsolute(f) || f === '') {
+ abs = f
+ } else if (self.changedCwd) {
+ abs = path.resolve(self.cwd, f)
+ } else {
+ abs = path.resolve(f)
+ }
-function localstorage() {
- try {
- // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
- // The Browser also has localStorage in the global context.
- return localStorage;
- } catch (error) {
- // Swallow
- // XXX (@Qix-) should we be logging these?
- }
+ if (process.platform === 'win32')
+ abs = abs.replace(/\\/g, '/')
+
+ return abs
}
-module.exports = __nccwpck_require__(6243)(exports);
-const {formatters} = module.exports;
+// Return true, if pattern ends with globstar '**', for the accompanying parent directory.
+// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
+function isIgnored (self, path) {
+ if (!self.ignore.length)
+ return false
-/**
- * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
- */
+ return self.ignore.some(function(item) {
+ return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
+ })
+}
-formatters.j = function (v) {
- try {
- return JSON.stringify(v);
- } catch (error) {
- return '[UnexpectedJSONParseError]: ' + error.message;
- }
-};
+function childrenIgnored (self, path) {
+ if (!self.ignore.length)
+ return false
+
+ return self.ignore.some(function(item) {
+ return !!(item.gmatcher && item.gmatcher.match(path))
+ })
+}
/***/ }),
-/***/ 6243:
+/***/ 1957:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+// Approach:
+//
+// 1. Get the minimatch set
+// 2. For each pattern in the set, PROCESS(pattern, false)
+// 3. Store matches per-set, then uniq them
+//
+// PROCESS(pattern, inGlobStar)
+// Get the first [n] items from pattern that are all strings
+// Join these together. This is PREFIX.
+// If there is no more remaining, then stat(PREFIX) and
+// add to matches if it succeeds. END.
+//
+// If inGlobStar and PREFIX is symlink and points to dir
+// set ENTRIES = []
+// else readdir(PREFIX) as ENTRIES
+// If fail, END
+//
+// with ENTRIES
+// If pattern[n] is GLOBSTAR
+// // handle the case where the globstar match is empty
+// // by pruning it out, and testing the resulting pattern
+// PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
+// // handle other cases.
+// for ENTRY in ENTRIES (not dotfiles)
+// // attach globstar + tail onto the entry
+// // Mark that this entry is a globstar match
+// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
+//
+// else // not globstar
+// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
+// Test ENTRY against pattern[n]
+// If fails, continue
+// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
+//
+// Caveat:
+// Cache all stats and readdirs results to minimize syscall. Since all
+// we ever care about is existence and directory-ness, we can just keep
+// `true` for files, and [children,...] for directories, or `false` for
+// things that don't exist.
-/**
- * This is the common logic for both the Node.js and web browser
- * implementations of `debug()`.
- */
+module.exports = glob
-function setup(env) {
- createDebug.debug = createDebug;
- createDebug.default = createDebug;
- createDebug.coerce = coerce;
- createDebug.disable = disable;
- createDebug.enable = enable;
- createDebug.enabled = enabled;
- createDebug.humanize = __nccwpck_require__(900);
- createDebug.destroy = destroy;
+var rp = __nccwpck_require__(6863)
+var minimatch = __nccwpck_require__(6453)
+var Minimatch = minimatch.Minimatch
+var inherits = __nccwpck_require__(4124)
+var EE = (__nccwpck_require__(2361).EventEmitter)
+var path = __nccwpck_require__(1017)
+var assert = __nccwpck_require__(9491)
+var isAbsolute = (__nccwpck_require__(1017).isAbsolute)
+var globSync = __nccwpck_require__(9010)
+var common = __nccwpck_require__(7625)
+var setopts = common.setopts
+var ownProp = common.ownProp
+var inflight = __nccwpck_require__(2492)
+var util = __nccwpck_require__(3837)
+var childrenIgnored = common.childrenIgnored
+var isIgnored = common.isIgnored
- Object.keys(env).forEach(key => {
- createDebug[key] = env[key];
- });
+var once = __nccwpck_require__(1223)
- /**
- * The currently active debug mode names, and names to skip.
- */
+function glob (pattern, options, cb) {
+ if (typeof options === 'function') cb = options, options = {}
+ if (!options) options = {}
- createDebug.names = [];
- createDebug.skips = [];
+ if (options.sync) {
+ if (cb)
+ throw new TypeError('callback provided to sync glob')
+ return globSync(pattern, options)
+ }
- /**
- * Map of special "%n" handling functions, for the debug "format" argument.
- *
- * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
- */
- createDebug.formatters = {};
+ return new Glob(pattern, options, cb)
+}
- /**
- * Selects a color for a debug namespace
- * @param {String} namespace The namespace string for the debug instance to be colored
- * @return {Number|String} An ANSI color code for the given namespace
- * @api private
- */
- function selectColor(namespace) {
- let hash = 0;
+glob.sync = globSync
+var GlobSync = glob.GlobSync = globSync.GlobSync
- for (let i = 0; i < namespace.length; i++) {
- hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
- hash |= 0; // Convert to 32bit integer
- }
+// old api surface
+glob.glob = glob
- return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
- }
- createDebug.selectColor = selectColor;
+function extend (origin, add) {
+ if (add === null || typeof add !== 'object') {
+ return origin
+ }
- /**
- * Create a debugger with the given `namespace`.
- *
- * @param {String} namespace
- * @return {Function}
- * @api public
- */
- function createDebug(namespace) {
- let prevTime;
- let enableOverride = null;
- let namespacesCache;
- let enabledCache;
+ var keys = Object.keys(add)
+ var i = keys.length
+ while (i--) {
+ origin[keys[i]] = add[keys[i]]
+ }
+ return origin
+}
- function debug(...args) {
- // Disabled?
- if (!debug.enabled) {
- return;
- }
+glob.hasMagic = function (pattern, options_) {
+ var options = extend({}, options_)
+ options.noprocess = true
- const self = debug;
+ var g = new Glob(pattern, options)
+ var set = g.minimatch.set
- // Set `diff` timestamp
- const curr = Number(new Date());
- const ms = curr - (prevTime || curr);
- self.diff = ms;
- self.prev = prevTime;
- self.curr = curr;
- prevTime = curr;
+ if (!pattern)
+ return false
- args[0] = createDebug.coerce(args[0]);
+ if (set.length > 1)
+ return true
- if (typeof args[0] !== 'string') {
- // Anything else let's inspect with %O
- args.unshift('%O');
- }
+ for (var j = 0; j < set[0].length; j++) {
+ if (typeof set[0][j] !== 'string')
+ return true
+ }
- // Apply any `formatters` transformations
- let index = 0;
- args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
- // If we encounter an escaped % then don't increase the array index
- if (match === '%%') {
- return '%';
- }
- index++;
- const formatter = createDebug.formatters[format];
- if (typeof formatter === 'function') {
- const val = args[index];
- match = formatter.call(self, val);
+ return false
+}
+
+glob.Glob = Glob
+inherits(Glob, EE)
+function Glob (pattern, options, cb) {
+ if (typeof options === 'function') {
+ cb = options
+ options = null
+ }
+
+ if (options && options.sync) {
+ if (cb)
+ throw new TypeError('callback provided to sync glob')
+ return new GlobSync(pattern, options)
+ }
+
+ if (!(this instanceof Glob))
+ return new Glob(pattern, options, cb)
+
+ setopts(this, pattern, options)
+ this._didRealPath = false
+
+ // process each pattern in the minimatch set
+ var n = this.minimatch.set.length
+
+ // The matches are stored as {: true,...} so that
+ // duplicates are automagically pruned.
+ // Later, we do an Object.keys() on these.
+ // Keep them as a list so we can fill in when nonull is set.
+ this.matches = new Array(n)
+
+ if (typeof cb === 'function') {
+ cb = once(cb)
+ this.on('error', cb)
+ this.on('end', function (matches) {
+ cb(null, matches)
+ })
+ }
+
+ var self = this
+ this._processing = 0
+
+ this._emitQueue = []
+ this._processQueue = []
+ this.paused = false
+
+ if (this.noprocess)
+ return this
+
+ if (n === 0)
+ return done()
- // Now we need to remove `args[index]` since it's inlined in the `format`
- args.splice(index, 1);
- index--;
- }
- return match;
- });
+ var sync = true
+ for (var i = 0; i < n; i ++) {
+ this._process(this.minimatch.set[i], i, false, done)
+ }
+ sync = false
- // Apply env-specific formatting (colors, etc.)
- createDebug.formatArgs.call(self, args);
+ function done () {
+ --self._processing
+ if (self._processing <= 0) {
+ if (sync) {
+ process.nextTick(function () {
+ self._finish()
+ })
+ } else {
+ self._finish()
+ }
+ }
+ }
+}
- const logFn = self.log || createDebug.log;
- logFn.apply(self, args);
- }
+Glob.prototype._finish = function () {
+ assert(this instanceof Glob)
+ if (this.aborted)
+ return
- debug.namespace = namespace;
- debug.useColors = createDebug.useColors();
- debug.color = createDebug.selectColor(namespace);
- debug.extend = extend;
- debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
+ if (this.realpath && !this._didRealpath)
+ return this._realpath()
- Object.defineProperty(debug, 'enabled', {
- enumerable: true,
- configurable: false,
- get: () => {
- if (enableOverride !== null) {
- return enableOverride;
- }
- if (namespacesCache !== createDebug.namespaces) {
- namespacesCache = createDebug.namespaces;
- enabledCache = createDebug.enabled(namespace);
- }
+ common.finish(this)
+ this.emit('end', this.found)
+}
- return enabledCache;
- },
- set: v => {
- enableOverride = v;
- }
- });
+Glob.prototype._realpath = function () {
+ if (this._didRealpath)
+ return
- // Env-specific initialization logic for debug instances
- if (typeof createDebug.init === 'function') {
- createDebug.init(debug);
- }
+ this._didRealpath = true
- return debug;
- }
+ var n = this.matches.length
+ if (n === 0)
+ return this._finish()
- function extend(namespace, delimiter) {
- const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
- newDebug.log = this.log;
- return newDebug;
- }
+ var self = this
+ for (var i = 0; i < this.matches.length; i++)
+ this._realpathSet(i, next)
- /**
- * Enables a debug mode by namespaces. This can include modes
- * separated by a colon and wildcards.
- *
- * @param {String} namespaces
- * @api public
- */
- function enable(namespaces) {
- createDebug.save(namespaces);
- createDebug.namespaces = namespaces;
+ function next () {
+ if (--n === 0)
+ self._finish()
+ }
+}
- createDebug.names = [];
- createDebug.skips = [];
+Glob.prototype._realpathSet = function (index, cb) {
+ var matchset = this.matches[index]
+ if (!matchset)
+ return cb()
- let i;
- const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
- const len = split.length;
+ var found = Object.keys(matchset)
+ var self = this
+ var n = found.length
- for (i = 0; i < len; i++) {
- if (!split[i]) {
- // ignore empty strings
- continue;
- }
+ if (n === 0)
+ return cb()
- namespaces = split[i].replace(/\*/g, '.*?');
+ var set = this.matches[index] = Object.create(null)
+ found.forEach(function (p, i) {
+ // If there's a problem with the stat, then it means that
+ // one or more of the links in the realpath couldn't be
+ // resolved. just return the abs value in that case.
+ p = self._makeAbs(p)
+ rp.realpath(p, self.realpathCache, function (er, real) {
+ if (!er)
+ set[real] = true
+ else if (er.syscall === 'stat')
+ set[p] = true
+ else
+ self.emit('error', er) // srsly wtf right here
- if (namespaces[0] === '-') {
- createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
- } else {
- createDebug.names.push(new RegExp('^' + namespaces + '$'));
- }
- }
- }
+ if (--n === 0) {
+ self.matches[index] = set
+ cb()
+ }
+ })
+ })
+}
- /**
- * Disable debug output.
- *
- * @return {String} namespaces
- * @api public
- */
- function disable() {
- const namespaces = [
- ...createDebug.names.map(toNamespace),
- ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
- ].join(',');
- createDebug.enable('');
- return namespaces;
- }
+Glob.prototype._mark = function (p) {
+ return common.mark(this, p)
+}
- /**
- * Returns true if the given mode name is enabled, false otherwise.
- *
- * @param {String} name
- * @return {Boolean}
- * @api public
- */
- function enabled(name) {
- if (name[name.length - 1] === '*') {
- return true;
- }
+Glob.prototype._makeAbs = function (f) {
+ return common.makeAbs(this, f)
+}
- let i;
- let len;
+Glob.prototype.abort = function () {
+ this.aborted = true
+ this.emit('abort')
+}
- for (i = 0, len = createDebug.skips.length; i < len; i++) {
- if (createDebug.skips[i].test(name)) {
- return false;
- }
- }
+Glob.prototype.pause = function () {
+ if (!this.paused) {
+ this.paused = true
+ this.emit('pause')
+ }
+}
- for (i = 0, len = createDebug.names.length; i < len; i++) {
- if (createDebug.names[i].test(name)) {
- return true;
- }
- }
+Glob.prototype.resume = function () {
+ if (this.paused) {
+ this.emit('resume')
+ this.paused = false
+ if (this._emitQueue.length) {
+ var eq = this._emitQueue.slice(0)
+ this._emitQueue.length = 0
+ for (var i = 0; i < eq.length; i ++) {
+ var e = eq[i]
+ this._emitMatch(e[0], e[1])
+ }
+ }
+ if (this._processQueue.length) {
+ var pq = this._processQueue.slice(0)
+ this._processQueue.length = 0
+ for (var i = 0; i < pq.length; i ++) {
+ var p = pq[i]
+ this._processing--
+ this._process(p[0], p[1], p[2], p[3])
+ }
+ }
+ }
+}
- return false;
- }
+Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
+ assert(this instanceof Glob)
+ assert(typeof cb === 'function')
- /**
- * Convert regexp to namespace
- *
- * @param {RegExp} regxep
- * @return {String} namespace
- * @api private
- */
- function toNamespace(regexp) {
- return regexp.toString()
- .substring(2, regexp.toString().length - 2)
- .replace(/\.\*\?$/, '*');
- }
+ if (this.aborted)
+ return
- /**
- * Coerce `val`.
- *
- * @param {Mixed} val
- * @return {Mixed}
- * @api private
- */
- function coerce(val) {
- if (val instanceof Error) {
- return val.stack || val.message;
- }
- return val;
- }
+ this._processing++
+ if (this.paused) {
+ this._processQueue.push([pattern, index, inGlobStar, cb])
+ return
+ }
- /**
- * XXX DO NOT USE. This is a temporary stub function.
- * XXX It WILL be removed in the next major release.
- */
- function destroy() {
- console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
- }
+ //console.error('PROCESS %d', this._processing, pattern)
- createDebug.enable(createDebug.load());
+ // Get the first [n] parts of pattern that are all strings.
+ var n = 0
+ while (typeof pattern[n] === 'string') {
+ n ++
+ }
+ // now n is the index of the first one that is *not* a string.
- return createDebug;
-}
+ // see if there's anything else
+ var prefix
+ switch (n) {
+ // if not, then this is rather simple
+ case pattern.length:
+ this._processSimple(pattern.join('/'), index, cb)
+ return
-module.exports = setup;
+ case 0:
+ // pattern *starts* with some non-trivial item.
+ // going to readdir(cwd), but not include the prefix in matches.
+ prefix = null
+ break
+ default:
+ // pattern has some string bits in the front.
+ // whatever it starts with, whether that's 'absolute' like /foo/bar,
+ // or 'relative' like '../baz'
+ prefix = pattern.slice(0, n).join('/')
+ break
+ }
-/***/ }),
+ var remain = pattern.slice(n)
-/***/ 8237:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // get the list of entries.
+ var read
+ if (prefix === null)
+ read = '.'
+ else if (isAbsolute(prefix) ||
+ isAbsolute(pattern.map(function (p) {
+ return typeof p === 'string' ? p : '[*]'
+ }).join('/'))) {
+ if (!prefix || !isAbsolute(prefix))
+ prefix = '/' + prefix
+ read = prefix
+ } else
+ read = prefix
-/**
- * Detect Electron renderer / nwjs process, which is node, but we should
- * treat as a browser.
- */
+ var abs = this._makeAbs(read)
-if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
- module.exports = __nccwpck_require__(8222);
-} else {
- module.exports = __nccwpck_require__(4874);
+ //if ignored, skip _processing
+ if (childrenIgnored(this, read))
+ return cb()
+
+ var isGlobStar = remain[0] === minimatch.GLOBSTAR
+ if (isGlobStar)
+ this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb)
+ else
+ this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb)
}
+Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
+ var self = this
+ this._readdir(abs, inGlobStar, function (er, entries) {
+ return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
+ })
+}
-/***/ }),
+Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
-/***/ 4874:
-/***/ ((module, exports, __nccwpck_require__) => {
+ // if the abs isn't a dir, then nothing can match!
+ if (!entries)
+ return cb()
-/**
- * Module dependencies.
- */
+ // It will only match dot entries if it starts with a dot, or if
+ // dot is set. Stuff like @(.foo|.bar) isn't allowed.
+ var pn = remain[0]
+ var negate = !!this.minimatch.negate
+ var rawGlob = pn._glob
+ var dotOk = this.dot || rawGlob.charAt(0) === '.'
-const tty = __nccwpck_require__(6224);
-const util = __nccwpck_require__(3837);
+ var matchedEntries = []
+ for (var i = 0; i < entries.length; i++) {
+ var e = entries[i]
+ if (e.charAt(0) !== '.' || dotOk) {
+ var m
+ if (negate && !prefix) {
+ m = !e.match(pn)
+ } else {
+ m = e.match(pn)
+ }
+ if (m)
+ matchedEntries.push(e)
+ }
+ }
-/**
- * This is the Node.js implementation of `debug()`.
- */
+ //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
-exports.init = init;
-exports.log = log;
-exports.formatArgs = formatArgs;
-exports.save = save;
-exports.load = load;
-exports.useColors = useColors;
-exports.destroy = util.deprecate(
- () => {},
- 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
-);
+ var len = matchedEntries.length
+ // If there are no matched entries, then nothing matches.
+ if (len === 0)
+ return cb()
-/**
- * Colors.
- */
+ // if this is the last remaining pattern bit, then no need for
+ // an additional stat *unless* the user has specified mark or
+ // stat explicitly. We know they exist, since readdir returned
+ // them.
-exports.colors = [6, 2, 3, 4, 5, 1];
+ if (remain.length === 1 && !this.mark && !this.stat) {
+ if (!this.matches[index])
+ this.matches[index] = Object.create(null)
-try {
- // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
- // eslint-disable-next-line import/no-extraneous-dependencies
- const supportsColor = __nccwpck_require__(9318);
+ for (var i = 0; i < len; i ++) {
+ var e = matchedEntries[i]
+ if (prefix) {
+ if (prefix !== '/')
+ e = prefix + '/' + e
+ else
+ e = prefix + e
+ }
- if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
- exports.colors = [
- 20,
- 21,
- 26,
- 27,
- 32,
- 33,
- 38,
- 39,
- 40,
- 41,
- 42,
- 43,
- 44,
- 45,
- 56,
- 57,
- 62,
- 63,
- 68,
- 69,
- 74,
- 75,
- 76,
- 77,
- 78,
- 79,
- 80,
- 81,
- 92,
- 93,
- 98,
- 99,
- 112,
- 113,
- 128,
- 129,
- 134,
- 135,
- 148,
- 149,
- 160,
- 161,
- 162,
- 163,
- 164,
- 165,
- 166,
- 167,
- 168,
- 169,
- 170,
- 171,
- 172,
- 173,
- 178,
- 179,
- 184,
- 185,
- 196,
- 197,
- 198,
- 199,
- 200,
- 201,
- 202,
- 203,
- 204,
- 205,
- 206,
- 207,
- 208,
- 209,
- 214,
- 215,
- 220,
- 221
- ];
- }
-} catch (error) {
- // Swallow - we only care if `supports-color` is available; it doesn't have to be.
+ if (e.charAt(0) === '/' && !this.nomount) {
+ e = path.join(this.root, e)
+ }
+ this._emitMatch(index, e)
+ }
+ // This was the last one, and no stats were needed
+ return cb()
+ }
+
+ // now test all matched entries as stand-ins for that part
+ // of the pattern.
+ remain.shift()
+ for (var i = 0; i < len; i ++) {
+ var e = matchedEntries[i]
+ var newPattern
+ if (prefix) {
+ if (prefix !== '/')
+ e = prefix + '/' + e
+ else
+ e = prefix + e
+ }
+ this._process([e].concat(remain), index, inGlobStar, cb)
+ }
+ cb()
}
-/**
- * Build up the default `inspectOpts` object from the environment variables.
- *
- * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
- */
+Glob.prototype._emitMatch = function (index, e) {
+ if (this.aborted)
+ return
-exports.inspectOpts = Object.keys(process.env).filter(key => {
- return /^debug_/i.test(key);
-}).reduce((obj, key) => {
- // Camel-case
- const prop = key
- .substring(6)
- .toLowerCase()
- .replace(/_([a-z])/g, (_, k) => {
- return k.toUpperCase();
- });
+ if (isIgnored(this, e))
+ return
- // Coerce string value into JS value
- let val = process.env[key];
- if (/^(yes|on|true|enabled)$/i.test(val)) {
- val = true;
- } else if (/^(no|off|false|disabled)$/i.test(val)) {
- val = false;
- } else if (val === 'null') {
- val = null;
- } else {
- val = Number(val);
- }
+ if (this.paused) {
+ this._emitQueue.push([index, e])
+ return
+ }
- obj[prop] = val;
- return obj;
-}, {});
+ var abs = isAbsolute(e) ? e : this._makeAbs(e)
-/**
- * Is stdout a TTY? Colored output is enabled when `true`.
- */
+ if (this.mark)
+ e = this._mark(e)
-function useColors() {
- return 'colors' in exports.inspectOpts ?
- Boolean(exports.inspectOpts.colors) :
- tty.isatty(process.stderr.fd);
-}
+ if (this.absolute)
+ e = abs
-/**
- * Adds ANSI color escape codes if enabled.
- *
- * @api public
- */
+ if (this.matches[index][e])
+ return
-function formatArgs(args) {
- const {namespace: name, useColors} = this;
+ if (this.nodir) {
+ var c = this.cache[abs]
+ if (c === 'DIR' || Array.isArray(c))
+ return
+ }
- if (useColors) {
- const c = this.color;
- const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
- const prefix = ` ${colorCode};1m${name} \u001B[0m`;
+ this.matches[index][e] = true
- args[0] = prefix + args[0].split('\n').join('\n' + prefix);
- args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
- } else {
- args[0] = getDate() + name + ' ' + args[0];
- }
+ var st = this.statCache[abs]
+ if (st)
+ this.emit('stat', e, st)
+
+ this.emit('match', e)
}
-function getDate() {
- if (exports.inspectOpts.hideDate) {
- return '';
- }
- return new Date().toISOString() + ' ';
+Glob.prototype._readdirInGlobStar = function (abs, cb) {
+ if (this.aborted)
+ return
+
+ // follow all symlinked directories forever
+ // just proceed as if this is a non-globstar situation
+ if (this.follow)
+ return this._readdir(abs, false, cb)
+
+ var lstatkey = 'lstat\0' + abs
+ var self = this
+ var lstatcb = inflight(lstatkey, lstatcb_)
+
+ if (lstatcb)
+ self.fs.lstat(abs, lstatcb)
+
+ function lstatcb_ (er, lstat) {
+ if (er && er.code === 'ENOENT')
+ return cb()
+
+ var isSym = lstat && lstat.isSymbolicLink()
+ self.symlinks[abs] = isSym
+
+ // If it's not a symlink or a dir, then it's definitely a regular file.
+ // don't bother doing a readdir in that case.
+ if (!isSym && lstat && !lstat.isDirectory()) {
+ self.cache[abs] = 'FILE'
+ cb()
+ } else
+ self._readdir(abs, false, cb)
+ }
}
-/**
- * Invokes `util.format()` with the specified arguments and writes to stderr.
- */
+Glob.prototype._readdir = function (abs, inGlobStar, cb) {
+ if (this.aborted)
+ return
-function log(...args) {
- return process.stderr.write(util.format(...args) + '\n');
+ cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb)
+ if (!cb)
+ return
+
+ //console.error('RD %j %j', +inGlobStar, abs)
+ if (inGlobStar && !ownProp(this.symlinks, abs))
+ return this._readdirInGlobStar(abs, cb)
+
+ if (ownProp(this.cache, abs)) {
+ var c = this.cache[abs]
+ if (!c || c === 'FILE')
+ return cb()
+
+ if (Array.isArray(c))
+ return cb(null, c)
+ }
+
+ var self = this
+ self.fs.readdir(abs, readdirCb(this, abs, cb))
}
-/**
- * Save `namespaces`.
- *
- * @param {String} namespaces
- * @api private
- */
-function save(namespaces) {
- if (namespaces) {
- process.env.DEBUG = namespaces;
- } else {
- // If you set a process.env field to null or undefined, it gets cast to the
- // string 'null' or 'undefined'. Just delete instead.
- delete process.env.DEBUG;
- }
+function readdirCb (self, abs, cb) {
+ return function (er, entries) {
+ if (er)
+ self._readdirError(abs, er, cb)
+ else
+ self._readdirEntries(abs, entries, cb)
+ }
}
-/**
- * Load `namespaces`.
- *
- * @return {String} returns the previously persisted debug modes
- * @api private
- */
+Glob.prototype._readdirEntries = function (abs, entries, cb) {
+ if (this.aborted)
+ return
-function load() {
- return process.env.DEBUG;
+ // if we haven't asked to stat everything, then just
+ // assume that everything in there exists, so we can avoid
+ // having to stat it a second time.
+ if (!this.mark && !this.stat) {
+ for (var i = 0; i < entries.length; i ++) {
+ var e = entries[i]
+ if (abs === '/')
+ e = abs + e
+ else
+ e = abs + '/' + e
+ this.cache[e] = true
+ }
+ }
+
+ this.cache[abs] = entries
+ return cb(null, entries)
}
-/**
- * Init logic for `debug` instances.
- *
- * Create a new `inspectOpts` object in case `useColors` is set
- * differently for a particular `debug` instance.
- */
+Glob.prototype._readdirError = function (f, er, cb) {
+ if (this.aborted)
+ return
-function init(debug) {
- debug.inspectOpts = {};
+ // handle errors, and cache the information
+ switch (er.code) {
+ case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
+ case 'ENOTDIR': // totally normal. means it *does* exist.
+ var abs = this._makeAbs(f)
+ this.cache[abs] = 'FILE'
+ if (abs === this.cwdAbs) {
+ var error = new Error(er.code + ' invalid cwd ' + this.cwd)
+ error.path = this.cwd
+ error.code = er.code
+ this.emit('error', error)
+ this.abort()
+ }
+ break
- const keys = Object.keys(exports.inspectOpts);
- for (let i = 0; i < keys.length; i++) {
- debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
- }
+ case 'ENOENT': // not terribly unusual
+ case 'ELOOP':
+ case 'ENAMETOOLONG':
+ case 'UNKNOWN':
+ this.cache[this._makeAbs(f)] = false
+ break
+
+ default: // some unusual error. Treat as failure.
+ this.cache[this._makeAbs(f)] = false
+ if (this.strict) {
+ this.emit('error', er)
+ // If the error is handled, then we abort
+ // if not, we threw out of here
+ this.abort()
+ }
+ if (!this.silent)
+ console.error('glob error', er)
+ break
+ }
+
+ return cb()
}
-module.exports = __nccwpck_require__(6243)(exports);
+Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
+ var self = this
+ this._readdir(abs, inGlobStar, function (er, entries) {
+ self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
+ })
+}
-const {formatters} = module.exports;
-/**
- * Map %o to `util.inspect()`, all on a single line.
- */
+Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
+ //console.error('pgs2', prefix, remain[0], entries)
-formatters.o = function (v) {
- this.inspectOpts.colors = this.useColors;
- return util.inspect(v, this.inspectOpts)
- .split('\n')
- .map(str => str.trim())
- .join(' ');
-};
+ // no entries means not a dir, so it can never have matches
+ // foo.txt/** doesn't match foo.txt
+ if (!entries)
+ return cb()
-/**
- * Map %O to `util.inspect()`, allowing multiple lines if needed.
- */
+ // test without the globstar, and with every child both below
+ // and replacing the globstar.
+ var remainWithoutGlobStar = remain.slice(1)
+ var gspref = prefix ? [ prefix ] : []
+ var noGlobStar = gspref.concat(remainWithoutGlobStar)
-formatters.O = function (v) {
- this.inspectOpts.colors = this.useColors;
- return util.inspect(v, this.inspectOpts);
-};
+ // the noGlobStar pattern exits the inGlobStar state
+ this._process(noGlobStar, index, false, cb)
+ var isSym = this.symlinks[abs]
+ var len = entries.length
-/***/ }),
+ // If it's a symlink, and we're in a globstar, then stop
+ if (isSym && inGlobStar)
+ return cb()
-/***/ 8611:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ for (var i = 0; i < len; i++) {
+ var e = entries[i]
+ if (e.charAt(0) === '.' && !this.dot)
+ continue
-var Stream = (__nccwpck_require__(2781).Stream);
-var util = __nccwpck_require__(3837);
+ // these two cases enter the inGlobStar state
+ var instead = gspref.concat(entries[i], remainWithoutGlobStar)
+ this._process(instead, index, true, cb)
-module.exports = DelayedStream;
-function DelayedStream() {
- this.source = null;
- this.dataSize = 0;
- this.maxDataSize = 1024 * 1024;
- this.pauseStream = true;
+ var below = gspref.concat(entries[i], remain)
+ this._process(below, index, true, cb)
+ }
- this._maxDataSizeExceeded = false;
- this._released = false;
- this._bufferedEvents = [];
+ cb()
}
-util.inherits(DelayedStream, Stream);
-DelayedStream.create = function(source, options) {
- var delayedStream = new this();
+Glob.prototype._processSimple = function (prefix, index, cb) {
+ // XXX review this. Shouldn't it be doing the mounting etc
+ // before doing stat? kinda weird?
+ var self = this
+ this._stat(prefix, function (er, exists) {
+ self._processSimple2(prefix, index, er, exists, cb)
+ })
+}
+Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
- options = options || {};
- for (var option in options) {
- delayedStream[option] = options[option];
- }
+ //console.error('ps2', prefix, exists)
- delayedStream.source = source;
+ if (!this.matches[index])
+ this.matches[index] = Object.create(null)
- var realEmit = source.emit;
- source.emit = function() {
- delayedStream._handleEmit(arguments);
- return realEmit.apply(source, arguments);
- };
+ // If it doesn't exist, then just mark the lack of results
+ if (!exists)
+ return cb()
- source.on('error', function() {});
- if (delayedStream.pauseStream) {
- source.pause();
+ if (prefix && isAbsolute(prefix) && !this.nomount) {
+ var trail = /[\/\\]$/.test(prefix)
+ if (prefix.charAt(0) === '/') {
+ prefix = path.join(this.root, prefix)
+ } else {
+ prefix = path.resolve(this.root, prefix)
+ if (trail)
+ prefix += '/'
+ }
}
- return delayedStream;
-};
+ if (process.platform === 'win32')
+ prefix = prefix.replace(/\\/g, '/')
-Object.defineProperty(DelayedStream.prototype, 'readable', {
- configurable: true,
- enumerable: true,
- get: function() {
- return this.source.readable;
- }
-});
+ // Mark this as a match
+ this._emitMatch(index, prefix)
+ cb()
+}
-DelayedStream.prototype.setEncoding = function() {
- return this.source.setEncoding.apply(this.source, arguments);
-};
+// Returns either 'DIR', 'FILE', or false
+Glob.prototype._stat = function (f, cb) {
+ var abs = this._makeAbs(f)
+ var needDir = f.slice(-1) === '/'
-DelayedStream.prototype.resume = function() {
- if (!this._released) {
- this.release();
- }
+ if (f.length > this.maxLength)
+ return cb()
- this.source.resume();
-};
+ if (!this.stat && ownProp(this.cache, abs)) {
+ var c = this.cache[abs]
-DelayedStream.prototype.pause = function() {
- this.source.pause();
-};
+ if (Array.isArray(c))
+ c = 'DIR'
-DelayedStream.prototype.release = function() {
- this._released = true;
+ // It exists, but maybe not how we need it
+ if (!needDir || c === 'DIR')
+ return cb(null, c)
- this._bufferedEvents.forEach(function(args) {
- this.emit.apply(this, args);
- }.bind(this));
- this._bufferedEvents = [];
-};
+ if (needDir && c === 'FILE')
+ return cb()
-DelayedStream.prototype.pipe = function() {
- var r = Stream.prototype.pipe.apply(this, arguments);
- this.resume();
- return r;
-};
+ // otherwise we have to stat, because maybe c=true
+ // if we know it exists, but not what it is.
+ }
-DelayedStream.prototype._handleEmit = function(args) {
- if (this._released) {
- this.emit.apply(this, args);
- return;
+ var exists
+ var stat = this.statCache[abs]
+ if (stat !== undefined) {
+ if (stat === false)
+ return cb(null, stat)
+ else {
+ var type = stat.isDirectory() ? 'DIR' : 'FILE'
+ if (needDir && type === 'FILE')
+ return cb()
+ else
+ return cb(null, type, stat)
+ }
}
- if (args[0] === 'data') {
- this.dataSize += args[1].length;
- this._checkIfMaxDataSizeExceeded();
+ var self = this
+ var statcb = inflight('stat\0' + abs, lstatcb_)
+ if (statcb)
+ self.fs.lstat(abs, statcb)
+
+ function lstatcb_ (er, lstat) {
+ if (lstat && lstat.isSymbolicLink()) {
+ // If it's a symlink, then treat it as the target, unless
+ // the target does not exist, then treat it as a file.
+ return self.fs.stat(abs, function (er, stat) {
+ if (er)
+ self._stat2(f, abs, null, lstat, cb)
+ else
+ self._stat2(f, abs, er, stat, cb)
+ })
+ } else {
+ self._stat2(f, abs, er, lstat, cb)
+ }
}
+}
- this._bufferedEvents.push(args);
-};
+Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
+ if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
+ this.statCache[abs] = false
+ return cb()
+ }
+
+ var needDir = f.slice(-1) === '/'
+ this.statCache[abs] = stat
+
+ if (abs.slice(-1) === '/' && stat && !stat.isDirectory())
+ return cb(null, false, stat)
+
+ var c = true
+ if (stat)
+ c = stat.isDirectory() ? 'DIR' : 'FILE'
+ this.cache[abs] = this.cache[abs] || c
+
+ if (needDir && c === 'FILE')
+ return cb()
+
+ return cb(null, c, stat)
+}
+
+
+/***/ }),
+
+/***/ 1046:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+var balanced = __nccwpck_require__(9417);
+
+module.exports = expandTop;
+
+var escSlash = '\0SLASH'+Math.random()+'\0';
+var escOpen = '\0OPEN'+Math.random()+'\0';
+var escClose = '\0CLOSE'+Math.random()+'\0';
+var escComma = '\0COMMA'+Math.random()+'\0';
+var escPeriod = '\0PERIOD'+Math.random()+'\0';
+
+function numeric(str) {
+ return parseInt(str, 10) == str
+ ? parseInt(str, 10)
+ : str.charCodeAt(0);
+}
+
+function escapeBraces(str) {
+ return str.split('\\\\').join(escSlash)
+ .split('\\{').join(escOpen)
+ .split('\\}').join(escClose)
+ .split('\\,').join(escComma)
+ .split('\\.').join(escPeriod);
+}
+
+function unescapeBraces(str) {
+ return str.split(escSlash).join('\\')
+ .split(escOpen).join('{')
+ .split(escClose).join('}')
+ .split(escComma).join(',')
+ .split(escPeriod).join('.');
+}
+
+
+// Basically just str.split(","), but handling cases
+// where we have nested braced sections, which should be
+// treated as individual members, like {a,{b,c},d}
+function parseCommaParts(str) {
+ if (!str)
+ return [''];
-DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() {
- if (this._maxDataSizeExceeded) {
- return;
- }
+ var parts = [];
+ var m = balanced('{', '}', str);
- if (this.dataSize <= this.maxDataSize) {
- return;
- }
+ if (!m)
+ return str.split(',');
- this._maxDataSizeExceeded = true;
- var message =
- 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'
- this.emit('error', new Error(message));
-};
+ var pre = m.pre;
+ var body = m.body;
+ var post = m.post;
+ var p = pre.split(',');
+ p[p.length-1] += '{' + body + '}';
+ var postParts = parseCommaParts(post);
+ if (post.length) {
+ p[p.length-1] += postParts.shift();
+ p.push.apply(p, postParts);
+ }
-/***/ }),
+ parts.push.apply(parts, p);
-/***/ 1133:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ return parts;
+}
-var debug;
+function expandTop(str) {
+ if (!str)
+ return [];
-module.exports = function () {
- if (!debug) {
- try {
- /* eslint global-require: off */
- debug = __nccwpck_require__(8237)("follow-redirects");
- }
- catch (error) { /* */ }
- if (typeof debug !== "function") {
- debug = function () { /* */ };
- }
+ // I don't know why Bash 4.3 does this, but it does.
+ // Anything starting with {} will have the first two bytes preserved
+ // but *only* at the top level, so {},a}b will not expand to anything,
+ // but a{},b}c will be expanded to [a}c,abc].
+ // One could argue that this is a bug in Bash, but since the goal of
+ // this module is to match Bash's rules, we escape a leading {}
+ if (str.substr(0, 2) === '{}') {
+ str = '\\{\\}' + str.substr(2);
}
- debug.apply(null, arguments);
-};
+ return expand(escapeBraces(str), true).map(unescapeBraces);
+}
-/***/ }),
+function embrace(str) {
+ return '{' + str + '}';
+}
+function isPadded(el) {
+ return /^-?0\d/.test(el);
+}
-/***/ 7707:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+function lte(i, y) {
+ return i <= y;
+}
+function gte(i, y) {
+ return i >= y;
+}
-var url = __nccwpck_require__(7310);
-var URL = url.URL;
-var http = __nccwpck_require__(3685);
-var https = __nccwpck_require__(5687);
-var Writable = (__nccwpck_require__(2781).Writable);
-var assert = __nccwpck_require__(9491);
-var debug = __nccwpck_require__(1133);
+function expand(str, isTop) {
+ var expansions = [];
-// Create handlers that pass events from native requests
-var events = ["abort", "aborted", "connect", "error", "socket", "timeout"];
-var eventHandlers = Object.create(null);
-events.forEach(function (event) {
- eventHandlers[event] = function (arg1, arg2, arg3) {
- this._redirectable.emit(event, arg1, arg2, arg3);
- };
-});
+ var m = balanced('{', '}', str);
+ if (!m) return [str];
-var InvalidUrlError = createErrorType(
- "ERR_INVALID_URL",
- "Invalid URL",
- TypeError
-);
-// Error types with codes
-var RedirectionError = createErrorType(
- "ERR_FR_REDIRECTION_FAILURE",
- "Redirected request failed"
-);
-var TooManyRedirectsError = createErrorType(
- "ERR_FR_TOO_MANY_REDIRECTS",
- "Maximum number of redirects exceeded"
-);
-var MaxBodyLengthExceededError = createErrorType(
- "ERR_FR_MAX_BODY_LENGTH_EXCEEDED",
- "Request body larger than maxBodyLength limit"
-);
-var WriteAfterEndError = createErrorType(
- "ERR_STREAM_WRITE_AFTER_END",
- "write after end"
-);
+ // no need to expand pre, since it is guaranteed to be free of brace-sets
+ var pre = m.pre;
+ var post = m.post.length
+ ? expand(m.post, false)
+ : [''];
-// An HTTP(S) request that can be redirected
-function RedirectableRequest(options, responseCallback) {
- // Initialize the request
- Writable.call(this);
- this._sanitizeOptions(options);
- this._options = options;
- this._ended = false;
- this._ending = false;
- this._redirectCount = 0;
- this._redirects = [];
- this._requestBodyLength = 0;
- this._requestBodyBuffers = [];
+ if (/\$$/.test(m.pre)) {
+ for (var k = 0; k < post.length; k++) {
+ var expansion = pre+ '{' + m.body + '}' + post[k];
+ expansions.push(expansion);
+ }
+ } else {
+ var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
+ var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
+ var isSequence = isNumericSequence || isAlphaSequence;
+ var isOptions = m.body.indexOf(',') >= 0;
+ if (!isSequence && !isOptions) {
+ // {a},b}
+ if (m.post.match(/,.*\}/)) {
+ str = m.pre + '{' + m.body + escClose + m.post;
+ return expand(str);
+ }
+ return [str];
+ }
- // Attach a callback if passed
- if (responseCallback) {
- this.on("response", responseCallback);
- }
+ var n;
+ if (isSequence) {
+ n = m.body.split(/\.\./);
+ } else {
+ n = parseCommaParts(m.body);
+ if (n.length === 1) {
+ // x{{a,b}}y ==> x{a}y x{b}y
+ n = expand(n[0], false).map(embrace);
+ if (n.length === 1) {
+ return post.map(function(p) {
+ return m.pre + n[0] + p;
+ });
+ }
+ }
+ }
- // React to responses of native requests
- var self = this;
- this._onNativeResponse = function (response) {
- self._processResponse(response);
- };
+ // at this point, n is the parts, and we know it's not a comma set
+ // with a single entry.
+ var N;
- // Perform the first request
- this._performRequest();
-}
-RedirectableRequest.prototype = Object.create(Writable.prototype);
+ if (isSequence) {
+ var x = numeric(n[0]);
+ var y = numeric(n[1]);
+ var width = Math.max(n[0].length, n[1].length)
+ var incr = n.length == 3
+ ? Math.abs(numeric(n[2]))
+ : 1;
+ var test = lte;
+ var reverse = y < x;
+ if (reverse) {
+ incr *= -1;
+ test = gte;
+ }
+ var pad = n.some(isPadded);
-RedirectableRequest.prototype.abort = function () {
- abortRequest(this._currentRequest);
- this.emit("abort");
-};
+ N = [];
-// Writes buffered data to the current native request
-RedirectableRequest.prototype.write = function (data, encoding, callback) {
- // Writing is not allowed if end has been called
- if (this._ending) {
- throw new WriteAfterEndError();
- }
+ for (var i = x; test(i, y); i += incr) {
+ var c;
+ if (isAlphaSequence) {
+ c = String.fromCharCode(i);
+ if (c === '\\')
+ c = '';
+ } else {
+ c = String(i);
+ if (pad) {
+ var need = width - c.length;
+ if (need > 0) {
+ var z = new Array(need + 1).join('0');
+ if (i < 0)
+ c = '-' + z + c.slice(1);
+ else
+ c = z + c;
+ }
+ }
+ }
+ N.push(c);
+ }
+ } else {
+ N = [];
- // Validate input and shift parameters if necessary
- if (!isString(data) && !isBuffer(data)) {
- throw new TypeError("data should be a string, Buffer or Uint8Array");
- }
- if (isFunction(encoding)) {
- callback = encoding;
- encoding = null;
- }
+ for (var j = 0; j < n.length; j++) {
+ N.push.apply(N, expand(n[j], false));
+ }
+ }
- // Ignore empty buffers, since writing them doesn't invoke the callback
- // https://github.com/nodejs/node/issues/22066
- if (data.length === 0) {
- if (callback) {
- callback();
+ for (var j = 0; j < N.length; j++) {
+ for (var k = 0; k < post.length; k++) {
+ var expansion = pre + N[j] + post[k];
+ if (!isTop || isSequence || expansion)
+ expansions.push(expansion);
+ }
}
- return;
}
- // Only write when we don't exceed the maximum body length
- if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {
- this._requestBodyLength += data.length;
- this._requestBodyBuffers.push({ data: data, encoding: encoding });
- this._currentRequest.write(data, encoding, callback);
- }
- // Error when we exceed the maximum body length
- else {
- this.emit("error", new MaxBodyLengthExceededError());
- this.abort();
- }
-};
-// Ends the current native request
-RedirectableRequest.prototype.end = function (data, encoding, callback) {
- // Shift parameters if necessary
- if (isFunction(data)) {
- callback = data;
- data = encoding = null;
- }
- else if (isFunction(encoding)) {
- callback = encoding;
- encoding = null;
- }
+ return expansions;
+}
- // Write data if needed and end
- if (!data) {
- this._ended = this._ending = true;
- this._currentRequest.end(null, null, callback);
- }
- else {
- var self = this;
- var currentRequest = this._currentRequest;
- this.write(data, encoding, function () {
- self._ended = true;
- currentRequest.end(null, null, callback);
- });
- this._ending = true;
- }
-};
-// Sets a header value on the current native request
-RedirectableRequest.prototype.setHeader = function (name, value) {
- this._options.headers[name] = value;
- this._currentRequest.setHeader(name, value);
-};
-// Clears a header value on the current native request
-RedirectableRequest.prototype.removeHeader = function (name) {
- delete this._options.headers[name];
- this._currentRequest.removeHeader(name);
-};
+/***/ }),
-// Global timeout for all underlying requests
-RedirectableRequest.prototype.setTimeout = function (msecs, callback) {
- var self = this;
+/***/ 3438:
+/***/ ((module) => {
- // Destroys the socket on timeout
- function destroyOnTimeout(socket) {
- socket.setTimeout(msecs);
- socket.removeListener("timeout", socket.destroy);
- socket.addListener("timeout", socket.destroy);
- }
+const isWindows = typeof process === 'object' &&
+ process &&
+ process.platform === 'win32'
+module.exports = isWindows ? { sep: '\\' } : { sep: '/' }
- // Sets up a timer to trigger a timeout event
- function startTimer(socket) {
- if (self._timeout) {
- clearTimeout(self._timeout);
- }
- self._timeout = setTimeout(function () {
- self.emit("timeout");
- clearTimer();
- }, msecs);
- destroyOnTimeout(socket);
- }
- // Stops a timeout from triggering
- function clearTimer() {
- // Clear the timeout
- if (self._timeout) {
- clearTimeout(self._timeout);
- self._timeout = null;
- }
+/***/ }),
- // Clean up all attached listeners
- self.removeListener("abort", clearTimer);
- self.removeListener("error", clearTimer);
- self.removeListener("response", clearTimer);
- if (callback) {
- self.removeListener("timeout", callback);
- }
- if (!self.socket) {
- self._currentRequest.removeListener("socket", startTimer);
- }
- }
+/***/ 6453:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // Attach callback if passed
- if (callback) {
- this.on("timeout", callback);
- }
+const minimatch = module.exports = (p, pattern, options = {}) => {
+ assertValidPattern(pattern)
- // Start the timer if or when the socket is opened
- if (this.socket) {
- startTimer(this.socket);
- }
- else {
- this._currentRequest.once("socket", startTimer);
+ // shortcut: comments match nothing.
+ if (!options.nocomment && pattern.charAt(0) === '#') {
+ return false
}
- // Clean up on events
- this.on("socket", destroyOnTimeout);
- this.on("abort", clearTimer);
- this.on("error", clearTimer);
- this.on("response", clearTimer);
+ return new Minimatch(pattern, options).match(p)
+}
- return this;
-};
+module.exports = minimatch
-// Proxy all other public ClientRequest methods
-[
- "flushHeaders", "getHeader",
- "setNoDelay", "setSocketKeepAlive",
-].forEach(function (method) {
- RedirectableRequest.prototype[method] = function (a, b) {
- return this._currentRequest[method](a, b);
- };
-});
+const path = __nccwpck_require__(3438)
+minimatch.sep = path.sep
-// Proxy all public ClientRequest properties
-["aborted", "connection", "socket"].forEach(function (property) {
- Object.defineProperty(RedirectableRequest.prototype, property, {
- get: function () { return this._currentRequest[property]; },
- });
-});
+const GLOBSTAR = Symbol('globstar **')
+minimatch.GLOBSTAR = GLOBSTAR
+const expand = __nccwpck_require__(1046)
-RedirectableRequest.prototype._sanitizeOptions = function (options) {
- // Ensure headers are always present
- if (!options.headers) {
- options.headers = {};
- }
+const plTypes = {
+ '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
+ '?': { open: '(?:', close: ')?' },
+ '+': { open: '(?:', close: ')+' },
+ '*': { open: '(?:', close: ')*' },
+ '@': { open: '(?:', close: ')' }
+}
- // Since http.request treats host as an alias of hostname,
- // but the url module interprets host as hostname plus port,
- // eliminate the host property to avoid confusion.
- if (options.host) {
- // Use hostname if set, because it has precedence
- if (!options.hostname) {
- options.hostname = options.host;
- }
- delete options.host;
- }
+// any single thing other than /
+// don't need to escape / when using new RegExp()
+const qmark = '[^/]'
- // Complete the URL object when necessary
- if (!options.pathname && options.path) {
- var searchPos = options.path.indexOf("?");
- if (searchPos < 0) {
- options.pathname = options.path;
- }
- else {
- options.pathname = options.path.substring(0, searchPos);
- options.search = options.path.substring(searchPos);
- }
- }
-};
+// * => any number of characters
+const star = qmark + '*?'
+// ** when dots are allowed. Anything goes, except .. and .
+// not (^ or / followed by one or two dots followed by $ or /),
+// followed by anything, any number of times.
+const twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'
-// Executes the next native request (initial or redirect)
-RedirectableRequest.prototype._performRequest = function () {
- // Load the native protocol
- var protocol = this._options.protocol;
- var nativeProtocol = this._options.nativeProtocols[protocol];
- if (!nativeProtocol) {
- this.emit("error", new TypeError("Unsupported protocol " + protocol));
- return;
- }
+// not a ^ or / followed by a dot,
+// followed by anything, any number of times.
+const twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'
- // If specified, use the agent corresponding to the protocol
- // (HTTP and HTTPS use different types of agents)
- if (this._options.agents) {
- var scheme = protocol.slice(0, -1);
- this._options.agent = this._options.agents[scheme];
- }
+// "abc" -> { a:true, b:true, c:true }
+const charSet = s => s.split('').reduce((set, c) => {
+ set[c] = true
+ return set
+}, {})
- // Create the native request and set up its event handlers
- var request = this._currentRequest =
- nativeProtocol.request(this._options, this._onNativeResponse);
- request._redirectable = this;
- for (var event of events) {
- request.on(event, eventHandlers[event]);
- }
+// characters that need to be escaped in RegExp.
+const reSpecials = charSet('().*{}+?[]^$\\!')
- // RFC7230§5.3.1: When making a request directly to an origin server, […]
- // a client MUST send only the absolute path […] as the request-target.
- this._currentUrl = /^\//.test(this._options.path) ?
- url.format(this._options) :
- // When making a request to a proxy, […]
- // a client MUST send the target URI in absolute-form […].
- this._options.path;
+// characters that indicate we have to add the pattern start
+const addPatternStartSet = charSet('[.(')
- // End a redirected request
- // (The first request must be ended explicitly with RedirectableRequest#end)
- if (this._isRedirect) {
- // Write the request entity and end
- var i = 0;
- var self = this;
- var buffers = this._requestBodyBuffers;
- (function writeNext(error) {
- // Only write if this request has not been redirected yet
- /* istanbul ignore else */
- if (request === self._currentRequest) {
- // Report any write errors
- /* istanbul ignore if */
- if (error) {
- self.emit("error", error);
- }
- // Write the next buffer if there are still left
- else if (i < buffers.length) {
- var buffer = buffers[i++];
- /* istanbul ignore else */
- if (!request.finished) {
- request.write(buffer.data, buffer.encoding, writeNext);
- }
- }
- // End the request if `end` has been called on us
- else if (self._ended) {
- request.end();
- }
- }
- }());
+// normalizes slashes.
+const slashSplit = /\/+/
+
+minimatch.filter = (pattern, options = {}) =>
+ (p, i, list) => minimatch(p, pattern, options)
+
+const ext = (a, b = {}) => {
+ const t = {}
+ Object.keys(a).forEach(k => t[k] = a[k])
+ Object.keys(b).forEach(k => t[k] = b[k])
+ return t
+}
+
+minimatch.defaults = def => {
+ if (!def || typeof def !== 'object' || !Object.keys(def).length) {
+ return minimatch
}
-};
-// Processes a response from the current native request
-RedirectableRequest.prototype._processResponse = function (response) {
- // Store the redirected response
- var statusCode = response.statusCode;
- if (this._options.trackRedirects) {
- this._redirects.push({
- url: this._currentUrl,
- headers: response.headers,
- statusCode: statusCode,
- });
+ const orig = minimatch
+
+ const m = (p, pattern, options) => orig(p, pattern, ext(def, options))
+ m.Minimatch = class Minimatch extends orig.Minimatch {
+ constructor (pattern, options) {
+ super(pattern, ext(def, options))
+ }
}
+ m.Minimatch.defaults = options => orig.defaults(ext(def, options)).Minimatch
+ m.filter = (pattern, options) => orig.filter(pattern, ext(def, options))
+ m.defaults = options => orig.defaults(ext(def, options))
+ m.makeRe = (pattern, options) => orig.makeRe(pattern, ext(def, options))
+ m.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext(def, options))
+ m.match = (list, pattern, options) => orig.match(list, pattern, ext(def, options))
- // RFC7231§6.4: The 3xx (Redirection) class of status code indicates
- // that further action needs to be taken by the user agent in order to
- // fulfill the request. If a Location header field is provided,
- // the user agent MAY automatically redirect its request to the URI
- // referenced by the Location field value,
- // even if the specific status code is not understood.
+ return m
+}
- // If the response is not a redirect; return it as-is
- var location = response.headers.location;
- if (!location || this._options.followRedirects === false ||
- statusCode < 300 || statusCode >= 400) {
- response.responseUrl = this._currentUrl;
- response.redirects = this._redirects;
- this.emit("response", response);
- // Clean up
- this._requestBodyBuffers = [];
- return;
- }
- // The response is a redirect, so abort the current request
- abortRequest(this._currentRequest);
- // Discard the remainder of the response to avoid waiting for data
- response.destroy();
- // RFC7231§6.4: A client SHOULD detect and intervene
- // in cyclical redirections (i.e., "infinite" redirection loops).
- if (++this._redirectCount > this._options.maxRedirects) {
- this.emit("error", new TooManyRedirectsError());
- return;
+
+// Brace expansion:
+// a{b,c}d -> abd acd
+// a{b,}c -> abc ac
+// a{0..3}d -> a0d a1d a2d a3d
+// a{b,c{d,e}f}g -> abg acdfg acefg
+// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
+//
+// Invalid sets are not expanded.
+// a{2..}b -> a{2..}b
+// a{b}c -> a{b}c
+minimatch.braceExpand = (pattern, options) => braceExpand(pattern, options)
+
+const braceExpand = (pattern, options = {}) => {
+ assertValidPattern(pattern)
+
+ // Thanks to Yeting Li for
+ // improving this regexp to avoid a ReDOS vulnerability.
+ if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
+ // shortcut. no need to expand.
+ return [pattern]
}
- // Store the request headers if applicable
- var requestHeaders;
- var beforeRedirect = this._options.beforeRedirect;
- if (beforeRedirect) {
- requestHeaders = Object.assign({
- // The Host header was set by nativeProtocol.request
- Host: response.req.getHeader("host"),
- }, this._options.headers);
+ return expand(pattern)
+}
+
+const MAX_PATTERN_LENGTH = 1024 * 64
+const assertValidPattern = pattern => {
+ if (typeof pattern !== 'string') {
+ throw new TypeError('invalid pattern')
}
- // RFC7231§6.4: Automatic redirection needs to done with
- // care for methods not known to be safe, […]
- // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change
- // the request method from POST to GET for the subsequent request.
- var method = this._options.method;
- if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" ||
- // RFC7231§6.4.4: The 303 (See Other) status code indicates that
- // the server is redirecting the user agent to a different resource […]
- // A user agent can perform a retrieval request targeting that URI
- // (a GET or HEAD request if using HTTP) […]
- (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) {
- this._options.method = "GET";
- // Drop a possible entity and headers related to it
- this._requestBodyBuffers = [];
- removeMatchingHeaders(/^content-/i, this._options.headers);
+ if (pattern.length > MAX_PATTERN_LENGTH) {
+ throw new TypeError('pattern is too long')
}
+}
- // Drop the Host header, as the redirect might lead to a different host
- var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers);
+// parse a component of the expanded set.
+// At this point, no pattern may contain "/" in it
+// so we're going to return a 2d array, where each entry is the full
+// pattern, split on '/', and then turned into a regular expression.
+// A regexp is made at the end which joins each array with an
+// escaped /, and another full one which joins each regexp with |.
+//
+// Following the lead of Bash 4.1, note that "**" only has special meaning
+// when it is the *only* thing in a path portion. Otherwise, any series
+// of * is equivalent to a single *. Globstar behavior is enabled by
+// default, and can be disabled by setting options.noglobstar.
+const SUBPARSE = Symbol('subparse')
- // If the redirect is relative, carry over the host of the last request
- var currentUrlParts = url.parse(this._currentUrl);
- var currentHost = currentHostHeader || currentUrlParts.host;
- var currentUrl = /^\w+:/.test(location) ? this._currentUrl :
- url.format(Object.assign(currentUrlParts, { host: currentHost }));
+minimatch.makeRe = (pattern, options) =>
+ new Minimatch(pattern, options || {}).makeRe()
- // Determine the URL of the redirection
- var redirectUrl;
- try {
- redirectUrl = url.resolve(currentUrl, location);
- }
- catch (cause) {
- this.emit("error", new RedirectionError({ cause: cause }));
- return;
+minimatch.match = (list, pattern, options = {}) => {
+ const mm = new Minimatch(pattern, options)
+ list = list.filter(f => mm.match(f))
+ if (mm.options.nonull && !list.length) {
+ list.push(pattern)
}
+ return list
+}
- // Create the redirected request
- debug("redirecting to", redirectUrl);
- this._isRedirect = true;
- var redirectUrlParts = url.parse(redirectUrl);
- Object.assign(this._options, redirectUrlParts);
+// replace stuff like \* with *
+const globUnescape = s => s.replace(/\\(.)/g, '$1')
+const charUnescape = s => s.replace(/\\([^-\]])/g, '$1')
+const regExpEscape = s => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
+const braExpEscape = s => s.replace(/[[\]\\]/g, '\\$&')
- // Drop confidential headers when redirecting to a less secure protocol
- // or to a different domain that is not a superdomain
- if (redirectUrlParts.protocol !== currentUrlParts.protocol &&
- redirectUrlParts.protocol !== "https:" ||
- redirectUrlParts.host !== currentHost &&
- !isSubdomain(redirectUrlParts.host, currentHost)) {
- removeMatchingHeaders(/^(?:authorization|cookie)$/i, this._options.headers);
+class Minimatch {
+ constructor (pattern, options) {
+ assertValidPattern(pattern)
+
+ if (!options) options = {}
+
+ this.options = options
+ this.set = []
+ this.pattern = pattern
+ this.windowsPathsNoEscape = !!options.windowsPathsNoEscape ||
+ options.allowWindowsEscape === false
+ if (this.windowsPathsNoEscape) {
+ this.pattern = this.pattern.replace(/\\/g, '/')
+ }
+ this.regexp = null
+ this.negate = false
+ this.comment = false
+ this.empty = false
+ this.partial = !!options.partial
+
+ // make the set of regexps etc.
+ this.make()
}
- // Evaluate the beforeRedirect callback
- if (isFunction(beforeRedirect)) {
- var responseDetails = {
- headers: response.headers,
- statusCode: statusCode,
- };
- var requestDetails = {
- url: currentUrl,
- method: method,
- headers: requestHeaders,
- };
- try {
- beforeRedirect(this._options, responseDetails, requestDetails);
+ debug () {}
+
+ make () {
+ const pattern = this.pattern
+ const options = this.options
+
+ // empty patterns and comments match nothing.
+ if (!options.nocomment && pattern.charAt(0) === '#') {
+ this.comment = true
+ return
}
- catch (err) {
- this.emit("error", err);
- return;
+ if (!pattern) {
+ this.empty = true
+ return
}
- this._sanitizeOptions(this._options);
- }
- // Perform the redirected request
- try {
- this._performRequest();
- }
- catch (cause) {
- this.emit("error", new RedirectionError({ cause: cause }));
- }
-};
+ // step 1: figure out negation, etc.
+ this.parseNegate()
-// Wraps the key/value object of protocols with redirect functionality
-function wrap(protocols) {
- // Default settings
- var exports = {
- maxRedirects: 21,
- maxBodyLength: 10 * 1024 * 1024,
- };
+ // step 2: expand braces
+ let set = this.globSet = this.braceExpand()
- // Wrap each protocol
- var nativeProtocols = {};
- Object.keys(protocols).forEach(function (scheme) {
- var protocol = scheme + ":";
- var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];
- var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol);
+ if (options.debug) this.debug = (...args) => console.error(...args)
- // Executes a request, following redirects
- function request(input, options, callback) {
- // Parse parameters
- if (isString(input)) {
- var parsed;
- try {
- parsed = urlToOptions(new URL(input));
- }
- catch (err) {
- /* istanbul ignore next */
- parsed = url.parse(input);
- }
- if (!isString(parsed.protocol)) {
- throw new InvalidUrlError({ input });
- }
- input = parsed;
- }
- else if (URL && (input instanceof URL)) {
- input = urlToOptions(input);
- }
- else {
- callback = options;
- options = input;
- input = { protocol: protocol };
- }
- if (isFunction(options)) {
- callback = options;
- options = null;
- }
+ this.debug(this.pattern, set)
- // Set defaults
- options = Object.assign({
- maxRedirects: exports.maxRedirects,
- maxBodyLength: exports.maxBodyLength,
- }, input, options);
- options.nativeProtocols = nativeProtocols;
- if (!isString(options.host) && !isString(options.hostname)) {
- options.hostname = "::1";
- }
+ // step 3: now we have a set, so turn each one into a series of path-portion
+ // matching patterns.
+ // These will be regexps, except in the case of "**", which is
+ // set to the GLOBSTAR object for globstar behavior,
+ // and will not contain any / characters
+ set = this.globParts = set.map(s => s.split(slashSplit))
- assert.equal(options.protocol, protocol, "protocol mismatch");
- debug("options", options);
- return new RedirectableRequest(options, callback);
- }
+ this.debug(this.pattern, set)
- // Executes a GET request, following redirects
- function get(input, options, callback) {
- var wrappedRequest = wrappedProtocol.request(input, options, callback);
- wrappedRequest.end();
- return wrappedRequest;
- }
+ // glob --> regexps
+ set = set.map((s, si, set) => s.map(this.parse, this))
- // Expose the properties on the wrapped protocol
- Object.defineProperties(wrappedProtocol, {
- request: { value: request, configurable: true, enumerable: true, writable: true },
- get: { value: get, configurable: true, enumerable: true, writable: true },
- });
- });
- return exports;
-}
+ this.debug(this.pattern, set)
-/* istanbul ignore next */
-function noop() { /* empty */ }
+ // filter out everything that didn't compile properly.
+ set = set.filter(s => s.indexOf(false) === -1)
-// from https://github.com/nodejs/node/blob/master/lib/internal/url.js
-function urlToOptions(urlObject) {
- var options = {
- protocol: urlObject.protocol,
- hostname: urlObject.hostname.startsWith("[") ?
- /* istanbul ignore next */
- urlObject.hostname.slice(1, -1) :
- urlObject.hostname,
- hash: urlObject.hash,
- search: urlObject.search,
- pathname: urlObject.pathname,
- path: urlObject.pathname + urlObject.search,
- href: urlObject.href,
- };
- if (urlObject.port !== "") {
- options.port = Number(urlObject.port);
- }
- return options;
-}
+ this.debug(this.pattern, set)
-function removeMatchingHeaders(regex, headers) {
- var lastValue;
- for (var header in headers) {
- if (regex.test(header)) {
- lastValue = headers[header];
- delete headers[header];
- }
+ this.set = set
}
- return (lastValue === null || typeof lastValue === "undefined") ?
- undefined : String(lastValue).trim();
-}
-function createErrorType(code, message, baseClass) {
- // Create constructor
- function CustomError(properties) {
- Error.captureStackTrace(this, this.constructor);
- Object.assign(this, properties || {});
- this.code = code;
- this.message = this.cause ? message + ": " + this.cause.message : message;
- }
+ parseNegate () {
+ if (this.options.nonegate) return
- // Attach constructor and set default properties
- CustomError.prototype = new (baseClass || Error)();
- CustomError.prototype.constructor = CustomError;
- CustomError.prototype.name = "Error [" + code + "]";
- return CustomError;
-}
+ const pattern = this.pattern
+ let negate = false
+ let negateOffset = 0
-function abortRequest(request) {
- for (var event of events) {
- request.removeListener(event, eventHandlers[event]);
- }
- request.on("error", noop);
- request.abort();
-}
+ for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
+ negate = !negate
+ negateOffset++
+ }
-function isSubdomain(subdomain, domain) {
- assert(isString(subdomain) && isString(domain));
- var dot = subdomain.length - domain.length - 1;
- return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain);
-}
+ if (negateOffset) this.pattern = pattern.slice(negateOffset)
+ this.negate = negate
+ }
-function isString(value) {
- return typeof value === "string" || value instanceof String;
-}
+ // set partial to true to test if, for example,
+ // "/a/b" matches the start of "/*/b/*/d"
+ // Partial means, if you run out of file before you run
+ // out of pattern, then that's fine, as long as all
+ // the parts match.
+ matchOne (file, pattern, partial) {
+ var options = this.options
-function isFunction(value) {
- return typeof value === "function";
-}
+ this.debug('matchOne',
+ { 'this': this, file: file, pattern: pattern })
-function isBuffer(value) {
- return typeof value === "object" && ("length" in value);
-}
+ this.debug('matchOne', file.length, pattern.length)
-// Exports
-module.exports = wrap({ http: http, https: https });
-module.exports.wrap = wrap;
+ for (var fi = 0,
+ pi = 0,
+ fl = file.length,
+ pl = pattern.length
+ ; (fi < fl) && (pi < pl)
+ ; fi++, pi++) {
+ this.debug('matchOne loop')
+ var p = pattern[pi]
+ var f = file[fi]
+ this.debug(pattern, p, f)
-/***/ }),
+ // should be impossible.
+ // some invalid regexp stuff in the set.
+ /* istanbul ignore if */
+ if (p === false) return false
-/***/ 4334:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (p === GLOBSTAR) {
+ this.debug('GLOBSTAR', [pattern, p, f])
-var CombinedStream = __nccwpck_require__(5443);
-var util = __nccwpck_require__(3837);
-var path = __nccwpck_require__(1017);
-var http = __nccwpck_require__(3685);
-var https = __nccwpck_require__(5687);
-var parseUrl = (__nccwpck_require__(7310).parse);
-var fs = __nccwpck_require__(7147);
-var Stream = (__nccwpck_require__(2781).Stream);
-var mime = __nccwpck_require__(3583);
-var asynckit = __nccwpck_require__(4812);
-var populate = __nccwpck_require__(7142);
+ // "**"
+ // a/**/b/**/c would match the following:
+ // a/b/x/y/z/c
+ // a/x/y/z/b/c
+ // a/b/x/b/x/c
+ // a/b/c
+ // To do this, take the rest of the pattern after
+ // the **, and see if it would match the file remainder.
+ // If so, return success.
+ // If not, the ** "swallows" a segment, and try again.
+ // This is recursively awful.
+ //
+ // a/**/b/**/c matching a/b/x/y/z/c
+ // - a matches a
+ // - doublestar
+ // - matchOne(b/x/y/z/c, b/**/c)
+ // - b matches b
+ // - doublestar
+ // - matchOne(x/y/z/c, c) -> no
+ // - matchOne(y/z/c, c) -> no
+ // - matchOne(z/c, c) -> no
+ // - matchOne(c, c) yes, hit
+ var fr = fi
+ var pr = pi + 1
+ if (pr === pl) {
+ this.debug('** at the end')
+ // a ** at the end will just swallow the rest.
+ // We have found a match.
+ // however, it will not swallow /.x, unless
+ // options.dot is set.
+ // . and .. are *never* matched by **, for explosively
+ // exponential reasons.
+ for (; fi < fl; fi++) {
+ if (file[fi] === '.' || file[fi] === '..' ||
+ (!options.dot && file[fi].charAt(0) === '.')) return false
+ }
+ return true
+ }
-// Public API
-module.exports = FormData;
+ // ok, let's see if we can swallow whatever we can.
+ while (fr < fl) {
+ var swallowee = file[fr]
-// make it a Stream
-util.inherits(FormData, CombinedStream);
+ this.debug('\nglobstar while', file, fr, pattern, pr, swallowee)
-/**
- * Create readable "multipart/form-data" streams.
- * Can be used to submit forms
- * and file uploads to other web applications.
- *
- * @constructor
- * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream
- */
-function FormData(options) {
- if (!(this instanceof FormData)) {
- return new FormData(options);
- }
+ // XXX remove this slice. Just pass the start index.
+ if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
+ this.debug('globstar found match!', fr, fl, swallowee)
+ // found a match.
+ return true
+ } else {
+ // can't swallow "." or ".." ever.
+ // can only swallow ".foo" when explicitly asked.
+ if (swallowee === '.' || swallowee === '..' ||
+ (!options.dot && swallowee.charAt(0) === '.')) {
+ this.debug('dot detected!', file, fr, pattern, pr)
+ break
+ }
- this._overheadLength = 0;
- this._valueLength = 0;
- this._valuesToMeasure = [];
+ // ** swallows a segment, and continue.
+ this.debug('globstar swallow a segment, and continue')
+ fr++
+ }
+ }
- CombinedStream.call(this);
+ // no match was found.
+ // However, in partial mode, we can't say this is necessarily over.
+ // If there's more *pattern* left, then
+ /* istanbul ignore if */
+ if (partial) {
+ // ran out of file
+ this.debug('\n>>> no match, partial?', file, fr, pattern, pr)
+ if (fr === fl) return true
+ }
+ return false
+ }
- options = options || {};
- for (var option in options) {
- this[option] = options[option];
- }
-}
+ // something other than **
+ // non-magic patterns just have to match exactly
+ // patterns with magic have been turned into regexps.
+ var hit
+ if (typeof p === 'string') {
+ hit = f === p
+ this.debug('string match', p, f, hit)
+ } else {
+ hit = f.match(p)
+ this.debug('pattern match', p, f, hit)
+ }
-FormData.LINE_BREAK = '\r\n';
-FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream';
+ if (!hit) return false
+ }
-FormData.prototype.append = function(field, value, options) {
+ // Note: ending in / means that we'll get a final ""
+ // at the end of the pattern. This can only match a
+ // corresponding "" at the end of the file.
+ // If the file ends in /, then it can only match a
+ // a pattern that ends in /, unless the pattern just
+ // doesn't have any more for it. But, a/b/ should *not*
+ // match "a/b/*", even though "" matches against the
+ // [^/]*? pattern, except in partial mode, where it might
+ // simply not be reached yet.
+ // However, a/b/ should still satisfy a/*
- options = options || {};
+ // now either we fell off the end of the pattern, or we're done.
+ if (fi === fl && pi === pl) {
+ // ran out of pattern and filename at the same time.
+ // an exact hit!
+ return true
+ } else if (fi === fl) {
+ // ran out of file, but still had pattern left.
+ // this is ok if we're doing the match as part of
+ // a glob fs traversal.
+ return partial
+ } else /* istanbul ignore else */ if (pi === pl) {
+ // ran out of pattern, still have file left.
+ // this is only acceptable if we're on the very last
+ // empty segment of a file with a trailing slash.
+ // a/* should match a/b/
+ return (fi === fl - 1) && (file[fi] === '')
+ }
- // allow filename as single option
- if (typeof options == 'string') {
- options = {filename: options};
+ // should be unreachable.
+ /* istanbul ignore next */
+ throw new Error('wtf?')
}
- var append = CombinedStream.prototype.append.bind(this);
-
- // all that streamy business can't handle numbers
- if (typeof value == 'number') {
- value = '' + value;
+ braceExpand () {
+ return braceExpand(this.pattern, this.options)
}
- // https://github.com/felixge/node-form-data/issues/38
- if (util.isArray(value)) {
- // Please convert your array into string
- // the way web server expects it
- this._error(new Error('Arrays are not supported.'));
- return;
- }
+ parse (pattern, isSub) {
+ assertValidPattern(pattern)
- var header = this._multiPartHeader(field, value, options);
- var footer = this._multiPartFooter();
+ const options = this.options
- append(header);
- append(value);
- append(footer);
+ // shortcuts
+ if (pattern === '**') {
+ if (!options.noglobstar)
+ return GLOBSTAR
+ else
+ pattern = '*'
+ }
+ if (pattern === '') return ''
- // pass along options.knownLength
- this._trackLength(header, value, options);
-};
+ let re = ''
+ let hasMagic = false
+ let escaping = false
+ // ? => one single character
+ const patternListStack = []
+ const negativeLists = []
+ let stateChar
+ let inClass = false
+ let reClassStart = -1
+ let classStart = -1
+ let cs
+ let pl
+ let sp
+ // . and .. never match anything that doesn't start with .,
+ // even when options.dot is set. However, if the pattern
+ // starts with ., then traversal patterns can match.
+ let dotTravAllowed = pattern.charAt(0) === '.'
+ let dotFileAllowed = options.dot || dotTravAllowed
+ const patternStart = () =>
+ dotTravAllowed
+ ? ''
+ : dotFileAllowed
+ ? '(?!(?:^|\\/)\\.{1,2}(?:$|\\/))'
+ : '(?!\\.)'
+ const subPatternStart = (p) =>
+ p.charAt(0) === '.'
+ ? ''
+ : options.dot
+ ? '(?!(?:^|\\/)\\.{1,2}(?:$|\\/))'
+ : '(?!\\.)'
-FormData.prototype._trackLength = function(header, value, options) {
- var valueLength = 0;
- // used w/ getLengthSync(), when length is known.
- // e.g. for streaming directly from a remote server,
- // w/ a known file a size, and not wanting to wait for
- // incoming file to finish to get its size.
- if (options.knownLength != null) {
- valueLength += +options.knownLength;
- } else if (Buffer.isBuffer(value)) {
- valueLength = value.length;
- } else if (typeof value === 'string') {
- valueLength = Buffer.byteLength(value);
- }
+ const clearStateChar = () => {
+ if (stateChar) {
+ // we had some state-tracking character
+ // that wasn't consumed by this pass.
+ switch (stateChar) {
+ case '*':
+ re += star
+ hasMagic = true
+ break
+ case '?':
+ re += qmark
+ hasMagic = true
+ break
+ default:
+ re += '\\' + stateChar
+ break
+ }
+ this.debug('clearStateChar %j %j', stateChar, re)
+ stateChar = false
+ }
+ }
- this._valueLength += valueLength;
+ for (let i = 0, c; (i < pattern.length) && (c = pattern.charAt(i)); i++) {
+ this.debug('%s\t%s %s %j', pattern, i, re, c)
- // @check why add CRLF? does this account for custom/multiple CRLFs?
- this._overheadLength +=
- Buffer.byteLength(header) +
- FormData.LINE_BREAK.length;
+ // skip over any that are escaped.
+ if (escaping) {
+ /* istanbul ignore next - completely not allowed, even escaped. */
+ if (c === '/') {
+ return false
+ }
- // empty or either doesn't have path or not an http response or not a stream
- if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) && !(value instanceof Stream))) {
- return;
- }
+ if (reSpecials[c]) {
+ re += '\\'
+ }
+ re += c
+ escaping = false
+ continue
+ }
- // no need to bother with the length
- if (!options.knownLength) {
- this._valuesToMeasure.push(value);
- }
-};
+ switch (c) {
+ /* istanbul ignore next */
+ case '/': {
+ // Should already be path-split by now.
+ return false
+ }
-FormData.prototype._lengthRetriever = function(value, callback) {
+ case '\\':
+ if (inClass && pattern.charAt(i + 1) === '-') {
+ re += c
+ continue
+ }
- if (value.hasOwnProperty('fd')) {
+ clearStateChar()
+ escaping = true
+ continue
- // take read range into a account
- // `end` = Infinity –> read file till the end
- //
- // TODO: Looks like there is bug in Node fs.createReadStream
- // it doesn't respect `end` options without `start` options
- // Fix it when node fixes it.
- // https://github.com/joyent/node/issues/7819
- if (value.end != undefined && value.end != Infinity && value.start != undefined) {
+ // the various stateChar values
+ // for the "extglob" stuff.
+ case '?':
+ case '*':
+ case '+':
+ case '@':
+ case '!':
+ this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c)
- // when end specified
- // no need to calculate range
- // inclusive, starts with 0
- callback(null, value.end + 1 - (value.start ? value.start : 0));
+ // all of those are literals inside a class, except that
+ // the glob [!a] means [^a] in regexp
+ if (inClass) {
+ this.debug(' in class')
+ if (c === '!' && i === classStart + 1) c = '^'
+ re += c
+ continue
+ }
- // not that fast snoopy
- } else {
- // still need to fetch file size from fs
- fs.stat(value.path, function(err, stat) {
+ // if we already have a stateChar, then it means
+ // that there was something like ** or +? in there.
+ // Handle the stateChar, then proceed with this one.
+ this.debug('call clearStateChar %j', stateChar)
+ clearStateChar()
+ stateChar = c
+ // if extglob is disabled, then +(asdf|foo) isn't a thing.
+ // just clear the statechar *now*, rather than even diving into
+ // the patternList stuff.
+ if (options.noext) clearStateChar()
+ continue
- var fileSize;
+ case '(': {
+ if (inClass) {
+ re += '('
+ continue
+ }
- if (err) {
- callback(err);
- return;
- }
+ if (!stateChar) {
+ re += '\\('
+ continue
+ }
- // update final size based on the range options
- fileSize = stat.size - (value.start ? value.start : 0);
- callback(null, fileSize);
- });
- }
+ const plEntry = {
+ type: stateChar,
+ start: i - 1,
+ reStart: re.length,
+ open: plTypes[stateChar].open,
+ close: plTypes[stateChar].close,
+ }
+ this.debug(this.pattern, '\t', plEntry)
+ patternListStack.push(plEntry)
+ // negation is (?:(?!(?:js)(?:))[^/]*)
+ re += plEntry.open
+ // next entry starts with a dot maybe?
+ if (plEntry.start === 0 && plEntry.type !== '!') {
+ dotTravAllowed = true
+ re += subPatternStart(pattern.slice(i + 1))
+ }
+ this.debug('plType %j %j', stateChar, re)
+ stateChar = false
+ continue
+ }
- // or http response
- } else if (value.hasOwnProperty('httpVersion')) {
- callback(null, +value.headers['content-length']);
+ case ')': {
+ const plEntry = patternListStack[patternListStack.length - 1]
+ if (inClass || !plEntry) {
+ re += '\\)'
+ continue
+ }
+ patternListStack.pop()
- // or request stream http://github.com/mikeal/request
- } else if (value.hasOwnProperty('httpModule')) {
- // wait till response come back
- value.on('response', function(response) {
- value.pause();
- callback(null, +response.headers['content-length']);
- });
- value.resume();
+ // closing an extglob
+ clearStateChar()
+ hasMagic = true
+ pl = plEntry
+ // negation is (?:(?!js)[^/]*)
+ // The others are (?:)
+ re += pl.close
+ if (pl.type === '!') {
+ negativeLists.push(Object.assign(pl, { reEnd: re.length }))
+ }
+ continue
+ }
- // something else
- } else {
- callback('Unknown stream');
- }
-};
+ case '|': {
+ const plEntry = patternListStack[patternListStack.length - 1]
+ if (inClass || !plEntry) {
+ re += '\\|'
+ continue
+ }
-FormData.prototype._multiPartHeader = function(field, value, options) {
- // custom header specified (as string)?
- // it becomes responsible for boundary
- // (e.g. to handle extra CRLFs on .NET servers)
- if (typeof options.header == 'string') {
- return options.header;
- }
+ clearStateChar()
+ re += '|'
+ // next subpattern can start with a dot?
+ if (plEntry.start === 0 && plEntry.type !== '!') {
+ dotTravAllowed = true
+ re += subPatternStart(pattern.slice(i + 1))
+ }
+ continue
+ }
- var contentDisposition = this._getContentDisposition(value, options);
- var contentType = this._getContentType(value, options);
+ // these are mostly the same in regexp and glob
+ case '[':
+ // swallow any state-tracking char before the [
+ clearStateChar()
- var contents = '';
- var headers = {
- // add custom disposition as third element or keep it two elements if not
- 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []),
- // if no content type. allow it to be empty array
- 'Content-Type': [].concat(contentType || [])
- };
+ if (inClass) {
+ re += '\\' + c
+ continue
+ }
- // allow custom headers.
- if (typeof options.header == 'object') {
- populate(headers, options.header);
- }
+ inClass = true
+ classStart = i
+ reClassStart = re.length
+ re += c
+ continue
- var header;
- for (var prop in headers) {
- if (!headers.hasOwnProperty(prop)) continue;
- header = headers[prop];
+ case ']':
+ // a right bracket shall lose its special
+ // meaning and represent itself in
+ // a bracket expression if it occurs
+ // first in the list. -- POSIX.2 2.8.3.2
+ if (i === classStart + 1 || !inClass) {
+ re += '\\' + c
+ continue
+ }
- // skip nullish headers.
- if (header == null) {
- continue;
- }
+ // split where the last [ was, make sure we don't have
+ // an invalid re. if so, re-walk the contents of the
+ // would-be class to re-translate any characters that
+ // were passed through as-is
+ // TODO: It would probably be faster to determine this
+ // without a try/catch and a new RegExp, but it's tricky
+ // to do safely. For now, this is safe and works.
+ cs = pattern.substring(classStart + 1, i)
+ try {
+ RegExp('[' + braExpEscape(charUnescape(cs)) + ']')
+ // looks good, finish up the class.
+ re += c
+ } catch (er) {
+ // out of order ranges in JS are errors, but in glob syntax,
+ // they're just a range that matches nothing.
+ re = re.substring(0, reClassStart) + '(?:$.)' // match nothing ever
+ }
+ hasMagic = true
+ inClass = false
+ continue
- // convert all headers to arrays.
- if (!Array.isArray(header)) {
- header = [header];
- }
+ default:
+ // swallow any state char that wasn't consumed
+ clearStateChar()
- // add non-empty headers.
- if (header.length) {
- contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK;
- }
- }
+ if (reSpecials[c] && !(c === '^' && inClass)) {
+ re += '\\'
+ }
- return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK;
-};
+ re += c
+ break
-FormData.prototype._getContentDisposition = function(value, options) {
+ } // switch
+ } // for
- var filename
- , contentDisposition
- ;
+ // handle the case where we left a class open.
+ // "[abc" is valid, equivalent to "\[abc"
+ if (inClass) {
+ // split where the last [ was, and escape it
+ // this is a huge pita. We now have to re-walk
+ // the contents of the would-be class to re-translate
+ // any characters that were passed through as-is
+ cs = pattern.slice(classStart + 1)
+ sp = this.parse(cs, SUBPARSE)
+ re = re.substring(0, reClassStart) + '\\[' + sp[0]
+ hasMagic = hasMagic || sp[1]
+ }
- if (typeof options.filepath === 'string') {
- // custom filepath for relative paths
- filename = path.normalize(options.filepath).replace(/\\/g, '/');
- } else if (options.filename || value.name || value.path) {
- // custom filename take precedence
- // formidable and the browser add a name property
- // fs- and request- streams have path property
- filename = path.basename(options.filename || value.name || value.path);
- } else if (value.readable && value.hasOwnProperty('httpVersion')) {
- // or try http response
- filename = path.basename(value.client._httpMessage.path || '');
- }
+ // handle the case where we had a +( thing at the *end*
+ // of the pattern.
+ // each pattern list stack adds 3 chars, and we need to go through
+ // and escape any | chars that were passed through as-is for the regexp.
+ // Go through and escape them, taking care not to double-escape any
+ // | chars that were already escaped.
+ for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
+ let tail
+ tail = re.slice(pl.reStart + pl.open.length)
+ this.debug('setting tail', re, pl)
+ // maybe some even number of \, then maybe 1 \, followed by a |
+ tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_, $1, $2) => {
+ /* istanbul ignore else - should already be done */
+ if (!$2) {
+ // the | isn't already escaped, so escape it.
+ $2 = '\\'
+ }
- if (filename) {
- contentDisposition = 'filename="' + filename + '"';
- }
+ // need to escape all those slashes *again*, without escaping the
+ // one that we need for escaping the | character. As it works out,
+ // escaping an even number of slashes can be done by simply repeating
+ // it exactly after itself. That's why this trick works.
+ //
+ // I am sorry that you have to see this.
+ return $1 + $1 + $2 + '|'
+ })
- return contentDisposition;
-};
+ this.debug('tail=%j\n %s', tail, tail, pl, re)
+ const t = pl.type === '*' ? star
+ : pl.type === '?' ? qmark
+ : '\\' + pl.type
-FormData.prototype._getContentType = function(value, options) {
+ hasMagic = true
+ re = re.slice(0, pl.reStart) + t + '\\(' + tail
+ }
- // use custom content-type above all
- var contentType = options.contentType;
+ // handle trailing things that only matter at the very end.
+ clearStateChar()
+ if (escaping) {
+ // trailing \\
+ re += '\\\\'
+ }
- // or try `name` from formidable, browser
- if (!contentType && value.name) {
- contentType = mime.lookup(value.name);
- }
+ // only need to apply the nodot start if the re starts with
+ // something that could conceivably capture a dot
+ const addPatternStart = addPatternStartSet[re.charAt(0)]
- // or try `path` from fs-, request- streams
- if (!contentType && value.path) {
- contentType = mime.lookup(value.path);
- }
+ // Hack to work around lack of negative lookbehind in JS
+ // A pattern like: *.!(x).!(y|z) needs to ensure that a name
+ // like 'a.xyz.yz' doesn't match. So, the first negative
+ // lookahead, has to look ALL the way ahead, to the end of
+ // the pattern.
+ for (let n = negativeLists.length - 1; n > -1; n--) {
+ const nl = negativeLists[n]
- // or if it's http-reponse
- if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) {
- contentType = value.headers['content-type'];
- }
+ const nlBefore = re.slice(0, nl.reStart)
+ const nlFirst = re.slice(nl.reStart, nl.reEnd - 8)
+ let nlAfter = re.slice(nl.reEnd)
+ const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter
- // or guess it from the filepath or filename
- if (!contentType && (options.filepath || options.filename)) {
- contentType = mime.lookup(options.filepath || options.filename);
- }
+ // Handle nested stuff like *(*.js|!(*.json)), where open parens
+ // mean that we should *not* include the ) in the bit that is considered
+ // "after" the negated section.
+ const closeParensBefore = nlBefore.split(')').length
+ const openParensBefore = nlBefore.split('(').length - closeParensBefore
+ let cleanAfter = nlAfter
+ for (let i = 0; i < openParensBefore; i++) {
+ cleanAfter = cleanAfter.replace(/\)[+*?]?/, '')
+ }
+ nlAfter = cleanAfter
- // fallback to the default content type if `value` is not simple value
- if (!contentType && typeof value == 'object') {
- contentType = FormData.DEFAULT_CONTENT_TYPE;
- }
+ const dollar = nlAfter === '' && isSub !== SUBPARSE ? '(?:$|\\/)' : ''
- return contentType;
-};
+ re = nlBefore + nlFirst + nlAfter + dollar + nlLast
+ }
-FormData.prototype._multiPartFooter = function() {
- return function(next) {
- var footer = FormData.LINE_BREAK;
+ // if the re is not "" at this point, then we need to make sure
+ // it doesn't match against an empty path part.
+ // Otherwise a/* will match a/, which it should not.
+ if (re !== '' && hasMagic) {
+ re = '(?=.)' + re
+ }
- var lastPart = (this._streams.length === 0);
- if (lastPart) {
- footer += this._lastBoundary();
+ if (addPatternStart) {
+ re = patternStart() + re
}
- next(footer);
- }.bind(this);
-};
+ // parsing just a piece of a larger pattern.
+ if (isSub === SUBPARSE) {
+ return [re, hasMagic]
+ }
-FormData.prototype._lastBoundary = function() {
- return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK;
-};
+ // if it's nocase, and the lcase/uppercase don't match, it's magic
+ if (options.nocase && !hasMagic) {
+ hasMagic = pattern.toUpperCase() !== pattern.toLowerCase()
+ }
-FormData.prototype.getHeaders = function(userHeaders) {
- var header;
- var formHeaders = {
- 'content-type': 'multipart/form-data; boundary=' + this.getBoundary()
- };
+ // skip the regexp for non-magical patterns
+ // unescape anything in it, though, so that it'll be
+ // an exact match against a file etc.
+ if (!hasMagic) {
+ return globUnescape(pattern)
+ }
- for (header in userHeaders) {
- if (userHeaders.hasOwnProperty(header)) {
- formHeaders[header.toLowerCase()] = userHeaders[header];
+ const flags = options.nocase ? 'i' : ''
+ try {
+ return Object.assign(new RegExp('^' + re + '$', flags), {
+ _glob: pattern,
+ _src: re,
+ })
+ } catch (er) /* istanbul ignore next - should be impossible */ {
+ // If it was an invalid regular expression, then it can't match
+ // anything. This trick looks for a character after the end of
+ // the string, which is of course impossible, except in multi-line
+ // mode, but it's not a /m regex.
+ return new RegExp('$.')
}
}
- return formHeaders;
-};
+ makeRe () {
+ if (this.regexp || this.regexp === false) return this.regexp
-FormData.prototype.setBoundary = function(boundary) {
- this._boundary = boundary;
-};
+ // at this point, this.set is a 2d array of partial
+ // pattern strings, or "**".
+ //
+ // It's better to use .match(). This function shouldn't
+ // be used, really, but it's pretty convenient sometimes,
+ // when you just want to work with a regex.
+ const set = this.set
-FormData.prototype.getBoundary = function() {
- if (!this._boundary) {
- this._generateBoundary();
- }
+ if (!set.length) {
+ this.regexp = false
+ return this.regexp
+ }
+ const options = this.options
- return this._boundary;
-};
+ const twoStar = options.noglobstar ? star
+ : options.dot ? twoStarDot
+ : twoStarNoDot
+ const flags = options.nocase ? 'i' : ''
-FormData.prototype.getBuffer = function() {
- var dataBuffer = new Buffer.alloc( 0 );
- var boundary = this.getBoundary();
+ // coalesce globstars and regexpify non-globstar patterns
+ // if it's the only item, then we just do one twoStar
+ // if it's the first, and there are more, prepend (\/|twoStar\/)? to next
+ // if it's the last, append (\/twoStar|) to previous
+ // if it's in the middle, append (\/|\/twoStar\/) to previous
+ // then filter out GLOBSTAR symbols
+ let re = set.map(pattern => {
+ pattern = pattern.map(p =>
+ typeof p === 'string' ? regExpEscape(p)
+ : p === GLOBSTAR ? GLOBSTAR
+ : p._src
+ ).reduce((set, p) => {
+ if (!(set[set.length - 1] === GLOBSTAR && p === GLOBSTAR)) {
+ set.push(p)
+ }
+ return set
+ }, [])
+ pattern.forEach((p, i) => {
+ if (p !== GLOBSTAR || pattern[i-1] === GLOBSTAR) {
+ return
+ }
+ if (i === 0) {
+ if (pattern.length > 1) {
+ pattern[i+1] = '(?:\\\/|' + twoStar + '\\\/)?' + pattern[i+1]
+ } else {
+ pattern[i] = twoStar
+ }
+ } else if (i === pattern.length - 1) {
+ pattern[i-1] += '(?:\\\/|' + twoStar + ')?'
+ } else {
+ pattern[i-1] += '(?:\\\/|\\\/' + twoStar + '\\\/)' + pattern[i+1]
+ pattern[i+1] = GLOBSTAR
+ }
+ })
+ return pattern.filter(p => p !== GLOBSTAR).join('/')
+ }).join('|')
- // Create the form content. Add Line breaks to the end of data.
- for (var i = 0, len = this._streams.length; i < len; i++) {
- if (typeof this._streams[i] !== 'function') {
+ // must match entire pattern
+ // ending in a * or ** will make it less strict.
+ re = '^(?:' + re + ')$'
- // Add content to the buffer.
- if(Buffer.isBuffer(this._streams[i])) {
- dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]);
- }else {
- dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]);
- }
+ // can match anything, as long as it's not this.
+ if (this.negate) re = '^(?!' + re + ').*$'
- // Add break after content.
- if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) {
- dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData.LINE_BREAK)] );
- }
+ try {
+ this.regexp = new RegExp(re, flags)
+ } catch (ex) /* istanbul ignore next - should be impossible */ {
+ this.regexp = false
}
+ return this.regexp
}
- // Add the footer and return the Buffer object.
- return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] );
-};
-
-FormData.prototype._generateBoundary = function() {
- // This generates a 50 character boundary similar to those used by Firefox.
- // They are optimized for boyer-moore parsing.
- var boundary = '--------------------------';
- for (var i = 0; i < 24; i++) {
- boundary += Math.floor(Math.random() * 10).toString(16);
- }
-
- this._boundary = boundary;
-};
+ match (f, partial = this.partial) {
+ this.debug('match', f, this.pattern)
+ // short-circuit in the case of busted things.
+ // comments, etc.
+ if (this.comment) return false
+ if (this.empty) return f === ''
-// Note: getLengthSync DOESN'T calculate streams length
-// As workaround one can calculate file size manually
-// and add it as knownLength option
-FormData.prototype.getLengthSync = function() {
- var knownLength = this._overheadLength + this._valueLength;
+ if (f === '/' && partial) return true
- // Don't get confused, there are 3 "internal" streams for each keyval pair
- // so it basically checks if there is any value added to the form
- if (this._streams.length) {
- knownLength += this._lastBoundary().length;
- }
+ const options = this.options
- // https://github.com/form-data/form-data/issues/40
- if (!this.hasKnownLength()) {
- // Some async length retrievers are present
- // therefore synchronous length calculation is false.
- // Please use getLength(callback) to get proper length
- this._error(new Error('Cannot calculate proper length in synchronous way.'));
- }
+ // windows: need to use /, not \
+ if (path.sep !== '/') {
+ f = f.split(path.sep).join('/')
+ }
- return knownLength;
-};
+ // treat the test path as a set of pathparts.
+ f = f.split(slashSplit)
+ this.debug(this.pattern, 'split', f)
-// Public API to check if length of added values is known
-// https://github.com/form-data/form-data/issues/196
-// https://github.com/form-data/form-data/issues/262
-FormData.prototype.hasKnownLength = function() {
- var hasKnownLength = true;
+ // just ONE of the pattern sets in this.set needs to match
+ // in order for it to be valid. If negating, then just one
+ // match means that we have failed.
+ // Either way, return on the first hit.
- if (this._valuesToMeasure.length) {
- hasKnownLength = false;
- }
+ const set = this.set
+ this.debug(this.pattern, 'set', set)
- return hasKnownLength;
-};
+ // Find the basename of the path by looking for the last non-empty segment
+ let filename
+ for (let i = f.length - 1; i >= 0; i--) {
+ filename = f[i]
+ if (filename) break
+ }
-FormData.prototype.getLength = function(cb) {
- var knownLength = this._overheadLength + this._valueLength;
+ for (let i = 0; i < set.length; i++) {
+ const pattern = set[i]
+ let file = f
+ if (options.matchBase && pattern.length === 1) {
+ file = [filename]
+ }
+ const hit = this.matchOne(file, pattern, partial)
+ if (hit) {
+ if (options.flipNegate) return true
+ return !this.negate
+ }
+ }
- if (this._streams.length) {
- knownLength += this._lastBoundary().length;
+ // didn't get any hits. this is success if it's a negative
+ // pattern, failure otherwise.
+ if (options.flipNegate) return false
+ return this.negate
}
- if (!this._valuesToMeasure.length) {
- process.nextTick(cb.bind(this, null, knownLength));
- return;
+ static defaults (def) {
+ return minimatch.defaults(def).Minimatch
}
+}
- asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) {
- if (err) {
- cb(err);
- return;
- }
+minimatch.Minimatch = Minimatch
- values.forEach(function(length) {
- knownLength += length;
- });
- cb(null, knownLength);
- });
-};
+/***/ }),
-FormData.prototype.submit = function(params, cb) {
- var request
- , options
- , defaults = {method: 'post'}
- ;
+/***/ 9010:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // parse provided url if it's string
- // or treat it as options object
- if (typeof params == 'string') {
+module.exports = globSync
+globSync.GlobSync = GlobSync
- params = parseUrl(params);
- options = populate({
- port: params.port,
- path: params.pathname,
- host: params.hostname,
- protocol: params.protocol
- }, defaults);
+var rp = __nccwpck_require__(6863)
+var minimatch = __nccwpck_require__(6453)
+var Minimatch = minimatch.Minimatch
+var Glob = (__nccwpck_require__(1957).Glob)
+var util = __nccwpck_require__(3837)
+var path = __nccwpck_require__(1017)
+var assert = __nccwpck_require__(9491)
+var isAbsolute = (__nccwpck_require__(1017).isAbsolute)
+var common = __nccwpck_require__(7625)
+var setopts = common.setopts
+var ownProp = common.ownProp
+var childrenIgnored = common.childrenIgnored
+var isIgnored = common.isIgnored
- // use custom params
- } else {
+function globSync (pattern, options) {
+ if (typeof options === 'function' || arguments.length === 3)
+ throw new TypeError('callback provided to sync glob\n'+
+ 'See: https://github.com/isaacs/node-glob/issues/167')
- options = populate(params, defaults);
- // if no port provided use default one
- if (!options.port) {
- options.port = options.protocol == 'https:' ? 443 : 80;
- }
- }
+ return new GlobSync(pattern, options).found
+}
- // put that good code in getHeaders to some use
- options.headers = this.getHeaders(params.headers);
+function GlobSync (pattern, options) {
+ if (!pattern)
+ throw new Error('must provide pattern')
- // https if specified, fallback to http in any other case
- if (options.protocol == 'https:') {
- request = https.request(options);
- } else {
- request = http.request(options);
- }
+ if (typeof options === 'function' || arguments.length === 3)
+ throw new TypeError('callback provided to sync glob\n'+
+ 'See: https://github.com/isaacs/node-glob/issues/167')
- // get content length and fire away
- this.getLength(function(err, length) {
- if (err && err !== 'Unknown stream') {
- this._error(err);
- return;
- }
+ if (!(this instanceof GlobSync))
+ return new GlobSync(pattern, options)
- // add content length
- if (length) {
- request.setHeader('Content-Length', length);
- }
+ setopts(this, pattern, options)
- this.pipe(request);
- if (cb) {
- var onResponse;
+ if (this.noprocess)
+ return this
- var callback = function (error, responce) {
- request.removeListener('error', callback);
- request.removeListener('response', onResponse);
+ var n = this.minimatch.set.length
+ this.matches = new Array(n)
+ for (var i = 0; i < n; i ++) {
+ this._process(this.minimatch.set[i], i, false)
+ }
+ this._finish()
+}
- return cb.call(this, error, responce);
- };
+GlobSync.prototype._finish = function () {
+ assert.ok(this instanceof GlobSync)
+ if (this.realpath) {
+ var self = this
+ this.matches.forEach(function (matchset, index) {
+ var set = self.matches[index] = Object.create(null)
+ for (var p in matchset) {
+ try {
+ p = self._makeAbs(p)
+ var real = rp.realpathSync(p, self.realpathCache)
+ set[real] = true
+ } catch (er) {
+ if (er.syscall === 'stat')
+ set[self._makeAbs(p)] = true
+ else
+ throw er
+ }
+ }
+ })
+ }
+ common.finish(this)
+}
- onResponse = callback.bind(this, null);
- request.on('error', callback);
- request.on('response', onResponse);
- }
- }.bind(this));
+GlobSync.prototype._process = function (pattern, index, inGlobStar) {
+ assert.ok(this instanceof GlobSync)
- return request;
-};
+ // Get the first [n] parts of pattern that are all strings.
+ var n = 0
+ while (typeof pattern[n] === 'string') {
+ n ++
+ }
+ // now n is the index of the first one that is *not* a string.
-FormData.prototype._error = function(err) {
- if (!this.error) {
- this.error = err;
- this.pause();
- this.emit('error', err);
+ // See if there's anything else
+ var prefix
+ switch (n) {
+ // if not, then this is rather simple
+ case pattern.length:
+ this._processSimple(pattern.join('/'), index)
+ return
+
+ case 0:
+ // pattern *starts* with some non-trivial item.
+ // going to readdir(cwd), but not include the prefix in matches.
+ prefix = null
+ break
+
+ default:
+ // pattern has some string bits in the front.
+ // whatever it starts with, whether that's 'absolute' like /foo/bar,
+ // or 'relative' like '../baz'
+ prefix = pattern.slice(0, n).join('/')
+ break
}
-};
-FormData.prototype.toString = function () {
- return '[object FormData]';
-};
+ var remain = pattern.slice(n)
+ // get the list of entries.
+ var read
+ if (prefix === null)
+ read = '.'
+ else if (isAbsolute(prefix) ||
+ isAbsolute(pattern.map(function (p) {
+ return typeof p === 'string' ? p : '[*]'
+ }).join('/'))) {
+ if (!prefix || !isAbsolute(prefix))
+ prefix = '/' + prefix
+ read = prefix
+ } else
+ read = prefix
-/***/ }),
+ var abs = this._makeAbs(read)
-/***/ 7142:
-/***/ ((module) => {
+ //if ignored, skip processing
+ if (childrenIgnored(this, read))
+ return
-// populates missing values
-module.exports = function(dst, src) {
+ var isGlobStar = remain[0] === minimatch.GLOBSTAR
+ if (isGlobStar)
+ this._processGlobStar(prefix, read, abs, remain, index, inGlobStar)
+ else
+ this._processReaddir(prefix, read, abs, remain, index, inGlobStar)
+}
- Object.keys(src).forEach(function(prop)
- {
- dst[prop] = dst[prop] || src[prop];
- });
- return dst;
-};
+GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
+ var entries = this._readdir(abs, inGlobStar)
+ // if the abs isn't a dir, then nothing can match!
+ if (!entries)
+ return
-/***/ }),
+ // It will only match dot entries if it starts with a dot, or if
+ // dot is set. Stuff like @(.foo|.bar) isn't allowed.
+ var pn = remain[0]
+ var negate = !!this.minimatch.negate
+ var rawGlob = pn._glob
+ var dotOk = this.dot || rawGlob.charAt(0) === '.'
-/***/ 6863:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ var matchedEntries = []
+ for (var i = 0; i < entries.length; i++) {
+ var e = entries[i]
+ if (e.charAt(0) !== '.' || dotOk) {
+ var m
+ if (negate && !prefix) {
+ m = !e.match(pn)
+ } else {
+ m = e.match(pn)
+ }
+ if (m)
+ matchedEntries.push(e)
+ }
+ }
-module.exports = realpath
-realpath.realpath = realpath
-realpath.sync = realpathSync
-realpath.realpathSync = realpathSync
-realpath.monkeypatch = monkeypatch
-realpath.unmonkeypatch = unmonkeypatch
+ var len = matchedEntries.length
+ // If there are no matched entries, then nothing matches.
+ if (len === 0)
+ return
-var fs = __nccwpck_require__(7147)
-var origRealpath = fs.realpath
-var origRealpathSync = fs.realpathSync
+ // if this is the last remaining pattern bit, then no need for
+ // an additional stat *unless* the user has specified mark or
+ // stat explicitly. We know they exist, since readdir returned
+ // them.
-var version = process.version
-var ok = /^v[0-5]\./.test(version)
-var old = __nccwpck_require__(1734)
+ if (remain.length === 1 && !this.mark && !this.stat) {
+ if (!this.matches[index])
+ this.matches[index] = Object.create(null)
-function newError (er) {
- return er && er.syscall === 'realpath' && (
- er.code === 'ELOOP' ||
- er.code === 'ENOMEM' ||
- er.code === 'ENAMETOOLONG'
- )
-}
+ for (var i = 0; i < len; i ++) {
+ var e = matchedEntries[i]
+ if (prefix) {
+ if (prefix.slice(-1) !== '/')
+ e = prefix + '/' + e
+ else
+ e = prefix + e
+ }
-function realpath (p, cache, cb) {
- if (ok) {
- return origRealpath(p, cache, cb)
+ if (e.charAt(0) === '/' && !this.nomount) {
+ e = path.join(this.root, e)
+ }
+ this._emitMatch(index, e)
+ }
+ // This was the last one, and no stats were needed
+ return
}
- if (typeof cache === 'function') {
- cb = cache
- cache = null
+ // now test all matched entries as stand-ins for that part
+ // of the pattern.
+ remain.shift()
+ for (var i = 0; i < len; i ++) {
+ var e = matchedEntries[i]
+ var newPattern
+ if (prefix)
+ newPattern = [prefix, e]
+ else
+ newPattern = [e]
+ this._process(newPattern.concat(remain), index, inGlobStar)
}
- origRealpath(p, cache, function (er, result) {
- if (newError(er)) {
- old.realpath(p, cache, cb)
- } else {
- cb(er, result)
- }
- })
}
-function realpathSync (p, cache) {
- if (ok) {
- return origRealpathSync(p, cache)
+
+GlobSync.prototype._emitMatch = function (index, e) {
+ if (isIgnored(this, e))
+ return
+
+ var abs = this._makeAbs(e)
+
+ if (this.mark)
+ e = this._mark(e)
+
+ if (this.absolute) {
+ e = abs
}
- try {
- return origRealpathSync(p, cache)
- } catch (er) {
- if (newError(er)) {
- return old.realpathSync(p, cache)
- } else {
- throw er
- }
+ if (this.matches[index][e])
+ return
+
+ if (this.nodir) {
+ var c = this.cache[abs]
+ if (c === 'DIR' || Array.isArray(c))
+ return
}
-}
-function monkeypatch () {
- fs.realpath = realpath
- fs.realpathSync = realpathSync
-}
+ this.matches[index][e] = true
-function unmonkeypatch () {
- fs.realpath = origRealpath
- fs.realpathSync = origRealpathSync
+ if (this.stat)
+ this._stat(e)
}
-/***/ }),
+GlobSync.prototype._readdirInGlobStar = function (abs) {
+ // follow all symlinked directories forever
+ // just proceed as if this is a non-globstar situation
+ if (this.follow)
+ return this._readdir(abs, false)
-/***/ 1734:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ var entries
+ var lstat
+ var stat
+ try {
+ lstat = this.fs.lstatSync(abs)
+ } catch (er) {
+ if (er.code === 'ENOENT') {
+ // lstat failed, doesn't exist
+ return null
+ }
+ }
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
+ var isSym = lstat && lstat.isSymbolicLink()
+ this.symlinks[abs] = isSym
-var pathModule = __nccwpck_require__(1017);
-var isWindows = process.platform === 'win32';
-var fs = __nccwpck_require__(7147);
+ // If it's not a symlink or a dir, then it's definitely a regular file.
+ // don't bother doing a readdir in that case.
+ if (!isSym && lstat && !lstat.isDirectory())
+ this.cache[abs] = 'FILE'
+ else
+ entries = this._readdir(abs, false)
-// JavaScript implementation of realpath, ported from node pre-v6
+ return entries
+}
-var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
+GlobSync.prototype._readdir = function (abs, inGlobStar) {
+ var entries
-function rethrow() {
- // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
- // is fairly slow to generate.
- var callback;
- if (DEBUG) {
- var backtrace = new Error;
- callback = debugCallback;
- } else
- callback = missingCallback;
+ if (inGlobStar && !ownProp(this.symlinks, abs))
+ return this._readdirInGlobStar(abs)
- return callback;
+ if (ownProp(this.cache, abs)) {
+ var c = this.cache[abs]
+ if (!c || c === 'FILE')
+ return null
- function debugCallback(err) {
- if (err) {
- backtrace.message = err.message;
- err = backtrace;
- missingCallback(err);
- }
+ if (Array.isArray(c))
+ return c
}
- function missingCallback(err) {
- if (err) {
- if (process.throwDeprecation)
- throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
- else if (!process.noDeprecation) {
- var msg = 'fs: missing callback ' + (err.stack || err.message);
- if (process.traceDeprecation)
- console.trace(msg);
- else
- console.error(msg);
- }
- }
+ try {
+ return this._readdirEntries(abs, this.fs.readdirSync(abs))
+ } catch (er) {
+ this._readdirError(abs, er)
+ return null
}
}
-function maybeCallback(cb) {
- return typeof cb === 'function' ? cb : rethrow();
-}
+GlobSync.prototype._readdirEntries = function (abs, entries) {
+ // if we haven't asked to stat everything, then just
+ // assume that everything in there exists, so we can avoid
+ // having to stat it a second time.
+ if (!this.mark && !this.stat) {
+ for (var i = 0; i < entries.length; i ++) {
+ var e = entries[i]
+ if (abs === '/')
+ e = abs + e
+ else
+ e = abs + '/' + e
+ this.cache[e] = true
+ }
+ }
-var normalize = pathModule.normalize;
+ this.cache[abs] = entries
-// Regexp that finds the next partion of a (partial) path
-// result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
-if (isWindows) {
- var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
-} else {
- var nextPartRe = /(.*?)(?:[\/]+|$)/g;
+ // mark and cache dir-ness
+ return entries
}
-// Regex to find the device root, including trailing slash. E.g. 'c:\\'.
-if (isWindows) {
- var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
-} else {
- var splitRootRe = /^[\/]*/;
-}
+GlobSync.prototype._readdirError = function (f, er) {
+ // handle errors, and cache the information
+ switch (er.code) {
+ case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
+ case 'ENOTDIR': // totally normal. means it *does* exist.
+ var abs = this._makeAbs(f)
+ this.cache[abs] = 'FILE'
+ if (abs === this.cwdAbs) {
+ var error = new Error(er.code + ' invalid cwd ' + this.cwd)
+ error.path = this.cwd
+ error.code = er.code
+ throw error
+ }
+ break
-exports.realpathSync = function realpathSync(p, cache) {
- // make p is absolute
- p = pathModule.resolve(p);
+ case 'ENOENT': // not terribly unusual
+ case 'ELOOP':
+ case 'ENAMETOOLONG':
+ case 'UNKNOWN':
+ this.cache[this._makeAbs(f)] = false
+ break
- if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
- return cache[p];
+ default: // some unusual error. Treat as failure.
+ this.cache[this._makeAbs(f)] = false
+ if (this.strict)
+ throw er
+ if (!this.silent)
+ console.error('glob error', er)
+ break
}
+}
- var original = p,
- seenLinks = {},
- knownHard = {};
+GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
- // current character position in p
- var pos;
- // the partial path so far, including a trailing slash if any
- var current;
- // the partial path without a trailing slash (except when pointing at a root)
- var base;
- // the partial path scanned in the previous round, with slash
- var previous;
+ var entries = this._readdir(abs, inGlobStar)
- start();
+ // no entries means not a dir, so it can never have matches
+ // foo.txt/** doesn't match foo.txt
+ if (!entries)
+ return
- function start() {
- // Skip over roots
- var m = splitRootRe.exec(p);
- pos = m[0].length;
- current = m[0];
- base = m[0];
- previous = '';
+ // test without the globstar, and with every child both below
+ // and replacing the globstar.
+ var remainWithoutGlobStar = remain.slice(1)
+ var gspref = prefix ? [ prefix ] : []
+ var noGlobStar = gspref.concat(remainWithoutGlobStar)
- // On windows, check that the root exists. On unix there is no need.
- if (isWindows && !knownHard[base]) {
- fs.lstatSync(base);
- knownHard[base] = true;
- }
- }
+ // the noGlobStar pattern exits the inGlobStar state
+ this._process(noGlobStar, index, false)
- // walk down the path, swapping out linked pathparts for their real
- // values
- // NB: p.length changes.
- while (pos < p.length) {
- // find the next part
- nextPartRe.lastIndex = pos;
- var result = nextPartRe.exec(p);
- previous = current;
- current += result[0];
- base = previous + result[1];
- pos = nextPartRe.lastIndex;
+ var len = entries.length
+ var isSym = this.symlinks[abs]
- // continue if not a symlink
- if (knownHard[base] || (cache && cache[base] === base)) {
- continue;
- }
+ // If it's a symlink, and we're in a globstar, then stop
+ if (isSym && inGlobStar)
+ return
- var resolvedLink;
- if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
- // some known symbolic link. no need to stat again.
- resolvedLink = cache[base];
- } else {
- var stat = fs.lstatSync(base);
- if (!stat.isSymbolicLink()) {
- knownHard[base] = true;
- if (cache) cache[base] = base;
- continue;
- }
+ for (var i = 0; i < len; i++) {
+ var e = entries[i]
+ if (e.charAt(0) === '.' && !this.dot)
+ continue
- // read the link if it wasn't read before
- // dev/ino always return 0 on windows, so skip the check.
- var linkTarget = null;
- if (!isWindows) {
- var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
- if (seenLinks.hasOwnProperty(id)) {
- linkTarget = seenLinks[id];
- }
- }
- if (linkTarget === null) {
- fs.statSync(base);
- linkTarget = fs.readlinkSync(base);
- }
- resolvedLink = pathModule.resolve(previous, linkTarget);
- // track this, if given a cache.
- if (cache) cache[base] = resolvedLink;
- if (!isWindows) seenLinks[id] = linkTarget;
- }
+ // these two cases enter the inGlobStar state
+ var instead = gspref.concat(entries[i], remainWithoutGlobStar)
+ this._process(instead, index, true)
- // resolve the link, then start over
- p = pathModule.resolve(resolvedLink, p.slice(pos));
- start();
+ var below = gspref.concat(entries[i], remain)
+ this._process(below, index, true)
}
+}
- if (cache) cache[original] = p;
+GlobSync.prototype._processSimple = function (prefix, index) {
+ // XXX review this. Shouldn't it be doing the mounting etc
+ // before doing stat? kinda weird?
+ var exists = this._stat(prefix)
- return p;
-};
+ if (!this.matches[index])
+ this.matches[index] = Object.create(null)
+ // If it doesn't exist, then just mark the lack of results
+ if (!exists)
+ return
-exports.realpath = function realpath(p, cache, cb) {
- if (typeof cb !== 'function') {
- cb = maybeCallback(cache);
- cache = null;
+ if (prefix && isAbsolute(prefix) && !this.nomount) {
+ var trail = /[\/\\]$/.test(prefix)
+ if (prefix.charAt(0) === '/') {
+ prefix = path.join(this.root, prefix)
+ } else {
+ prefix = path.resolve(this.root, prefix)
+ if (trail)
+ prefix += '/'
+ }
}
- // make p is absolute
- p = pathModule.resolve(p);
+ if (process.platform === 'win32')
+ prefix = prefix.replace(/\\/g, '/')
- if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
- return process.nextTick(cb.bind(null, null, cache[p]));
- }
+ // Mark this as a match
+ this._emitMatch(index, prefix)
+}
- var original = p,
- seenLinks = {},
- knownHard = {};
+// Returns either 'DIR', 'FILE', or false
+GlobSync.prototype._stat = function (f) {
+ var abs = this._makeAbs(f)
+ var needDir = f.slice(-1) === '/'
- // current character position in p
- var pos;
- // the partial path so far, including a trailing slash if any
- var current;
- // the partial path without a trailing slash (except when pointing at a root)
- var base;
- // the partial path scanned in the previous round, with slash
- var previous;
+ if (f.length > this.maxLength)
+ return false
- start();
+ if (!this.stat && ownProp(this.cache, abs)) {
+ var c = this.cache[abs]
- function start() {
- // Skip over roots
- var m = splitRootRe.exec(p);
- pos = m[0].length;
- current = m[0];
- base = m[0];
- previous = '';
+ if (Array.isArray(c))
+ c = 'DIR'
- // On windows, check that the root exists. On unix there is no need.
- if (isWindows && !knownHard[base]) {
- fs.lstat(base, function(err) {
- if (err) return cb(err);
- knownHard[base] = true;
- LOOP();
- });
- } else {
- process.nextTick(LOOP);
- }
- }
+ // It exists, but maybe not how we need it
+ if (!needDir || c === 'DIR')
+ return c
- // walk down the path, swapping out linked pathparts for their real
- // values
- function LOOP() {
- // stop if scanned past end of path
- if (pos >= p.length) {
- if (cache) cache[original] = p;
- return cb(null, p);
- }
+ if (needDir && c === 'FILE')
+ return false
- // find the next part
- nextPartRe.lastIndex = pos;
- var result = nextPartRe.exec(p);
- previous = current;
- current += result[0];
- base = previous + result[1];
- pos = nextPartRe.lastIndex;
+ // otherwise we have to stat, because maybe c=true
+ // if we know it exists, but not what it is.
+ }
- // continue if not a symlink
- if (knownHard[base] || (cache && cache[base] === base)) {
- return process.nextTick(LOOP);
+ var exists
+ var stat = this.statCache[abs]
+ if (!stat) {
+ var lstat
+ try {
+ lstat = this.fs.lstatSync(abs)
+ } catch (er) {
+ if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
+ this.statCache[abs] = false
+ return false
+ }
}
- if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
- // known symbolic link. no need to stat again.
- return gotResolvedLink(cache[base]);
+ if (lstat && lstat.isSymbolicLink()) {
+ try {
+ stat = this.fs.statSync(abs)
+ } catch (er) {
+ stat = lstat
+ }
+ } else {
+ stat = lstat
}
-
- return fs.lstat(base, gotStat);
}
- function gotStat(err, stat) {
- if (err) return cb(err);
+ this.statCache[abs] = stat
- // if not a symlink, skip to the next path part
- if (!stat.isSymbolicLink()) {
- knownHard[base] = true;
- if (cache) cache[base] = base;
- return process.nextTick(LOOP);
- }
+ var c = true
+ if (stat)
+ c = stat.isDirectory() ? 'DIR' : 'FILE'
- // stat & read the link if not read before
- // call gotTarget as soon as the link target is known
- // dev/ino always return 0 on windows, so skip the check.
- if (!isWindows) {
- var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
- if (seenLinks.hasOwnProperty(id)) {
- return gotTarget(null, seenLinks[id], base);
- }
- }
- fs.stat(base, function(err) {
- if (err) return cb(err);
+ this.cache[abs] = this.cache[abs] || c
- fs.readlink(base, function(err, target) {
- if (!isWindows) seenLinks[id] = target;
- gotTarget(err, target);
- });
- });
- }
+ if (needDir && c === 'FILE')
+ return false
- function gotTarget(err, target, base) {
- if (err) return cb(err);
+ return c
+}
- var resolvedLink = pathModule.resolve(previous, target);
- if (cache) cache[base] = resolvedLink;
- gotResolvedLink(resolvedLink);
- }
+GlobSync.prototype._mark = function (p) {
+ return common.mark(this, p)
+}
- function gotResolvedLink(resolvedLink) {
- // resolve the link, then start over
- p = pathModule.resolve(resolvedLink, p.slice(pos));
- start();
- }
-};
+GlobSync.prototype._makeAbs = function (f) {
+ return common.makeAbs(this, f)
+}
/***/ }),
@@ -38972,7 +39175,7 @@ const api_wrapper_1 = __nccwpck_require__(4636);
};
const parameters = (0, input_parameters_1.getInputParameters)();
const config = {
- userAgentApp: 'GitHubActions create-release-action',
+ userAgentApp: 'GitHubActions (release;create;v3)',
instanceURL: parameters.server,
apiKey: parameters.apiKey,
logging: logger
@@ -39184,7 +39387,7 @@ module.exports = require("zlib");
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
-// Axios v1.2.1 Copyright (c) 2022 Matt Zabriskie and contributors
+// Axios v1.2.6 Copyright (c) 2023 Matt Zabriskie and contributors
const FormData$1 = __nccwpck_require__(4334);
@@ -39489,7 +39692,11 @@ function findKey(obj, key) {
return null;
}
-const _global = typeof self === "undefined" ? typeof global === "undefined" ? undefined : global : self;
+const _global = (() => {
+ /*eslint no-undef:0*/
+ if (typeof globalThis !== "undefined") return globalThis;
+ return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global)
+})();
const isContextDefined = (context) => !isUndefined(context) && context !== _global;
@@ -40971,7 +41178,7 @@ class AxiosHeaders {
}
}
-AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent']);
+AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);
utils.freezeMethods(AxiosHeaders.prototype);
utils.freezeMethods(AxiosHeaders);
@@ -41093,7 +41300,7 @@ function buildFullPath(baseURL, requestedURL) {
return requestedURL;
}
-const VERSION = "1.2.1";
+const VERSION = "1.2.6";
function parseProtocol(url) {
const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
@@ -41420,6 +41627,11 @@ const zlibOptions = {
finishFlush: zlib__default["default"].constants.Z_SYNC_FLUSH
};
+const brotliOptions = {
+ flush: zlib__default["default"].constants.BROTLI_OPERATION_FLUSH,
+ finishFlush: zlib__default["default"].constants.BROTLI_OPERATION_FLUSH
+};
+
const isBrotliSupported = utils.isFunction(zlib__default["default"].createBrotliDecompress);
const {http: httpFollow, https: httpsFollow} = followRedirects__default["default"];
@@ -41810,7 +42022,9 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
switch (res.headers['content-encoding']) {
/*eslint default-case:0*/
case 'gzip':
+ case 'x-gzip':
case 'compress':
+ case 'x-compress':
case 'deflate':
// add the unzipper to the body stream processing pipeline
streams.push(zlib__default["default"].createUnzip(zlibOptions));
@@ -41820,7 +42034,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
break;
case 'br':
if (isBrotliSupported) {
- streams.push(zlib__default["default"].createBrotliDecompress(zlibOptions));
+ streams.push(zlib__default["default"].createBrotliDecompress(brotliOptions));
delete res.headers['content-encoding'];
}
}
@@ -42995,6 +43209,78 @@ function isAxiosError(payload) {
return utils.isObject(payload) && (payload.isAxiosError === true);
}
+const HttpStatusCode = {
+ Continue: 100,
+ SwitchingProtocols: 101,
+ Processing: 102,
+ EarlyHints: 103,
+ Ok: 200,
+ Created: 201,
+ Accepted: 202,
+ NonAuthoritativeInformation: 203,
+ NoContent: 204,
+ ResetContent: 205,
+ PartialContent: 206,
+ MultiStatus: 207,
+ AlreadyReported: 208,
+ ImUsed: 226,
+ MultipleChoices: 300,
+ MovedPermanently: 301,
+ Found: 302,
+ SeeOther: 303,
+ NotModified: 304,
+ UseProxy: 305,
+ Unused: 306,
+ TemporaryRedirect: 307,
+ PermanentRedirect: 308,
+ BadRequest: 400,
+ Unauthorized: 401,
+ PaymentRequired: 402,
+ Forbidden: 403,
+ NotFound: 404,
+ MethodNotAllowed: 405,
+ NotAcceptable: 406,
+ ProxyAuthenticationRequired: 407,
+ RequestTimeout: 408,
+ Conflict: 409,
+ Gone: 410,
+ LengthRequired: 411,
+ PreconditionFailed: 412,
+ PayloadTooLarge: 413,
+ UriTooLong: 414,
+ UnsupportedMediaType: 415,
+ RangeNotSatisfiable: 416,
+ ExpectationFailed: 417,
+ ImATeapot: 418,
+ MisdirectedRequest: 421,
+ UnprocessableEntity: 422,
+ Locked: 423,
+ FailedDependency: 424,
+ TooEarly: 425,
+ UpgradeRequired: 426,
+ PreconditionRequired: 428,
+ TooManyRequests: 429,
+ RequestHeaderFieldsTooLarge: 431,
+ UnavailableForLegalReasons: 451,
+ InternalServerError: 500,
+ NotImplemented: 501,
+ BadGateway: 502,
+ ServiceUnavailable: 503,
+ GatewayTimeout: 504,
+ HttpVersionNotSupported: 505,
+ VariantAlsoNegotiates: 506,
+ InsufficientStorage: 507,
+ LoopDetected: 508,
+ NotExtended: 510,
+ NetworkAuthenticationRequired: 511,
+};
+
+Object.entries(HttpStatusCode).forEach(([key, value]) => {
+ HttpStatusCode[value] = key;
+});
+
+const HttpStatusCode$1 = HttpStatusCode;
+
/**
* Create an instance of Axios
*
@@ -43056,6 +43342,8 @@ axios.AxiosHeaders = AxiosHeaders$1;
axios.formToJSON = thing => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
+axios.HttpStatusCode = HttpStatusCode$1;
+
axios.default = axios;
module.exports = axios;
diff --git a/package-lock.json b/package-lock.json
index cf0114e4..45706775 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "create-release-action",
- "version": "3.0.2",
+ "version": "3.0.3",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "create-release-action",
- "version": "3.0.2",
+ "version": "3.0.3",
"license": "Apache-2.0",
"dependencies": {
"@actions/core": "^1.10.0",
diff --git a/package.json b/package.json
index efbac818..dd6a80fa 100644
--- a/package.json
+++ b/package.json
@@ -84,5 +84,5 @@
"test:unit": "jest --ci --reporters=default --reporters=jest-junit --testPathPattern=__tests__/unit",
"test:integration": "jest --ci --reporters=default --reporters=jest-junit --testPathPattern=__tests__/integration"
},
- "version": "3.0.2"
+ "version": "3.0.3"
}